@preventive/triage 1.0.0-alpha.86 → 1.0.0-alpha.88

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 (61) hide show
  1. package/common/bundle-compare-diff.js +3 -2
  2. package/common/default-scan-models.ts +1 -0
  3. package/common/dependency-reviews.d.ts +1 -0
  4. package/common/dependency-reviews.js +3 -0
  5. package/common/github-issue-labels.d.ts +3 -1
  6. package/common/github-issue-labels.js +37 -6
  7. package/common/line-diff.d.ts +2 -1
  8. package/common/line-diff.js +12 -5
  9. package/common/managed/roles.ts +7 -0
  10. package/common/managed/routes.js +7 -6
  11. package/common/pretty-json.js +25 -0
  12. package/common/pretty-print.d.ts +1 -0
  13. package/common/pretty-print.js +5 -0
  14. package/out/activity.js +2 -2
  15. package/out/{chunk-ULI2BIWN.js → chunk-3TJCEPHF.js} +1 -1
  16. package/out/chunk-4GHLPL2P.js +1 -0
  17. package/out/chunk-5PWEAEA5.js +1 -0
  18. package/out/chunk-7KUZQB6S.js +267 -0
  19. package/out/{chunk-YU3IUQY6.js → chunk-A4HSJCXG.js} +1 -1
  20. package/out/{chunk-ZQQALNFP.js → chunk-BZJU5EEV.js} +1 -1
  21. package/out/{chunk-6CCSTJWB.js → chunk-ESXA7KID.js} +1 -1
  22. package/out/{chunk-CE2FMDK3.js → chunk-TKPNRQNN.js} +1 -1
  23. package/out/{chunk-GM6GP6TA.js → chunk-U6JONPTN.js} +2 -2
  24. package/out/chunk-VRFGZ6MV.js +1 -0
  25. package/out/{chunk-XHYX3Q34.js → chunk-XRAAYXPR.js} +1 -1
  26. package/out/chunk-ZPIUN4FW.js +55 -0
  27. package/out/client-managed-import.js +1 -1
  28. package/out/client-managed.js +28 -28
  29. package/out/compare.js +13 -13
  30. package/out/dialogs.js +38 -38
  31. package/out/graph.js +1 -1
  32. package/out/index.html +9 -9
  33. package/out/scan.js +2 -2
  34. package/out/view.css +1 -1
  35. package/out/view.js +15 -15
  36. package/package.json +2 -2
  37. package/risk/files/script.js +19 -9
  38. package/server-e2e/config.ts +3 -1
  39. package/server-managed/bundle-build-worker.js +13 -6
  40. package/server-managed/bundle-build.ts +7 -5
  41. package/server-managed/dependabot-access.ts +41 -17
  42. package/server-managed/dependabot-alerts.ts +19 -2
  43. package/server-managed/github-issues.ts +26 -14
  44. package/server-managed/github-users.ts +23 -0
  45. package/server-managed/http.ts +271 -123
  46. package/server-managed/npm-delta-worker.js +56 -8
  47. package/server-managed/npm-delta.ts +1 -1
  48. package/server-managed/npm-patch.ts +3 -1
  49. package/server-managed/pretty-format.d.ts +3 -2
  50. package/server-managed/pretty-format.js +17 -3
  51. package/server-managed/pretty-print.ts +18 -16
  52. package/server-managed/repository-browser.ts +3 -2
  53. package/server-managed/repository-risk-assess.ts +10 -0
  54. package/server-managed/stasis-dependencies.ts +14 -5
  55. package/server-managed/type-only-proof.js +22 -2
  56. package/out/chunk-2F7GGMMR.js +0 -266
  57. package/out/chunk-R7HUX4PF.js +0 -1
  58. package/out/chunk-V4U7URJF.js +0 -54
  59. package/out/chunk-WOCJFOXN.js +0 -1
  60. package/out/chunk-ZQHKSKD7.js +0 -1
  61. /package/out/{chunk-6WMQVUT2.js → chunk-WBK5ZN4K.js} +0 -0
@@ -123,6 +123,8 @@
123
123
  // or the default icon (organization null) | 400/401/403/404/502
124
124
  // GET/POST /api/npm/reviews → read private/team reviews; save, publish, revoke or continue a set; a patched version's
125
125
  // (patchHash) changed with where its patch is (patchRepoId, patchCommit, patchPath) | 400/401/403/404/409/422
126
+ // 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
126
128
  // POST /api/npm/reviews/discard → author discards an unpublished review and its file rows | 400/401/403/409
127
129
  // GET /api/npm/reviews/latest → latest own review for exact target bytes, across all bases | 400/401/403
128
130
  // GET /api/npm/reviews/team?teamId=&beforeTime=&beforeId= → the reviews published to a team, the latest first, for one who
@@ -213,7 +215,7 @@ import { createClient } from '@preventive/upstream/github.js'
213
215
  import type { ConnectedRepo } from './github-app.ts'
214
216
  import { canAddAnyPublicRepository, canAddRepositories, passesPublicRepositorySafeguard } from './repository-policy.ts'
215
217
  import { RepositoryDiscovery } from './repository-discovery.ts'
216
- import { RISK_KEPT_MS, SCAN_READ_KEPT_MS, type ScanProgress, repositoryRiskLines } from './repository-risk.ts'
218
+ import { RISK_KEPT_MS, type RepositoryRiskLine, SCAN_READ_KEPT_MS, type ScanProgress, repositoryRiskLines } from './repository-risk.ts'
217
219
  import { keptRepositories } from './repository-risk-kept.ts'
218
220
  import { type RiskStasisRead, lockfileOf, stasisConfigRow } from './repository-risk-read.ts'
219
221
  import { WORKFLOWS_DIR } from './repository-actions.ts'
