@preventive/triage 1.0.0-alpha.89 → 1.0.0-alpha.90
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/out/activity.js +2 -2
- package/out/{chunk-U6JONPTN.js → chunk-3DOSBILK.js} +1 -1
- package/out/{chunk-A4HSJCXG.js → chunk-CJVMNJDZ.js} +2 -2
- package/out/chunk-HGWFRZNC.js +267 -0
- package/out/{chunk-3TJCEPHF.js → chunk-JZAROLQT.js} +1 -1
- package/out/{chunk-4GHLPL2P.js → chunk-LRWB6QVO.js} +1 -1
- package/out/{chunk-G5JKKNZF.js → chunk-SMNFBOLO.js} +1 -1
- package/out/{chunk-ZPIUN4FW.js → chunk-SZTCJVZJ.js} +1 -1
- package/out/{chunk-VRFGZ6MV.js → chunk-UTYWTUTC.js} +1 -1
- package/out/client-managed.js +28 -28
- package/out/compare.js +13 -13
- package/out/dialogs.js +15 -15
- package/out/graph.js +1 -1
- package/out/index.html +5 -5
- package/out/prism.js +1 -1
- package/out/scan.js +2 -2
- package/out/view.css +1 -1
- package/out/view.js +7 -7
- package/package.json +3 -1
- package/risk/index.d.ts +15 -0
- package/risk/index.js +1 -1
- package/risk/npm/assess.js +21 -3
- package/risk/npm/registry.js +16 -7
- package/server-managed/bundle-advisories.ts +97 -0
- package/server-managed/config.ts +1 -1
- package/server-managed/github-issue-links.ts +1 -1
- package/server-managed/github-metadata.ts +6 -1
- package/server-managed/github-pulls.ts +43 -10
- package/server-managed/http.ts +170 -52
- package/server-managed/known-listings.ts +112 -0
- package/server-managed/npm-packages.ts +10 -2
- package/server-managed/npm-risk.ts +31 -8
- package/server-managed/public-workspace.ts +6 -7
- package/server-managed/pull-dependency-reviews.ts +64 -13
- package/server-managed/queue.ts +1 -1
- package/server-managed/repository-dependency-reviews.ts +38 -0
- package/server-managed/repository-risk-audit.ts +83 -16
- package/server-managed/repository-risk.ts +33 -12
- package/server-managed/team-app.ts +1 -1
- package/server-managed/team-progress.ts +77 -0
- package/server-managed/upstream-cache.ts +42 -23
- package/out/chunk-7KUZQB6S.js +0 -267
|
@@ -26,6 +26,9 @@
|
|
|
26
26
|
// - `npm/tarballs`: none asked, as tarballs are read as the viewer's loads
|
|
27
27
|
// read them, kept where they keep them (npm-loads.ts loadNpmTarball), and
|
|
28
28
|
// an assessment kept needs none.
|
|
29
|
+
// - Upstream's own, as risk asks a version's repository's advisories (its
|
|
30
|
+
// listing, `github/advisories`, and `npm/public`): `upstream`, the caller's
|
|
31
|
+
// store of them (known-listings.ts), else none.
|
|
29
32
|
//
|
|
30
33
|
// What memory keeps is held to 2,000 records and 64 MiB as JSON, the first
|
|
31
34
|
// kept going first.
|
|
@@ -38,8 +41,9 @@
|
|
|
38
41
|
// unpacking up to two tarballs: one past them is refused as busy.
|
|
39
42
|
import { Buffer } from 'node:buffer'
|
|
40
43
|
import { createHash } from 'node:crypto'
|
|
44
|
+
import type { Client } from '@preventive/upstream/github.js'
|
|
41
45
|
import type { CacheStore } from '@preventive/upstream/npm.js'
|
|
42
|
-
import { DEFAULT_MINIMUM_RELEASE_AGE, type NpmAssessment, assessNpm, npmReadyDownload, npmReadyDownloads } from '../risk/index.js'
|
|
46
|
+
import { DEFAULT_MINIMUM_RELEASE_AGE, type Finding, type NpmAssessment, assessNpm, npmMalware, npmReadyDownload, npmReadyDownloads } from '../risk/index.js'
|
|
43
47
|
import { readBytes } from './blob-store.ts'
|
|
44
48
|
import { CacheMissError, type CacheStorage } from './cache-storage.ts'
|
|
45
49
|
import { npmVersionStore, pruneKept } from './npm-kept.ts'
|
|
@@ -93,6 +97,7 @@ const databaseKey = (type: string, key: string) => HOURLY.has(type) ? `${HOURLY_
|
|
|
93
97
|
export interface NpmRiskStores {
|
|
94
98
|
db: UpstreamCacheStore
|
|
95
99
|
npmCache?: CacheStorage | undefined
|
|
100
|
+
upstream?: CacheStore | undefined
|
|
96
101
|
debug?: boolean | undefined
|
|
97
102
|
}
|
|
98
103
|
|
|
@@ -110,7 +115,7 @@ export interface NpmRiskCache extends CacheStore {
|
|
|
110
115
|
|
|
111
116
|
// Risk's cache for one package: `isPublic` whether anyone can read it, so
|
|
112
117
|
// that what is kept of it can be shared.
|
|
113
|
-
export function npmRiskCache({ db, npmCache, debug }: NpmRiskStores, isPublic: boolean): NpmRiskCache {
|
|
118
|
+
export function npmRiskCache({ db, npmCache, upstream, debug }: NpmRiskStores, isPublic: boolean): NpmRiskCache {
|
|
114
119
|
const warn = (what: string, error: unknown) => { if (debug) console.warn(`managed: risk cache ${what} failed:`, error) }
|
|
115
120
|
// The rows under `prefix` kept `keptMs` before `at` removed, as rows under
|
|
116
121
|
// it are written (pruneKept).
|
|
@@ -149,7 +154,7 @@ export function npmRiskCache({ db, npmCache, debug }: NpmRiskStores, isPublic: b
|
|
|
149
154
|
if (type === 'risk/npm/downloads') await prune(`${type}/`, DOWNLOADS_KEPT_MS, at)
|
|
150
155
|
},
|
|
151
156
|
async read(type, key) {
|
|
152
|
-
if (type === 'npm/tarballs')
|
|
157
|
+
if (!type.startsWith('risk/')) return type === 'npm/tarballs' ? null : await upstream?.read(type, key) ?? null
|
|
153
158
|
try {
|
|
154
159
|
if (isPublic && type === 'risk/npm/assessments' && npmCache) return JSON.parse((await readBytes(await npmCache.open(hashed(type, key)))).toString('utf8'))
|
|
155
160
|
if (ofDatabase(type, key)) return readOf(type, key, await db.getUpstreamCacheEntry(databaseKey(type, key)))
|
|
@@ -157,7 +162,7 @@ export function npmRiskCache({ db, npmCache, debug }: NpmRiskStores, isPublic: b
|
|
|
157
162
|
return memory.get(memoryKey(type, key))?.value ?? null
|
|
158
163
|
},
|
|
159
164
|
async write(type, key, value) {
|
|
160
|
-
if (type
|
|
165
|
+
if (!type.startsWith('risk/')) { if (type !== 'npm/tarballs') await upstream?.write(type, key, value); return }
|
|
161
166
|
if (isPublic && HOURLY.has(type)) remember(memoryKey(type, key), value)
|
|
162
167
|
try {
|
|
163
168
|
if (isPublic && type === 'risk/npm/assessments' && npmCache) { await npmCache.put(hashed(type, key), Buffer.from(JSON.stringify(value))); return }
|
|
@@ -210,14 +215,15 @@ async function tarballOf(doc: NpmVersionDocument | undefined, signal: AbortSigna
|
|
|
210
215
|
// (`privileged`, as readNpmVersion), its dependencies' without; what is kept
|
|
211
216
|
// of it is shared only where neither version is private, and OSV is asked of
|
|
212
217
|
// its advisories only where it isn't, a private package's name never sent to
|
|
213
|
-
// OSV, as it never is to Socket (http.ts)
|
|
218
|
+
// OSV, as it never is to Socket (http.ts); with `github`, its repository's
|
|
219
|
+
// too where it isn't private (assessNpm `github`). A `spare` one, no
|
|
214
220
|
// reader waiting on it, is made only within MAX_SPARE_ASSESSMENTS, and tells
|
|
215
221
|
// its dependencies without asking npm of their packages (assessNpm
|
|
216
222
|
// `dependencies`), nor its advisories, which a scan asks of a lockfile's
|
|
217
223
|
// packages at once (repository-risk.ts).
|
|
218
224
|
export function npmRisk(doc: NpmVersionDocument, old: NpmVersionDocument | 'pick' | null,
|
|
219
|
-
{ teamScoped, ownScope = () => Promise.resolve(false), fromEmpty = false, privileged, signal, spare = false, ...stores }: NpmRiskStores & { teamScoped: boolean;
|
|
220
|
-
ownScope?: (scope: string) => Promise<boolean>; fromEmpty?: boolean; privileged: boolean; signal: AbortSignal; spare?: boolean }): Promise<NpmAssessment> {
|
|
225
|
+
{ teamScoped, ownScope = () => Promise.resolve(false), fromEmpty = false, privileged, signal, spare = false, github = null, ...stores }: NpmRiskStores & { teamScoped: boolean;
|
|
226
|
+
ownScope?: (scope: string) => Promise<boolean>; fromEmpty?: boolean; privileged: boolean; signal: AbortSignal; spare?: boolean; github?: Client | null }): Promise<NpmAssessment> {
|
|
221
227
|
const scopes = new Map<string, Promise<boolean>>()
|
|
222
228
|
const owned = (name: string) => {
|
|
223
229
|
const scope = npmPackageScope(name)
|
|
@@ -231,11 +237,28 @@ export function npmRisk(doc: NpmVersionDocument, old: NpmVersionDocument | 'pick
|
|
|
231
237
|
?? await readNpmVersion(doc.name, version, privileged, signal, npmVersionStore(stores.db, stores.debug)) ?? undefined
|
|
232
238
|
return bounded(spare, () => assessNpm(doc.name, doc.version, { oldVersion: old === 'pick' ? true : old?.version ?? null, fromEmpty,
|
|
233
239
|
minimumReleaseAge: teamScoped ? 0 : DEFAULT_MINIMUM_RELEASE_AGE,
|
|
234
|
-
popularity: !teamScoped, cache: npmRiskCache(stores, !doc.private && !given?.private), signal, dependencies: !spare, advisories: !spare, osv: !doc.private,
|
|
240
|
+
popularity: !teamScoped, cache: npmRiskCache(stores, !doc.private && !given?.private), signal, dependencies: !spare, advisories: !spare, osv: !doc.private,
|
|
241
|
+
github: doc.private ? null : github, owned,
|
|
235
242
|
packument: (name, { authorized }) => readNpmPackument(name, privileged && authorized, signal),
|
|
236
243
|
tarball: async (_name, version) => tarballOf(await documentOf(version), signal) }))
|
|
237
244
|
}
|
|
238
245
|
|
|
246
|
+
// The malware finding npmRisk would tell of the version `doc` names, alone
|
|
247
|
+
// (risk npmMalware): its package taken down by npm, and npm's advisories of
|
|
248
|
+
// malware naming it, OSV's too where it isn't private, read and kept as
|
|
249
|
+
// npmRisk reads and keeps them, but its repository's, which a caller wanting
|
|
250
|
+
// them asks itself (as http.ts npmAdvisories does); none of its tarball nor
|
|
251
|
+
// its dependencies read, so none of the assessments' places taken. Its
|
|
252
|
+
// package's whole document as `packument` reads it, where given, as for its
|
|
253
|
+
// reader (`privileged`) it would be read: a caller reading it too reads it
|
|
254
|
+
// once. Null where none tells of any; an NpmRiskError where npm has no such
|
|
255
|
+
// version, nor malware explaining one removed, or can't be asked.
|
|
256
|
+
export function npmRiskMalware(doc: NpmVersionDocument, { privileged, signal, packument, ...stores }: NpmRiskStores & { privileged: boolean; signal: AbortSignal;
|
|
257
|
+
packument?: () => Promise<Record<string, unknown> | null> }): Promise<Finding | null> {
|
|
258
|
+
return npmMalware(doc.name, doc.version, { cache: npmRiskCache(stores, !doc.private), signal, osv: !doc.private,
|
|
259
|
+
packument: (name, { authorized }) => packument && name === doc.name && authorized ? packument() : readNpmPackument(name, privileged && authorized, signal) })
|
|
260
|
+
}
|
|
261
|
+
|
|
239
262
|
// An assessment made within MAX_ACTIVE_ASSESSMENTS, a `spare` one within
|
|
240
263
|
// MAX_SPARE_ASSESSMENTS, all across the server; one past them refused as
|
|
241
264
|
// busy (`npm-busy`).
|
|
@@ -12,8 +12,7 @@ import { TeamReportsError, loadTeamAnnotations, loadTeamReportsResponse, teamRep
|
|
|
12
12
|
import { triageWireEntry } from './triage-response.ts'
|
|
13
13
|
import { MAX_PACKAGE_INVENTORY_BYTES } from './bundle-cache.ts'
|
|
14
14
|
import { backfillBundleSummaries, bundleSummaries } from './bundle-catalog.ts'
|
|
15
|
-
import { ADVISORIES_TIMEOUT_MS,
|
|
16
|
-
import { auditCache, auditedKeys } from './upstream-cache.ts'
|
|
15
|
+
import { ADVISORIES_TIMEOUT_MS, fetchKnownBundleAdvisories } from './bundle-advisories.ts'
|
|
17
16
|
import { serveTeamFeed } from './team-feed.ts'
|
|
18
17
|
import { type ComparedSide, PrettyError, compared, prettyRequest, prettyText } from './pretty-print.ts'
|
|
19
18
|
import { renameDiffOf, renameDiffRequest, renamedPairs } from './rename-diff.ts'
|
|
@@ -209,13 +208,13 @@ async function serveBundle(res: ServerResponse, deps: ManagedHttpDeps, bundle: M
|
|
|
209
208
|
if (inventory === undefined) { json(res, 400, { error: entry ? 'unknown-entry' : 'unknown-reason' }); return }
|
|
210
209
|
if (Buffer.byteLength(JSON.stringify(inventory)) > MAX_PACKAGE_INVENTORY_BYTES) { json(res, 413, { error: 'payload-too-large' }); return }
|
|
211
210
|
const signal = AbortSignal.timeout(ADVISORIES_TIMEOUT_MS)
|
|
212
|
-
|
|
213
|
-
const result = await
|
|
214
|
-
debug: deps.config.debug, repoAdvisories, details: url.searchParams.get('details') === 'true',
|
|
215
|
-
|
|
211
|
+
// As a member's (http.ts handleBundleAdvisories), GitHub asked anonymously.
|
|
212
|
+
const result = await fetchKnownBundleAdvisories(inventory.packages, signal, {
|
|
213
|
+
debug: deps.config.debug, recheck: url.searchParams.get('repoAdvisories') === 'true', details: url.searchParams.get('details') === 'true',
|
|
214
|
+
db: deps.db, behind: work => { deps.track(work); deps.waitUntil?.(work) },
|
|
216
215
|
})
|
|
217
216
|
await recheck()
|
|
218
|
-
json(res, result.status, result.status === 200 ? { ...inventory, advisories: result.body } : result.body); return
|
|
217
|
+
json(res, result.status, result.status === 200 ? { ...inventory, advisories: result.body, unchecked: result.unchecked } : result.body); return
|
|
219
218
|
}
|
|
220
219
|
let cached
|
|
221
220
|
try { cached = await deps.bundleCache.open(bundle, part as 'metadata' | 'contents') }
|
|
@@ -35,8 +35,9 @@ import type { LockedPackage } from './locked-packages.ts'
|
|
|
35
35
|
import { EVERY_LOCKFILE, type LockfileScope, heldTo, isEvery, reviewedIn } from './lockfile-scope.ts'
|
|
36
36
|
import { type Lru, lru } from './lru.ts'
|
|
37
37
|
import { type AddedPackage, type DirectoryDependencies, type GithubAsked, type LockfileStore, MAX_ADDED, type PullDependencies, lockedAs, lockedWith } from './pull-dependencies.ts'
|
|
38
|
-
import type { PublishedReview, RepoReviewState } from './repository-dependency-reviews.ts'
|
|
38
|
+
import type { DraftReview, PublishedReview, RepoReviewState, ReviewedVersionKey } from './repository-dependency-reviews.ts'
|
|
39
39
|
import { type ReviewedBase, type ReviewedDependencies, type ReviewedDependency, askBases, askReviewed } from './reviewed-dependencies.ts'
|
|
40
|
+
import { reviewBase } from '../common/managed/npm-packages.js'
|
|
40
41
|
|
|
41
42
|
// The other versions told unreviewed, and those told unsupported, of each
|
|
42
43
|
// directory, those past them counted.
|
|
@@ -191,6 +192,18 @@ function judge(pkg: LockedPackage, bases: string[] | 'any', { state, reviews, ba
|
|
|
191
192
|
return { review: told, wants: passing < state.required }
|
|
192
193
|
}
|
|
193
194
|
|
|
195
|
+
// The versions of a directory's rows that want reviews, each way it is locked.
|
|
196
|
+
const wanted = (rows: { wanting: LockedPackage[] }[]) => rows.flatMap(({ wanting }) => wanting.map(shown))
|
|
197
|
+
// The reader's own draft of a version (`pkg`, as it is locked), against the
|
|
198
|
+
// version its row is reviewed against (`base`, reviewBase, null for its whole
|
|
199
|
+
// package's): how many files it gives a verdict; none where they have none.
|
|
200
|
+
type Drafted = (pkg: LockedPackage, base: { name: string; version: string } | null) => { checked: number } | null
|
|
201
|
+
// How a directory is told (reviewedDirectory): read without its base
|
|
202
|
+
// (`baseless`); those of npm's registry locked with no integrity that
|
|
203
|
+
// `lookup` passed (`vouched`); each version it adds with the reader's draft
|
|
204
|
+
// of it (`drafted`), against its base as the host names it (`namedBases`),
|
|
205
|
+
// else as it was; and only those the reader didn't review (`remaining`).
|
|
206
|
+
interface Telling { baseless?: boolean; vouched?: Set<string>; drafted?: Drafted | null; namedBases?: boolean; remaining?: boolean }
|
|
194
207
|
// A directory as the client is told it: what it adds, as many as MAX_ADDED,
|
|
195
208
|
// each version with its review (`review`, as judged), those past them judged
|
|
196
209
|
// as they are, against the versions they were, as is every one its lockfiles
|
|
@@ -201,7 +214,13 @@ function judge(pkg: LockedPackage, bases: string[] | 'any', { state, reviews, ba
|
|
|
201
214
|
// aren't checked; without `review`, what it adds alone. Read without its
|
|
202
215
|
// base (`baseless`), it tells only those it adds that pass none, or pass by
|
|
203
216
|
// its comments alone, which the host doesn't take in till it is merged.
|
|
204
|
-
|
|
217
|
+
// Each it adds is told the reader's draft of it (`draft`, where `drafted`
|
|
218
|
+
// finds one); where `remaining`, those the reader reviewed (`yours`) are
|
|
219
|
+
// left out of what it adds before they are cut to MAX_ADDED, and counted
|
|
220
|
+
// in `more` no more, nor among those its review wants (`remainingToReview`,
|
|
221
|
+
// told in place of `toReview`, which still holds them all for Stasis).
|
|
222
|
+
function reviewedDirectory(dir: DirectoryDependencies, review: Judge | null,
|
|
223
|
+
{ baseless = false, vouched = new Set(), drafted = null, namedBases = false, remaining = false }: Telling = {}) {
|
|
205
224
|
if ('error' in dir) return dir
|
|
206
225
|
const { locked, moreLocked, added, ...told } = dir
|
|
207
226
|
if (!review) return { ...told, added: baseless ? [] : added.slice(0, MAX_ADDED).map(shown), ...baseless ? { more: 0 } : {} }
|
|
@@ -220,18 +239,25 @@ function reviewedDirectory(dir: DirectoryDependencies, review: Judge | null, bas
|
|
|
220
239
|
const as = reviewedAs(pkg)
|
|
221
240
|
return as === 'version' || as === 'skip' || (as === 'integrity' && vouched.has(askedOf(pkg)[0])) ? [] : [{ ...shown(pkg), unsupported: as }]
|
|
222
241
|
})
|
|
223
|
-
const
|
|
224
|
-
|
|
242
|
+
const kept = baseless ? own.filter(({ judged }) => judged.wants || 'unsupported' in judged.review || 'commented' in judged.review) : own
|
|
243
|
+
const listed = remaining ? kept.filter(({ judged }) => !judged.yours) : kept
|
|
244
|
+
// Those it adds past those it holds (as many as MAX_LOCKED), never judged here.
|
|
245
|
+
const past = baseless || told.more === 0 ? 0 : Math.max(0, told.more + MAX_ADDED - added.length)
|
|
246
|
+
// Each row against the base of the way it is locked that it is told by,
|
|
247
|
+
// with the reader's draft of it against that base.
|
|
225
248
|
const row = ({ pkg, judged }: (typeof own)[number]) => {
|
|
226
249
|
const { base: _base, ...rest } = shown(pkg as AddedPackage), { base } = judged.variant as AddedPackage
|
|
227
|
-
|
|
250
|
+
const version = { ...rest, ...base ? { base } : {} }
|
|
251
|
+
const draft = drafted?.(judged.variant, reviewBase(version, { reviewedBases: namedBases }))
|
|
252
|
+
return { ...version, ...judged.review, ...judged.yours ? { yours: judged.yours } : {}, ...draft ? { draft } : {} }
|
|
228
253
|
}
|
|
229
|
-
return { ...told, ...baseless ? { more: Math.max(0, listed.length - MAX_ADDED) } : {}, added: listed.slice(0, MAX_ADDED).map(row),
|
|
230
|
-
toReview: own
|
|
254
|
+
return { ...told, ...baseless || remaining ? { more: Math.max(0, listed.length - MAX_ADDED) + past } : {}, added: listed.slice(0, MAX_ADDED).map(row),
|
|
255
|
+
toReview: wanted(own), ...remaining ? { remainingToReview: wanted(listed) } : {},
|
|
231
256
|
unreviewed: others.filter(({ judged }) => judged.wants).map(({ pkg, judged }) => ({ ...shown(pkg), ...judged.review, ...judged.yours ? { yours: judged.yours } : {} })),
|
|
232
257
|
unsupported, moreLocked }
|
|
233
258
|
}
|
|
234
|
-
function capped<T extends { toReview: unknown[]; unreviewed: unknown[]; unsupported: unknown[] }>({ toReview: _toReview,
|
|
259
|
+
function capped<T extends { toReview: unknown[]; remainingToReview?: unknown[]; unreviewed: unknown[]; unsupported: unknown[] }>({ toReview: _toReview,
|
|
260
|
+
remainingToReview: _remaining, ...dir }: T) {
|
|
235
261
|
return { ...dir, unreviewed: dir.unreviewed.slice(0, MAX_UNREVIEWED), moreUnreviewed: Math.max(0, dir.unreviewed.length - MAX_UNREVIEWED),
|
|
236
262
|
unsupported: dir.unsupported.slice(0, MAX_UNREVIEWED), moreUnsupported: Math.max(0, dir.unsupported.length - MAX_UNREVIEWED) }
|
|
237
263
|
}
|
|
@@ -296,14 +322,23 @@ export function heldDependencies<T extends PullDependencies>(told: T, scope: Loc
|
|
|
296
322
|
// lockfiles than are read (`cut`). Those of directories none of whose
|
|
297
323
|
// lockfiles the review holds to (`lockfiles`, lockfile-scope.ts, told in its
|
|
298
324
|
// terms where not every one) are left out (heldDependencies).
|
|
325
|
+
// Where `drafts` reads `user`'s own drafts (listOwnDraftReviews), and they
|
|
326
|
+
// publish to a team counting for the repository, each version it adds is
|
|
327
|
+
// told theirs against the version its row reviews it against (`draft`,
|
|
328
|
+
// reviewBase), as a page reviewing them together continues it, all read
|
|
329
|
+
// at once rather than as each version opens. Where `remaining`, those it
|
|
330
|
+
// adds that `user` reviewed (`yours`) are left out (reviewedDirectory), and
|
|
331
|
+
// of how many want reviews (`toReview`), as that page tells what is left.
|
|
299
332
|
export async function reviewedDependencies(told: PullDependencies, state: RepoReviewState | null,
|
|
300
|
-
{ baseline = null, baselineUnread = [], baselineError = null, reviewed = null, commentReviews = null, namedBases = new Map(), wantedIn = new Map(), user = null
|
|
333
|
+
{ baseline = null, baselineUnread = [], baselineError = null, reviewed = null, commentReviews = null, namedBases = new Map(), wantedIn = new Map(), user = null,
|
|
334
|
+
drafts = null, remaining = false }: {
|
|
301
335
|
baseline?: Set<string> | null; baselineUnread?: string[]; baselineError?: string | null; reviewed?: ReviewedDependencies | null; commentReviews?: CommentReviews | null
|
|
302
|
-
namedBases?: Map<string, ReviewedBase>; wantedIn?: Map<string[], number>; user?: string | null
|
|
336
|
+
namedBases?: Map<string, ReviewedBase>; wantedIn?: Map<string[], number>; user?: string | null
|
|
337
|
+
drafts?: ((versions: ReviewedVersionKey[]) => Promise<DraftReview[]>) | null; remaining?: boolean } = {}) {
|
|
303
338
|
const scope = state?.lockfiles ?? EVERY_LOCKFILE
|
|
304
339
|
const answered = heldDependencies(told, scope)
|
|
305
340
|
const baseless = told.baseless === true
|
|
306
|
-
if (!state) return { ...answered, lockfiles: answered.lockfiles.map(dir => reviewedDirectory(dir, null, baseless)) }
|
|
341
|
+
if (!state) return { ...answered, lockfiles: answered.lockfiles.map(dir => reviewedDirectory(dir, null, { baseless })) }
|
|
307
342
|
const { cut } = answered
|
|
308
343
|
let held = answered.lockfiles
|
|
309
344
|
// Reviews published here count but where the host reads those pull
|
|
@@ -369,23 +404,39 @@ export async function reviewedDependencies(told: PullDependencies, state: RepoRe
|
|
|
369
404
|
const latest = reviewsOf(pkg, mine).reduce<PublishedReview | null>((one, other) => one && one.time >= other.time ? one : other, null)
|
|
370
405
|
return latest ? { yours: { status: latest.status, ...latest.full ? {} : { partial: true as const } } } : {}
|
|
371
406
|
}
|
|
407
|
+
const drafted = await draftedIn(held, user && state.canReview ? drafts : null)
|
|
372
408
|
const dirs = held.map(dir => reviewedDirectory(dir, (pkg, bases) => {
|
|
373
409
|
const judged = judge(pkg, bases, context)
|
|
374
410
|
return { ...judged.wants && passed.has(askedOf(pkg)[0]) ? { review: { reviewed: true as const }, wants: false } : judged, ...yours(pkg) }
|
|
375
|
-
}, baseless, vouching.passed))
|
|
411
|
+
}, { baseless, vouched: vouching.passed, drafted, namedBases: Boolean(reviewed?.base), remaining }))
|
|
376
412
|
const unread = baselineUnread.filter(path => heldTo(scope, path))
|
|
377
413
|
const listed = dirs.filter(dir => 'unreviewed' in dir)
|
|
378
414
|
for (const dir of listed) wantedIn.set(dir.paths, distinct([dir.toReview], versionKey))
|
|
379
415
|
return { ...answered, cut, lockfiles: dirs.map(dir => 'unreviewed' in dir ? capped(dir) : dir), review: { required: state.required,
|
|
380
416
|
since: reviewed ? null : state.since, canReview: state.canReview, ...reviewed ? { reviewedDependencies: true } : {}, ...reviewed?.base ? { reviewedBases: true } : {},
|
|
381
417
|
...reviewed?.parseComments ? { byComments: true } : {},
|
|
382
|
-
toReview: distinct(listed.map(dir => dir.toReview), versionKey), unreviewed: distinct(listed.map(dir => dir.unreviewed), versionKey),
|
|
418
|
+
toReview: distinct(listed.map(dir => dir.remainingToReview ?? dir.toReview), versionKey), unreviewed: distinct(listed.map(dir => dir.unreviewed), versionKey),
|
|
383
419
|
unsupported: distinct(listed.map(dir => dir.unsupported), sourceKey),
|
|
384
420
|
...unasked > 0 ? { unasked } : {}, ...baselineError && !reviewed ? { baselineError } : {},
|
|
385
421
|
...comments.reviews.length > 0 ? { commentReviews: new Set(comments.reviews.map(review => review.reviewer)).size } : {}, ...comments.failed ? { commentsFailed: true } : {},
|
|
386
422
|
...unread.length > 0 && !reviewed ? { baselineUnread: unread.slice(0, MAX_UNREVIEWED) } : {}, ...isEvery(scope) ? {} : { lockfiles: scope } } }
|
|
387
423
|
}
|
|
388
424
|
|
|
425
|
+
// The reader's own drafts of the versions `dirs` add, as `drafts` reads them
|
|
426
|
+
// (none where it is none), all at once: each version's of its integrity and
|
|
427
|
+
// patch, against the base its row reviews it against (Drafted).
|
|
428
|
+
async function draftedIn(dirs: DirectoryDependencies[], drafts: ((versions: ReviewedVersionKey[]) => Promise<DraftReview[]>) | null): Promise<Drafted> {
|
|
429
|
+
const adding = dirs.flatMap(dir => 'error' in dir ? [] : dir.added.filter(pkg => reviewedAs(pkg) === 'version'))
|
|
430
|
+
const asked = [...new Map(adding.map(pkg => [`${pkg.name}@${pkg.version}`, { name: pkg.name, version: pkg.version! }])).values()]
|
|
431
|
+
const own = Map.groupBy(drafts && asked.length > 0 ? await drafts(asked) : [], draft => `${draft.package}@${draft.version}`)
|
|
432
|
+
return (pkg, base) => {
|
|
433
|
+
const hashes = hashesOf(pkg)
|
|
434
|
+
const draft = own.get(`${pkg.name}@${pkg.version}`)?.find(one => hashes.includes(one.integrity) && (one.patchHash ?? '') === (pkg.patchHash ?? '')
|
|
435
|
+
&& one.basePackage === (base?.name ?? null) && one.baseVersion === (base?.version ?? null))
|
|
436
|
+
return draft ? { checked: draft.checked } : null
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
389
440
|
// The package versions a pull request's lockfiles lock that its reviews here
|
|
390
441
|
// may pass, whose reviews are asked: those that can be reviewed.
|
|
391
442
|
export const reviewedPackages = (told: PullDependencies) => told.lockfiles
|
package/server-managed/queue.ts
CHANGED
|
@@ -41,7 +41,7 @@ export function inTurns(count: number): <T>(work: () => Promise<T>) => Promise<T
|
|
|
41
41
|
|
|
42
42
|
// Runs `run` for each of `items`, as many at once as `parallel`, each's
|
|
43
43
|
// result in its place.
|
|
44
|
-
export async function eachOf<T, R>(items: T[], parallel: number, run: (item: T) => Promise<R>): Promise<R[]> {
|
|
44
|
+
export async function eachOf<T, R>(items: readonly T[], parallel: number, run: (item: T) => Promise<R>): Promise<R[]> {
|
|
45
45
|
const results: R[] = []
|
|
46
46
|
let next = 0
|
|
47
47
|
await Promise.all(Array.from({ length: Math.min(parallel, items.length) }, async () => {
|
|
@@ -43,6 +43,15 @@ export interface RepoReviewState extends Omit<RepoDependencyReview, 'enabled'> {
|
|
|
43
43
|
// A package version whose published reviews are asked.
|
|
44
44
|
export interface ReviewedVersionKey { name: string; version: string }
|
|
45
45
|
|
|
46
|
+
// A reader's own unpublished review of a version (their draft, one a
|
|
47
|
+
// comparison): its package, version, npm's integrity of it and its patch's
|
|
48
|
+
// hash, the version it is compared with (none for a whole package's), and
|
|
49
|
+
// how many files it gives a verdict (`checked`). One compared with a
|
|
50
|
+
// version as a patch changes it is none a pull request's row reviews.
|
|
51
|
+
export interface DraftReview {
|
|
52
|
+
package: string; version: string; integrity: string; patchHash?: string; basePackage: string | null; baseVersion: string | null; checked: number
|
|
53
|
+
}
|
|
54
|
+
|
|
46
55
|
export interface RepositoryDependencyReviewStore {
|
|
47
56
|
listRepoDependencyReviews(): Promise<Map<number, RepoDependencyReview>>
|
|
48
57
|
// One repository's, none where it isn't connected.
|
|
@@ -66,6 +75,9 @@ export interface RepositoryDependencyReviewStore {
|
|
|
66
75
|
// `repoIds` were published, to it or to one more team, or revoked, at
|
|
67
76
|
// `since` or after, each once.
|
|
68
77
|
changedReviewVersions(repoIds: number[], since: number, versions: ReviewedVersionKey[]): Promise<ReviewedVersionKey[]>
|
|
78
|
+
// `user`'s own drafts of `versions` (DraftReview), as a pull request's
|
|
79
|
+
// versions are told the reader's own reviews of them.
|
|
80
|
+
listOwnDraftReviews(user: string, versions: ReviewedVersionKey[]): Promise<DraftReview[]>
|
|
69
81
|
}
|
|
70
82
|
|
|
71
83
|
type SettingRow = { repoId: number; enabled: number; required: number; since: string | null; lockfiles: string | null }
|
|
@@ -112,6 +124,31 @@ async function publishedReviews(db: ManagedSql, repoId: number, versions: Review
|
|
|
112
124
|
return found
|
|
113
125
|
}
|
|
114
126
|
|
|
127
|
+
// `user`'s own drafts of `versions`, a couple of hundred versions a query,
|
|
128
|
+
// as publishedReviews reads published ones, each with how many files it
|
|
129
|
+
// gives a verdict: those against a version as a patch changes it left out.
|
|
130
|
+
async function draftReviews(db: ManagedSql, user: string, versions: ReviewedVersionKey[]): Promise<DraftReview[]> {
|
|
131
|
+
const found: DraftReview[] = []
|
|
132
|
+
for (let at = 0; at < versions.length; at += VERSIONS_AT_ONCE) {
|
|
133
|
+
const asked = versions.slice(at, at + VERSIONS_AT_ONCE)
|
|
134
|
+
const keys = new Set(asked.map(({ name, version }) => `${name}@${version}`))
|
|
135
|
+
const [names, numbers] = [[...new Set(asked.map(({ name }) => name))], [...new Set(asked.map(({ version }) => version))]]
|
|
136
|
+
const rows = await db.prepare(`SELECT r.package, r.version, r.integrity, r.patch_hash AS patchHash, NULLIF(r.base_package, '') AS basePackage,
|
|
137
|
+
NULLIF(r.base_version, '') AS baseVersion,
|
|
138
|
+
(SELECT COUNT(DISTINCT e.file) FROM managed_dependency_file_review e WHERE e.review_id = r.id AND e.status IS NOT NULL) AS checked
|
|
139
|
+
FROM managed_dependency_review r
|
|
140
|
+
WHERE r.user_id = ? AND r.ecosystem = 'npm' AND r.published_at IS NULL AND r.base_patch_hash = ''
|
|
141
|
+
AND r.package IN (${names.map(() => '?').join(',')}) AND r.version IN (${numbers.map(() => '?').join(',')})`).all(user, ...names, ...numbers) as
|
|
142
|
+
{ package: string; version: string; integrity: string; patchHash: string; basePackage: string | null; baseVersion: string | null; checked: number | string }[]
|
|
143
|
+
for (const row of rows) {
|
|
144
|
+
if (!keys.has(`${row.package}@${row.version}`)) continue
|
|
145
|
+
found.push({ package: row.package, version: row.version, integrity: row.integrity, ...row.patchHash ? { patchHash: row.patchHash } : {},
|
|
146
|
+
basePackage: row.basePackage, baseVersion: row.baseVersion, checked: Number(row.checked) })
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return found
|
|
150
|
+
}
|
|
151
|
+
|
|
115
152
|
export function repositoryDependencyReviewMethods(db: ManagedSql): RepositoryDependencyReviewStore {
|
|
116
153
|
const columns = `repo_id AS repoId, dependency_review AS enabled, dependency_reviews_required AS required, dependency_review_since AS since,
|
|
117
154
|
dependency_review_lockfiles AS lockfiles`
|
|
@@ -169,6 +206,7 @@ export function repositoryDependencyReviewMethods(db: ManagedSql): RepositoryDep
|
|
|
169
206
|
}
|
|
170
207
|
return [...found.values()]
|
|
171
208
|
},
|
|
209
|
+
listOwnDraftReviews: (user, versions) => draftReviews(db, user, versions),
|
|
172
210
|
async repoDependencyReviewState(repoId, user, versions, read) {
|
|
173
211
|
const now = read === undefined ? await readSetting(repoId) : read
|
|
174
212
|
if (!now?.enabled) return null
|
|
@@ -4,6 +4,12 @@
|
|
|
4
4
|
// of malware, as upstream tells (`malware`); kept by the lockfile's blob, in
|
|
5
5
|
// the instance's memory and the source's `audits`, for RISK_KEPT_MS, as npm
|
|
6
6
|
// publishes advisories, or why they couldn't be had for AUDIT_FAILED_KEPT_MS.
|
|
7
|
+
// Told with those its packages' repositories publish (the source's
|
|
8
|
+
// `repositories`) as known then, never waited on; where those weren't all
|
|
9
|
+
// known fresh, again with their listings waited on, and where packages'
|
|
10
|
+
// repositories still weren't known, once more (ToldAudit `again`, auditAgain),
|
|
11
|
+
// those still to be had as a scan's part ends had by its next (PendingAudit).
|
|
12
|
+
import { createHash } from 'node:crypto'
|
|
7
13
|
import type { Advisory } from '@preventive/upstream/advisories.js'
|
|
8
14
|
import { isExactVersion } from '@preventive/upstream/semver.js'
|
|
9
15
|
import { isNpmPackageName } from '../common/managed/npm-packages.js'
|
|
@@ -15,10 +21,20 @@ import { RISK_KEPT_MS, type RiskFailure, failureOf } from './repository-risk-ass
|
|
|
15
21
|
export type AdvisoryRow = Omit<Advisory, 'malware'> & { malware: boolean }
|
|
16
22
|
// A lockfile's advisories, or why they couldn't be had.
|
|
17
23
|
export type Audit = AdvisoryRow[] | RiskFailure
|
|
24
|
+
// A lockfile's audit as told, and whether its repositories' advisories were
|
|
25
|
+
// had (`had`: without them where they couldn't be), and where they weren't
|
|
26
|
+
// all known fresh, how to have it with them as they are then.
|
|
27
|
+
export type ToldAudit = { audit: Audit; had: boolean; again: ((signal: AbortSignal) => Promise<ToldAudit | null>) | null }
|
|
28
|
+
type AskedVersions = { name: string; versions: string[] }[]
|
|
18
29
|
|
|
19
30
|
export interface AuditSource {
|
|
20
31
|
// npm's registry's advisories of these packages' versions, asked at once.
|
|
21
|
-
advisories(packages:
|
|
32
|
+
advisories(packages: AskedVersions, signal: AbortSignal): Promise<Advisory[]>
|
|
33
|
+
// Those their repositories publish of them, as known: none waited on, but
|
|
34
|
+
// with `wait`, those not known fresh, until `signal` aborts. `again` where
|
|
35
|
+
// some weren't known fresh (a package's repository or its listing, asked
|
|
36
|
+
// behind meanwhile).
|
|
37
|
+
repositories?(packages: AskedVersions, signal: AbortSignal, wait: boolean): Promise<{ advisories: Advisory[]; again: boolean }>
|
|
22
38
|
// Where audits are kept beyond this instance, by the lockfile's blob.
|
|
23
39
|
audits?: KeptStore<Audit>
|
|
24
40
|
}
|
|
@@ -36,7 +52,7 @@ const isFresh = ({ at, audit }: { at: number; audit: Audit }) => Date.now() - at
|
|
|
36
52
|
// `inTurn` with others, asked at once: each null where it has none to ask
|
|
37
53
|
// of, or once `signal` aborts. Each is the caller's to tell once it may.
|
|
38
54
|
export function auditLockfiles(source: AuditSource, memory: Lru<{ at: number; audit: Audit }>, signal: AbortSignal,
|
|
39
|
-
lockfiles: { key: string; packages: readonly LockedPackage[] | null }[], inTurn: <T>(work: () => Promise<T>) => Promise<T>): Promise<
|
|
55
|
+
lockfiles: { key: string; packages: readonly LockedPackage[] | null }[], inTurn: <T>(work: () => Promise<T>) => Promise<T>): Promise<ToldAudit | null>[] {
|
|
40
56
|
return lockfiles.map(({ key, packages }) => {
|
|
41
57
|
const audit = packages ? inTurn(() => (signal.aborted ? Promise.resolve(null) : auditLockfile(source, memory, signal, key, packages))) : Promise.resolve(null)
|
|
42
58
|
// One no longer waited on, as the scan stopped, fails alone.
|
|
@@ -46,27 +62,27 @@ export function auditLockfiles(source: AuditSource, memory: Lru<{ at: number; au
|
|
|
46
62
|
}
|
|
47
63
|
|
|
48
64
|
// The audit of a lockfile's `packages`, by its `key` as kept (`memory`, then
|
|
49
|
-
// the source's), else asked and kept
|
|
50
|
-
// once `signal` aborts.
|
|
65
|
+
// the source's), else asked and kept, told with its repositories'; null
|
|
66
|
+
// where it locks none to ask of, or once `signal` aborts.
|
|
51
67
|
async function auditLockfile(source: AuditSource, memory: Lru<{ at: number; audit: Audit }>, signal: AbortSignal, key: string,
|
|
52
|
-
packages: readonly LockedPackage[]): Promise<
|
|
68
|
+
packages: readonly LockedPackage[]): Promise<ToldAudit | null> {
|
|
69
|
+
const versions = new Map<string, Set<string>>()
|
|
70
|
+
for (const { name, version, source: from } of packages) {
|
|
71
|
+
if ((from !== 'registry' && from !== 'mirror') || !isNpmPackageName(name) || !isExactVersion(version)) continue
|
|
72
|
+
if (!versions.has(name)) versions.set(name, new Set())
|
|
73
|
+
versions.get(name)!.add(version)
|
|
74
|
+
}
|
|
75
|
+
if (versions.size === 0) return null
|
|
76
|
+
const asked = [...versions].map(([name, each]) => ({ name, versions: [...each] }))
|
|
53
77
|
let kept = memory.get(key)
|
|
54
78
|
if (!kept || !isFresh(kept)) {
|
|
55
79
|
const stored = await source.audits?.read(key)
|
|
56
80
|
kept = stored ? { at: stored.at, audit: stored.value } : undefined
|
|
57
81
|
}
|
|
58
|
-
if (kept && isFresh(kept)) { memory.set(key, kept); return kept.audit }
|
|
59
|
-
const asked = new Map<string, Set<string>>()
|
|
60
|
-
for (const { name, version, source: from } of packages) {
|
|
61
|
-
if ((from !== 'registry' && from !== 'mirror') || !isNpmPackageName(name) || !isExactVersion(version)) continue
|
|
62
|
-
if (!asked.has(name)) asked.set(name, new Set())
|
|
63
|
-
asked.get(name)!.add(version)
|
|
64
|
-
}
|
|
65
|
-
if (asked.size === 0) return null
|
|
82
|
+
if (kept && isFresh(kept)) { memory.set(key, kept); return await withRepositories(source, kept.audit, asked, signal) }
|
|
66
83
|
let audit: Audit
|
|
67
84
|
try {
|
|
68
|
-
audit = (await source.advisories(
|
|
69
|
-
.map(advisory => ({ ...advisory, malware: advisory.malware === true }))
|
|
85
|
+
audit = (await source.advisories(asked, signal)).map(advisory => ({ ...advisory, malware: advisory.malware === true }))
|
|
70
86
|
} catch (error) {
|
|
71
87
|
if (signal.aborted) return null
|
|
72
88
|
audit = failureOf(error)
|
|
@@ -74,5 +90,56 @@ async function auditLockfile(source: AuditSource, memory: Lru<{ at: number; audi
|
|
|
74
90
|
const now = Date.now()
|
|
75
91
|
memory.set(key, { at: now, audit })
|
|
76
92
|
await source.audits?.write(key, audit, now)
|
|
77
|
-
return audit
|
|
93
|
+
return await withRepositories(source, audit, asked, signal)
|
|
78
94
|
}
|
|
95
|
+
|
|
96
|
+
const byName = (a: AdvisoryRow, b: AdvisoryRow) => Number(a.name > b.name) - Number(a.name < b.name)
|
|
97
|
+
|
|
98
|
+
// `audit`, where it has advisories, with those its packages' repositories
|
|
99
|
+
// publish, as known (or `waits` times on, as had by the time `signal`
|
|
100
|
+
// aborts): without them where they can't be had, as no audit fails for
|
|
101
|
+
// them. Asked again twice at most.
|
|
102
|
+
async function withRepositories(source: AuditSource, audit: Audit, asked: AskedVersions, signal: AbortSignal, waits = 0): Promise<ToldAudit> {
|
|
103
|
+
if (!source.repositories || !Array.isArray(audit)) return { audit, had: true, again: null }
|
|
104
|
+
const found = await source.repositories(asked, signal, waits > 0).catch(() => null)
|
|
105
|
+
const told = found && found.advisories.length > 0 ? [...audit, ...found.advisories.map(advisory => ({ ...advisory, malware: advisory.malware === true }))].toSorted(byName) : audit
|
|
106
|
+
return { audit: told, had: found !== null, again: waits >= 2 || (found && !found.again) ? null : next => withRepositories(source, audit, asked, next, waits + 1) }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// A lockfile's advisories still to be had again, of a repository a scan told
|
|
110
|
+
// whole, as its progress keeps them for its next part (repository-risk.ts
|
|
111
|
+
// ScanProgress): the lockfile's path and key, and a digest of the audit last
|
|
112
|
+
// told of it.
|
|
113
|
+
export type PendingAudit = { path: string; key: string; told: string }
|
|
114
|
+
const digestOf = (audit: Audit) => createHash('sha256').update(JSON.stringify(audit)).digest('base64url')
|
|
115
|
+
// `audit`, told of the lockfile at `path` by its `key`, noted among `pending`.
|
|
116
|
+
export function pend(pending: PendingAudit[], path: string, key: string, audit: Audit): PendingAudit {
|
|
117
|
+
const entry = { path, key, told: digestOf(audit) }
|
|
118
|
+
pending.push(entry)
|
|
119
|
+
return entry
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// A lockfile's audit `told` had again (its `again`), as `entry` of `pending`
|
|
123
|
+
// notes it was last told: told by `tell` where it changed, with its
|
|
124
|
+
// repositories' had, and so noted; that one where it may change once more,
|
|
125
|
+
// else null, `entry` let go of: but not once `signal` aborts, for a next
|
|
126
|
+
// part to have it.
|
|
127
|
+
export async function auditAgain(told: ToldAudit, pending: PendingAudit[], entry: PendingAudit, signal: AbortSignal, tell: (audit: Audit) => void): Promise<ToldAudit | null> {
|
|
128
|
+
const now = signal.aborted || !told.again ? null : await told.again(signal).catch(() => null)
|
|
129
|
+
if (signal.aborted) return null
|
|
130
|
+
if (now?.had && digestOf(now.audit) !== entry.told) {
|
|
131
|
+
entry.told = digestOf(now.audit)
|
|
132
|
+
tell(now.audit)
|
|
133
|
+
}
|
|
134
|
+
if (now?.again) return now
|
|
135
|
+
const at = pending.indexOf(entry)
|
|
136
|
+
if (at !== -1) pending.splice(at, 1)
|
|
137
|
+
return null
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// A lockfile's audit an earlier part of the scan was still to have again
|
|
141
|
+
// (`entry`), its `packages` as kept, to have as auditAgain has it: audited
|
|
142
|
+
// as at first (auditLockfile), its npm advisories as kept, its repositories'
|
|
143
|
+
// as known now.
|
|
144
|
+
export const resumedAudit = (source: AuditSource, memory: Lru<{ at: number; audit: Audit }>, entry: PendingAudit, packages: readonly LockedPackage[]): ToldAudit =>
|
|
145
|
+
({ audit: [], had: false, again: signal => auditLockfile(source, memory, signal, entry.key, packages) })
|