@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.
Files changed (42) hide show
  1. package/out/activity.js +2 -2
  2. package/out/{chunk-U6JONPTN.js → chunk-3DOSBILK.js} +1 -1
  3. package/out/{chunk-A4HSJCXG.js → chunk-CJVMNJDZ.js} +2 -2
  4. package/out/chunk-HGWFRZNC.js +267 -0
  5. package/out/{chunk-3TJCEPHF.js → chunk-JZAROLQT.js} +1 -1
  6. package/out/{chunk-4GHLPL2P.js → chunk-LRWB6QVO.js} +1 -1
  7. package/out/{chunk-G5JKKNZF.js → chunk-SMNFBOLO.js} +1 -1
  8. package/out/{chunk-ZPIUN4FW.js → chunk-SZTCJVZJ.js} +1 -1
  9. package/out/{chunk-VRFGZ6MV.js → chunk-UTYWTUTC.js} +1 -1
  10. package/out/client-managed.js +28 -28
  11. package/out/compare.js +13 -13
  12. package/out/dialogs.js +15 -15
  13. package/out/graph.js +1 -1
  14. package/out/index.html +5 -5
  15. package/out/prism.js +1 -1
  16. package/out/scan.js +2 -2
  17. package/out/view.css +1 -1
  18. package/out/view.js +7 -7
  19. package/package.json +3 -1
  20. package/risk/index.d.ts +15 -0
  21. package/risk/index.js +1 -1
  22. package/risk/npm/assess.js +21 -3
  23. package/risk/npm/registry.js +16 -7
  24. package/server-managed/bundle-advisories.ts +97 -0
  25. package/server-managed/config.ts +1 -1
  26. package/server-managed/github-issue-links.ts +1 -1
  27. package/server-managed/github-metadata.ts +6 -1
  28. package/server-managed/github-pulls.ts +43 -10
  29. package/server-managed/http.ts +170 -52
  30. package/server-managed/known-listings.ts +112 -0
  31. package/server-managed/npm-packages.ts +10 -2
  32. package/server-managed/npm-risk.ts +31 -8
  33. package/server-managed/public-workspace.ts +6 -7
  34. package/server-managed/pull-dependency-reviews.ts +64 -13
  35. package/server-managed/queue.ts +1 -1
  36. package/server-managed/repository-dependency-reviews.ts +38 -0
  37. package/server-managed/repository-risk-audit.ts +83 -16
  38. package/server-managed/repository-risk.ts +33 -12
  39. package/server-managed/team-app.ts +1 -1
  40. package/server-managed/team-progress.ts +77 -0
  41. package/server-managed/upstream-cache.ts +42 -23
  42. package/out/chunk-7KUZQB6S.js +0 -267
@@ -14,6 +14,9 @@
14
14
  // DELETE /api/auth/profile/accounts/<id> → CSRF, unlinks a linked GitHub account | 401/403/404
15
15
  // GET /api/oauth/github/link → 302 to GitHub to link another account (+ state cookie); the callback lands on /my/profile
16
16
  // GET /api/teams → the current user's teams + their reports and bundles | 401
17
+ // GET /api/teams/progress → each of the user's teams' findings In progress and Fixed and the GitHub issues (open,
18
+ // closed) and pull requests (open, merged) linked to them, by their cached status, GitHub not asked; and all of them
19
+ // together, each counted once (team-progress.ts) | 401
17
20
  // GET /api/teams/<id>/fixes → PR/issue metadata from visible findings' stored Fix links
18
21
  // GET /api/teams/<id>/reports → all reports and links filtered through this team | 401/404
19
22
  // GET /api/teams/<id>/feed → SSE notifications for visible triage and comments | 401/404
@@ -52,8 +55,9 @@
52
55
  // description's Markdown | 400/401/403/404/409/429/502
53
56
  // GET /api/admin/repositories/pull-dependencies?repoId=&number= → the package versions a pull request's npm, pnpm and
54
57
  // Yarn 1 lockfiles lock that they didn't at its merge base, an update's with those it was, by directory; with review=1, each's
55
- // review, where its repository reviews dependencies; with numbers=1,2,3 (twenty at most) in place of number, those of each,
56
- // { pulls }, one GitHub fails told { number, error } | 400/401/403/404/409/429/502
58
+ // review, where its repository reviews dependencies, with the reader's own draft of it; with review=1&remaining=1, those the
59
+ // reader reviewed left out, of what each adds and of how many want reviews; with numbers=1,2,3 (twenty at most) in place
60
+ // of number, those of each, { pulls }, one GitHub fails told { number, error } | 400/401/403/404/409/429/502
57
61
  // GET /api/admin/repositories/branch-dependencies?repoId= → the versions the default branch's lockfiles lock that want review, where
58
62
  // its review is in effect for the reader, GitHub not asked where it reviews none | 400/401/403/404/409/429/502
59
63
  // GET /api/admin/repositories/lockfiles?repoId= → the lockfiles of the default branch its dependency review reads, and its stasis.config.json files, by their
@@ -124,7 +128,9 @@
124
128
  // GET/POST /api/npm/reviews → read private/team reviews; save, publish, revoke or continue a set; a patched version's
125
129
  // (patchHash) changed with where its patch is (patchRepoId, patchCommit, patchPath) | 400/401/403/404/409/422
126
130
  // POST /api/npm/reviews/publish → publish several drafts at once, `{ reviews: [{ …context, reviewId, revision, teamIds,
127
- // finalStatus, finalComment }] }`, each answered in `results` as POST /api/npm/reviews would | 200/400/401/403
131
+ // finalStatus, finalComment }], pullRequest?: { repoId, number, remaining? } }`, each answered in `results` as POST
132
+ // /api/npm/reviews would, and, once one is published, the pull request's dependencies read again (`pull`), as GET
133
+ // pull-dependencies with review=1 (and remaining=1, where `remaining`) tells them, its copy button's reviews with them | 200/400/401/403
128
134
  // POST /api/npm/reviews/discard → author discards an unpublished review and its file rows | 400/401/403/409
129
135
  // GET /api/npm/reviews/latest → latest own review for exact target bytes, across all bases | 400/401/403
130
136
  // GET /api/npm/reviews/team?teamId=&beforeTime=&beforeId= → the reviews published to a team, the latest first, for one who
@@ -169,7 +175,8 @@ import { type KeptStore, REPOSITORY_READ_KEPT_MS, authoredCommitStore, branchTip
169
175
  scanReadStore, stasisDependencyStore, teamDependencyStore } from './npm-kept.ts'
170
176
  import { plainObject } from './npm-manifest.ts'
171
177
  import { type NpmDelta, countedDeltas, npmDelta, versionDeltaKey } from './npm-delta.ts'
