@preventive/triage 1.0.0-alpha.71 → 1.0.0-alpha.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/common/bundle-sources.d.ts +2 -0
- package/common/bundle-sources.js +19 -2
- package/common/finding-duplicates.js +5 -0
- package/common/finding-filters.js +45 -4
- package/common/line-diff.d.ts +2 -2
- package/common/line-diff.js +20 -8
- package/common/managed/finding-detail.js +1 -1
- package/common/managed/review-view-routes.js +23 -0
- package/common/managed/risk-routes.js +30 -0
- package/common/managed/routes.js +11 -6
- package/common/managed/team-app.d.ts +8 -6
- package/common/managed/team-app.js +15 -3
- package/common/stasis-files.d.ts +5 -0
- package/common/stasis-files.js +20 -0
- package/common/stasis-tgz.d.ts +6 -0
- package/common/stasis-tgz.js +27 -0
- package/common/workspace-app.js +20 -0
- package/out/activity.js +2 -4
- package/out/{chunk-2F3CYNPZ.js → chunk-2IHCVA3Y.js} +1 -1
- package/out/{chunk-HAZKDK4M.js → chunk-2V6Q4ZOZ.js} +1 -1
- package/out/{chunk-RRBIJL2B.js → chunk-4IW3VD3H.js} +1 -1
- package/out/chunk-4YZOXAXR.js +2 -0
- package/out/chunk-5NUDNLJA.js +6 -0
- package/out/chunk-5YP7P5KA.js +1 -0
- package/out/chunk-6VOB5WXX.js +2 -0
- package/out/chunk-74JZTGTO.js +11 -0
- package/out/chunk-7YFJUT2P.js +1 -0
- package/out/chunk-A4BBBHQU.js +1 -0
- package/out/{chunk-4ISO5F7Y.js → chunk-ADMVRLNP.js} +1 -1
- package/out/chunk-BIWPZT4E.js +52 -0
- package/out/{chunk-HETCVNO4.js → chunk-BLPHP4U3.js} +1 -1
- package/out/{chunk-Y5ZHFNBD.js → chunk-BXQCCW7F.js} +1 -1
- package/out/{chunk-JFL7WLRV.js → chunk-CU3FPB3P.js} +1 -1
- package/out/chunk-CXVBTUK3.js +4 -0
- package/out/{chunk-M37X4LCF.js → chunk-EXQQ5VQJ.js} +1 -1
- package/out/{chunk-NXATZJQ2.js → chunk-GSNSP3EF.js} +1 -1
- package/out/chunk-GV5U7OLP.js +40 -0
- package/out/{chunk-JOXLZXMI.js → chunk-GX5UXWT4.js} +1 -1
- package/out/{chunk-YF4M5OCI.js → chunk-I6UQQKAH.js} +1 -1
- package/out/{chunk-UCP3JRE2.js → chunk-LVW7WWV4.js} +1 -1
- package/out/chunk-NEFCZAIY.js +11 -0
- package/out/{chunk-TOXMUOIW.js → chunk-OQS2USZM.js} +1 -1
- package/out/chunk-PQPKHAI5.js +15 -0
- package/out/chunk-PX5DLFSD.js +1 -0
- package/out/chunk-QBFT2DDR.js +1 -0
- package/out/{chunk-GZ46SSTF.js → chunk-RGNF4OH6.js} +1 -1
- package/out/chunk-RLLA4GHZ.js +1 -0
- package/out/chunk-ROHACH7V.js +3 -0
- package/out/chunk-ROWUGPID.js +1 -0
- package/out/{chunk-QMVOEBWC.js → chunk-S2ZIKK45.js} +1 -1
- package/out/chunk-SSPDMA6D.js +1 -0
- package/out/chunk-TD7RVUTT.js +2 -0
- package/out/{chunk-4XIH7YTX.js → chunk-UH6NZBSU.js} +1 -1
- package/out/{chunk-M3Y6SLC4.js → chunk-UJP4PQJA.js} +1 -1
- package/out/{chunk-PAD2JHZT.js → chunk-UJSJMXEG.js} +1 -1
- package/out/{chunk-E3LFSUDJ.js → chunk-VYYUMYVW.js} +1 -1
- package/out/{chunk-VRX2APNA.js → chunk-XVKDPU4D.js} +1 -1
- package/out/chunk-Y2XGV3RC.js +8 -0
- package/out/chunk-YCEMQETS.js +255 -0
- package/out/client-managed-import.js +3 -3
- package/out/client-managed.js +30 -27
- package/out/compare.js +16 -25
- package/out/dialogs.js +38 -38
- package/out/graph.js +14 -14
- package/out/index.html +32 -52
- package/out/scan.js +2 -2
- package/out/terminal.js +239 -240
- package/out/view.css +1 -1
- package/out/view.js +15 -15
- package/package.json +21 -13
- package/risk/actions/resolve.js +56 -19
- package/risk/actions/uses.js +27 -9
- package/risk/actions/workflow.js +75 -2
- package/risk/files/characters.js +11 -0
- package/risk/files/hosts.js +4 -4
- package/risk/files/readability.js +5 -2
- package/risk/files/runs-code.js +12 -25
- package/risk/files/script.js +141 -19
- package/risk/files/source-map-link.js +43 -0
- package/risk/index.d.ts +24 -7
- package/risk/index.js +1 -0
- package/risk/npm/assess.js +1 -1
- package/risk/npm/compare.js +9 -30
- package/risk/npm/diff.js +1 -1
- package/risk/npm/held.js +6 -2
- package/risk/npm/registry.js +5 -2
- package/risk/npm/tarball.js +79 -22
- package/server-managed/bundle-advisories.ts +12 -36
- package/server-managed/bundle-build-worker.js +29 -11
- package/server-managed/bundle-build.ts +4 -3
- package/server-managed/bundle-cache.ts +53 -13
- package/server-managed/bundle.ts +45 -13
- package/server-managed/comparison.ts +3 -3
- package/server-managed/db-methods.ts +54 -17
- package/server-managed/db-neon.ts +9 -2
- package/server-managed/db-schema.ts +12 -2
- package/server-managed/db.ts +4 -1
- package/server-managed/dependency-reviews.ts +8 -5
- package/server-managed/github-errors.ts +22 -0
- package/server-managed/github-requests.ts +4 -2
- package/server-managed/http.ts +336 -76
- package/server-managed/management.ts +10 -4
- package/server-managed/npm-delta.ts +17 -2
- package/server-managed/npm-kept.ts +6 -0
- package/server-managed/npm-packages.ts +30 -29
- package/server-managed/npm-patch.ts +9 -9
- package/server-managed/package-entry-points.ts +54 -6
- package/server-managed/pull-dependencies.ts +4 -1
- package/server-managed/rename-diff-worker.js +11 -7
- package/server-managed/rename-diff.ts +5 -4
- package/server-managed/report-opening.ts +77 -0
- package/server-managed/report-sources.ts +2 -1
- package/server-managed/repository-aliases.ts +34 -0
- package/server-managed/repository-browser.ts +87 -32
- package/server-managed/repository-code.ts +6 -3
- package/server-managed/repository-dependency-reviews.ts +21 -0
- package/server-managed/repository-issues.ts +15 -9
- package/server-managed/repository-risk-read.ts +50 -4
- package/server-managed/repository-risk.ts +9 -2
- package/server-managed/stasis-config.ts +97 -5
- package/server-managed/stasis-dependencies.ts +7 -4
- package/server-managed/team-reports.ts +5 -3
- package/server-managed/type-only-proof.js +26 -4
- package/server-managed/upstream-cache.ts +18 -12
- package/server-managed/workspace-shares.ts +4 -4
- package/out/chunk-2HGKTQ5Q.js +0 -52
- package/out/chunk-45HTR22K.js +0 -4
- package/out/chunk-4RS3NDOG.js +0 -1
- package/out/chunk-7GJNLCXF.js +0 -15
- package/out/chunk-CGRIZ5M5.js +0 -1
- package/out/chunk-CQIT5UNK.js +0 -1
- package/out/chunk-D6NVKGGG.js +0 -10
- package/out/chunk-DTAR2BB6.js +0 -247
- package/out/chunk-MPXVKVPF.js +0 -3
- package/out/chunk-NB4JBTKK.js +0 -2
- package/out/chunk-QPGM3DTI.js +0 -42
- package/out/chunk-VFWMQ3LG.js +0 -2
- package/out/chunk-VG5RH6KN.js +0 -2
- package/out/chunk-WFDXHPT2.js +0 -12
- package/out/chunk-WMFDQS2L.js +0 -11
- package/out/chunk-WREU7JAG.js +0 -1
- /package/out/{chunk-JMG5DXII.js → chunk-7HP2VYIC.js} +0 -0
- /package/out/{chunk-HOB3YPS5.js → chunk-K4XJHM2T.js} +0 -0
- /package/out/{chunk-4EMM6UCD.js → chunk-QI66YA4F.js} +0 -0
- /package/out/{chunk-G3LY2FV4.js → chunk-WCDYSIKG.js} +0 -0
package/server-managed/http.ts
CHANGED
|
@@ -68,11 +68,16 @@
|
|
|
68
68
|
// POST /api/admin/repositories/remove → admin permanently removes a repo
|
|
69
69
|
// GET /api/admin/repositories/risk[?team=|?repo=] → admin: each connected repo's npm lockfiles, or a team's or one repo's,
|
|
70
70
|
// their packages and what risk tells of each, Brotli-encoded ndjson as each is found; the reader leaving stops it | 400/401/403/404
|
|
71
|
+
// GET /api/admin/repositories/risk/stasis?repoId=&commit=&path=… → admin: what Stasis reaches of a repo's stasis.config.json
|
|
72
|
+
// files at a commit, each built as its dependency review builds it, a build still to be made asked for again | 400/401/403/404
|
|
73
|
+
// GET /api/admin/repositories/risk/lockfile?repoId=&commit=&path= → admin: an npm lockfile of a repo at a commit, as a scan
|
|
74
|
+
// read it, and the package.json beside a yarn.lock, for what depends on a package it locks | 400/401/403/404/429/502
|
|
71
75
|
// GET /api/admin/reports → admin|manage list of uploaded reports | 401/403
|
|
72
76
|
// POST /api/admin/reports → admin|manage uploads a report (raw body) | 401/403/413
|
|
73
77
|
// GET /api/admin/reports/<id> → admin|manage downloads a stored report | 401/403/404
|
|
74
78
|
// DELETE /api/admin/reports/<id> → admin|manage deletes a report | 401/403/404
|
|
75
79
|
// POST /api/admin/reports/set-repo → admin|manage attaches/detaches a report's repo | 401/403/404
|
|
80
|
+
// POST /api/admin/reports/set-opening → admin|manage switches a report to open on Confirmed, where it offers that | 401/403/404/409/503
|
|
76
81
|
// GET /api/admin/reports/<id>/location → admin|manage live location suggestion | 401/403/404/503
|
|
77
82
|
// GET /api/bundles/<id>/{metadata,contents} → authorized encoded bytes | 401/404/422
|
|
78
83
|
// GET /api/bundles/<id>/advisories → published dependency advisories (security access), of one ?reason= or ?entry= point where given | 400/401/403/404
|
|
@@ -148,10 +153,10 @@ import { pipeline } from 'node:stream/promises'
|
|
|
148
153
|
import { setTimeout as delay } from 'node:timers/promises'
|
|
149
154
|
import { type KeptStore, REPOSITORY_READ_KEPT_MS, authoredCommitStore, branchTipStore, bundleValidationStore, codeHeadStore, codeTreeStore, commitPullStore, githubTagStore, historyChangeStore, historyPageStore, historySquashStore, historyTreeStore,
|
|
150
155
|
issueListStore, lockfileReadStore,
|
|
151
|
-
npmDeltaStore, npmPublishTimeStore, npmVersionStore, ownKeptPrunes, patchStore, pullDependencyStore, pullListStore, repositoryReadStore, reviewBaselineStore, riskLineStore,
|
|
156
|
+
npmDeltaStore, npmPublishTimeStore, npmVersionDeltaStore, npmVersionStore, ownKeptPrunes, patchStore, pullDependencyStore, pullListStore, repositoryReadStore, reviewBaselineStore, riskLineStore,
|
|
152
157
|
scanReadStore, stasisDependencyStore } from './npm-kept.ts'
|
|
153
158
|
import { plainObject } from './npm-manifest.ts'
|
|
154
|
-
import { type NpmDelta, deltaKey, keptNpmDeltas, npmDelta } from './npm-delta.ts'
|
|
159
|
+
import { type NpmDelta, deltaKey, keptNpmDeltas, keptVersionDeltas, npmDelta, versionDeltaKey } from './npm-delta.ts'
|
|
155
160
|
import { ADVISORIES_TIMEOUT_MS, fetchBundleAdvisories } from './bundle-advisories.ts'
|
|
156
161
|
import { auditCache, auditedKeys, lastListing } from './upstream-cache.ts'
|
|
157
162
|
import type { BundleAdvisoryInventory } from './bundle-advisory-inventory.ts'
|
|
@@ -169,7 +174,7 @@ import { createHash, randomUUID } from 'node:crypto'
|
|
|
169
174
|
import type { AvatarStore, CachedAvatar } from './avatar-store.ts'
|
|
170
175
|
import type { BlobStore, OpenedBlob } from './blob-store.ts'
|
|
171
176
|
import { bundleFilePrefix, bundleIntegrity, bundleKind, bundleRepo, reportBundleHashes } from './bundle.ts'
|
|
172
|
-
import { resolveRepositoryImportLocation } from './repository-aliases.ts'
|
|
177
|
+
import { ourRepositoryNames, resolveRepositoryImportLocation } from './repository-aliases.ts'
|
|
173
178
|
import type { ManagedConfig } from './config.ts'
|
|
174
179
|
import type { BundleBuildConditions, BundleProvenance, BundleReuse, ManagedBundle, ManagedDb, ManagedSession, ReportRecord, SelectedRepo, StoredUser, TriageEventRow } from './db.ts'
|
|
175
180
|
import type { OriginGate } from '../server-common/origin.ts'
|
|
@@ -192,11 +197,13 @@ import { collectRepos, fetchPublicRepository, installUrl, publicRepositoryName,
|
|
|
192
197
|
import { type TaggedRead, keepTaggedReadsIn } from './github-requests.ts'
|
|
193
198
|
import { SHA, timeOf } from './github-values.ts'
|
|
194
199
|
import { GithubApiError, upstreamGithub } from './github-errors.ts'
|
|
200
|
+
import { STASIS_CONFIG } from './stasis-config.ts'
|
|
195
201
|
import { createClient } from '@preventive/upstream/github.js'
|
|
196
202
|
import type { ConnectedRepo } from './github-app.ts'
|
|
197
203
|
import { canAddAnyPublicRepository, canAddRepositories, passesPublicRepositorySafeguard } from './repository-policy.ts'
|
|
198
204
|
import { RepositoryDiscovery } from './repository-discovery.ts'
|
|
199
205
|
import { RISK_KEPT_MS, SCAN_READ_KEPT_MS, type ScanProgress, repositoryRiskLines } from './repository-risk.ts'
|
|
206
|
+
import { stasisConfigRow } from './repository-risk-read.ts'
|
|
200
207
|
import { WORKFLOWS_DIR } from './repository-actions.ts'
|
|
201
208
|
import { githubActionsSource } from './github-actions.ts'
|
|
202
209
|
import { type RepositoryEntry, createRepositoryBrowser, repositoryTreeFiles, scopedDirectory } from './repository-browser.ts'
|
|
@@ -227,6 +234,7 @@ import { teamAppKey, teamAppStates, withWorkspaceSummary } from './team-app.ts'
|
|
|
227
234
|
import { hashToken, randomToken, safeEqual } from './crypto.ts'
|
|
228
235
|
import { canDeleteComment, parseCommentBody } from '../common/managed/comments.ts'
|
|
229
236
|
import { ManagedMutationError, reportReferenceSnapshot } from './management.ts'
|
|
237
|
+
import { confirmedDefaultOffered, readConfirmedOffered, withConfirmedOffered } from './report-opening.ts'
|
|
230
238
|
import { BundleBuildError, buildRepositoryBundle, buildRepositoryLockfile, parseBundleBuild, withBundleBuildLease } from './bundle-build.ts'
|
|
231
239
|
import { NpmPackageError, type NpmReader, type NpmVersionDocument, type NpmVersionStore, VERSION_KEPT_MS, canReadPrivateNpm, npmFileRows, npmPublishTime, npmScopesCount, npmTarballFilename, readNpmVersion, readNpmVersions, readTogether } from './npm-packages.ts'
|
|
232
240
|
import { loadNpmFiles, loadNpmPackageBody, loadNpmTarball } from './npm-loads.ts'
|
|
@@ -246,7 +254,7 @@ import { eachOf } from './queue.ts'
|
|
|
246
254
|
import { lockedAt, lockedIn, lockfilesAt } from './commit-lockfiles.ts'
|
|
247
255
|
import { MAX_REQUIRED_REVIEWS, type PublishedReview, type RepoDependencyReview } from './repository-dependency-reviews.ts'
|
|
248
256
|
import { EVERY_LOCKFILE, type LockfileScope, heldTo, isStasisConfig, reviewedIn, scopeOf, stasisConfigs } from './lockfile-scope.ts'
|
|
249
|
-
import { type StasisDependencyReader, type StasisWant, stasisDependencyReader, stasisDirectory, wantingBeside, withReach } from './stasis-dependencies.ts'
|
|
257
|
+
import { type StasisDependencyReader, type StasisRead, type StasisWant, stasisDependencyReader, stasisDirectory, wantingBeside, withReach } from './stasis-dependencies.ts'
|
|
250
258
|
import { type BundledVersion, bundleDependencies, installsBundle } from './bundle-dependency-reviews.ts'
|
|
251
259
|
import { type CommentReviews, type ReviewBaselineStore, baselineFor, heldDependencies, reviewedDependencies, reviewedPackages } from './pull-dependency-reviews.ts'
|
|
252
260
|
import { formattedPull, withFormatted } from './dependency-review-comments.ts'
|
|
@@ -305,9 +313,12 @@ const CONNECT_REPO_APP_PATH = '/api/admin/repositories/connect-app'
|
|
|
305
313
|
const REPO_IMPACT_PATH = '/api/admin/repositories/impact'
|
|
306
314
|
const REMOVE_REPO_PATH = '/api/admin/repositories/remove'
|
|
307
315
|
const REPO_RISK_PATH = '/api/admin/repositories/risk'
|
|
316
|
+
const REPO_RISK_STASIS_PATH = '/api/admin/repositories/risk/stasis'
|
|
317
|
+
const REPO_RISK_LOCKFILE_PATH = '/api/admin/repositories/risk/lockfile'
|
|
308
318
|
const ADMIN_REPORTS_PATH = '/api/admin/reports'
|
|
309
319
|
const REPORT_SET_REPO_PATH = '/api/admin/reports/set-repo'
|
|
310
320
|
const REPORT_SET_VISIBLE_PATH = '/api/admin/reports/set-visible'
|
|
321
|
+
const REPORT_SET_OPENING_PATH = '/api/admin/reports/set-opening'
|
|
311
322
|
const REPORT_PREFIX = '/api/admin/reports/'
|
|
312
323
|
const ADMIN_BUNDLES_PATH = '/api/admin/bundles'
|
|
313
324
|
const BUNDLE_CREATE_PATH = '/api/admin/bundles/create'
|
|
@@ -344,9 +355,10 @@ const NPM_RISK_PATH = '/api/npm/risk'
|
|
|
344
355
|
const NPM_DELTA_PATH = '/api/npm/delta'
|
|
345
356
|
const NPM_DELTAS_PATH = '/api/npm/deltas'
|
|
346
357
|
// What risk's errors (risk/npm/registry.js NpmRiskError) are answered as: npm
|
|
347
|
-
// having no such package or version,
|
|
348
|
-
//
|
|
349
|
-
|
|
358
|
+
// having no such package or version, a tarball unpacking past risk's bounds,
|
|
359
|
+
// or one installers would install other than one set of files from, as the
|
|
360
|
+
// viewer refuses it (npm-packages.ts readNpmTar); npm failing otherwise a 502.
|
|
361
|
+
const NPM_RISK_STATUS: Partial<Record<string, number>> = { 'package-not-found': 404, 'version-not-found': 404, 'package-too-large': 413, 'tarball-conflict': 422 }
|
|
350
362
|
// A risk failure answered with its code alone, as risk's status for it (NPM_RISK_STATUS, else 502), its cause
|
|
351
363
|
// logged where it is the server's or npm's, not the reader's (a 5xx), for the logs to say why.
|
|
352
364
|
function sendRiskError(res: ServerResponse, err: NpmRiskError) {
|
|
@@ -699,8 +711,10 @@ function sendViewOnly(res: ServerResponse): void {
|
|
|
699
711
|
// would link it to the viewed user.
|
|
700
712
|
function viewAllows(method: string, path: string): boolean {
|
|
701
713
|
if (method === 'GET' || method === 'HEAD') return path !== ISSUE_LOGIN_PATH && path !== LINK_LOGIN_PATH
|
|
702
|
-
return (method === 'DELETE' && path === VIEW_AS_PATH) || (method === 'POST' && (path === LOGOUT_PATH || path === REPORT_QUERY_PATH))
|
|
714
|
+
return (method === 'DELETE' && path === VIEW_AS_PATH) || (method === 'POST' && (path === LOGOUT_PATH || path === REPORT_QUERY_PATH || TEAM_REVIEW_CHANGES.test(path)))
|
|
703
715
|
}
|
|
716
|
+
// Where a team's Dependencies tab asks which versions' reviews changed (handleTeamReviewChanges).
|
|
717
|
+
const TEAM_REVIEW_CHANGES = /^\/api\/teams\/([^/]+)\/dependency-reviews\/changed$/u
|
|
704
718
|
|
|
705
719
|
// POST /api/auth/logout — drop the session (same-origin + CSRF), which also
|
|
706
720
|
// ends a view opened from it.
|
|
@@ -1306,6 +1320,31 @@ async function handleSetReportVisible(req: IncomingMessage, res: ServerResponse,
|
|
|
1306
1320
|
sendJson(res, 200, { ok: true, visible })
|
|
1307
1321
|
}
|
|
1308
1322
|
|
|
1323
|
+
// POST /api/admin/reports/set-opening — switch a stored report to open on
|
|
1324
|
+
// Confirmed whatever Confirmed hides, or back to the outcome its view works
|
|
1325
|
+
// out (report-opening.ts). Body { reportId, confirmedDefault }. On only where
|
|
1326
|
+
// the report offers it (409 `not-offered`): one not read for that yet is read
|
|
1327
|
+
// first, 503 where its bytes cannot be. Off is always allowed.
|
|
1328
|
+
async function handleSetReportOpening(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
1329
|
+
const s = await manageMutation(req, res, deps, cookie, { handed: true })
|
|
1330
|
+
if (s == null) return
|
|
1331
|
+
const body = await readBodyFields(req, res)
|
|
1332
|
+
if (!body) return
|
|
1333
|
+
const { reportId, confirmedDefault } = body
|
|
1334
|
+
if (typeof reportId !== 'string' || typeof confirmedDefault !== 'boolean') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
1335
|
+
if (confirmedDefault) {
|
|
1336
|
+
// The mutation checks access again as it writes; this read only for one
|
|
1337
|
+
// the manager may read, so it tells nothing of any other.
|
|
1338
|
+
const stored = await canViewReport(deps, s.user, reportId) ? await deps.db.getReport(reportId) : null
|
|
1339
|
+
if (stored?.confirmedOffered === null && await readConfirmedOffered(deps.db, deps.reportStore, stored) === null) { sendJson(res, 503, { error: 'unavailable' }); return }
|
|
1340
|
+
}
|
|
1341
|
+
const { report, user } = await deps.db.mutateReport(s.session.id, reportId, { type: 'opening', confirmedDefault })
|
|
1342
|
+
if (report.confirmedDefault !== confirmedDefault) {
|
|
1343
|
+
await activity(deps, user, 'visibility', confirmedDefault ? 'set a report to open on Confirmed' : 'set a report to open on its detected outcome', { reportId, report: report.filename, repo: await repositoryName(deps, report.repoId) })
|
|
1344
|
+
}
|
|
1345
|
+
sendJson(res, 200, { ok: true, confirmedDefault })
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1309
1348
|
async function handleSetBundleVisible(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
1310
1349
|
const s = await manageMutation(req, res, deps, cookie, { handed: true })
|
|
1311
1350
|
if (s == null) return
|
|
@@ -1340,10 +1379,13 @@ async function handleSetBundleRepo(req: IncomingMessage, res: ServerResponse, de
|
|
|
1340
1379
|
// GET /api/admin/reports — the uploaded reports for the "Manage reports" page.
|
|
1341
1380
|
// Visible to admin|manage. Read-only, so no CSRF (like /api/admin/users).
|
|
1342
1381
|
// `maxBytes` lets the page show / pre-check the upload size cap; `repos` feeds
|
|
1343
|
-
// the upload repo picker.
|
|
1382
|
+
// the upload repo picker. Reports uploaded before their opening was read are
|
|
1383
|
+
// read for it as they list, a bounded share each time (report-opening.ts).
|
|
1344
1384
|
async function handleListReports(res: ServerResponse, deps: ManagedHttpDeps, session: ManagedSession): Promise<void> {
|
|
1385
|
+
const catalog = await deps.db.getReportCatalog(session.id, Date.now())
|
|
1345
1386
|
sendJson(res, 200, {
|
|
1346
|
-
...
|
|
1387
|
+
...catalog,
|
|
1388
|
+
reports: await withConfirmedOffered(deps.db, deps.reportStore, catalog.reports),
|
|
1347
1389
|
maxBytes: deps.config.maxReportBytes,
|
|
1348
1390
|
})
|
|
1349
1391
|
}
|
|
@@ -1458,13 +1500,15 @@ async function handleUploadReport(req: IncomingMessage, res: ServerResponse, dep
|
|
|
1458
1500
|
const contentType = (firstHeader(req.headers['content-type']) ?? '').split(';', 1)[0]!.trim() || 'application/json'
|
|
1459
1501
|
// A JSON report's parse already in hand, not parsed again for its hashes.
|
|
1460
1502
|
const { bundleId, integrity } = await resolveReportBundle(deps, s.user, parsed.format === 'json' ? parsed.data : null)
|
|
1503
|
+
// Last, as it backfills the parse's finding IDs.
|
|
1504
|
+
const confirmedOffered = await confirmedDefaultOffered(filename, parsed.data)
|
|
1461
1505
|
const dataKey = await deps.reportStore.put(id, bytes)
|
|
1462
1506
|
let report: ReportRecord
|
|
1463
1507
|
try {
|
|
1464
1508
|
report = await deps.db.insertOrReuseReport({
|
|
1465
1509
|
id, filename, contentType, byteSize: bytes.length, sha256, dataKey,
|
|
1466
1510
|
uploadedBy: s.user.id, uploadedByLogin: s.user.login, repoId,
|
|
1467
|
-
repoDirectory: directory, repoEmbedded, analyzer, visible: false, bundleId, bundleIntegrity: integrity,
|
|
1511
|
+
repoDirectory: directory, repoEmbedded, analyzer, visible: false, bundleId, bundleIntegrity: integrity, confirmedOffered,
|
|
1468
1512
|
}, Date.now(), s.session.id)
|
|
1469
1513
|
} catch (err) {
|
|
1470
1514
|
// A successful COMMIT can lose its acknowledgement. Never delete a file
|
|
@@ -1542,10 +1586,18 @@ async function repositoryBrowserUser(deps: ManagedHttpDeps, userId: string) {
|
|
|
1542
1586
|
return { githubUserId, token }
|
|
1543
1587
|
}
|
|
1544
1588
|
|
|
1545
|
-
// The repository browser
|
|
1546
|
-
//
|
|
1589
|
+
// The repository browser of `user` (repository-browser.ts), with their own
|
|
1590
|
+
// GitHub access. A repository GitHub renamed or transferred since it was
|
|
1591
|
+
// connected is renamed here as it reads it, its old name an alias of it
|
|
1592
|
+
// where that names nothing else (renameRepository).
|
|
1593
|
+
function repositoryBrowser(deps: ManagedHttpDeps, user: Awaited<ReturnType<typeof repositoryBrowserUser>>) {
|
|
1594
|
+
return createRepositoryBrowser(deps.config, user, undefined, async (repo, from, redirected) => { await deps.db.renameRepository(repo, from, redirected) })
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
// The repository browser's reader of `repo`, with user `userId`'s own GitHub
|
|
1598
|
+
// access.
|
|
1547
1599
|
async function repositoryReader(deps: ManagedHttpDeps, userId: string, repo: SelectedRepo) {
|
|
1548
|
-
return
|
|
1600
|
+
return repositoryBrowser(deps, await repositoryBrowserUser(deps, userId)).reader(repo)
|
|
1549
1601
|
}
|
|
1550
1602
|
|
|
1551
1603
|
// After a catalog response: read the commit details it lacked with this
|
|
@@ -1557,7 +1609,7 @@ async function backfillCatalogCommits(deps: ManagedHttpDeps, userId: string, mis
|
|
|
1557
1609
|
// Read once for the repositories the backfill reaches, not once each.
|
|
1558
1610
|
const repo = (await (repos ??= deps.db.listAllRepos())).find(item => item.repoId === repoId)
|
|
1559
1611
|
if (!repo) return null
|
|
1560
|
-
browser ??=
|
|
1612
|
+
browser ??= repositoryBrowser(deps, await repositoryBrowserUser(deps, userId))
|
|
1561
1613
|
return browser.reader(repo)
|
|
1562
1614
|
}).catch(err => { console.warn('managed: commit backfill failed:', err) })
|
|
1563
1615
|
}
|
|
@@ -1606,6 +1658,35 @@ async function readRepositoryRefs(db: ManagedDb, reader: RepositoryReader, repo:
|
|
|
1606
1658
|
return { ...refs.value, defaultContents: contents.value }
|
|
1607
1659
|
}
|
|
1608
1660
|
|
|
1661
|
+
// Whether `user`'s grants reach all of repository `repoId`'s directory `path`.
|
|
1662
|
+
async function reachesDirectory(deps: ManagedHttpDeps, user: StoredUser, repoId: number, path: string) {
|
|
1663
|
+
return repositoryAccessIn(await repositoryGrants(deps, user), repoId, path)?.virtualEntries === null
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
const holdsConfig = (contents: { entries: RepositoryEntry[] }) => contents.entries.some(entry => entry.name === STASIS_CONFIG && entry.type === 'file')
|
|
1667
|
+
|
|
1668
|
+
// The directory Create a bundle opens at in place of the default branch's
|
|
1669
|
+
// root, `root`, as if browsed to from there: where the root, as the reader is
|
|
1670
|
+
// shown it, holds no stasis.config.json, that of the one stasis.config.json
|
|
1671
|
+
// the repository's dependency review names, where it names one alone, the
|
|
1672
|
+
// reader's grants reach all of it, and it holds that file at the root's
|
|
1673
|
+
// commit. Null otherwise, as where GitHub fails reading it.
|
|
1674
|
+
async function reviewedConfigContents(deps: ManagedHttpDeps, reader: RepositoryReader, user: StoredUser, repoId: number,
|
|
1675
|
+
root: RepositoryContents | null, listed: ListedAt): Promise<RepositoryContents | null> {
|
|
1676
|
+
if (!root || holdsConfig(root)) return null
|
|
1677
|
+
const configs = stasisConfigs((await deps.db.repoDependencyReview(repoId))?.lockfiles ?? EVERY_LOCKFILE)
|
|
1678
|
+
if (configs.length !== 1) return null
|
|
1679
|
+
const path = configs[0]!.includes('/') ? configs[0]!.slice(0, configs[0]!.lastIndexOf('/')) : ''
|
|
1680
|
+
if (!path || !await reachesDirectory(deps, user, repoId, path)) return null
|
|
1681
|
+
try {
|
|
1682
|
+
const contents = { ...await listed(root.commit, path, () => reader.directory(path, root.commit)), path, commit: root.commit }
|
|
1683
|
+
return holdsConfig(contents) ? contents : null
|
|
1684
|
+
} catch (err) {
|
|
1685
|
+
if (err instanceof GithubApiError) return null
|
|
1686
|
+
throw err
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1609
1690
|
function scopeRepositoryContents(contents: RepositoryContents | null, virtualEntries: RepositoryEntry[] | null) {
|
|
1610
1691
|
return contents && { ...contents, ...(virtualEntries ? {
|
|
1611
1692
|
entries: virtualEntries, limited: false, configEntryPoints: [], packageEntryPoints: [], solidityEntryPoints: [], soliditySuggestionsLimited: false,
|
|
@@ -1691,6 +1772,9 @@ function answerGithubFailure(res: ServerResponse, err: unknown): void {
|
|
|
1691
1772
|
}
|
|
1692
1773
|
|
|
1693
1774
|
// Recheck repository/path grants after upstream reads, before returning names.
|
|
1775
|
+
// Refs read `withDefault`, as Create a bundle opens a repository, carry its
|
|
1776
|
+
// default branch's root (`defaultContents`) and, where it opens elsewhere,
|
|
1777
|
+
// that directory too (`configContents`, reviewedConfigContents).
|
|
1694
1778
|
async function handleRepositoryBrowser(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams, refs: boolean): Promise<void> {
|
|
1695
1779
|
const asked = repositoryQuery(res, query)
|
|
1696
1780
|
if (!asked) return
|
|
@@ -1714,6 +1798,7 @@ async function handleRepositoryBrowser(res: ServerResponse, deps: ManagedHttpDep
|
|
|
1714
1798
|
const trees = repositoryTreesOf(deps)
|
|
1715
1799
|
const listedAt: ListedAt = (commit, at, read) => trees.listing(`${repoId}\0${LISTING_READ}\0${commit}\0${at}`, read)
|
|
1716
1800
|
const revisions = refs ? await readRepositoryRefs(deps.db, reader, access.repo, withDefault, access.virtualEntries, listedAt) : null
|
|
1801
|
+
const configContents = withDefault ? await reviewedConfigContents(deps, reader, access.user, repoId, revisions?.defaultContents ?? null, listedAt) : null
|
|
1717
1802
|
const contents = refs ? null : commitOnly ? { path, commit: await reader.commit(ref) } : await readRepositoryContents(reader, ref, path, access.virtualEntries, listedAt)
|
|
1718
1803
|
const { tagCommits, tagsComplete, ...listed } = revisions ?? { tagCommits: [], tagsComplete: false }
|
|
1719
1804
|
// Every refs read (Create a bundle's, and the code viewer's) refreshes the
|
|
@@ -1727,8 +1812,10 @@ async function handleRepositoryBrowser(res: ServerResponse, deps: ManagedHttpDep
|
|
|
1727
1812
|
// This request (or another reader) may have refreshed the shared hint.
|
|
1728
1813
|
const current = await stillAuthorized(res, reader, authorize, access.repo)
|
|
1729
1814
|
if (!current) return
|
|
1815
|
+
// The directory opened in the root's place, where the grants checked again still reach all of it.
|
|
1816
|
+
const opened = configContents && await reachesDirectory(deps, current.user, repoId, configContents.path) ? configContents : null
|
|
1730
1817
|
sendJson(res, 200, refs ? { ...listed, tagCommits, ...(withDefault ? {
|
|
1731
|
-
defaultContents: scopeRepositoryContents(revisions?.defaultContents ?? null, current.virtualEntries),
|
|
1818
|
+
defaultContents: scopeRepositoryContents(revisions?.defaultContents ?? null, current.virtualEntries), ...(opened && { configContents: opened }),
|
|
1732
1819
|
} : {}) } : commitOnly ? contents : scopeRepositoryContents(contents as RepositoryContents, current.virtualEntries))
|
|
1733
1820
|
} catch (err) {
|
|
1734
1821
|
answerGithubFailure(res, err)
|
|
@@ -2562,7 +2649,9 @@ function itemNumber(text: string | null): number | null {
|
|
|
2562
2649
|
// Up to MAX_ASKED_PULLS pull requests asked together (`numbers=1,2,3`) are
|
|
2563
2650
|
// answered together, as many read at once as PULLS_AT_ONCE, `{ pulls }`,
|
|
2564
2651
|
// each's answer, else `{ number, error }` where GitHub fails it, with one
|
|
2565
|
-
// check of its access before and one after, but where each was kept.
|
|
2652
|
+
// check of its access before and one after, but where each was kept. With
|
|
2653
|
+
// `review=1`, the lines its versions wanting reviews change, where they are
|
|
2654
|
+
// counted already (`deltas`, teamDeltas), as a team's Dependencies tells them.
|
|
2566
2655
|
const MAX_ASKED_PULLS = 20
|
|
2567
2656
|
const PULLS_AT_ONCE = 3
|
|
2568
2657
|
async function handleRepositoryPullDependencies(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
@@ -2578,9 +2667,12 @@ async function handleRepositoryPullDependencies(res: ServerResponse, deps: Manag
|
|
|
2578
2667
|
|| !['1', null].includes(query.get('review')) || !['1', null].includes(query.get('listed'))) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
2579
2668
|
await answerWholeRepository(res, deps, cookie, repoId, async (fullName, token, user) => {
|
|
2580
2669
|
const commits = tiles ? await keptPullCommits(deps, repoId, numbers as number[]) : new Map<number, PullCommits>()
|
|
2581
|
-
if (listed === null)
|
|
2670
|
+
if (listed === null) {
|
|
2671
|
+
const answer = await pullDependencyAnswer(deps, fullName, token, user, repoId, numbers[0]!, review, commits.get(numbers[0]!))
|
|
2672
|
+
return review ? { ...answer, value: { ...answer.value, ...await withDeltas(deps, [answer.value]) } } : answer
|
|
2673
|
+
}
|
|
2582
2674
|
const answers = await pullDependencyAnswers(deps, fullName, token, user, repoId, numbers as number[], review, commits)
|
|
2583
|
-
return { value: { pulls: answers.value }, kept: answers.kept }
|
|
2675
|
+
return { value: { pulls: answers.value, ...review ? await withDeltas(deps, answers.value) : {} }, kept: answers.kept }
|
|
2584
2676
|
})
|
|
2585
2677
|
}
|
|
2586
2678
|
|
|
@@ -2829,10 +2921,23 @@ const TEAM_PULL_READS = TEAM_PULLS / OPEN_PULLS_SIZES.at(-1)!
|
|
|
2829
2921
|
const TEAM_PULLS_TOGETHER = 20
|
|
2830
2922
|
const PARTIAL_ACCESS = new Set(['no-directory', 'no-repository'])
|
|
2831
2923
|
type TeamDependencyLine = Record<string, unknown> & { repoId?: number }
|
|
2832
|
-
type TeamPull = { number: number; touchesLockfile?: boolean | null }
|
|
2924
|
+
type TeamPull = { number: number; touchesLockfile?: boolean | null; base?: string; draft?: boolean }
|
|
2925
|
+
// Whether a pull request is to merge into its repository's default branch
|
|
2926
|
+
// (`defaultBranch`), as a team's Dependencies reads those alone unless
|
|
2927
|
+
// asked for every branch's: one whose branch, or the default, isn't told is.
|
|
2928
|
+
const ontoDefault = (item: TeamPull, defaultBranch: string | null) => !defaultBranch || !item.base || item.base === defaultBranch
|
|
2929
|
+
// Whether a team's read tells the dependencies of every branch's pull
|
|
2930
|
+
// requests (`branch`), and of drafts (`draft`), else of its default
|
|
2931
|
+
// branch's alone, and not of drafts.
|
|
2932
|
+
type TeamEvery = { branch: boolean; draft: boolean }
|
|
2933
|
+
const DEFAULT_ONLY: TeamEvery = { branch: false, draft: false }
|
|
2833
2934
|
async function handleTeamDependencies(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, s: { session: ManagedSession; user: StoredUser },
|
|
2834
2935
|
teamId: string, query: URLSearchParams): Promise<void> {
|
|
2835
2936
|
const deadline = Date.now() + TEAM_DEPENDENCIES_MS
|
|
2937
|
+
// The dependencies of the pull requests to merge into other branches than
|
|
2938
|
+
// their repository's default too, where asked (`branches=all`); and of
|
|
2939
|
+
// drafts too, where asked (`drafts=all`).
|
|
2940
|
+
const every = { branch: query.get('branches') === 'all', draft: query.get('drafts') === 'all' }
|
|
2836
2941
|
const named = query.get('repoIds')
|
|
2837
2942
|
const only = named === null ? null : new Set(named.split(',').map(Number))
|
|
2838
2943
|
if (only && (only.size === 0 || only.size > 1000 || [...only].some(id => !Number.isSafeInteger(id) || id <= 0))) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
@@ -2876,30 +2981,61 @@ async function handleTeamDependencies(res: ServerResponse, deps: ManagedHttpDeps
|
|
|
2876
2981
|
}
|
|
2877
2982
|
if (answered.length > 0 && !await send(...answered)) return
|
|
2878
2983
|
const done = await eachOf(reading, TEAM_REPOSITORIES_AT_ONCE, ({ access, setting }) => stopped || Date.now() > deadline ? Promise.resolve(false)
|
|
2879
|
-
: teamRepositoryDependencies(deps, access, setting, deadline, send, () => wholeRepositoryAccess(deps, cookie, access.repo.repoId)))
|
|
2984
|
+
: teamRepositoryDependencies(deps, access, setting, deadline, send, () => wholeRepositoryAccess(deps, cookie, access.repo.repoId), every))
|
|
2880
2985
|
if (stopped) return
|
|
2881
2986
|
const unread = reading.filter((_, at) => !done[at]).map(({ access }) => access.repo.repoId)
|
|
2882
2987
|
if (!await send(unread.length === 0 ? { done: true } : { done: false, unread })) return
|
|
2883
2988
|
await out.end()
|
|
2884
2989
|
}
|
|
2885
2990
|
|
|
2991
|
+
// POST /api/teams/:id/dependency-reviews/changed, `{ since, versions:
|
|
2992
|
+
// [[name, version], …] }`: those of `versions`, the npm versions its
|
|
2993
|
+
// Dependencies tab shows, whose reviews, published to a team counting for
|
|
2994
|
+
// any of the team's repositories, were published (to it or to one more
|
|
2995
|
+
// team) or revoked at `since` or after (the `now` an earlier answer told,
|
|
2996
|
+
// the server's time), for the tab to ask again of the pull requests listing
|
|
2997
|
+
// them: `{ now, versions: [[name, version], …] }`; with no `since`, `{ now }`
|
|
2998
|
+
// alone. Only those asked of are told, as many as MAX_CHANGED_ASKED, so it
|
|
2999
|
+
// lists no other team's reviews of packages the team's pull requests lock
|
|
3000
|
+
// none of. A POST of no effect, allowed while viewing as another user.
|
|
3001
|
+
const MAX_CHANGED_ASKED = 5000
|
|
3002
|
+
const MAX_CHANGED_BODY_BYTES = 512 * 1024
|
|
3003
|
+
async function handleTeamReviewChanges(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, teamId: string): Promise<void> {
|
|
3004
|
+
const s = await checkMutation(req, res, deps, cookie, { view: true })
|
|
3005
|
+
if (!s) return
|
|
3006
|
+
const body = await readBodyObject(req, res, MAX_CHANGED_BODY_BYTES)
|
|
3007
|
+
if (!body) return
|
|
3008
|
+
const { since = null, versions = [] } = body
|
|
3009
|
+
if ((since !== null && (!Number.isSafeInteger(since) || (since as number) < 0)) || !Array.isArray(versions) || versions.length > MAX_CHANGED_ASKED
|
|
3010
|
+
|| !versions.every(one => Array.isArray(one) && one.length === 2 && isNpmPackageName(one[0]) && isNpmPackageSpec(one[1]))) {
|
|
3011
|
+
sendJson(res, 400, { error: 'bad-request' }); return
|
|
3012
|
+
}
|
|
3013
|
+
const snapshot = await teamSnapshot(deps.db, s.session.id, teamId)
|
|
3014
|
+
const now = Date.now()
|
|
3015
|
+
if (since === null) { sendJson(res, 200, { now }); return }
|
|
3016
|
+
const changed = await deps.db.changedReviewVersions([...new Set(snapshot.repositories.map(repo => repo.repoId))], since as number,
|
|
3017
|
+
(versions as [string, string][]).map(([name, version]) => ({ name, version })))
|
|
3018
|
+
sendJson(res, 200, { now, versions: changed.map(({ name, version }) => [name, version]) })
|
|
3019
|
+
}
|
|
3020
|
+
|
|
2886
3021
|
// A repository's lines of its team's Dependencies, as handleTeamDependencies
|
|
2887
3022
|
// tells them; whether all were written, none left for its time.
|
|
2888
3023
|
async function teamRepositoryDependencies(deps: ManagedHttpDeps, access: WholeAccess, setting: RepoDependencyReview, deadline: number,
|
|
2889
|
-
send: (...lines: TeamDependencyLine[]) => Promise<boolean>, reauthorize: () => Promise<WholeAccess | Refusal
|
|
3024
|
+
send: (...lines: TeamDependencyLine[]) => Promise<boolean>, reauthorize: () => Promise<WholeAccess | Refusal>, every: TeamEvery = DEFAULT_ONLY): Promise<boolean> {
|
|
2890
3025
|
// The Stasis builds its answers want, asked for a batch of pull requests at a time, its default branch's with the first.
|
|
2891
3026
|
const wants: StasisWant[] = []
|
|
2892
|
-
try { return await teamRepositoryLines(deps, access, setting, deadline, send, reauthorize, wants) } finally { stasisReader(deps).build(wants) }
|
|
3027
|
+
try { return await teamRepositoryLines(deps, access, setting, deadline, send, reauthorize, wants, every) } finally { stasisReader(deps).build(wants) }
|
|
2893
3028
|
}
|
|
2894
3029
|
async function teamRepositoryLines(deps: ManagedHttpDeps, access: WholeAccess, setting: RepoDependencyReview, deadline: number,
|
|
2895
|
-
send: (...lines: TeamDependencyLine[]) => Promise<boolean>, reauthorize: () => Promise<WholeAccess | Refusal>, wants: StasisWant[]): Promise<boolean> {
|
|
3030
|
+
send: (...lines: TeamDependencyLine[]) => Promise<boolean>, reauthorize: () => Promise<WholeAccess | Refusal>, wants: StasisWant[], every: TeamEvery): Promise<boolean> {
|
|
2896
3031
|
const repoId = access.repo.repoId
|
|
2897
|
-
type Read = { branch: object | null; pulls?: { items: TeamPull[]; more: boolean; error?: string }; commits?: Map<number, PullCommits> }
|
|
3032
|
+
type Read = { branch: object | null; pulls?: { items: TeamPull[]; more: boolean; error?: string; defaultBranch?: string }; commits?: Map<number, PullCommits> }
|
|
2898
3033
|
const read = await readWholeRepositoryOf<Read>(deps, access, async (fullName, token, user) => {
|
|
2899
3034
|
const branch = await branchDependencyAnswer(deps, fullName, token, user, repoId, setting, wants)
|
|
2900
3035
|
if (!(branch.value as { review?: unknown }).review) return { value: { branch: null }, kept: branch.kept }
|
|
2901
3036
|
const pulls = await teamOpenPulls(deps, repoId, fullName, token, deadline)
|
|
2902
|
-
return { value: { branch: branch.value, pulls: { items: pulls.items, more: pulls.more, ...pulls.failed === null ? {} : { error: pulls.failed }
|
|
3037
|
+
return { value: { branch: branch.value, pulls: { items: pulls.items, more: pulls.more, ...pulls.failed === null ? {} : { error: pulls.failed },
|
|
3038
|
+
...pulls.defaultBranch ? { defaultBranch: pulls.defaultBranch } : {} }, commits: pulls.commits },
|
|
2903
3039
|
kept: branch.kept && pulls.kept }
|
|
2904
3040
|
}, reauthorize)
|
|
2905
3041
|
if ('error' in read) return send({ repoId, ...PARTIAL_ACCESS.has(read.error) ? { branch: null } : { error: read.error, status: read.status } })
|
|
@@ -2907,8 +3043,12 @@ async function teamRepositoryLines(deps: ManagedHttpDeps, access: WholeAccess, s
|
|
|
2907
3043
|
if (!branch) return send({ repoId, branch: null })
|
|
2908
3044
|
if (!await send({ repoId, branch, pulls, ...await withDeltas(deps, [branch]) })) return false
|
|
2909
3045
|
// Each by the commits its page names, where it names them, GitHub not asked
|
|
2910
|
-
// for them (pullDependencyAnswer); never told.
|
|
2911
|
-
|
|
3046
|
+
// for them (pullDependencyAnswer); never told. Those to merge into another
|
|
3047
|
+
// branch than the default, and drafts, but where asked, as the tab hides
|
|
3048
|
+
// them unless asked, and reads them alone once it shows them, their Stasis
|
|
3049
|
+
// builds none.
|
|
3050
|
+
const numbers = pulls!.items.filter(item => (item.touchesLockfile === true || item.touchesLockfile === null)
|
|
3051
|
+
&& (every.branch || ontoDefault(item, pulls!.defaultBranch ?? null)) && (every.draft || item.draft !== true)).map(item => item.number)
|
|
2912
3052
|
for (let at = 0; at < numbers.length; at += TEAM_PULLS_TOGETHER) {
|
|
2913
3053
|
if (Date.now() > deadline) return false
|
|
2914
3054
|
const batch = numbers.slice(at, at + TEAM_PULLS_TOGETHER)
|
|
@@ -2928,7 +3068,8 @@ const withDeltas = async (deps: ManagedHttpDeps, answers: object[]) => {
|
|
|
2928
3068
|
// A repository's open pull requests, the TEAM_PULLS updated latest, a page
|
|
2929
3069
|
// at a time (repository-issues.ts repositoryOpenPulls), each kept; each's
|
|
2930
3070
|
// base's and head's commits as its page has them (`commits`, by its number),
|
|
2931
|
-
// where it has them;
|
|
3071
|
+
// where it has them; the repository's default branch, by its name
|
|
3072
|
+
// (`defaultBranch`), where told; whether it has more, and whether all were kept. Where
|
|
2932
3073
|
// the repository has a label named DEPENDENCIES_LABEL (kept as a page is),
|
|
2933
3074
|
// those carrying it alone, by its name as the repository has it: a
|
|
2934
3075
|
// repository of many open pull requests, few of them its dependencies', read
|
|
@@ -2944,8 +3085,9 @@ async function teamOpenPulls(deps: ManagedHttpDeps, repoId: number, fullName: st
|
|
|
2944
3085
|
const items: TeamPull[] = []
|
|
2945
3086
|
const commits = new Map<number, PullCommits>()
|
|
2946
3087
|
let after: string | null = null, kept = labelled.kept, size = OPEN_PULLS_SIZES[0]!
|
|
3088
|
+
let defaultBranch: string | null = null
|
|
2947
3089
|
for (let page = 0; page < TEAM_PULL_READS && items.length < TEAM_PULLS; page++) {
|
|
2948
|
-
if (Date.now() > deadline) return { items, commits, more: true, kept: false, failed: 'time-up' }
|
|
3090
|
+
if (Date.now() > deadline) return { items, commits, more: true, kept: false, failed: 'time-up', defaultBranch }
|
|
2949
3091
|
const asked = size, cursor = after
|
|
2950
3092
|
let answer
|
|
2951
3093
|
try {
|
|
@@ -2953,19 +3095,20 @@ async function teamOpenPulls(deps: ManagedHttpDeps, repoId: number, fullName: st
|
|
|
2953
3095
|
} catch (err) {
|
|
2954
3096
|
if (!(err instanceof GithubApiError) || refusedRead(err)) throw err
|
|
2955
3097
|
console.warn('managed: open pull requests read failed:', err)
|
|
2956
|
-
return { items, commits, more: true, kept: false, failed: err.message }
|
|
3098
|
+
return { items, commits, more: true, kept: false, failed: err.message, defaultBranch }
|
|
2957
3099
|
}
|
|
2958
3100
|
kept &&= answer.kept
|
|
2959
3101
|
const value = answer.value as OpenPullsPage
|
|
2960
3102
|
if (typeof value.size === 'number' && value.size > 0) size = Math.min(size, value.size)
|
|
3103
|
+
if (typeof value.defaultBranch === 'string' && value.defaultBranch) defaultBranch ??= value.defaultBranch
|
|
2961
3104
|
items.push(...(Array.isArray(value.items) ? value.items : []).filter(item => Number.isSafeInteger(item?.number) && item.number > 0))
|
|
2962
3105
|
pageCommits(value, commits)
|
|
2963
|
-
if (value.more !== true || typeof value.after !== 'string') return { items, commits, more: false, kept, failed: null }
|
|
3106
|
+
if (value.more !== true || typeof value.after !== 'string') return { items, commits, more: false, kept, failed: null, defaultBranch }
|
|
2964
3107
|
after = value.after
|
|
2965
3108
|
}
|
|
2966
|
-
return { items, commits, more: true, kept, failed: null }
|
|
3109
|
+
return { items, commits, more: true, kept, failed: null, defaultBranch }
|
|
2967
3110
|
}
|
|
2968
|
-
type OpenPullsPage = { items?: unknown; more?: unknown; after?: unknown; commits?: unknown; size?: unknown }
|
|
3111
|
+
type OpenPullsPage = { items?: unknown; more?: unknown; after?: unknown; commits?: unknown; size?: unknown; defaultBranch?: unknown }
|
|
2969
3112
|
// Each open pull request's base's and head's commits a page of them names,
|
|
2970
3113
|
// into `commits` by its number.
|
|
2971
3114
|
function pageCommits(page: OpenPullsPage, commits: Map<number, PullCommits>) {
|
|
@@ -2999,9 +3142,11 @@ async function keptPullCommits(deps: ManagedHttpDeps, repoId: number, numbers: n
|
|
|
2999
3142
|
|
|
3000
3143
|
// The lines the versions wanting reviews of `answers` change, as their rows
|
|
3001
3144
|
// show them (npm-delta.js reviewBase), a patched one's none, where they are
|
|
3002
|
-
// counted already: of public versions alone,
|
|
3003
|
-
// (
|
|
3004
|
-
//
|
|
3145
|
+
// counted already: of public versions alone, kept by their names
|
|
3146
|
+
// (npmVersionDeltaStore), else, those npm answered for in a day
|
|
3147
|
+
// (npmVersionStore), by their integrities, as npmDelta keys them, then kept
|
|
3148
|
+
// by their names too. `[name, version, base, delta]` each, none counted here,
|
|
3149
|
+
// nor npm asked.
|
|
3005
3150
|
async function teamDeltas(deps: ManagedHttpDeps, answers: object[]) {
|
|
3006
3151
|
const asked = new Map<string, [string, string, string]>()
|
|
3007
3152
|
for (const answer of answers as { lockfiles?: { added?: unknown; unreviewed?: unknown }[]; review?: { required?: number; reviewedBases?: true } }[]) {
|
|
@@ -3020,6 +3165,14 @@ async function teamDeltas(deps: ManagedHttpDeps, answers: object[]) {
|
|
|
3020
3165
|
}
|
|
3021
3166
|
}
|
|
3022
3167
|
if (asked.size === 0) return []
|
|
3168
|
+
const byVersions = npmVersionDeltaStore<NpmDelta>(deps.db, deps.config.debug)
|
|
3169
|
+
const named = await keptVersionDeltas([...asked.values()].map(([name, version, base]) => versionDeltaKey(name, version, name, base)), byVersions)
|
|
3170
|
+
const told = [...asked.values()].flatMap(([name, version, base]) => {
|
|
3171
|
+
const delta = named.get(versionDeltaKey(name, version, name, base))
|
|
3172
|
+
return delta ? [[name, version, base, delta] as const] : []
|
|
3173
|
+
})
|
|
3174
|
+
for (const [key, [name, version, base]] of [...asked]) if (named.has(versionDeltaKey(name, version, name, base))) asked.delete(key)
|
|
3175
|
+
if (asked.size === 0) return told
|
|
3023
3176
|
const versions = [...asked.values()].flatMap(([name, version, base]) => [{ name, version }, ...base === '(empty)' || !isExactVersion(base) ? [] : [{ name, version: base }]])
|
|
3024
3177
|
const kept = await npmVersionStore(deps.db, deps.config.debug).readMany!(versions)
|
|
3025
3178
|
const integrity = (name: string, version: string) => {
|
|
@@ -3031,12 +3184,15 @@ async function teamDeltas(deps: ManagedHttpDeps, answers: object[]) {
|
|
|
3031
3184
|
const against = base === '(empty)' ? null : integrity(name, base), other = integrity(name, version)
|
|
3032
3185
|
return other && (base === '(empty)' || against) ? [{ name, version, base, key: [against, other] as [string | null, string] }] : []
|
|
3033
3186
|
})
|
|
3034
|
-
if (sides.length === 0) return
|
|
3187
|
+
if (sides.length === 0) return told
|
|
3035
3188
|
const counted = await keptNpmDeltas(sides.map(({ key }) => key), npmDeltaStore<NpmDelta>(deps.db, deps.config.debug))
|
|
3036
|
-
|
|
3189
|
+
const byIntegrity = sides.flatMap(({ name, version, base, key: [against, other] }) => {
|
|
3037
3190
|
const delta = counted.get(deltaKey(against, other))
|
|
3038
|
-
return delta ? [[name, version, base, delta]] : []
|
|
3191
|
+
return delta ? [[name, version, base, delta] as const] : []
|
|
3039
3192
|
})
|
|
3193
|
+
// Kept by their names too, as those npm told of are public, for a later read past the day.
|
|
3194
|
+
await Promise.all(byIntegrity.map(([name, version, base, delta]) => byVersions.write(versionDeltaKey(name, version, name, base), delta, Date.now())))
|
|
3195
|
+
return [...told, ...byIntegrity]
|
|
3040
3196
|
}
|
|
3041
3197
|
|
|
3042
3198
|
// The app's users `accounts` are, by their logins in lower case, of those
|
|
@@ -3404,6 +3560,82 @@ async function riskRepositories(db: ManagedDb, query: URLSearchParams): Promise<
|
|
|
3404
3560
|
})
|
|
3405
3561
|
}
|
|
3406
3562
|
|
|
3563
|
+
// What Stasis reaches of the stasis.config.json at `config` of `repo` at
|
|
3564
|
+
// `commit`, as its dependency review's reader has it (stasisReader): the
|
|
3565
|
+
// same builds, in the same worker, kept the same way. One not kept yet is
|
|
3566
|
+
// asked for with `token`, the reader's own, at no priority over a review's,
|
|
3567
|
+
// told the branch `branch` (none where `''`), whose history holds the
|
|
3568
|
+
// commit; none is waited for. One with no token to build it with fails, as
|
|
3569
|
+
// a review refuses it (readWholeRepositoryOf).
|
|
3570
|
+
async function riskStasis(deps: ManagedHttpDeps, repo: { repoId: number; fullName: string }, token: string | null, commit: string, branch: string,
|
|
3571
|
+
config: string): Promise<StasisRead> {
|
|
3572
|
+
const reader = stasisReader(deps)
|
|
3573
|
+
const read = await reader.read(repo.repoId, commit, config)
|
|
3574
|
+
if (read.status !== 'pending') return read
|
|
3575
|
+
if (!token) return { status: 'failed', error: 'github-token-required', transient: false }
|
|
3576
|
+
reader.build([{ repo: { repoId: repo.repoId, fullName: repo.fullName }, token, commit, config, ...branch ? { branch } : {}, priority: 0 }])
|
|
3577
|
+
return read
|
|
3578
|
+
}
|
|
3579
|
+
|
|
3580
|
+
// GET /api/admin/repositories/risk/stasis?repoId=&commit=&path=…: what
|
|
3581
|
+
// Stasis reaches of the stasis.config.json files at `path`, up to
|
|
3582
|
+
// MAX_RISK_STASIS, of repository `repoId` at `commit`, as a risk scan tells
|
|
3583
|
+
// them (repository-risk-read.ts StasisConfigRow), for its page to ask again
|
|
3584
|
+
// while builds of them are still to be made, every 30 seconds as a dependency
|
|
3585
|
+
// review's page asks: each asked for again (riskStasis), lest it lapse
|
|
3586
|
+
// (stasis-dependencies.ts). For admins, with their own GitHub access, as the
|
|
3587
|
+
// scan reads the repository; a path naming no stasis.config.json in the
|
|
3588
|
+
// commit's tree told so (`no-config`).
|
|
3589
|
+
const MAX_RISK_STASIS = 50
|
|
3590
|
+
async function handleRepositoryRiskStasis(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
3591
|
+
const s = await readAdminSession(res, deps, cookie)
|
|
3592
|
+
if (!s) return
|
|
3593
|
+
const commit = query.get('commit') ?? '', paths = query.getAll('path'), repoId = askedRepoId(query)
|
|
3594
|
+
if (repoId === null || !/^[\da-f]{40}$/u.test(commit) || paths.length === 0 || paths.length > MAX_RISK_STASIS || new Set(paths).size < paths.length
|
|
3595
|
+
|| !paths.every(isStasisConfig)) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
3596
|
+
const repo = (await deps.db.listSelectedRepos()).find(item => item.repoId === repoId)
|
|
3597
|
+
if (!repo) { sendJson(res, 404, { error: 'no-repository' }); return }
|
|
3598
|
+
try {
|
|
3599
|
+
const reader = await repositoryReader(deps, s.user.id, repo)
|
|
3600
|
+
const token = reader.readToken()
|
|
3601
|
+
const tree = await repositoryTree(repo.fullName, token, commit, commitTreeKept(deps, repoId))
|
|
3602
|
+
if (!tree) { sendJson(res, 404, { error: 'no-commit' }); return }
|
|
3603
|
+
const files = new Set(tree.files)
|
|
3604
|
+
sendJson(res, 200, { configs: await Promise.all(paths.map(async path => (files.has(path)
|
|
3605
|
+
? stasisConfigRow(path, await riskStasis(deps, repo, token, commit, reader.defaultBranch, path)) : { path, error: 'no-config' }))) })
|
|
3606
|
+
} catch (err) {
|
|
3607
|
+
if (err instanceof GithubApiError) { sendRefusal(res, githubRefusal(err)); return }
|
|
3608
|
+
throw err
|
|
3609
|
+
}
|
|
3610
|
+
}
|
|
3611
|
+
|
|
3612
|
+
// GET /api/admin/repositories/risk/lockfile?repoId=&commit=&path=: a lockfile
|
|
3613
|
+
// a risk scan reads (locked-packages.ts) at `commit`, for its page to show
|
|
3614
|
+
// what depends on a package in it: its text, and the package.json beside a
|
|
3615
|
+
// yarn.lock, which its reader there takes (null for none). For admins, with
|
|
3616
|
+
// their own GitHub access, as the scan reads the repository.
|
|
3617
|
+
const RISK_LOCKFILE = /^(?:(?!\.\.?\/)[^/]+\/)*(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock)$/u
|
|
3618
|
+
async function handleRepositoryRiskLockfile(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
3619
|
+
const s = await readAdminSession(res, deps, cookie)
|
|
3620
|
+
if (!s) return
|
|
3621
|
+
const commit = query.get('commit') ?? '', path = query.get('path') ?? '', repoId = askedRepoId(query)
|
|
3622
|
+
if (repoId === null || !/^[\da-f]{40}$/u.test(commit) || !RISK_LOCKFILE.test(path)) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
3623
|
+
const repo = (await deps.db.listSelectedRepos()).find(item => item.repoId === repoId)
|
|
3624
|
+
if (!repo) { sendJson(res, 404, { error: 'no-repository' }); return }
|
|
3625
|
+
try {
|
|
3626
|
+
const client = createClient({ token: (await repositoryReader(deps, s.user.id, repo)).readToken() })
|
|
3627
|
+
const file = (at: string) => upstreamGithub(() => client.getRepoFile({ repo: repo.fullName, path: at, ref: commit }))
|
|
3628
|
+
const [text, manifest] = await Promise.all([file(path), path.endsWith('yarn.lock') ? file(path.replace(/yarn\.lock$/u, 'package.json')).catch((err: unknown) => {
|
|
3629
|
+
if (err instanceof GithubApiError && err.status === 404) return null
|
|
3630
|
+
throw err
|
|
3631
|
+
}) : null])
|
|
3632
|
+
sendJson(res, 200, { text, manifest })
|
|
3633
|
+
} catch (err) {
|
|
3634
|
+
if (err instanceof GithubApiError) { sendRefusal(res, githubRefusal(err)); return }
|
|
3635
|
+
throw err
|
|
3636
|
+
}
|
|
3637
|
+
}
|
|
3638
|
+
|
|
3407
3639
|
// Where a scan in parts keeps its progress (repository-risk.ts
|
|
3408
3640
|
// ScanProgress) under `key`, for a day; none where the page gave no scan id.
|
|
3409
3641
|
function scanProgress(deps: ManagedHttpDeps, key: string, scan: string | null) {
|
|
@@ -3424,7 +3656,9 @@ function scanProgress(deps: ManagedHttpDeps, key: string, scan: string | null) {
|
|
|
3424
3656
|
// repository's Dependabot alerts, open or dismissed, read with the App's
|
|
3425
3657
|
// installation token where the admin's own access to it lets them see them on
|
|
3426
3658
|
// GitHub (dependabot-access.ts); and its GitHub Actions, the references they
|
|
3427
|
-
// make resolved with the admin's own GitHub token (github-actions.ts)
|
|
3659
|
+
// make resolved with the admin's own GitHub token (github-actions.ts); and
|
|
3660
|
+
// what Stasis reaches of each of its stasis.config.json files, as its
|
|
3661
|
+
// dependency review has them built (riskStasis). The
|
|
3428
3662
|
// reader leaving, losing their admin role or
|
|
3429
3663
|
// the server shutting down stops it.
|
|
3430
3664
|
async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
@@ -3440,7 +3674,7 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
|
|
|
3440
3674
|
res.on('close', () => { controller.abort() })
|
|
3441
3675
|
res.setTimeout(REPO_RISK_IDLE_MS, () => res.destroy())
|
|
3442
3676
|
const user = await repositoryBrowserUser(deps, s.user.id)
|
|
3443
|
-
const browser =
|
|
3677
|
+
const browser = repositoryBrowser(deps, user)
|
|
3444
3678
|
const scopes = new Map<string, Promise<boolean>>()
|
|
3445
3679
|
const teamScoped = (name: string) => {
|
|
3446
3680
|
const scope = npmPackageScope(name)
|
|
@@ -3459,7 +3693,8 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
|
|
|
3459
3693
|
async open(repo) {
|
|
3460
3694
|
const reader = await browser.reader(repo)
|
|
3461
3695
|
const commit = await reader.commit('')
|
|
3462
|
-
const
|
|
3696
|
+
const token = reader.readToken()
|
|
3697
|
+
const client = createClient({ token })
|
|
3463
3698
|
return {
|
|
3464
3699
|
commit,
|
|
3465
3700
|
lockfiles: async () => (await upstreamGithub(() => client.findRepoLockfiles({ repo: repo.fullName, sha: commit }))).lockfiles,
|
|
@@ -3469,6 +3704,10 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
|
|
|
3469
3704
|
dependabot: () => reader.dependabotAlerts(),
|
|
3470
3705
|
workflows: () => reader.directory(WORKFLOWS_DIR, commit).then(({ entries }) => entries.filter(entry => entry.type === 'file' && /\.ya?ml$/iu.test(entry.name)).map(entry => entry.path),
|
|
3471
3706
|
(error: unknown) => { if (error instanceof GithubApiError && error.status === 404) return []; throw error }),
|
|
3707
|
+
// Its files as its tree lists them at the commit, kept by it, as its
|
|
3708
|
+
// dependency review's settings read them (handleRepositoryLockfiles).
|
|
3709
|
+
files: async () => (await repositoryTree(repo.fullName, token, commit, commitTreeKept(deps, repo.repoId)))?.files ?? [],
|
|
3710
|
+
stasis: config => riskStasis(deps, repo, token, commit, reader.defaultBranch, config),
|
|
3472
3711
|
}
|
|
3473
3712
|
},
|
|
3474
3713
|
// References resolved with the admin's token, and each one's advisories
|
|
@@ -3950,14 +4189,14 @@ async function handleUploadBundle(req: IncomingMessage, res: ServerResponse, dep
|
|
|
3950
4189
|
try { rawDirectory = decodeURIComponent(firstHeader(req.headers['x-repo-directory']) ?? '') }
|
|
3951
4190
|
catch { sendJson(res, 400, { error: 'bad-directory' }); return }
|
|
3952
4191
|
if (!existing && repo.repoId == null && kind === 'stasis') {
|
|
3953
|
-
const embedded = await bundleRepo(bytes)
|
|
4192
|
+
const embedded = await bundleRepo(bytes, filename)
|
|
3954
4193
|
const github = reportRepoGithub({ repo: embedded })
|
|
3955
4194
|
const embeddedDirectory = normalizeTeamPath(embedded?.directory)
|
|
3956
4195
|
// Invalid optional metadata must not reject an otherwise unattached bundle.
|
|
3957
4196
|
// Only repository-wide aliases/direct connections can resolve without a
|
|
3958
4197
|
// valid directory; do not decode file paths or match directory aliases.
|
|
3959
4198
|
const location = github == null ? null : embeddedDirectory.ok
|
|
3960
|
-
? await resolveRepositoryImportLocation(deps.db, github, embeddedDirectory.path ?? '', () => bundleFilePrefix(bytes))
|
|
4199
|
+
? await resolveRepositoryImportLocation(deps.db, github, embeddedDirectory.path ?? '', () => bundleFilePrefix(bytes, filename))
|
|
3961
4200
|
: await deps.db.getRepositoryImportLocation(github, '')
|
|
3962
4201
|
if (location?.repoId != null) {
|
|
3963
4202
|
repo.repoId = location.repoId
|
|
@@ -4305,7 +4544,7 @@ async function handleViewReport(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
4305
4544
|
if (data == null) { sendJson(res, 422, { error: 'unreadable-report' }); return }
|
|
4306
4545
|
const links = mergeLinkGroups(snapshot.linkRevision ? await deps.db.getEnabledLinkGroups(snapshot.linkRevision) : [], await reportIds(data))
|
|
4307
4546
|
// Without a finding's `repo` none of ours (common/finding-repo.js isStrayRepo).
|
|
4308
|
-
const ours = ourRepoSlugs([...
|
|
4547
|
+
const ours = ourRepoSlugs([...await ourRepositoryNames(deps.db), access.repo.github])
|
|
4309
4548
|
envelope = { data: withoutStrayRepos(data, ours), repo: access.repo, ...(links.length > 0 ? { links } : {}) }
|
|
4310
4549
|
}
|
|
4311
4550
|
// Link decryption and finding-ID backfill can outlast access or link changes.
|
|
@@ -4346,7 +4585,7 @@ async function handleQueryReports(req: IncomingMessage, res: ServerResponse, dep
|
|
|
4346
4585
|
const reports = new Map(snapshot.reports.map(report => [report.id, report]))
|
|
4347
4586
|
// The repositories that are ours, for a finding's `repo` none of them
|
|
4348
4587
|
// (common/finding-repo.js isStrayRepo), which every report sent leaves out.
|
|
4349
|
-
const selected =
|
|
4588
|
+
const selected = await ourRepositoryNames(deps.db)
|
|
4350
4589
|
if (reports.size !== ids.length) { sendJson(res, 404, { error: 'no-report' }); return }
|
|
4351
4590
|
const storedBytes = snapshot.reports.reduce((total, report) => total + report.byteSize, 0)
|
|
4352
4591
|
if (storedBytes > MAX_REPORT_QUERY_BYTES) { sendJson(res, 413, { error: 'batch-too-large' }); return }
|
|
@@ -5132,17 +5371,21 @@ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
5132
5371
|
} finally { res.off('close', onClose) }
|
|
5133
5372
|
}
|
|
5134
5373
|
|
|
5135
|
-
// GET /api/npm/deltas?versions=[[name, version, otherVersion, patch?], …]:
|
|
5136
|
-
// each of up to MAX_ASKED_DELTAS versions changes against another,
|
|
5137
|
-
// `
|
|
5138
|
-
//
|
|
5139
|
-
//
|
|
5140
|
-
//
|
|
5141
|
-
//
|
|
5142
|
-
//
|
|
5143
|
-
//
|
|
5144
|
-
//
|
|
5145
|
-
//
|
|
5374
|
+
// GET /api/npm/deltas?versions=[[name, version, otherVersion, patch?, otherName?], …]:
|
|
5375
|
+
// the lines each of up to MAX_ASKED_DELTAS versions changes against another,
|
|
5376
|
+
// of its package or `otherName`'s, as the host may name a review's base
|
|
5377
|
+
// (reviewed-dependencies.ts `base`), or `(empty)`, as GET delta counts them,
|
|
5378
|
+
// a patched one's as its pnpm patch changes it (`patch`, `{ hash, repoId,
|
|
5379
|
+
// commit, path? }`, or null, read as Review reads it, npmPatchOf), as lines
|
|
5380
|
+
// of JSON as each is counted (`{ name, version, otherVersion, otherName?,
|
|
5381
|
+
// patchHash?, …delta }`, or the same with `error` and `status`), as a list's
|
|
5382
|
+
// rows near the viewport ask for them together (npm-delta.js),
|
|
5383
|
+
// DELTAS_AT_ONCE at a time. Each read as GET delta reads it, with the
|
|
5384
|
+
// reader's access to each package, which is checked again once it is
|
|
5385
|
+
// counted: a private one's told only to a reader who may still read it,
|
|
5386
|
+
// none told to one whose session is gone. Each of two public versions,
|
|
5387
|
+
// unpatched, kept by their names too (npmVersionDeltaStore), for a team's
|
|
5388
|
+
// Dependencies to tell it without asking npm of them (teamDeltas).
|
|
5146
5389
|
const MAX_ASKED_DELTAS = 50
|
|
5147
5390
|
const DELTAS_AT_ONCE = 2
|
|
5148
5391
|
// A version as npmDelta takes it: its integrity, and its files, loaded as
|
|
@@ -5155,36 +5398,44 @@ async function handleNpmDeltas(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
5155
5398
|
if (req.method !== 'GET') { send405(res, 'GET'); return }
|
|
5156
5399
|
let asked: unknown = null
|
|
5157
5400
|
try { asked = JSON.parse(params.get('versions') ?? '') } catch {}
|
|
5158
|
-
const patchOf = (item: unknown[]) => item.length
|
|
5159
|
-
if (!Array.isArray(asked) || asked.length === 0 || asked.length > MAX_ASKED_DELTAS || !asked.every(item => Array.isArray(item) &&
|
|
5160
|
-
&& isNpmPackageName(item[0]) && isNpmPackageSpec(item[1]) && (item[2] === '(empty)' || isNpmPackageSpec(item[2])) && patchOf(item) !== 'invalid'
|
|
5401
|
+
const patchOf = (item: unknown[]) => item[3] == null && item.length !== 4 ? null : plainObject(item[3]) ? requestedPatch(item[3] as { hash: unknown }) : 'invalid'
|
|
5402
|
+
if (!Array.isArray(asked) || asked.length === 0 || asked.length > MAX_ASKED_DELTAS || !asked.every(item => Array.isArray(item) && item.length >= 3 && item.length <= 5
|
|
5403
|
+
&& isNpmPackageName(item[0]) && isNpmPackageSpec(item[1]) && (item[2] === '(empty)' || isNpmPackageSpec(item[2])) && patchOf(item) !== 'invalid'
|
|
5404
|
+
&& (item.length < 5 || (isNpmPackageName(item[4]) && item[2] !== '(empty)')))) {
|
|
5161
5405
|
sendJson(res, 400, { error: 'bad-package' }); return
|
|
5162
5406
|
}
|
|
5163
|
-
const versions = (asked as unknown[][]).map(item => [...item.slice(0, 3), patchOf(item)] as [string, string, string, RequestedPatch | null])
|
|
5407
|
+
const versions = (asked as unknown[][]).map(item => [...item.slice(0, 3), patchOf(item), item[4] ?? item[0]] as [string, string, string, RequestedPatch | null, string])
|
|
5164
5408
|
// Each patch read once, by its hash.
|
|
5165
5409
|
const patches = new Map<string, Promise<ReadPatch | Refusal>>()
|
|
5166
|
-
const reader = await npmReader(deps, cookie, [...new Set(versions.
|
|
5410
|
+
const reader = await npmReader(deps, cookie, [...new Set(versions.flatMap(([name, , , , otherName]) => [name, otherName]))], { handed: true })
|
|
5167
5411
|
if (reader == null) { sendJson(res, 401, { error: 'unauthenticated' }); return }
|
|
5168
5412
|
const controller = new AbortController()
|
|
5169
5413
|
res.once('close', () => { if (!res.writableEnded) controller.abort() })
|
|
5170
5414
|
dropIdle(res)
|
|
5171
5415
|
const kept = npmDeltaStore<NpmDelta>(deps.db, deps.config.debug), keptVersions = npmVersionStore(deps.db, deps.config.debug)
|
|
5416
|
+
const byVersions = npmVersionDeltaStore<NpmDelta>(deps.db, deps.config.debug)
|
|
5172
5417
|
const out = openLines(res)
|
|
5173
5418
|
let stopped = false
|
|
5174
|
-
await eachOf(versions, DELTAS_AT_ONCE, async ([name, version, otherVersion, patch]) => {
|
|
5419
|
+
await eachOf(versions, DELTAS_AT_ONCE, async ([name, version, otherVersion, patch, otherName]) => {
|
|
5175
5420
|
if (stopped || controller.signal.aborted) return
|
|
5176
|
-
const asOne = { name, version, otherVersion, ...patch ? { patchHash: patch.hash } : {} }
|
|
5177
|
-
|
|
5421
|
+
const asOne = { name, version, otherVersion, ...otherName === name ? {} : { otherName }, ...patch ? { patchHash: patch.hash } : {} }
|
|
5422
|
+
// Of each package, whether it is private.
|
|
5423
|
+
let isPrivate = false, line: Record<string, unknown>, oldPrivate = false
|
|
5178
5424
|
try {
|
|
5179
|
-
const
|
|
5180
|
-
const
|
|
5181
|
-
|
|
5182
|
-
|
|
5183
|
-
|
|
5425
|
+
const together = otherVersion === '(empty)' ? keptVersions : readTogether(keptVersions, [{ name, version }, { name: otherName, version: otherVersion }])
|
|
5426
|
+
const [doc, old] = await Promise.all([readNpmVersion(name, version, canReadPrivateNpm(reader, name), controller.signal, together).then(found),
|
|
5427
|
+
otherVersion === '(empty)' ? null : readNpmVersion(otherName, otherVersion, canReadPrivateNpm(reader, otherName), controller.signal, together).then(found)])
|
|
5428
|
+
isPrivate = doc.private
|
|
5429
|
+
oldPrivate = old?.private === true
|
|
5184
5430
|
const patched = patch && await (patches.get(patch.hash) ?? patches.set(patch.hash, npmPatchOf(deps, cookie, patch)).get(patch.hash)!)
|
|
5185
5431
|
const side = deltaSide(doc)
|
|
5186
|
-
|
|
5187
|
-
|
|
5432
|
+
if (patched && 'error' in patched) line = { ...asOne, error: patched.error, status: patched.status }
|
|
5433
|
+
else {
|
|
5434
|
+
const delta = await npmDelta(old ? deltaSide(old) : null,
|
|
5435
|
+
patched ? { integrity: `${side.integrity} patch:${patch.hash}`, files: async () => patchedFiles(await side.files(), patched.files) } : side, kept)
|
|
5436
|
+
if (!patched && !doc.private && !old?.private) await byVersions.write(versionDeltaKey(doc.name, doc.version, old?.name ?? name, old?.version ?? '(empty)'), delta, Date.now())
|
|
5437
|
+
line = { ...asOne, ...delta }
|
|
5438
|
+
}
|
|
5188
5439
|
} catch (err) {
|
|
5189
5440
|
if (controller.signal.aborted) return
|
|
5190
5441
|
if (!(err instanceof NpmPackageError)) console.warn('managed: a package delta failed:', err)
|
|
@@ -5192,9 +5443,9 @@ async function handleNpmDeltas(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
5192
5443
|
}
|
|
5193
5444
|
// A reader who lost their session, or their access to a private one,
|
|
5194
5445
|
// while it was counted, is told nothing of it.
|
|
5195
|
-
const current = await npmReader(deps, cookie, isPrivate ? [name] : [])
|
|
5446
|
+
const current = await npmReader(deps, cookie, [...isPrivate ? [name] : [], ...oldPrivate ? [otherName] : []])
|
|
5196
5447
|
if (current == null) { stopped = true; out.cut(); return }
|
|
5197
|
-
if (isPrivate && !canReadPrivateNpm(current, name)) line = { ...asOne, error: 'package-not-found', status: 404 }
|
|
5448
|
+
if ((isPrivate && !canReadPrivateNpm(current, name)) || (oldPrivate && !canReadPrivateNpm(current, otherName))) line = { ...asOne, error: 'package-not-found', status: 404 }
|
|
5198
5449
|
if (!stopped && !await out.write(line)) stopped = true
|
|
5199
5450
|
})
|
|
5200
5451
|
if (!stopped) await out.end()
|
|
@@ -5522,7 +5773,7 @@ async function handleWorkspaceShare(req: IncomingMessage, res: ServerResponse, d
|
|
|
5522
5773
|
|
|
5523
5774
|
// The repositories' reads that are GETs of their query alone, by their paths.
|
|
5524
5775
|
const REPOSITORY_QUERY_READS = new Map<string, (res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams) => Promise<void>>([
|
|
5525
|
-
[REPO_RISK_PATH, handleRepositoryRisk], [REPO_CODE_PATH, handleRepositoryCode], [REPO_HISTORY_PATH, handleRepositoryHistory],
|
|
5776
|
+
[REPO_RISK_PATH, handleRepositoryRisk], [REPO_RISK_STASIS_PATH, handleRepositoryRiskStasis], [REPO_RISK_LOCKFILE_PATH, handleRepositoryRiskLockfile], [REPO_CODE_PATH, handleRepositoryCode], [REPO_HISTORY_PATH, handleRepositoryHistory],
|
|
5526
5777
|
[REPO_CHANGES_PATH, handleRepositoryChanges], [REPO_TREE_PATH, handleRepositoryTree], [REPO_ISSUES_PATH, handleRepositoryIssues],
|
|
5527
5778
|
[REPO_AGENTS_PATH, handleRepositoryAgents], [REPO_ITEM_PATH, handleRepositoryItem], [REPO_PULL_DEPENDENCIES_PATH, handleRepositoryPullDependencies],
|
|
5528
5779
|
[REPO_BRANCH_DEPENDENCIES_PATH, handleRepositoryBranchDependencies], [REPO_LOCKFILES_PATH, handleRepositoryLockfiles],
|
|
@@ -5721,6 +5972,10 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
|
|
|
5721
5972
|
if (method !== 'POST') { send405(res, 'POST'); return }
|
|
5722
5973
|
await handleSetReportVisible(req, res, deps, cookie); return
|
|
5723
5974
|
}
|
|
5975
|
+
if (path === REPORT_SET_OPENING_PATH) {
|
|
5976
|
+
if (method !== 'POST') { send405(res, 'POST'); return }
|
|
5977
|
+
await handleSetReportOpening(req, res, deps, cookie); return
|
|
5978
|
+
}
|
|
5724
5979
|
if (path === '/api/admin/reports/finding-ids') {
|
|
5725
5980
|
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5726
5981
|
await handleImportFindingIds(res, deps, cookie, url.searchParams); return
|
|
@@ -5823,6 +6078,11 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
|
|
|
5823
6078
|
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5824
6079
|
await handleTeamDependencies(res, deps, cookie, workspaceSession!, teamDependencies[1]!, url.searchParams); return
|
|
5825
6080
|
}
|
|
6081
|
+
const teamReviewChanges = TEAM_REVIEW_CHANGES.exec(path)
|
|
6082
|
+
if (teamReviewChanges) {
|
|
6083
|
+
if (method !== 'POST') { send405(res, 'POST'); return }
|
|
6084
|
+
await handleTeamReviewChanges(req, res, deps, cookie, teamReviewChanges[1]!); return
|
|
6085
|
+
}
|
|
5826
6086
|
const teamFixes = /^\/api\/teams\/([^/]+)\/fixes$/u.exec(path)
|
|
5827
6087
|
if (teamFixes) {
|
|
5828
6088
|
if (method !== 'GET') { send405(res, 'GET'); return }
|