@@ -236,7 +238,7 @@ import { IssueError, MAX_ISSUE_BODY_BYTES, createGithubIssue, parseIssueContext,
236
238
  import { ISSUE_LOGIN_PATH, isIssueOAuthCallback, issueLoginRedirect, issueOAuthCallback } from './github-issue-oauth.ts'
237
239
  import { LINK_LOGIN_PATH, isLinkOAuthCallback, linkLoginRedirect, linkOAuthCallback } from './github-link-oauth.ts'
238
240
  import type { ProfileChoice } from './github-links.ts'
239
- import { withAppUsers } from './github-users.ts'
241
+ import { withAppUsers, withLineUsers } from './github-users.ts'
240
242
  import { isBlobId } from './object-storage.ts'
241
243
  import { attachmentDisposition, openLines, sendJson, sendLines, writeResponse, writeResponseParts } from './http-response.ts'
242
244
  import { triageWireEntry } from './triage-response.ts'
@@ -262,7 +264,8 @@ import { DEPENDENCIES_LABEL, ISSUES_CURSOR, ISSUES_READ_VERSION, OPEN_PULLS_READ
262
264
  import { type DirectoryDependencies, type GithubAsked, type ListedLockfile, type LockfileRead, type LockfileStore, MAX_LOCKED, PULL_DEPENDENCIES_READ, type PullCommits,
263
265
  type PullDependencies,
264
266
  type PullDependencyStore, type PullRefs, lockfileFormat, pullDependenciesAt, pullKey, pullRefs } from './pull-dependencies.ts'
265
- import { eachOf } from './queue.ts'
267
+ import { eachOf, inTurns } from './queue.ts'
268
+ import { isBusy, notBusy } from './repository-risk-assess.ts'
266
269
  import { lockedAt, lockedIn, lockfilesAt } from './commit-lockfiles.ts'
267
270
  import { MAX_REQUIRED_REVIEWS, type PublishedReview, type RepoDependencyReview } from './repository-dependency-reviews.ts'
268
271
  import { EVERY_LOCKFILE, type LockfileScope, heldTo, isStasisConfig, reviewedIn, scopeOf, stasisConfigs } from './lockfile-scope.ts'
@@ -282,8 +285,8 @@ import { ISSUES_LIST_READ_VERSION, type IssueList, type Listed, PULLS_READ_VERSI
282
285
  import { AGENT_MARKS_READ } from './app-agents.ts'
283
286
  import { releaseCommits } from './release-commits.ts'
284
287
  import { bundleFileMeta, computeBundleDiff } from '../common/bundle-compare-diff.js'
285
- import type { ReviewChange, ReviewContext, ReviewInput, ReviewedTarballs } from './dependency-reviews.ts'
286
- import { allowedReviewVerdicts, isReviewableFile, npmReviewVerdictLimit, npmTakenDown } from '../common/dependency-reviews.js'
288
+ import type { DependencyReview, ReviewChange, ReviewContext, ReviewInput, ReviewedTarballs } from './dependency-reviews.ts'
289
+ import { MAX_PUBLISHED_REVIEWS, allowedReviewVerdicts, isReviewableFile, npmReviewVerdictLimit, npmTakenDown } from '../common/dependency-reviews.js'
287
290
  import { type NpmAdvisoryOptions, npmAdvisories, npmCommitTags, npmDownloads, npmGithubStats, npmKnown, npmLatestRepo, npmSocketReport } from './npm-insights.ts'
288
291
  import { npmProvenance } from './npm-provenance.ts'
289
292
  import { npmReadyScanDownload, npmReadyScanDownloads, npmRisk, npmRiskRemoved } from './npm-risk.ts'
@@ -376,10 +379,10 @@ const NPM_DELTAS_PATH = '/api/npm/deltas'
376
379
  const NPM_RISK_STATUS: Partial<Record<string, number>> = { 'package-not-found': 404, 'version-not-found': 404, 'package-too-large': 413, 'tarball-conflict': 422 }
377
380
  // A risk failure answered with its code alone, as risk's status for it (NPM_RISK_STATUS, else 502), its cause
378
381
  // logged where it is the server's or npm's, not the reader's (a 5xx), for the logs to say why.
379
- function sendRiskError(res: ServerResponse, err: NpmRiskError) {
382
+ function riskRefusal(err: NpmRiskError): Refusal {
380
383
  const status = NPM_RISK_STATUS[err.code] ?? 502
381
384
  if (status >= 500) console.error(`managed: npm risk failed (${err.code}):`, err.message)
382
- sendJson(res, status, { error: err.code })
385
+ return refusal(status, err.code)
383
386
  }
384
387
  const NPM_PATHS = new Set([NPM_PACKAGE_PATH, NPM_VERSIONS_PATH, NPM_DOWNLOAD_PATH, NPM_STATS_PATH, NPM_ADVISORIES_PATH, NPM_TAGS_PATH, NPM_SOCKET_PATH, NPM_PROVENANCE_PATH, NPM_PRETTY_PATH,
385
388
  NPM_RENAME_DIFF_PATH, NPM_TYPE_ONLY_PATH, NPM_RISK_PATH, NPM_COMPARISON_PATH, NPM_DELTA_PATH])
@@ -959,11 +962,16 @@ async function handleListRepositories(req: IncomingMessage, res: ServerResponse,
959
962
  if (scope === 'connected') {
960
963
  const reviews = await deps.db.listRepoDependencyReviews()
961
964
  const reviewTeams = await deps.db.listRepoReviewTeams()
965
+ // The teams each repository is in, whole or by a directory, by name and
966
+ // with their icons, as the sidebar shows them: but a hidden one, which grants nothing.
967
+ const teams = Map.groupBy((await deps.db.listTeams()).filter(team => !team.hidden)
968
+ .flatMap(({ id, name, icon, repos }) => [...new Set(repos.map(link => link.repoId))].map(repoId => ({ repoId, team: { id, name, ...icon ? { icon } : {} } }))), entry => entry.repoId)
962
969
  repositories = allRows.map((r) => ({
963
970
  id: r.repoId, fullName: r.fullName, private: r.private, htmlUrl: r.htmlUrl,
964
971
  installed: r.installationId != null, selected: r.active, active: r.active,
965
972
  dependencyReview: reviews.get(r.repoId) ?? { enabled: false, required: 1, since: null, lockfiles: EVERY_LOCKFILE },
966
973
  reviewTeams: reviewTeams.get(r.repoId) ?? [],
974
+ teams: (teams.get(r.repoId) ?? []).map(entry => entry.team),
967
975
  }))
968
976
  } else {
969
977
  const showAll = scope === 'installed' && url.searchParams.get('showAll') === 'true'
@@ -3770,6 +3778,10 @@ function scanProgress(deps: ManagedHttpDeps, key: string, scan: string | null) {
3770
3778
  // own access. The reader leaving, losing what let them read it or the
3771
3779
  // server shutting down stops it. With `kept=1`, as a scan's first part asks,
3772
3780
  // what is kept of its last for the reader is told first (keptRepositories).
3781
+ // Who dismissed a scan's Dependabot line's alerts, by login, for the page
3782
+ // to name them as the app does (withLineUsers).
3783
+ const dismissersOf = (line: RepositoryRiskLine) => line.type === 'dependabot' && 'alerts' in line ? line.alerts.flatMap(alert => alert.dismissed?.by ? [alert.dismissed.by] : []) : []
3784
+
3773
3785
  async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
3774
3786
  if (!['1', null].includes(query.get('kept'))) { sendJson(res, 400, { error: 'bad-request' }); return }
3775
3787
  const s = await readRiskSession(res, deps, cookie, query, { handed: true })
@@ -3886,7 +3898,7 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3886
3898
  },
3887
3899
  }, controller.signal, undefined, { partMs: deps.config.serverless ? REPO_RISK_PART_MS : null, kept: query.get('kept') === '1' })
3888
3900
  let checked = Date.now()
3889
- await sendLines(res, lines, async () => {
3901
+ await sendLines(res, withLineUsers(deps.db, lines, dismissersOf), async () => {
3890
3902
  if (deps.isShuttingDown()) return false
3891
3903
  if (Date.now() - checked < REPO_RISK_RECHECK_MS) return true
3892
3904
  const current = await readSession(deps.config, deps.db, cookie, Date.now())
@@ -5338,21 +5350,18 @@ async function readableNpmReviews<T extends ReviewContext>(res: ServerResponse,
5338
5350
  const onClose = () => { if (!res.writableEnded) controller.abort() }
5339
5351
  res.on('close', onClose)
5340
5352
  try {
5341
- const names = reviews.flatMap(review => [review.package, ...review.basePackage ? [review.basePackage] : []])
5342
- const reader = await npmReaderOf(deps, session, names)
5353
+ const reader = await npmReaderOf(deps, session, reviewedNames(reviews))
5343
5354
  if (!reader || reader.userId !== user) { sendJson(res, 401, { error: 'unauthenticated' }); return null }
5344
5355
  // Public versions' documents as the viewer keeps them (npm-kept.ts), a
5345
5356
  // day, all read of the database at once: a list asks npm for none it read
5346
5357
  // within it. Each version once, as many at once as REVIEW_READS_AT_ONCE.
5347
5358
  const versionsOf = (review: T) => [[review.package, review.version], ...review.basePackage ? [[review.basePackage, review.baseVersion!]] : []] as [string, string][]
5348
5359
  const asked = new Map(reviews.flatMap(versionsOf).map(([name, version]) => [`${name}\0${version}`, [name, version] as const]))
5349
- const store = npmVersionStore(deps.db, deps.config.debug)
5350
- const held = await store.readMany?.([...asked.values()].map(([name, version]) => ({ name, version }))) ?? new Map()
5351
- const kept: NpmVersionStore = { read: (name, version) => Promise.resolve(held.get(`${name}@${version}`) ?? null), write: store.write }
5360
+ const kept = reviewedKept(deps, reviews)
5352
5361
  const read = await eachOf([...asked], REVIEW_READS_AT_ONCE, ([, [name, version]]) => readNpmVersion(name, version, canReadPrivateNpm(reader, name), controller.signal, kept))
5353
5362
  const documents = new Map([...asked.keys()].map((key, at) => [key, read[at] ?? null]))
5354
5363
  const packages = reviews.map(review => versionsOf(review).map(([name, version]) => documents.get(`${name}\0${version}`) ?? null))
5355
- const current = teamId === undefined ? await npmReader(deps, cookie, packages.flat().flatMap(doc => doc?.private ? [doc.name] : []))
5364
+ const current = teamId === undefined ? await npmReader(deps, cookie, privateNames(packages.flat()))
5356
5365
  : await npmReviewReader(deps, cookie, teamId)
5357
5366
  if (!current || current.userId !== user) { sendJson(res, 401, { error: 'unauthenticated' }); return null }
5358
5367
  if ('readsTeam' in current && !current.readsTeam) { sendJson(res, 404, { error: 'no-team' }); return null }
@@ -5388,30 +5397,28 @@ async function npmReviewPublicationLimit(deps: ManagedHttpDeps, reader: NpmReade
5388
5397
  () => ensureUserAccessToken(deps.config, deps.db, reader.userId, Date.now()).catch(() => null),
5389
5398
  () => readNpmVersion(doc.name, 'latest', privileged, signal)))
5390
5399
  }
5391
- const [list, socket, risk] = await Promise.all([advisories().catch(() => null), doc.private ? null : npmSocketReport(doc.name, doc.version).catch(() => null),
5400
+ // 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 }),
5402
+ doc.private ? null : npmSocketReport(doc.name, doc.version).catch(() => null),
5392
5403
  npmRisk(doc, null, { db: deps.db, npmCache: deps.npmCacheStorage, debug: deps.config.debug, teamScoped: true, privileged, signal })])
5393
5404
  return npmReviewVerdictLimit(doc, list, socket, risk)
5394
5405
  }
5395
5406
 
5396
5407
  // The change a POST of reviews asks for, as its `body` names it: a review
5397
- // started, an entry saved, a set published, continued or revoked. Null,
5398
- // answered 400, where it names none.
5399
- function reviewChange(res: ServerResponse, body: Record<string, unknown>): ReviewChange | null {
5408
+ // started, an entry saved, a set published, continued or revoked; else why
5409
+ // not, as a 400 tells it.
5410
+ function reviewChange(body: Record<string, unknown>): ReviewChange | string {
5400
5411
  const action = body['action'], reviewId = body['reviewId'] ?? null, revision = body['revision'] ?? null
5401
5412
  if (typeof action !== 'string' || !['start', 'save', 'publish', 'continue', 'revoke'].includes(action)
5402
5413
  || (reviewId !== null && (typeof reviewId !== 'string' || reviewId.length === 0 || reviewId.length > 100 || !Number.isSafeInteger(revision) || Number(revision) < 1))
5403
- || (!['save', 'start'].includes(action) && reviewId === null) || (action === 'start' && reviewId !== null)) { sendJson(res, 400, { error: 'bad-review' }); return null }
5414
+ || (!['save', 'start'].includes(action) && reviewId === null) || (action === 'start' && reviewId !== null)) return 'bad-review'
5404
5415
  if (action === 'start') return { action, reviewId: null, revision: null }
5405
5416
  if (action === 'publish') {
5406
5417
  const teamIds = body['teamIds']
5407
- if (!Array.isArray(teamIds) || teamIds.length === 0 || teamIds.length > 100 || teamIds.some(id => typeof id !== 'string' || id.length > 100)) {
5408
- sendJson(res, 400, { error: 'bad-review-teams' }); return null
5409
- }
5418
+ if (!Array.isArray(teamIds) || teamIds.length === 0 || teamIds.length > 100 || teamIds.some(id => typeof id !== 'string' || id.length > 100)) return 'bad-review-teams'
5410
5419
  const finalComment = body['finalComment'] ?? '', finalStatus = body['finalStatus'] ?? null
5411
5420
  if (typeof finalComment !== 'string' || finalComment.length > 20000 || finalStatus !== null
5412
- && (typeof finalStatus !== 'string' || !['accept', 'accept-with-nits', 'request-changes', 'reject'].includes(finalStatus))) {
5413
- sendJson(res, 400, { error: 'bad-final-verdict' }); return null
5414
- }
5421
+ && (typeof finalStatus !== 'string' || !['accept', 'accept-with-nits', 'request-changes', 'reject'].includes(finalStatus))) return 'bad-final-verdict'
5415
5422
  return { action, reviewId: reviewId as string, revision: revision as number, teamIds, files: [], nonTextFiles: [],
5416
5423
  final: finalStatus === null ? null : { status: finalStatus as ReviewInput['status'] & string, comment: finalComment } }
5417
5424
  }
@@ -5423,32 +5430,25 @@ function reviewChange(res: ServerResponse, body: Record<string, unknown>): Revie
5423
5430
  if (typeof file !== 'string' || !file || file.length > 4096 || file.includes('\0')
5424
5431
  || (entryId !== null && (typeof entryId !== 'string' || entryId.length === 0 || entryId.length > 100))
5425
5432
  || typeof comment !== 'string' || comment.length > 20000
5426
- || (status !== null && (typeof status !== 'string' || !['accept', 'accept-with-nits', 'request-changes', 'reject'].includes(status))) || (status === null && entryId === null)) {
5427
- sendJson(res, 400, { error: 'bad-review' }); return null
5428
- }
5433
+ || (status !== null && (typeof status !== 'string' || !['accept', 'accept-with-nits', 'request-changes', 'reject'].includes(status))) || (status === null && entryId === null)) return 'bad-review'
5429
5434
  return { action: 'save', reviewId: reviewId as string | null, revision: revision as number | null, entryId: entryId as string | null,
5430
5435
  entry: { file, comment, status: status as ReviewInput['status'] } }
5431
5436
  }
5432
5437
 
5433
- // Reviews are scoped to the bytes actually displayed, including the base:
5434
- // each change but a revocation loads both versions' files, of tarballs held
5435
- // to their integrity and to their shasum where npm tells one (npm-loads.ts),
5436
- // and the review keeps those shasums. A patched version's (`patchHash`) are
5437
- // its files as its patch changes them, the patch read as kept, else where the
5438
- // request says (`patchRepoId`, `patchCommit`, `patchPath`), of the whole of a
5439
- // repository its reader reads (npmPatchOf), the review keeping where it was
5440
- // read; and a patched base's (`basePatchHash`) as its patch, kept, changes
5441
- // them. Access to both versions is rechecked before returning or saving annotations.
5442
- async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, params: URLSearchParams): Promise<void> {
5443
- const method = req.method ?? 'GET'
5444
- if (!['GET', 'POST'].includes(method)) { send405(res, 'GET, POST'); return }
5445
- const mutation = method !== 'GET'
5446
- const session = mutation ? await checkMutation(req, res, deps, cookie, { handed: true }) : await readSession(deps.config, deps.db, cookie, Date.now(), { handed: true })
5447
- if (!session) { if (!mutation) sendJson(res, 401, { error: 'unauthenticated' }); return }
5448
- if (!roleAtLeast(session.user.role, mutation ? 'triage' : 'view')) { sendJson(res, 403, { error: 'forbidden' }); return }
5449
- const body: Record<string, unknown> | null = mutation ? await readBodyObject(req, res, 128 * 1024) : {}
5450
- if (!body) return
5451
- const field = (key: string) => mutation ? body[key] : params.get(key)
5438
+ // An npm failure as a review request is refused for it: npm's own, or
5439
+ // risk's (riskRefusal); any other thrown on.
5440
+ function npmRefusal(err: unknown): Refusal {
5441
+ if (err instanceof NpmPackageError) return refusal(err.status, err.message)
5442
+ if (err instanceof NpmRiskError) return riskRefusal(err)
5443
+ throw err
5444
+ }
5445
+
5446
+ // The versions a review is of, as a request names them (`field`, a body's or
5447
+ // a query's): the reviewed version, its patch (`patchHash`, where it is named
5448
+ // with where that is: patchFields) and its base and the base's patch, where
5449
+ // it has one; null where any is not one.
5450
+ type ReviewAsked = { context: ReviewContext; patch: RequestedPatch | null }
5451
+ function reviewContextOf(field: (key: string) => unknown): ReviewAsked | null {
5452
5452
  const name = field('package')
5453
5453
  const version = field('version')
5454
5454
  const integrity = field('integrity')
@@ -5457,98 +5457,243 @@ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps:
5457
5457
  const baseIntegrity = field('baseIntegrity') ?? null
5458
5458
  const patchHash = field('patchHash') ?? null
5459
5459
  const basePatchHash = field('basePatchHash') ?? null
5460
- // Where its patch is, where it names that: its hash alone where only listed.
5461
5460
  const patch = patchFields(field)
5462
5461
  const validIntegrity = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && value.length <= 1024
5463
5462
  if (field('ecosystem') !== 'npm' || !isNpmPackageName(name) || !isNpmPackageSpec(version) || !validIntegrity(integrity)
5464
5463
  || (basePackage !== null || baseVersion !== null || baseIntegrity !== null)
5465
5464
  && (!isNpmPackageName(basePackage) || !isNpmPackageSpec(baseVersion) || !validIntegrity(baseIntegrity))
5466
- || (patchHash !== null && !isPatchHash(patchHash)) || patch === 'invalid' || (basePatchHash !== null && (!isPatchHash(basePatchHash) || basePackage === null))) {
5467
- sendJson(res, 400, { error: 'bad-review-context' }); return
5468
- }
5469
- const context: ReviewContext = { ecosystem: 'npm', package: name, version, integrity, patchHash: patchHash as string | null,
5465
+ || (patchHash !== null && !isPatchHash(patchHash)) || patch === 'invalid' || (basePatchHash !== null && (!isPatchHash(basePatchHash) || basePackage === null))) return null
5466
+ return { patch, context: { ecosystem: 'npm', package: name, version, integrity, patchHash: patchHash as string | null,
5470
5467
  basePackage: basePackage as string | null, baseVersion: baseVersion as string | null, baseIntegrity: baseIntegrity as string | null,
5471
- basePatchHash: basePatchHash as string | null }
5472
- let change: ReviewChange | null = null
5473
- if (mutation) {
5474
- change = reviewChange(res, body)
5475
- if (!change) return
5476
- // Each change but a revocation reads a patched version's patch.
5477
- if (patchHash !== null && change.action !== 'revoke' && !patch) { sendJson(res, 400, { error: 'bad-review-context' }); return }
5478
- }
5479
- const controller = new AbortController()
5480
- const onClose = () => { if (!res.writableEnded) controller.abort() }
5481
- res.on('close', onClose)
5468
+ basePatchHash: basePatchHash as string | null } }
5469
+ }
5470
+ // The change a POST's `fields` ask of the versions they name
5471
+ // (reviewContextOf, reviewChange), as a 400 tells why not: each change but a
5472
+ // revocation reads a patched version's patch, so one named by its hash alone,
5473
+ // not where it is, is none.
5474
+ type AskedChange = ReviewAsked & { change: ReviewChange }
5475
+ function askedChange(fields: Record<string, unknown>): AskedChange | string {
5476
+ const asked = reviewContextOf(key => fields[key])
5477
+ if (!asked) return 'bad-review-context'
5478
+ const change = reviewChange(fields)
5479
+ if (typeof change === 'string') return change
5480
+ return asked.context.patchHash !== null && change.action !== 'revoke' && !asked.patch ? 'bad-review-context' : { ...asked, change }
5481
+ }
5482
+ // The packages reviews of `contexts` are of, and their versions, read of the
5483
+ // store together (readTogether).
5484
+ const reviewedNames = (contexts: ReviewContext[]) => [...new Set(contexts.flatMap(context => [context.package, ...context.basePackage ? [context.basePackage] : []]))]
5485
+ const reviewedKept = (deps: ManagedHttpDeps, contexts: ReviewContext[]) => readTogether(npmVersionStore(deps.db, deps.config.debug),
5486
+ contexts.flatMap(({ package: name, version, basePackage, baseVersion }) => [{ name, version }, ...basePackage ? [{ name: basePackage, version: baseVersion! }] : []]))
5487
+ // The private ones of `docs`, by name, as their reader's access is asked again.
5488
+ const privateNames = (docs: (NpmVersionDocument | null)[]) => docs.flatMap(doc => doc?.private ? [doc.name] : [])
5489
+
5490
+ // Both versions a review of `context` is of, as `reader` reads npm, of the
5491
+ // store `kept`, each as npm has it at the integrity the review names: else
5492
+ // why not.
5493
+ async function reviewedVersions(reader: NpmReader, context: ReviewContext, kept: NpmVersionStore, signal: AbortSignal):
5494
+ Promise<{ doc: NpmVersionDocument; base: NpmVersionDocument | null } | Refusal> {
5495
+ const { package: name, version, integrity, basePackage, baseVersion, baseIntegrity } = context
5496
+ const read = (pkg: string, spec: string) => readNpmVersion(pkg, spec, canReadPrivateNpm(reader, pkg), signal, kept)
5497
+ const [doc, base] = await Promise.all([read(name, version), basePackage ? read(basePackage, baseVersion!) : null])
5498
+ if (!doc || (basePackage && !base)) return refusal(404, 'package-not-found')
5499
+ if (doc.version !== version || doc.dist.integrity !== integrity || (base && (base.version !== baseVersion || base.dist.integrity !== baseIntegrity))) {
5500
+ return refusal(409, 'review-content-changed')
5501
+ }
5502
+ return { doc, base: base ?? null }
5503
+ }
5504
+
5505
+ // A change of a review (askedChange) by `reader`, worked out before it is
5506
+ // made: reviews are scoped to the bytes actually displayed, including the
5507
+ // base, so each change but a revocation loads both versions' files, of
5508
+ // tarballs held to their integrity and to their shasum where npm tells one
5509
+ // (npm-loads.ts), the review keeping those shasums; a save names a file they
5510
+ // change, and a publication holds to every one they change. A patched
5511
+ // version's (`patchHash`) are its files as its patch changes them, the patch
5512
+ // read as kept, else where the request says (of the whole of a repository its
5513
+ // reader reads: npmPatchOf), the review keeping where it was read; and a
5514
+ // patched base's (`basePatchHash`) as its patch, kept, changes them. A
5515
+ // 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.
5521
+ type PreparedChange = { privates: string[]; commit(sessionId: string, current: NpmReader): Promise<Refusal | { review: DependencyReview }> }
5522
+ const INTERACTIVE_BUSY_RETRIES = 3
5523
+ 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> {
5526
+ // What it asks given up where it is refused before it is worked out.
5527
+ const own = new AbortController()
5528
+ const asking = AbortSignal.any([signal, own.signal])
5529
+ let prepared = false
5482
5530
  try {
5483
- const reader = await npmReader(deps, cookie, [context.package, ...context.basePackage ? [context.basePackage] : []])
5484
- if (!reader || reader.userId !== session.user.id) { sendJson(res, 401, { error: 'unauthenticated' }); return }
5485
- const kept = readTogether(npmVersionStore(deps.db, deps.config.debug), [{ name, version }, ...context.basePackage ? [{ name: context.basePackage, version: context.baseVersion! }] : []])
5486
- const read = (pkg: string, spec: string) => readNpmVersion(pkg, spec, canReadPrivateNpm(reader, pkg), controller.signal, kept)
5487
- const [doc, base] = await Promise.all([read(name, version), context.basePackage ? read(context.basePackage, context.baseVersion!) : null])
5488
- if (!doc || (context.basePackage && !base)) { sendJson(res, 404, { error: 'package-not-found' }); return }
5489
- if (doc.version !== version || doc.dist.integrity !== integrity
5490
- || (base && (base.version !== baseVersion || base.dist.integrity !== baseIntegrity))) {
5491
- sendJson(res, 409, { error: 'review-content-changed' }); return
5492
- }
5493
- // Each change but a revocation loads both versions' files, and a patched
5494
- // one's patch; a save or a publication is held to them.
5495
- const reading = change && change.action !== 'revoke'
5496
- const patchRead = reading && patch ? await npmPatchOf(deps, cookie, patch) : null
5497
- if (patchRead && 'error' in patchRead) { sendRefusal(res, patchRead); return }
5498
- const basePatchRead = reading && basePatchHash ? await npmPatchOf(deps, cookie, { hash: basePatchHash as string }) : null
5499
- if (basePatchRead && 'error' in basePatchRead) { sendRefusal(res, basePatchRead); return }
5500
- const loads = reading ? [doc, ...base ? [base] : []].map(loadNpmFiles) : []
5501
- let tarballs: ReviewedTarballs | undefined
5502
- try {
5503
- const files = await Promise.all(loads.map(load => load.result))
5504
- if (loads.length > 0) {
5505
- tarballs = { shasum: doc.dist.shasum, baseShasum: base?.dist.shasum ?? null, ...patchRead ? { patch: patchRead.source } : {} }
5506
- }
5507
- if (change?.action === 'publish' || change?.action === 'save') {
5508
- const patchOf = [patchRead, basePatchRead]
5509
- const lists = files.map((list, at) => patchOf[at] ? patchedFiles(list, patchOf[at].files) : list)
5531
+ const versions = await reviewedVersions(reader, context, kept, asking)
5532
+ if ('error' in versions) return versions
5533
+ const { doc, base } = versions
5534
+ const docs = [doc, ...base ? [base] : []]
5535
+ const limiting = change.action === 'publish' && change.final && change.final.status !== 'reject'
5536
+ ? heavy(() => npmReviewPublicationLimit(deps, reader, doc, asking)) : Promise.resolve('accept' as const)
5537
+ limiting.catch(() => {})
5538
+ const reading = change.action !== 'revoke'
5539
+ const [patchRead, basePatchRead] = await Promise.all([reading && patch ? npmPatchOf(deps, cookie, patch) : null,
5540
+ reading && context.basePatchHash ? npmPatchOf(deps, cookie, { hash: context.basePatchHash }) : null])
5541
+ if (patchRead && 'error' in patchRead) return patchRead
5542
+ if (basePatchRead && 'error' in basePatchRead) return basePatchRead
5543
+ // Both versions' files, as their patches change them, and the paths they change.
5544
+ const pair = async () => {
5545
+ const loads = docs.map(loadNpmFiles)
5546
+ try {
5547
+ const lists = (await Promise.all(loads.map(load => load.result))).map((list, at) => {
5548
+ const read = [patchRead, basePatchRead][at]
5549
+ return read ? patchedFiles(list, read.files) : list
5550
+ })
5510
5551
  const maps = lists.map(list => new Map<string, unknown>(npmFileRows(list).map(([path, size, text, digest]) => [path, text ?? { format: 'digest', size, digest }])))
5511
5552
  // A file made executable or not is one changed, as Compare shows it.
5512
5553
  const modes = lists.map(list => bundleFileMeta({ npmExecutable: new Set(npmExecutablePaths(list)) }))
5513
5554
  const after = maps[0]!, before = maps[1] ?? new Map<string, unknown>()
5514
- const diff = computeBundleDiff(before, after, () => '.', undefined, [modes[1] ?? null, modes[0]!])
5515
- const changed: { path: string; basePath?: string }[] = [...diff.files.onlyBase, ...diff.files.onlyOther, ...diff.files.changed]
5516
- const reviewable = (file: typeof changed[number]) => isReviewableFile(before.get(file.basePath ?? file.path), after.get(file.path))
5517
- const reviewedPath = change.action === 'save' ? change.entry.file : null
5518
- const reviewedFile = changed.find(file => file.path === reviewedPath)
5519
- if (change.action === 'save' && !reviewedFile) { sendJson(res, 400, { error: 'unknown-review-file' }); return }
5520
- if (change.action === 'save' && change.entry.status !== null && reviewedFile && !reviewable(reviewedFile)) { sendJson(res, 400, { error: 'non-text-review-file' }); return }
5521
- if (change.action === 'publish') {
5522
- change.files = changed.map(file => file.path)
5523
- change.nonTextFiles = changed.filter(file => !reviewable(file)).map(file => file.path)
5555
+ const { files } = computeBundleDiff(before, after, () => '.', undefined, [modes[1] ?? null, modes[0]!])
5556
+ const changed: { path: string; basePath?: string }[] = [...files.onlyBase, ...files.onlyOther, ...files.changed]
5557
+ return changed.map(file => ({ path: file.path, text: isReviewableFile(before.get(file.basePath ?? file.path), after.get(file.path)) }))
5558
+ } finally { loads.forEach(load => load.release()) }
5559
+ }
5560
+ const changed = reading ? await heavy(pair) : []
5561
+ if (change.action === 'save') {
5562
+ const file = changed.find(each => each.path === change.entry.file)
5563
+ if (!file) return refusal(400, 'unknown-review-file')
5564
+ if (change.entry.status !== null && !file.text) return refusal(400, 'non-text-review-file')
5565
+ }
5566
+ if (change.action === 'publish') {
5567
+ change.files = changed.map(file => file.path)
5568
+ change.nonTextFiles = changed.flatMap(file => file.text ? [] : [file.path])
5569
+ }
5570
+ const tarballs: ReviewedTarballs | undefined = reading ? { shasum: doc.dist.shasum, baseShasum: base?.dist.shasum ?? null, ...patchRead ? { patch: patchRead.source } : {} }
5571
+ : undefined
5572
+ const limit = await limiting
5573
+ const privates = privateNames(docs)
5574
+ prepared = true
5575
+ return {
5576
+ privates,
5577
+ async commit(sessionId, current) {
5578
+ if (current.userId !== reader.userId || !roleAtLeast(current.role, 'triage')) return refusal(403, 'forbidden')
5579
+ if (privates.some(name => !canReadPrivateNpm(current, name))) return refusal(404, 'package-not-found')
5580
+ if (change.action === 'publish' && change.final && !allowedReviewVerdicts([], limit).includes(change.final.status)) {
5581
+ return refusal(400, limit === 'reject' ? 'review-malware' : 'review-critical-vulnerability')
5524
5582
  }
5525
- }
5526
- } finally { loads.forEach(load => load.release()) }
5527
- const limit = change?.action === 'publish' && change.final && change.final.status !== 'reject'
5528
- ? await npmReviewPublicationLimit(deps, reader, doc, controller.signal) : 'accept'
5529
- const current = await npmReader(deps, cookie, [doc, base].flatMap(item => item?.private ? [item.name] : []))
5530
- if (!current || current.userId !== session.user.id) { sendJson(res, 401, { error: 'unauthenticated' }); return }
5531
- if ([doc, base].some(item => item?.private && !canReadPrivateNpm(current, item.name))) { sendJson(res, 404, { error: 'package-not-found' }); return }
5532
- if (!change) {
5533
- const allBases = params.get('allBases') === 'true'
5534
- const rows = await deps.db.listDependencyReviews(context, current.userId, allBases)
5535
- const reviews = allBases ? await readableNpmReviews(res, deps, cookie, current.userId, rows, { id: current.userId, role: current.role }) : rows
5536
- if (reviews) sendJson(res, 200, { reviews: await withFormatted(deps.reviewedDependencies ?? null, current.userId, reviews), teams: await deps.db.listDependencyReviewTeams(current.userId) })
5583
+ try { return { review: await deps.db.changeDependencyReview(context, sessionId, change, Date.now(), tarballs) } }
5584
+ catch (err) {
5585
+ if (err instanceof ManagedMutationError) return refusal(err.status, err.message)
5586
+ throw err
5587
+ }
5588
+ },
5589
+ }
5590
+ } catch (err) { return npmRefusal(err) }
5591
+ finally { if (!prepared) own.abort() }
5592
+ }
5593
+
5594
+ // GET /api/npm/reviews: the reviews of the versions a query names
5595
+ // (reviewContextOf), those of every base with `allBases`, as the reader
5596
+ // reads them, and the teams they publish to; POST: a change of them
5597
+ // (askedChange, preparedReviewChange), the session checked again before it
5598
+ // is made. Access to both versions is rechecked before returning or saving.
5599
+ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, params: URLSearchParams): Promise<void> {
5600
+ const method = req.method ?? 'GET'
5601
+ if (!['GET', 'POST'].includes(method)) { send405(res, 'GET, POST'); return }
5602
+ const mutation = method !== 'GET'
5603
+ const session = mutation ? await checkMutation(req, res, deps, cookie, { handed: true }) : await readSession(deps.config, deps.db, cookie, Date.now(), { handed: true })
5604
+ if (!session) { if (!mutation) sendJson(res, 401, { error: 'unauthenticated' }); return }
5605
+ if (!roleAtLeast(session.user.role, mutation ? 'triage' : 'view')) { sendJson(res, 403, { error: 'forbidden' }); return }
5606
+ const body: Record<string, unknown> | null = mutation ? await readBodyObject(req, res, 128 * 1024) : {}
5607
+ if (!body) return
5608
+ const asked: AskedChange | (ReviewAsked & { change?: undefined }) | string = mutation ? askedChange(body) : reviewContextOf(key => params.get(key)) ?? 'bad-review-context'
5609
+ if (typeof asked === 'string') { sendJson(res, 400, { error: asked }); return }
5610
+ const { context } = asked
5611
+ const controller = new AbortController()
5612
+ const onClose = () => { if (!res.writableEnded) controller.abort() }
5613
+ res.on('close', onClose)
5614
+ try {
5615
+ // Of a reader whose role was read just now.
5616
+ const reader = (await npmReaderOf(deps, session.user, reviewedNames([context])))!
5617
+ const kept = reviewedKept(deps, [context])
5618
+ if (asked.change) {
5619
+ const prepared = await preparedReviewChange(deps, cookie, reader, asked, kept, controller.signal)
5620
+ if (controller.signal.aborted) return
5621
+ if ('error' in prepared) { sendRefusal(res, prepared); return }
5622
+ const checked = await checkMutation(req, res, deps, cookie)
5623
+ if (!checked) return
5624
+ const current = await npmReaderOf(deps, checked.user, prepared.privates)
5625
+ if (!current) { sendJson(res, 401, { error: 'unauthenticated' }); return }
5626
+ const done = await prepared.commit(checked.session.id, current)
5627
+ if ('error' in done) sendRefusal(res, done)
5628
+ else sendJson(res, 200, { review: (await withFormatted(deps.reviewedDependencies ?? null, current.userId, [done.review]))[0] })
5537
5629
  return
5538
5630
  }
5631
+ const versions = await reviewedVersions(reader, context, kept, controller.signal).catch(npmRefusal)
5632
+ if ('error' in versions) { if (!controller.signal.aborted) sendRefusal(res, versions); return }
5633
+ // Its access asked again, as it may have been taken while npm was read.
5634
+ const privates = privateNames([versions.doc, versions.base])
5635
+ const current = await npmReader(deps, cookie, privates)
5636
+ if (!current || current.userId !== session.user.id) { sendJson(res, 401, { error: 'unauthenticated' }); return }
5637
+ if (privates.some(name => !canReadPrivateNpm(current, name))) { sendJson(res, 404, { error: 'package-not-found' }); return }
5638
+ const allBases = params.get('allBases') === 'true'
5639
+ const rows = await deps.db.listDependencyReviews(context, current.userId, allBases)
5640
+ const reviews = allBases ? await readableNpmReviews(res, deps, cookie, current.userId, rows, { id: current.userId, role: current.role }) : rows
5641
+ if (reviews) sendJson(res, 200, { reviews: await withFormatted(deps.reviewedDependencies ?? null, current.userId, reviews), teams: await deps.db.listDependencyReviewTeams(current.userId) })
5642
+ } catch (err) {
5643
+ // Its reader gone, answered none.
5644
+ if (!controller.signal.aborted) throw err
5645
+ } finally { res.off('close', onClose) }
5646
+ }
5647
+
5648
+ // POST /api/npm/reviews/publish: drafts published together, as a pull
5649
+ // request's versions are, each as POST /api/npm/reviews publishes one
5650
+ // (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
5658
+ const HEAVY_AT_ONCE = 2
5659
+ async function handlePublishNpmReviews(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
5660
+ if (req.method !== 'POST') { send405(res, 'POST'); return }
5661
+ const session = await checkMutation(req, res, deps, cookie, { handed: true })
5662
+ if (!session) return
5663
+ if (!roleAtLeast(session.user.role, 'triage')) { sendJson(res, 403, { error: 'forbidden' }); return }
5664
+ const body = await readBodyObject(req, res, 8 * 1024 * 1024)
5665
+ if (!body) return
5666
+ const listed = body['reviews']
5667
+ if (!Array.isArray(listed) || listed.length === 0 || listed.length > MAX_PUBLISHED_REVIEWS) { sendJson(res, 400, { error: 'bad-review' }); return }
5668
+ const asked: AskedChange[] = []
5669
+ for (const [at, item] of listed.entries()) {
5670
+ const one = plainObject(item) ? askedChange({ ...item, action: 'publish' }) : 'bad-review-context'
5671
+ if (typeof one === 'string') { sendJson(res, 400, { error: one, at }); return }
5672
+ asked.push(one)
5673
+ }
5674
+ const controller = new AbortController()
5675
+ const onClose = () => { if (!res.writableEnded) controller.abort() }
5676
+ res.on('close', onClose)
5677
+ try {
5678
+ const contexts = asked.map(one => one.context)
5679
+ // Of a reader whose role was read just now.
5680
+ const reader = (await npmReaderOf(deps, session.user, reviewedNames(contexts)))!
5681
+ const kept = reviewedKept(deps, contexts)
5682
+ 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))
5685
+ if (controller.signal.aborted) return
5539
5686
  const checked = await checkMutation(req, res, deps, cookie)
5540
5687
  if (!checked) return
5541
- if (checked.user.id !== current.userId || !roleAtLeast(checked.user.role, 'triage')) { sendJson(res, 403, { error: 'forbidden' }); return }
5542
- if (change.action === 'publish' && change.final && !allowedReviewVerdicts([], limit).includes(change.final.status)) {
5543
- sendJson(res, 400, { error: limit === 'reject' ? 'review-malware' : 'review-critical-vulnerability' }); return
5544
- }
5545
- const review = await deps.db.changeDependencyReview(context, checked.session.id, change, Date.now(), tarballs)
5546
- sendJson(res, 200, { review: (await withFormatted(deps.reviewedDependencies ?? null, current.userId, [review]))[0] })
5688
+ const current = await npmReaderOf(deps, checked.user, prepared.flatMap(one => 'error' in one ? [] : one.privates))
5689
+ if (!current) { sendJson(res, 401, { error: 'unauthenticated' }); return }
5690
+ const done: (Refusal | { review: DependencyReview })[] = []
5691
+ for (const one of prepared) done.push('error' in one ? one : await one.commit(checked.session.id, current))
5692
+ const formatted = await withFormatted(deps.reviewedDependencies ?? null, current.userId, done.flatMap(one => 'error' in one ? [] : [one.review]))
5693
+ let next = 0
5694
+ sendJson(res, 200, { results: done.map(one => 'error' in one ? { error: one.error, status: one.status } : { review: formatted[next++] }) })
5547
5695
  } catch (err) {
5548
- if (controller.signal.aborted) return
5549
- if (err instanceof NpmPackageError) { sendJson(res, err.status, { error: err.message }); return }
5550
- if (err instanceof NpmRiskError) { sendRiskError(res, err); return }
5551
- throw err
5696
+ if (!controller.signal.aborted) throw err
5552
5697
  } finally { res.off('close', onClose) }
5553
5698
  }
5554
5699
 
@@ -5919,7 +6064,7 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
5919
6064
  writeResponse(res, Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength))
5920
6065
  } catch (err) {
5921
6066
  if (err instanceof NpmPackageError || err instanceof PrettyError) { if (!res.headersSent && !res.destroyed) sendJson(res, err.status, { error: err.message }); return }
5922
- if (err instanceof NpmRiskError) { if (!res.headersSent && !res.destroyed) sendRiskError(res, err); return }
6067
+ if (err instanceof NpmRiskError) { if (!res.headersSent && !res.destroyed) sendRefusal(res, riskRefusal(err)); return }
5923
6068
  if (controller.signal.aborted) return
5924
6069
  throw err
5925
6070
  } finally {
@@ -6421,6 +6566,9 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
6421
6566
  if (reviews) sendJson(res, 200, { ...page, reviews })
6422
6567
  return
6423
6568
  }
6569
+ if (path === '/api/npm/reviews/publish') {
6570
+ await handlePublishNpmReviews(req, res, deps, cookie); return
6571
+ }
6424
6572
  if (path === '/api/npm/reviews') {
6425
6573
  await handleNpmReviews(req, res, deps, cookie, url.searchParams); return
6426
6574
  }