172
- import { ADVISORIES_TIMEOUT_MS, fetchBundleAdvisories } from './bundle-advisories.ts'
178
+ import { ADVISORIES_TIMEOUT_MS, fetchBundleAdvisories, fetchKnownBundleAdvisories, fetchKnownRepositoryAdvisories, lazyGithubClient, versionsRepositories } from './bundle-advisories.ts'
179
+ import { knownListings } from './known-listings.ts'
173
180
  import { auditCache, auditedKeys, lastListing } from './upstream-cache.ts'
174
181
  import type { BundleAdvisoryInventory } from './bundle-advisory-inventory.ts'
175
182
  import { UPLOAD_CHUNK_BYTES, type UploadKind, deleteUpload, newUploadKey, openSessionUpload, putUploadPart, readUpload, uploadPublicKey, validUpload, validUploadPart } from './uploads.ts'
@@ -231,7 +238,8 @@ import type { ActivityContext, ActivityInput } from './activity.ts'
231
238
  import { acceptsReportMetadata } from './report-response.ts'
232
239
  import { TeamReportsError, type TeamResponsePart, loadTeamAnnotations, loadTeamReportsResponse, recheckTeam, teamFindingIds, teamResponsePart, teamSnapshot, teamSourcePaths, teamWorkspaceFindingIds } from './team-reports.ts'
233
240
  import { FINDING_CATALOG_PAGE_BYTES, FINDING_CATALOG_PAGE_COUNT, MAX_REPORT_QUERY_BYTES, MAX_REPORT_QUERY_COUNT } from './report-query.ts'
234
- import { lookupFixes, storedFixUrls } from './github-pulls.ts'
241
+ import { lookupFixes, storedFixUrls, workspaceFixUrls } from './github-pulls.ts'
242
+ import { teamProgress } from './team-progress.ts'
235
243
  import { lookupIssueLinks } from './github-issue-links.ts'
236
244
  import { visibleManagedIssues } from './managed-issues.ts'
237
245
  import { IssueError, MAX_ISSUE_BODY_BYTES, createGithubIssue, parseIssueContext, prepareGithubIssue } from './github-issues.ts'
@@ -250,7 +258,7 @@ import { canDeleteComment, parseCommentBody } from '../common/managed/comments.t
250
258
  import { ManagedMutationError, reportReferenceSnapshot } from './management.ts'
251
259
  import { confirmedDefaultOffered, readConfirmedOffered, withConfirmedOffered } from './report-opening.ts'
252
260
  import { BundleBuildError, buildRepositoryBundle, buildRepositoryLockfile, parseBundleBuild, withBundleBuildLease } from './bundle-build.ts'
253
- import { NpmPackageError, type NpmReader, type NpmVersionDocument, type NpmVersionStore, canReadPrivateNpm, npmExecutablePaths, npmFileRows, npmPublishTime, npmScopesCount, npmTarballFilename, readNpmVersion, readNpmVersions, readTogether } from './npm-packages.ts'
261
+ import { NpmPackageError, type NpmReader, type NpmVersionDocument, type NpmVersionStore, canReadPrivateNpm, npmExecutablePaths, npmFileRows, npmListedVersions, npmPublishTime, npmScopesCount, npmTarballFilename, readNpmPackument, readNpmVersion, readNpmVersions, readTogether } from './npm-packages.ts'
254
262
  import { loadNpmFiles, loadNpmPackageBody, loadNpmTarball } from './npm-loads.ts'
255
263
  import { type ReadPatch, type RequestedPatch, foundPatch, keptPatch, patchedFiles, readPatch, requestedPatch, withPatchFiles } from './npm-patch.ts'
256
264
  import { type RepositoryCodeKept, loadRepositoryCodeBody, repositoryCodeFits, repositoryCodeKept } from './repository-code.ts'
@@ -289,7 +297,7 @@ import type { DependencyReview, ReviewChange, ReviewContext, ReviewInput, Review
289
297
  import { MAX_PUBLISHED_REVIEWS, allowedReviewVerdicts, isReviewableFile, npmReviewVerdictLimit, npmTakenDown } from '../common/dependency-reviews.js'
290
298
  import { type NpmAdvisoryOptions, npmAdvisories, npmCommitTags, npmDownloads, npmGithubStats, npmKnown, npmLatestRepo, npmSocketReport } from './npm-insights.ts'
291
299
  import { npmProvenance } from './npm-provenance.ts'
292
- import { npmReadyScanDownload, npmReadyScanDownloads, npmRisk, npmRiskRemoved } from './npm-risk.ts'
300
+ import { npmReadyScanDownload, npmReadyScanDownloads, npmRisk, npmRiskMalware, npmRiskRemoved } from './npm-risk.ts'
293
301
  import { NpmRiskError } from '../risk/index.js'
294
302
  import { type ComparedSide, type PrettyCache, PrettyError, type PrettyRequest, compared, prettyRequest, prettyText } from './pretty-print.ts'
295
303
  import { npmCopies } from './pretty-copies.ts'
@@ -342,6 +350,7 @@ const BUNDLE_SET_REPO_PATH = '/api/admin/bundles/set-repo'
342
350
  const BUNDLE_SET_VISIBLE_PATH = '/api/admin/bundles/set-visible'
343
351
  const BUNDLE_PREFIX = '/api/admin/bundles/'
344
352
  const MY_TEAMS_PATH = '/api/teams'
353
+ const MY_TEAM_PROGRESS_PATH = '/api/teams/progress'
345
354
  const MY_REPORT_PREFIX = '/api/reports/'
346
355
  const REPORT_QUERY_PATH = '/api/reports/query'
347
356
  const MY_REPORT_TRIAGE_SUFFIX = '/triage'
@@ -398,6 +407,15 @@ const MANAGED_DATA_PREFIXES = ['/api/admin', '/api/reports', '/api/bundles', '/a
398
407
  const VIEW_PREFIXES = [...MANAGED_DATA_PREFIXES, '/api/auth', '/api/oauth']
399
408
  const underPrefix = (path: string, prefixes: readonly string[]) => prefixes.some(prefix => path === prefix || path.startsWith(prefix + '/'))
400
409
 
410
+ // GET /api/teams/progress: the landing's counts of the user's teams.
411
+ async function handleTeamProgress(res: ServerResponse, deps: ManagedHttpDeps, session: ManagedSession): Promise<void> {
412
+ const snapshot = await deps.db.getUserTeamFeedSnapshot(session.id, Date.now())
413
+ if (!snapshot) { sendJson(res, 401, { error: 'unauthenticated' }); return }
414
+ // A team of no reports has no findings to count.
415
+ const teamIds = snapshot.teams.filter(team => team.reports.length > 0).map(team => team.id)
416
+ sendJson(res, 200, await teamProgress(deps.db, deps.reportStore, session.id, teamIds))
417
+ }
418
+
401
419
  async function handleWorkspaceFixes(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, teamId: string, reportId: string | null): Promise<void> {
402
420
  const s = await readWorkspaceSession(res, deps, cookie, { handed: true })
403
421
  if (!s) return
@@ -409,7 +427,7 @@ async function handleWorkspaceFixes(res: ServerResponse, deps: ManagedHttpDeps,
409
427
  const visibleIds = new Set(issues.map(issue => issue.findingId))
410
428
  // A saved issue's duplicate is read with it, as a kept redirect is followed:
411
429
  // its status even where only cached metadata can be shown.
412
- const urls = [...new Set([...manualUrls, ...issues.flatMap(issue => [issue.issueUrl, issue.autoFixUrl, issue.duplicateOfUrl].filter(url => url !== null))])]
430
+ const urls = workspaceFixUrls(manualUrls, issues)
413
431
  await recheckTeam(deps.db, s.session.id, snapshot)
414
432
  const result = issues.length > 0
415
433
  ? await lookupIssueLinks(deps.config, deps.db, snapshot, urls, storedIssues.filter(issue => visibleIds.has(issue.findingId)))
@@ -2680,12 +2698,18 @@ function itemNumber(text: string | null): number | null {
2680
2698
  // each's answer, else `{ number, error }` where GitHub fails it, with one
2681
2699
  // check of its access before and one after, but where each was kept. With
2682
2700
  // `review=1`, the lines its versions wanting reviews change, where they are
2683
- // counted already (`deltas`, teamDeltas), as a team's Dependencies tells them.
2701
+ // counted already (`deltas`, teamDeltas), as a team's Dependencies tells them;
2702
+ // and each version it adds told the reader's own draft of it (`draft`,
2703
+ // pull-dependency-reviews.ts reviewedDependencies), as reviewing them
2704
+ // together shows it before each is read. With `remaining=1` too, those the
2705
+ // reader reviewed (`yours`) left out of what each adds, of how many want
2706
+ // reviews (`toReview`), and so of the lines told, as that page asks for them.
2684
2707
  const MAX_ASKED_PULLS = 20
2685
2708
  const PULLS_AT_ONCE = 3
2686
2709
  async function handleRepositoryPullDependencies(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
2687
2710
  const repoId = askedRepoId(query)
2688
2711
  const review = query.get('review') === '1'
2712
+ const remaining = query.get('remaining') === '1'
2689
2713
  // As an open one's tile on the Pull requests tab asks (`listed=1`): each
2690
2714
  // by the commits the page it is of names, where one kept names them
2691
2715
  // (keptPullCommits); else by its number, kept a while, as a popup's.
@@ -2693,14 +2717,15 @@ async function handleRepositoryPullDependencies(res: ServerResponse, deps: Manag
2693
2717
  const listed = query.get('numbers')
2694
2718
  const numbers = listed === null ? [itemNumber(query.get('number'))] : listed.split(',').map(text => itemNumber(text))
2695
2719
  if (repoId === null || numbers.length > MAX_ASKED_PULLS || numbers.some(number => number === null) || new Set(numbers).size < numbers.length
2696
- || !['1', null].includes(query.get('review')) || !['1', null].includes(query.get('listed'))) { sendJson(res, 400, { error: 'bad-request' }); return }
2720
+ || !['1', null].includes(query.get('review')) || !['1', null].includes(query.get('listed')) || !['1', null].includes(query.get('remaining'))
2721
+ || (remaining && !review)) { sendJson(res, 400, { error: 'bad-request' }); return }
2697
2722
  await answerWholeRepository(res, deps, cookie, repoId, async (fullName, token, user) => {
2698
2723
  const commits = tiles ? await keptPullCommits(deps, repoId, numbers as number[]) : new Map<number, PullCommits>()
2699
2724
  if (listed === null) {
2700
- const answer = await pullDependencyAnswer(deps, fullName, token, user, repoId, numbers[0]!, review, commits.get(numbers[0]!))
2725
+ const answer = await pullDependencyAnswer(deps, fullName, token, user, repoId, numbers[0]!, review, commits.get(numbers[0]!), undefined, remaining)
2701
2726
  return review ? { ...answer, value: { ...answer.value, ...await withDeltas(deps, [answer.value]) } } : answer
2702
2727
  }
2703
- const answers = await pullDependencyAnswers(deps, fullName, token, user, repoId, numbers as number[], review, commits)
2728
+ const answers = await pullDependencyAnswers(deps, fullName, token, user, repoId, numbers as number[], review, commits, undefined, remaining)
2704
2729
  return { value: { pulls: answers.value, ...review ? await withDeltas(deps, answers.value) : {} }, kept: answers.kept }
2705
2730
  })
2706
2731
  }
@@ -2710,11 +2735,12 @@ async function handleRepositoryPullDependencies(res: ServerResponse, deps: Manag
2710
2735
  // does, else `{ number, error }` where GitHub fails it; and whether all of
2711
2736
  // them were kept. The Stasis builds they want asked for together, once all
2712
2737
  // are known, so the one of highest priority is built first; or added to
2713
- // `wants`, where given, for its caller to ask for with others.
2738
+ // `wants`, where given, for its caller to ask for with others. Where
2739
+ // `remaining`, each without the versions its reader reviewed.
2714
2740
  async function pullDependencyAnswers(deps: ManagedHttpDeps, fullName: string, token: string, user: StoredUser, repoId: number, numbers: number[], review: boolean,
2715
- commits: Map<number, PullCommits> | undefined, wants?: StasisWant[]) {
2741
+ commits: Map<number, PullCommits> | undefined, wants?: StasisWant[], remaining = false) {
2716
2742
  const asking = wants ?? []
2717
- const answers = await eachOf(numbers, PULLS_AT_ONCE, number => pullDependencyAnswer(deps, fullName, token, user, repoId, number, review, commits?.get(number), asking)
2743
+ const answers = await eachOf(numbers, PULLS_AT_ONCE, number => pullDependencyAnswer(deps, fullName, token, user, repoId, number, review, commits?.get(number), asking, remaining)
2718
2744
  .catch((err: unknown) => {
2719
2745
  // GitHub asked, though it failed: its access asked again after.
2720
2746
  if (err instanceof GithubApiError) return { value: { number, error: err.message }, kept: false }
@@ -2729,8 +2755,10 @@ async function pullDependencyAnswers(deps: ManagedHttpDeps, fullName: string, to
2729
2755
  // as a page of its repository's open pull requests read them (`commits`,
2730
2756
  // kept and read again as that page is), else as kept by its number. The
2731
2757
  // Stasis builds it wants asked for once its review is known (askBuilds).
2758
+ // Each version it adds told its reader's own draft of it, and where
2759
+ // `remaining`, those they reviewed left out (reviewedDependencies).
2732
2760
  async function pullDependencyAnswer(deps: ManagedHttpDeps, fullName: string, token: string, user: StoredUser, repoId: number, number: number, review: boolean,
2733
- commits?: PullCommits, wants?: StasisWant[]) {
2761
+ commits?: PullCommits, wants?: StasisWant[], remaining = false) {
2734
2762
  const kept = pullDependencyKept(deps, repoId)
2735
2763
  const reading: { told?: PullDependencies } = {}
2736
2764
  // Where its review is on, those of lockfiles it leaves out told to none,
@@ -2784,7 +2812,7 @@ async function pullDependencyAnswer(deps: ManagedHttpDeps, fullName: string, tok
2784
2812
  const patched = state ? await withPatchFiles(told, repoId, fullName, token, patchStore(deps.db, deps.config.debug), asked) : told
2785
2813
  const bases = new Map<string, ReviewedBase>(), wantedIn = new Map<string[], number>()
2786
2814
  const dependencies = await reviewedDependencies(patched, state, { baseline, baselineUnread: unread, baselineError: error, reviewed, commentReviews: noting, namedBases: bases, user: user.id,
2787
- wantedIn })
2815
+ wantedIn, drafts: versions => deps.db.listOwnDraftReviews(user.id, versions), remaining })
2788
2816
  askBuilds(deps, wanted, wantedIn, wants)
2789
2817
  // The comment the host formats of the reader's reviews of its versions, for
2790
2818
  // its copy button, but those its comments make of theirs already; with the
@@ -3806,6 +3834,7 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3806
3834
  }
3807
3835
  const versions = npmVersionStore(deps.db, deps.config.debug)
3808
3836
  const stores = { db: deps.db, npmCache: deps.npmCacheStorage, debug: deps.config.debug }
3837
+ const repositoriesGithub = lazyGithubClient(() => Promise.resolve(user.token))
3809
3838
  const lines = repositoryRiskLines({
3810
3839
  // Which repositories a scan in parts told whole, by the admin, the id the
3811
3840
  // page gives the scan (`scan`) and its scope, for the next part to go on
@@ -3885,7 +3914,7 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3885
3914
  // And each lockfile's advisories, for as long as a scan tells them.
3886
3915
  audits: scanReadStore(deps.db, 'advisories', RISK_KEPT_MS, deps.config.debug),
3887
3916
  // As a bundle's advisories are asked (bundle-advisories.ts), npm's registry
3888
- // and, for packages anyone may read, OSV: no repository's. Each lockfile's
3917
+ // and, for packages anyone may read, OSV: repositories' apart. Each lockfile's
3889
3918
  // audit is bounded on its own, for one npm doesn't answer to fail alone and
3890
3919
  // the scan to carry on.
3891
3920
  async advisories(asked, scanning) {
@@ -3896,6 +3925,15 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3896
3925
  if (audited.status !== 200) throw new NpmPackageError(502, audited.body.error)
3897
3926
  return audited.body
3898
3927
  },
3928
+ // And those their repositories publish (bundle-advisories.ts), each
3929
+ // package's as its versions' kept documents name it, as known, GitHub
3930
+ // asked with the admin's token behind the scan, or waited on.
3931
+ async repositories(asked, scanning, wait) {
3932
+ const { packages, unknown } = await versionsRepositories(versions, asked)
3933
+ const known = await fetchKnownRepositoryAdvisories(packages.map(pkg => ({ ecosystem: 'npm' as const, ...pkg })), scanning, { db: deps.db, github: repositoriesGithub,
3934
+ behind: work => { trackBehind(deps, work) }, wait: wait ? AbortSignal.any([scanning, AbortSignal.timeout(ADVISORIES_TIMEOUT_MS)]) : undefined, debug: deps.config.debug })
3935
+ return { advisories: known.advisories, again: known.again || unknown }
3936
+ },
3899
3937
  }, controller.signal, undefined, { partMs: deps.config.serverless ? REPO_RISK_PART_MS : null, kept: query.get('kept') === '1' })
3900
3938
  let checked = Date.now()
3901
3939
  await sendLines(res, withLineUsers(deps.db, lines, dismissersOf), async () => {
@@ -4033,13 +4071,16 @@ async function handleBundleAdvisories(res: ServerResponse, deps: ManagedHttpDeps
4033
4071
  ...init, signal: init?.signal ? AbortSignal.any([controller.signal, init.signal]) : controller.signal,
4034
4072
  })) : null
4035
4073
  if (res.destroyed || (needsGithub && !(await authorize()))) return
4036
- const result = await fetchBundleAdvisories(inventory.packages, controller.signal, {
4037
- debug: deps.config.debug, repoAdvisories, details, githubToken,
4038
- cache: auditCache(deps.config.upstreamCacheDir, deps.db, controller.signal, deps.config.debug, auditedKeys(inventory.packages, repoAdvisories)),
4074
+ // Its repositories' advisories as known, GitHub asked behind the answer,
4075
+ // with the reader's token asked for then where it wasn't before;
4076
+ // `repoAdvisories`, the reader's recheck, asks GitHub first (`unchecked`).
4077
+ const result = await fetchKnownBundleAdvisories(inventory.packages, controller.signal, {
4078
+ debug: deps.config.debug, recheck: repoAdvisories, details, db: deps.db, behind: work => { trackBehind(deps, work) },
4079
+ githubToken: async () => githubToken ?? await ensureUserAccessToken(deps.config, deps.db, session.userId, Date.now()),
4039
4080
  })
4040
4081
  if (res.destroyed || !(await authorize())) return
4041
4082
  // Return just inventory and public advisories, never source or report data.
4042
- sendJson(res, result.status, result.status === 200 ? { ...inventory, advisories: result.body } : result.body)
4083
+ sendJson(res, result.status, result.status === 200 ? { ...inventory, advisories: result.body, unchecked: result.unchecked } : result.body)
4043
4084
  } finally {
4044
4085
  clearTimeout(timer)
4045
4086
  res.off('close', onClose)
@@ -5380,28 +5421,39 @@ function npmAdvisoryOptions(deps: ManagedHttpDeps, githubToken: NpmAdvisoryOptio
5380
5421
  githubToken,
5381
5422
  repo: async () => { const doc = await latestDoc(); return doc && githubRepoOf(doc) },
5382
5423
  cache: signal => auditCache(deps.config.upstreamCacheDir, deps.db, signal, deps.config.debug),
5383
- lastListing: repo => lastListing(deps.config.upstreamCacheDir, deps.db, repo, deps.config.debug),
5424
+ lastListing: repo => lastListing(deps.db, repo, deps.config.debug),
5384
5425
  debug: deps.config.debug,
5385
5426
  }
5386
5427
  }
5387
5428
 
5388
5429
  // Read the same target-version evidence as the viewer. Missing upstream
5389
- // reports impose no extra verdict restriction; detected findings do.
5390
- async function npmReviewPublicationLimit(deps: ManagedHttpDeps, reader: NpmReader, doc: NpmVersionDocument, signal: AbortSignal) {
5430
+ // reports impose no extra verdict restriction; detected findings do. Of
5431
+ // risk's, its malware alone counts (npmReviewVerdictLimit), so that alone is
5432
+ // asked (npmRiskMalware): its package taken down, and its advisories of
5433
+ // malware, npm's and OSV's, failing the publication where they can't be had,
5434
+ // as its assessment would; nothing of its tarball read for it, so that it
5435
+ // waits on none of the loads a publication's files take. Its package's
5436
+ // whole document read once between them, in its turn (`inTurn`), the
5437
+ // versions its advisories are asked of as it lists them (npmListedVersions),
5438
+ // so that it holds one document's place in the budget npm's are read within
5439
+ // (npm-packages.ts withDocumentBudget).
5440
+ async function npmReviewPublicationLimit(deps: ManagedHttpDeps, reader: NpmReader, doc: NpmVersionDocument, signal: AbortSignal, inTurn: Turn = untimed) {
5391
5441
  if (npmTakenDown({ npm: doc })) return 'reject' as const
5392
5442
  const privileged = canReadPrivateNpm(reader, doc.name)
5443
+ let read: Promise<Record<string, unknown> | null> | undefined
5444
+ const packument = () => read ??= inTurn(() => readNpmPackument(doc.name, privileged, signal))
5393
5445
  const advisories = async () => {
5394
- const versions = await readNpmVersions(doc.name, privileged, signal)
5395
- if (!versions) return null
5396
- return npmAdvisories(doc.name, versions.versions, npmAdvisoryOptions(deps,
5446
+ const json = await packument()
5447
+ if (!json) return null
5448
+ return npmAdvisories(doc.name, npmListedVersions(doc.name, json), npmAdvisoryOptions(deps,
5397
5449
  () => ensureUserAccessToken(deps.config, deps.db, reader.userId, Date.now()).catch(() => null),
5398
5450
  () => readNpmVersion(doc.name, 'latest', privileged, signal)))
5399
5451
  }
5400
5452
  // Advisories that can't be had count for none, but where npm is too busy for them, asked again (notBusy) rather than let pass.
5401
- const [list, socket, risk] = await Promise.all([advisories().catch((err: unknown) => { if (isBusy(err)) throw err; return null }),
5453
+ const [list, socket, malware] = await Promise.all([advisories().catch((err: unknown) => { if (isBusy(err)) throw err; return null }),
5402
5454
  doc.private ? null : npmSocketReport(doc.name, doc.version).catch(() => null),
5403
- npmRisk(doc, null, { db: deps.db, npmCache: deps.npmCacheStorage, debug: deps.config.debug, teamScoped: true, privileged, signal })])
5404
- return npmReviewVerdictLimit(doc, list, socket, risk)
5455
+ npmRiskMalware(doc, { db: deps.db, npmCache: deps.npmCacheStorage, debug: deps.config.debug, privileged, signal, packument })])
5456
+ return npmReviewVerdictLimit(doc, list, socket, { findings: malware ? [malware] : [] })
5405
5457
  }
5406
5458
 
5407
5459
  // The change a POST of reviews asks for, as its `body` names it: a review
@@ -5513,27 +5565,36 @@ async function reviewedVersions(reader: NpmReader, context: ReviewContext, kept:
5513
5565
  // reader reads: npmPatchOf), the review keeping where it was read; and a
5514
5566
  // patched base's (`basePatchHash`) as its patch, kept, changes them. A
5515
5567
  // publication's verdict is held to what its package allows
5516
- // (npmReviewPublicationLimit), asked while its files are read. Both, which
5517
- // the server holds few of at once, by `heavy`: as each is asked, once more,
5518
- // three times, where the server is too busy for it (notBusy). Then `commit`
5519
- // makes it for the reader as they are then (`current`), the private versions
5520
- // (`privates`) theirs still: the review made, else why not.
5568
+ // (npmReviewPublicationLimit), asked while its files are read. Each part in
5569
+ // its turn (`turns`): its versions' documents (`read`); what its package
5570
+ // allows (`limit`), its package's whole document read for it in a turn of
5571
+ // its own (`packument`), as npm's documents are read within a budget
5572
+ // (npm-packages.ts withDocumentBudget); and its files, which the server
5573
+ // holds few of at once (`heavy`). Alone, what its package allows and its
5574
+ // files are each asked again, as many as three times, where the server is
5575
+ // too busy for them (notBusy). Then `commit` makes it for the reader as they
5576
+ // are then (`current`), the private versions (`privates`) theirs still: the
5577
+ // review made, else why not.
5521
5578
  type PreparedChange = { privates: string[]; commit(sessionId: string, current: NpmReader): Promise<Refusal | { review: DependencyReview }> }
5579
+ type Turn = <T>(work: () => Promise<T>) => Promise<T>
5580
+ interface Turns { read: Turn; limit: Turn; packument: Turn; heavy: Turn }
5581
+ const untimed: Turn = work => work()
5522
5582
  const INTERACTIVE_BUSY_RETRIES = 3
5583
+ const aloneTurns = (signal: AbortSignal): Turns => ({ read: untimed, limit: work => notBusy(work, signal, INTERACTIVE_BUSY_RETRIES), packument: untimed,
5584
+ heavy: work => notBusy(work, signal, INTERACTIVE_BUSY_RETRIES) })
5523
5585
  async function preparedReviewChange(deps: ManagedHttpDeps, cookie: string | undefined, reader: NpmReader, { context, patch, change }: AskedChange,
5524
- kept: NpmVersionStore, signal: AbortSignal, heavy: <T>(work: () => Promise<T>) => Promise<T> = work => notBusy(work, signal, INTERACTIVE_BUSY_RETRIES)):
5525
- Promise<PreparedChange | Refusal> {
5586
+ kept: NpmVersionStore, signal: AbortSignal, turns: Turns = aloneTurns(signal)): Promise<PreparedChange | Refusal> {
5526
5587
  // What it asks given up where it is refused before it is worked out.
5527
5588
  const own = new AbortController()
5528
5589
  const asking = AbortSignal.any([signal, own.signal])
5529
5590
  let prepared = false
5530
5591
  try {
5531
- const versions = await reviewedVersions(reader, context, kept, asking)
5592
+ const versions = await turns.read(() => reviewedVersions(reader, context, kept, asking))
5532
5593
  if ('error' in versions) return versions
5533
5594
  const { doc, base } = versions
5534
5595
  const docs = [doc, ...base ? [base] : []]
5535
5596
  const limiting = change.action === 'publish' && change.final && change.final.status !== 'reject'
5536
- ? heavy(() => npmReviewPublicationLimit(deps, reader, doc, asking)) : Promise.resolve('accept' as const)
5597
+ ? turns.limit(() => npmReviewPublicationLimit(deps, reader, doc, asking, turns.packument)) : Promise.resolve('accept' as const)
5537
5598
  limiting.catch(() => {})
5538
5599
  const reading = change.action !== 'revoke'
5539
5600
  const [patchRead, basePatchRead] = await Promise.all([reading && patch ? npmPatchOf(deps, cookie, patch) : null,
@@ -5557,7 +5618,7 @@ async function preparedReviewChange(deps: ManagedHttpDeps, cookie: string | unde
5557
5618
  return changed.map(file => ({ path: file.path, text: isReviewableFile(before.get(file.basePath ?? file.path), after.get(file.path)) }))
5558
5619
  } finally { loads.forEach(load => load.release()) }
5559
5620
  }
5560
- const changed = reading ? await heavy(pair) : []
5621
+ const changed = reading ? await turns.heavy(pair) : []
5561
5622
  if (change.action === 'save') {
5562
5623
  const file = changed.find(each => each.path === change.entry.file)
5563
5624
  if (!file) return refusal(400, 'unknown-review-file')
@@ -5648,14 +5709,23 @@ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps:
5648
5709
  // POST /api/npm/reviews/publish: drafts published together, as a pull
5649
5710
  // request's versions are, each as POST /api/npm/reviews publishes one
5650
5711
  // (askedChange), their reader and versions read once between them. Each
5651
- // worked out (preparedReviewChange) PREPARED_AT_ONCE at a time, its files and
5652
- // what its package allows HEAVY_AT_ONCE at a time between them, as the server
5653
- // holds few at once (npm-loads.ts, npm-risk.ts), each asked again while it is
5654
- // too busy for them (notBusy); the session and the reader's access checked
5655
- // again once all are, then each published in turn, one refused none of the
5656
- // others. One that names no publication refuses them all (400, `at` its place).
5657
- const PREPARED_AT_ONCE = 4
5712
+ // worked out (preparedReviewChange) PREPARED_AT_ONCE at a time; between
5713
+ // them, their files HEAVY_AT_ONCE at a time, as the server holds few at once
5714
+ // (npm-loads.ts), and their packages' whole documents PACKUMENTS_AT_ONCE at
5715
+ // a time, half as many as npm's documents are read within (npm-packages.ts
5716
+ // withDocumentBudget), the rest left to the server's other readers; each
5717
+ // part asked again while the server is too busy for it (notBusy). The
5718
+ // session and the reader's access checked again once all are, then each
5719
+ // published in turn, one refused none of the others. One that names no
5720
+ // publication refuses them all (400, `at` its place).
5721
+ // Where they are of a pull request's versions (`pullRequest`, `{ repoId,
5722
+ // number, remaining? }`), and one is published, its dependencies are read
5723
+ // again (publishedPull), those its reader reviewed left out where
5724
+ // `remaining`, and told with them (`pull`), its copy button's reviews among
5725
+ // them, so its reader needn't ask for them again.
5726
+ const PREPARED_AT_ONCE = 8
5658
5727
  const HEAVY_AT_ONCE = 2
5728
+ const PACKUMENTS_AT_ONCE = 2
5659
5729
  async function handlePublishNpmReviews(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
5660
5730
  if (req.method !== 'POST') { send405(res, 'POST'); return }
5661
5731
  const session = await checkMutation(req, res, deps, cookie, { handed: true })
@@ -5665,6 +5735,8 @@ async function handlePublishNpmReviews(req: IncomingMessage, res: ServerResponse
5665
5735
  if (!body) return
5666
5736
  const listed = body['reviews']
5667
5737
  if (!Array.isArray(listed) || listed.length === 0 || listed.length > MAX_PUBLISHED_REVIEWS) { sendJson(res, 400, { error: 'bad-review' }); return }
5738
+ const pull = body['pullRequest'] === undefined ? null : pullRequestOf(body['pullRequest'])
5739
+ if (pull === 'bad') { sendJson(res, 400, { error: 'bad-pull-request' }); return }
5668
5740
  const asked: AskedChange[] = []
5669
5741
  for (const [at, item] of listed.entries()) {
5670
5742
  const one = plainObject(item) ? askedChange({ ...item, action: 'publish' }) : 'bad-review-context'
@@ -5680,8 +5752,9 @@ async function handlePublishNpmReviews(req: IncomingMessage, res: ServerResponse
5680
5752
  const reader = (await npmReaderOf(deps, session.user, reviewedNames(contexts)))!
5681
5753
  const kept = reviewedKept(deps, contexts)
5682
5754
  const inTurn = inTurns(HEAVY_AT_ONCE)
5683
- const heavy = <T>(work: () => Promise<T>) => notBusy(() => inTurn(work), controller.signal)
5684
- const prepared = await eachOf(asked, PREPARED_AT_ONCE, one => preparedReviewChange(deps, cookie, reader, one, kept, controller.signal, heavy))
5755
+ const turns: Turns = { read: work => notBusy(work, controller.signal), limit: work => notBusy(work, controller.signal),
5756
+ packument: inTurns(PACKUMENTS_AT_ONCE), heavy: work => notBusy(() => inTurn(work), controller.signal) }
5757
+ const prepared = await eachOf(asked, PREPARED_AT_ONCE, one => preparedReviewChange(deps, cookie, reader, one, kept, controller.signal, turns))
5685
5758
  if (controller.signal.aborted) return
5686
5759
  const checked = await checkMutation(req, res, deps, cookie)
5687
5760
  if (!checked) return
@@ -5690,13 +5763,47 @@ async function handlePublishNpmReviews(req: IncomingMessage, res: ServerResponse
5690
5763
  const done: (Refusal | { review: DependencyReview })[] = []
5691
5764
  for (const one of prepared) done.push('error' in one ? one : await one.commit(checked.session.id, current))
5692
5765
  const formatted = await withFormatted(deps.reviewedDependencies ?? null, current.userId, done.flatMap(one => 'error' in one ? [] : [one.review]))
5766
+ const read = pull && formatted.length > 0 ? await publishedPull(deps, cookie, pull) : null
5767
+ if (controller.signal.aborted) return
5693
5768
  let next = 0
5694
- sendJson(res, 200, { results: done.map(one => 'error' in one ? { error: one.error, status: one.status } : { review: formatted[next++] }) })
5769
+ sendJson(res, 200, { results: done.map(one => 'error' in one ? { error: one.error, status: one.status } : { review: formatted[next++] }), ...read ? { pull: read } : {} })
5695
5770
  } catch (err) {
5696
5771
  if (!controller.signal.aborted) throw err
5697
5772
  } finally { res.off('close', onClose) }
5698
5773
  }
5699
5774
 
5775
+ // The pull request a publication names its versions of (`{ repoId, number }`),
5776
+ // and whether it is read again as its versions its reader didn't review
5777
+ // (`remaining`), else 'bad'.
5778
+ interface PublishedPull { repoId: number; number: number; remaining: boolean }
5779
+ function pullRequestOf(value: unknown): PublishedPull | 'bad' {
5780
+ if (!plainObject(value)) return 'bad'
5781
+ const { repoId, number, remaining = false } = value
5782
+ return Number.isSafeInteger(repoId) && (repoId as number) > 0 && itemNumber(String(number)) === number && typeof remaining === 'boolean'
5783
+ ? { repoId: repoId as number, number: number as number, remaining } : 'bad'
5784
+ }
5785
+
5786
+ // Pull request `pull`'s dependencies with their review, as GET
5787
+ // pull-dependencies?review=1 tells them (pullDependencyAnswer, but the lines
5788
+ // its rows hold already), with remaining=1 where `remaining`, read again as its reader's reviews of its
5789
+ // versions were just published, for its copy button (`formatted`) to tell
5790
+ // them at once; its reader's access to the whole of its repository asked
5791
+ // afresh, before and after, as answerWholeRepository asks it. None where
5792
+ // they read no longer all of it, or it couldn't be read: its reader then asks
5793
+ // for it again, the reviews published all the same.
5794
+ async function publishedPull(deps: ManagedHttpDeps, cookie: string | undefined, { repoId, number, remaining }: PublishedPull): Promise<object | null> {
5795
+ try {
5796
+ const access = await wholeRepositoryAccess(deps, cookie, repoId)
5797
+ if ('error' in access) return null
5798
+ const read = await readWholeRepositoryOf(deps, access, (fullName, token, user) => pullDependencyAnswer(deps, fullName, token, user, repoId, number, true, undefined, undefined, remaining),
5799
+ () => wholeRepositoryAccess(deps, cookie, repoId))
5800
+ return 'error' in read ? null : await withAppUsers(deps.db, read.value)
5801
+ } catch (err) {
5802
+ console.warn('dependency reviews: failed to read the pull request published of again', err instanceof Error ? err.message : err)
5803
+ return null
5804
+ }
5805
+ }
5806
+
5700
5807
  // GET /api/npm/deltas?versions=[[name, version, otherVersion, patch?, otherName?], …]:
5701
5808
  // the lines each of up to MAX_ASKED_DELTAS versions changes against another,
5702
5809
  // of its package or `otherName`'s, as the host may name a review's base
@@ -5913,8 +6020,15 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
5913
6020
  const old = otherSpec === '' || otherSpec === '(empty)' ? null : await otherDoc()
5914
6021
  const scope = npmPackageScope(name)
5915
6022
  const teamScoped = scope !== null && await deps.db.hasTeamNpmScope(scope)
6023
+ // Its repository's advisories too, its listing as kept where it is
6024
+ // fresh, else asked of GitHub with the reader's token and waited on for
6025
+ // half an audit's time at most, the last kept taken where it can't be
6026
+ // had by then (known-listings.ts `wait`).
6027
+ const github = lazyGithubClient(githubToken)
6028
+ const upstream = knownListings(deps.db, controller.signal, { github, behind: work => { trackBehind(deps, work) },
6029
+ wait: AbortSignal.any([controller.signal, AbortSignal.timeout(ADVISORIES_TIMEOUT_MS / 2)]) })
5916
6030
  const assessment = await npmRisk(doc, otherSpec === '' ? 'pick' : old, { db: deps.db, npmCache: deps.npmCacheStorage, debug: deps.config.debug, teamScoped, fromEmpty: otherSpec === '(empty)',
5917
- ownScope: listed => deps.db.hasTeamNpmScope(listed), privileged, signal: controller.signal })
6031
+ ownScope: listed => deps.db.hasTeamNpmScope(listed), privileged, signal: controller.signal, github, upstream })
5918
6032
  // What it tells is read of both versions: private where either is.
5919
6033
  dropIdle(res)
5920
6034
  await reply(doc.private || old?.private === true, { ...assessment })
@@ -6479,6 +6593,10 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
6479
6593
  if (method !== 'GET') { send405(res, 'GET'); return }
6480
6594
  await handleMyTeams(res, deps, workspaceSession!.session); return
6481
6595
  }
6596
+ if (path === MY_TEAM_PROGRESS_PATH) {
6597
+ if (method !== 'GET') { send405(res, 'GET'); return }
6598
+ await handleTeamProgress(res, deps, workspaceSession!.session); return
6599
+ }
6482
6600
  // Teams: list / create on the exact path; the link mutations are POST-only
6483
6601
  // action sub-paths (each carries its ids in the JSON body).
6484
6602
  if (path === ADMIN_TEAMS_PATH) {
@@ -0,0 +1,112 @@
1
+ // Repositories' advisory listings as known, so that no answer waits on GitHub
2
+ // for one: each kept for good where audits keep listings (upstream-cache.ts),
3
+ // answered however old as kept just now, so that upstream takes it, and one
4
+ // none is kept of answered as listing none for now. Each of those older than
5
+ // upstream takes, and each missing, is asked of GitHub behind the answer; a
6
+ // failure leaves the listing as kept. A reader's recheck (`recheck`) asks
7
+ // each first instead, and a wait (`wait`) each of those, waited on until it
8
+ // aborts at most.
9
+ import { type CacheStore, advisories } from '@preventive/upstream/advisories.js'
10
+ import type { Client } from '@preventive/upstream/github.js'
11
+ import { type Lru, lru } from './lru.ts'
12
+ import { inTurns } from './queue.ts'
13
+ import { LISTINGS, type UpstreamCacheStore, upstreamCache } from './upstream-cache.ts'
14
+
15
+ // How long upstream takes a listing as it is (its github.js LISTING_TTL_MS),
16
+ // and the record version it keeps one as (its VERSION).
17
+ const FRESH_MS = 90 * 60_000
18
+ const VERSION = 3
19
+ // How long a repository asked behind an answer isn't asked behind another
20
+ // by this instance, whatever came of it, by the database it is kept in; and
21
+ // how many are asked at once.
22
+ const AGAIN_MS = 10 * 60_000
23
+ const askedAt = new WeakMap<UpstreamCacheStore, Lru<number>>()
24
+ const inTurn = inTurns(4)
25
+
26
+ // `repo`'s listing asked of GitHub, however fresh the one `db` keeps (none is
27
+ // read, so that a recheck rechecks), as upstream asks a `github` package's
28
+ // own advisories alone (`internal`), and kept as upstream keeps one: as
29
+ // upstream gave it to keep, kept or not (null where it kept none, as for a
30
+ // repository gone), or null where that failed; `queued` in turn with others
31
+ // asked behind an answer. One asked for another meanwhile, queued or under
32
+ // way, is that one's. Kept however long GitHub took to give it, as the
33
+ // work behind an answer is waited for (http.ts trackBehind), and each kept
34
+ // as given, so that what is had of many is kept though the rest never are.
35
+ const asking = new Map<string, Promise<{ listing: unknown } | null>>()
36
+ const keeping = new AbortController().signal
37
+ function ask(repo: string, github: Client, db: UpstreamCacheStore, queued = false): Promise<{ listing: unknown } | null> {
38
+ let asked = asking.get(repo)
39
+ if (!asked) {
40
+ const listed = () => {
41
+ const kept = upstreamCache(db, keeping)
42
+ let listing: unknown = null
43
+ const cache: CacheStore = { read: (type, key) => type === LISTINGS ? Promise.resolve(null) : kept.read(type, key),
44
+ async write(type, key, value) { if (type === LISTINGS) listing = value; await kept.write(type, key, value) } }
45
+ return advisories([{ ecosystem: 'github', name: repo, versions: ['0.0.0'], internal: true }], { github, cache, githubAliases: false }).then(() => ({ listing }), () => null)
46
+ }
47
+ asked = (queued ? inTurn(listed) : listed()).finally(() => { asking.delete(repo) })
48
+ asking.set(repo, asked)
49
+ }
50
+ return asked
51
+ }
52
+
53
+ const isListing = (value: unknown, key: string): value is { at: number } => typeof value === 'object' && value !== null
54
+ && (value as { v?: unknown }).v === VERSION && (value as { name?: unknown }).name === key
55
+ && typeof (value as { at?: unknown }).at === 'number' && Array.isArray((value as { advisories?: unknown }).advisories)
56
+ const isFresh = (value: unknown, key: string) => isListing(value, key) && Date.now() - value.at >= 0 && Date.now() - value.at < FRESH_MS
57
+
58
+ // The store upstream reads listings in, kept in `db` (those of `keys` read at
59
+ // once, upstream-cache.ts auditedKeys), and the rest it keeps as `db` keeps
60
+ // them; GitHub asked with `github`, behind the answer as `behind` (http.ts
61
+ // trackBehind) lets work go on past it. With `recheck` or `wait`, the
62
+ // repositories whose listing it asked wasn't had by then (GitHub failed, or
63
+ // is still answering) are noted in `unchecked`, lowercased; without, those
64
+ // not fresh, asked behind.
65
+ export function knownListings(db: UpstreamCacheStore, signal: AbortSignal, { github, behind, keys = [], recheck, wait }: {
66
+ github: Client; behind: (work: Promise<unknown>) => void; keys?: Iterable<string>; recheck?: AbortSignal | undefined; wait?: AbortSignal | undefined
67
+ }): CacheStore & { unchecked: Set<string> } {
68
+ // A recheck reads each listing once it is asked, not all at once before.
69
+ const base = upstreamCache(db, signal, false, recheck ? [] : keys)
70
+ const unchecked = new Set<string>()
71
+ const read = new Map<string, Promise<unknown>>()
72
+ let behindAt = askedAt.get(db)
73
+ if (!behindAt) askedAt.set(db, behindAt = lru<number>(10_000))
74
+ const by = recheck ?? wait
75
+ const until = by && new Promise<false>(resolve => {
76
+ if (by.aborted) resolve(false)
77
+ else by.addEventListener('abort', () => { resolve(false) }, { once: true })
78
+ })
79
+ // With a recheck, or a wait one not fresh, as GitHub gave it, else as kept.
80
+ const readOnce = async (key: string) => {
81
+ if (!until) return await base.read(LISTINGS, key)
82
+ if (!recheck) {
83
+ const kept = await base.read(LISTINGS, key)
84
+ if (isFresh(kept, key)) return kept
85
+ }
86
+ const asked = ask(key, github, db)
87
+ behind(asked)
88
+ const had = await Promise.race([asked, until])
89
+ if (had) return had.listing
90
+ unchecked.add(key)
91
+ return await base.read(LISTINGS, key)
92
+ }
93
+ return {
94
+ unchecked,
95
+ async read(type, key) {
96
+ if (type !== LISTINGS) return await base.read(type, key)
97
+ let kept = read.get(key)
98
+ if (!kept) read.set(key, kept = readOnce(key))
99
+ const listing = await kept
100
+ const last = behindAt.get(key), now = Date.now()
101
+ if (!until && !isFresh(listing, key)) {
102
+ unchecked.add(key)
103
+ if (!(last !== undefined && now - last >= 0 && now - last < AGAIN_MS)) {
104
+ behindAt.set(key, now)
105
+ behind(ask(key, github, db, true))
106
+ }
107
+ }
108
+ return isListing(listing, key) ? { ...listing, at: now } : { v: VERSION, at: now, name: key, advisories: [] }
109
+ },
110
+ write: (type, key, value) => base.write(type, key, value),
111
+ }
112
+ }
@@ -305,6 +305,15 @@ export function readTogether(store: NpmVersionStore, versions: { name: string; v
305
305
  } }
306
306
  }
307
307
 
308
+ // Each version package `name`'s document `json` lists, newest published
309
+ // first, its abbreviated document's and its whole one's alike; a document of
310
+ // another package, or of no versions, is npm's answer gone wrong
311
+ // (`upstream-invalid`).
312
+ export function npmListedVersions(name: string, json: Record<string, unknown>): string[] {
313
+ if (json['name'] !== name || !plainObject(json['versions'])) throw new NpmPackageError(502, 'upstream-invalid')
314
+ return Object.keys(json['versions']).filter(isNpmPackageSpec).toReversed()
315
+ }
316
+
308
317
  // The package's dist-tags and versions, newest published first, from its
309
318
  // abbreviated document; with `times`, from its whole one, which alone has
310
319
  // when each was published, `times` by version (ISO dates), and `created`,
@@ -319,8 +328,7 @@ export function readNpmVersions(name: string, privileged: boolean, signal: Abort
319
328
  const found = await readDocument(name, registryUrl(name), privileged, { accept, limit: PACKUMENT_BYTES, signal, whole: times })
320
329
  if (!found) return null
321
330
  const { json } = found
322
- if (json['name'] !== name || !plainObject(json['versions'])) throw new NpmPackageError(502, 'upstream-invalid')
323
- const versions = Object.keys(json['versions']).filter(isNpmPackageSpec).toReversed()
331
+ const versions = npmListedVersions(name, json)
324
332
  const distTags = Object.fromEntries(Object.entries(stringRecord(json['dist-tags']) ?? {}).filter(([, version]) => versions.includes(version)))
325
333
  const listed = { name, private: found.private, distTags, versions }
326
334
  if (!times) return listed