@preventive/triage 1.0.0-alpha.60 → 1.0.0-alpha.62
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/default-scan-models.ts +6 -5
- package/common/managed/comments.ts +9 -0
- package/out/activity.js +3 -3
- package/out/brotli-fallback.js +1 -1
- package/out/chunk-4ISO5F7Y.js +1 -1
- package/out/chunk-65PLAG3I.js +12 -0
- package/out/chunk-6CCSTJWB.js +1 -0
- package/out/chunk-7GJNLCXF.js +15 -0
- package/out/chunk-BZP3CT2V.js +244 -0
- package/out/{chunk-TZS7KERJ.js → chunk-DCBXCBLL.js} +2 -2
- package/out/chunk-E3LFSUDJ.js +1 -1
- package/out/chunk-EQ5EQXV5.js +1 -0
- package/out/chunk-F3UI65ZI.js +42 -0
- package/out/chunk-FAG6E5RC.js +3 -0
- package/out/chunk-HAZKDK4M.js +1 -1
- package/out/chunk-IZ6MYRYB.js +1 -1
- package/out/{chunk-VZJIHHTQ.js → chunk-K2QJLP3E.js} +1 -1
- package/out/chunk-NXATZJQ2.js +1 -1
- package/out/chunk-OBNHCORJ.js +2 -0
- package/out/chunk-OGNTXZYM.js +4 -0
- package/out/chunk-QRKFPLA4.js +2 -2
- package/out/chunk-QVKFY4FA.js +1 -0
- package/out/chunk-TOXMUOIW.js +2 -2
- package/out/chunk-WMFDQS2L.js +2 -2
- package/out/chunk-Y5ZHFNBD.js +1 -1
- package/out/client-managed-import.js +1 -1
- package/out/client-managed.js +7 -7
- package/out/client-sync.js +3 -3
- package/out/compare.js +19 -14
- package/out/dialogs.js +38 -38
- package/out/graph.js +12 -12
- package/out/index.html +5 -5
- package/out/prism.js +2 -2
- package/out/scan.js +2 -2
- package/out/terminal.js +150 -148
- package/out/view.css +1 -1
- package/out/view.js +5 -5
- package/package.json +21 -18
- package/risk/files/runs-code.js +2 -2
- package/server-e2e/static.ts +1 -1
- package/server-managed/activity.ts +23 -43
- package/server-managed/agent-merges.ts +2 -2
- package/server-managed/blob-store.ts +10 -1
- package/server-managed/bundle-advisories.ts +3 -2
- package/server-managed/bundle-advisory-inventory.ts +1 -1
- package/server-managed/bundle-build-worker.js +41 -6
- package/server-managed/bundle-build.ts +26 -14
- package/server-managed/bundle-cache.ts +29 -41
- package/server-managed/bundle-catalog.ts +11 -11
- package/server-managed/bundle-commits.ts +9 -16
- package/server-managed/bundle-dependency-reviews.ts +5 -11
- package/server-managed/bundle-summary-cache.ts +23 -14
- package/server-managed/bundle-validation.ts +2 -1
- package/server-managed/combined.ts +1 -5
- package/server-managed/comments.ts +15 -28
- package/server-managed/commit-coauthors.ts +4 -5
- package/server-managed/commit-lockfiles.ts +6 -5
- package/server-managed/comparison.ts +3 -5
- package/server-managed/config.ts +1 -2
- package/server-managed/db-methods.ts +163 -244
- package/server-managed/db-neon.ts +82 -178
- package/server-managed/db-schema.ts +15 -0
- package/server-managed/db.ts +5 -11
- package/server-managed/dependabot-access.ts +2 -1
- package/server-managed/dependabot-alerts.ts +7 -12
- package/server-managed/dependency-review-comments.ts +7 -13
- package/server-managed/dependency-reviews.ts +14 -15
- package/server-managed/github-accounts.ts +4 -5
- package/server-managed/github-actions.ts +6 -6
- package/server-managed/github-app.ts +19 -48
- package/server-managed/github-graphql.ts +5 -2
- package/server-managed/github-issue-links.ts +62 -42
- package/server-managed/github-issue-oauth.ts +7 -24
- package/server-managed/github-issues.ts +9 -7
- package/server-managed/github-link-oauth.ts +7 -20
- package/server-managed/github-oauth.ts +38 -12
- package/server-managed/github-pulls.ts +37 -26
- package/server-managed/github-requests.ts +21 -8
- package/server-managed/github-values.ts +26 -0
- package/server-managed/history-windows.ts +7 -7
- package/server-managed/http.ts +495 -554
- package/server-managed/index.ts +6 -6
- package/server-managed/link-reports.ts +6 -19
- package/server-managed/lockfile-scope.ts +1 -1
- package/server-managed/management.ts +14 -3
- package/server-managed/npm-delta.ts +22 -57
- package/server-managed/npm-insights.ts +31 -26
- package/server-managed/npm-kept.ts +9 -8
- package/server-managed/npm-loads.ts +2 -7
- package/server-managed/npm-manifest.ts +6 -4
- package/server-managed/npm-packages.ts +17 -9
- package/server-managed/npm-patch.ts +8 -16
- package/server-managed/npm-provenance.ts +12 -8
- package/server-managed/npm-risk.ts +9 -7
- package/server-managed/object-storage-disk.ts +2 -3
- package/server-managed/object-storage-vercel.ts +15 -11
- package/server-managed/object-storage.ts +7 -0
- package/server-managed/pretty-print.ts +8 -19
- package/server-managed/public-workspace.ts +50 -46
- package/server-managed/pull-comment-reviews.ts +2 -2
- package/server-managed/pull-dependencies.ts +20 -31
- package/server-managed/pull-dependency-reviews.ts +17 -24
- package/server-managed/pull-reviews.ts +4 -7
- package/server-managed/queue.ts +14 -0
- package/server-managed/release-commits.ts +9 -8
- package/server-managed/rename-diff.ts +17 -60
- package/server-managed/report-migration.ts +5 -8
- package/server-managed/report-sources.ts +6 -10
- package/server-managed/report-store.ts +2 -10
- package/server-managed/repository-actions.ts +7 -8
- package/server-managed/repository-agents.ts +31 -57
- package/server-managed/repository-aliases.ts +3 -9
- package/server-managed/repository-browser.ts +18 -16
- package/server-managed/repository-changes.ts +33 -37
- package/server-managed/repository-code.ts +5 -5
- package/server-managed/repository-dependency-reviews.ts +6 -13
- package/server-managed/repository-discovery.ts +2 -1
- package/server-managed/repository-history.ts +47 -51
- package/server-managed/repository-issues.ts +59 -30
- package/server-managed/repository-pulls.ts +7 -12
- package/server-managed/repository-pulse.ts +51 -45
- package/server-managed/repository-risk-assess.ts +5 -2
- package/server-managed/repository-risk-audit.ts +1 -1
- package/server-managed/repository-risk-read.ts +6 -6
- package/server-managed/repository-risk.ts +32 -40
- package/server-managed/repository-squashes.ts +7 -15
- package/server-managed/request-timing.ts +1 -1
- package/server-managed/sql.ts +18 -0
- package/server-managed/storage-encryption.ts +5 -7
- package/server-managed/team-app.ts +4 -7
- package/server-managed/team-npm-scopes.ts +5 -8
- package/server-managed/team-reports.ts +15 -15
- package/server-managed/type-only-proof.js +108 -0
- package/server-managed/type-only-worker.js +26 -14
- package/server-managed/type-only.ts +90 -60
- package/server-managed/uploads.ts +3 -3
- package/server-managed/upstream-cache.ts +5 -7
- package/server-managed/worker-turns.ts +76 -0
- package/server-managed/workspace-shares.ts +1 -2
- package/strip-types-loader.js +13 -10
- package/out/chunk-2SY4PYUQ.js +0 -4
- package/out/chunk-4HI2MSAV.js +0 -17
- package/out/chunk-4TQKM3JC.js +0 -42
- package/out/chunk-6VDDCFHT.js +0 -3
- package/out/chunk-EEQHVKR3.js +0 -1
- package/out/chunk-HNQNDNIE.js +0 -12
- package/out/chunk-OFPDMZJF.js +0 -244
- package/out/chunk-OQRSIBSC.js +0 -1
- package/out/chunk-YGRRXC2L.js +0 -1
- package/out/chunk-YTO6AQZM.js +0 -2
package/server-managed/http.ts
CHANGED
|
@@ -88,8 +88,9 @@
|
|
|
88
88
|
// bundle's, both pretty-printed, renamed names hidden, whitespace changes shown and hidden | 400/401/404/409/413/422/429/504
|
|
89
89
|
// GET /api/bundles/<id>/rename-diff?other=&scope= → every pair of its JavaScript files and another bundle's the viewer
|
|
90
90
|
// diffs so, within a reason scope where given, Brotli-encoded ndjson | 400/401/404/422/503
|
|
91
|
-
// GET /api/bundles/<id>/type-only?other=&scope= → the files that changed between it and another bundle in types alone, as
|
|
92
|
-
// @preventive/compare proves them, within a reason scope where given,
|
|
91
|
+
// GET /api/bundles/<id>/type-only?other=&scope=&runs= → the files that changed between it and another bundle in types alone, as
|
|
92
|
+
// @preventive/compare proves them, within a reason scope where given, and with runs=1 those in types alone but for
|
|
93
|
+
// what runs, with the lines that hold it, Brotli-encoded ndjson | 400/401/404/422/501/503
|
|
93
94
|
// GET /api/admin/bundles → admin all bundles; managers own/team bundles | 401/403
|
|
94
95
|
// POST /api/admin/bundles → admin|manage uploads a bundle (raw body) | 401/403/413
|
|
95
96
|
// GET /api/admin/bundles/<id> → admin|manage downloads a stored bundle | 401/403/404
|
|
@@ -130,8 +131,8 @@
|
|
|
130
131
|
// another version's, both pretty-printed, renamed names hidden, whitespace changes shown and hidden | 400/401/404/409/413/422/429/502/503/504
|
|
131
132
|
// GET /api/npm/rename-diff?name=&version=&otherVersion= → every pair of their JavaScript files the viewer diffs so,
|
|
132
133
|
// Brotli-encoded ndjson | 400/401/404/413/429/502/503
|
|
133
|
-
// GET /api/npm/type-only?name=&version=&otherVersion= → the files that changed between two versions in types alone,
|
|
134
|
-
// Brotli-encoded ndjson | 400/401/404/413/429/502/503
|
|
134
|
+
// GET /api/npm/type-only?name=&version=&otherVersion=&runs= → the files that changed between two versions in types alone,
|
|
135
|
+
// and with runs=1 those in types alone but for what runs, Brotli-encoded ndjson | 400/401/404/413/429/501/502/503
|
|
135
136
|
// GET /api/npm/delta?name=&version=&otherVersion= → the lines a version adds and removes against another, or `(empty)`, and
|
|
136
137
|
// those but for declaration files changed in types alone, where any are, and whether binary files changed
|
|
137
138
|
// | 400/401/404/413/422/429/502/503/504
|
|
@@ -148,7 +149,7 @@ import { type KeptStore, REPOSITORY_READ_KEPT_MS, authoredCommitStore, branchTip
|
|
|
148
149
|
issueListStore, lockfileReadStore,
|
|
149
150
|
npmDeltaStore, npmPublishTimeStore, npmVersionStore, ownKeptPrunes, pullDependencyStore, pullListStore, repositoryReadStore, reviewBaselineStore, riskLineStore, scanReadStore } from './npm-kept.ts'
|
|
150
151
|
import { plainObject } from './npm-manifest.ts'
|
|
151
|
-
import { type NpmDelta, keptNpmDeltas, npmDelta } from './npm-delta.ts'
|
|
152
|
+
import { type NpmDelta, deltaKey, keptNpmDeltas, npmDelta } from './npm-delta.ts'
|
|
152
153
|
import { ADVISORIES_TIMEOUT_MS, fetchBundleAdvisories } from './bundle-advisories.ts'
|
|
153
154
|
import { auditCache, auditedKeys, lastListing } from './upstream-cache.ts'
|
|
154
155
|
import type { BundleAdvisoryInventory } from './bundle-advisory-inventory.ts'
|
|
@@ -184,9 +185,10 @@ import { normalizeTeamPath } from './repo-path.ts'
|
|
|
184
185
|
import { DEFAULT_MANAGED_SCAN_MODEL, MANAGED_SCAN_MODELS } from '../common/managed/scan-models.ts'
|
|
185
186
|
import { CONFIG_PATH, type ManagedSessionInfo, type ServerInfo } from '../common/server-info.ts'
|
|
186
187
|
import { bundleCommitHash } from '../common/bundle-commit.js'
|
|
187
|
-
import {
|
|
188
|
+
import { collectRepos, fetchPublicRepository, installUrl, publicRepositoryName, repositoryInstallation } from './github-app.ts'
|
|
188
189
|
import { type TaggedRead, keepTaggedReadsIn } from './github-requests.ts'
|
|
189
|
-
import {
|
|
190
|
+
import { SHA, timeOf } from './github-values.ts'
|
|
191
|
+
import { GithubApiError, upstreamGithub } from './github-errors.ts'
|
|
190
192
|
import { createClient } from '@preventive/upstream/github.js'
|
|
191
193
|
import type { ConnectedRepo } from './github-app.ts'
|
|
192
194
|
import { canAddAnyPublicRepository, canAddRepositories, passesPublicRepositorySafeguard } from './repository-policy.ts'
|
|
@@ -233,11 +235,12 @@ import { type AllHeads, type HistoryCommit, type HistoryPages, MAX_HISTORY_PAGE,
|
|
|
233
235
|
repositoryAllHeads, repositoryAllHistory, repositoryHistory, repositoryRefTips } from './repository-history.ts'
|
|
234
236
|
import { type KnownMerges, type SquashedPull, type Squashes, squashedPulls } from './repository-squashes.ts'
|
|
235
237
|
import { AGENTS_READ_VERSION, type AuthoredCommit, type BranchTip, type BranchTips, COMMITS_CURSOR, type CommitPulls, repositoryAgents } from './repository-agents.ts'
|
|
236
|
-
import { ISSUES_CURSOR, ISSUES_READ_VERSION, repositoryIssues, repositoryItem } from './repository-issues.ts'
|
|
238
|
+
import { DEPENDENCIES_LABEL, ISSUES_CURSOR, ISSUES_READ_VERSION, repositoryIssues, repositoryItem, repositoryLabel } from './repository-issues.ts'
|
|
237
239
|
import { type GithubAsked, type ListedLockfile, type LockfileRead, type LockfileStore, MAX_LOCKED, PULL_DEPENDENCIES_READ, type PullCommits, type PullDependencies,
|
|
238
|
-
type PullDependencyStore,
|
|
240
|
+
type PullDependencyStore, lockfileFormat, pullDependenciesAt } from './pull-dependencies.ts'
|
|
241
|
+
import { eachOf } from './queue.ts'
|
|
239
242
|
import { lockedAt, lockedIn, lockfilesAt } from './commit-lockfiles.ts'
|
|
240
|
-
import { MAX_REQUIRED_REVIEWS, type RepoDependencyReview
|
|
243
|
+
import { MAX_REQUIRED_REVIEWS, type RepoDependencyReview } from './repository-dependency-reviews.ts'
|
|
241
244
|
import { EVERY_LOCKFILE, heldTo, reviewedIn, scopeOf } from './lockfile-scope.ts'
|
|
242
245
|
import { type BundledVersion, bundleDependencies, installsBundle } from './bundle-dependency-reviews.ts'
|
|
243
246
|
import { type ReviewBaselineStore, baselineFor, heldDependencies, reviewedDependencies, reviewedPackages } from './pull-dependency-reviews.ts'
|
|
@@ -260,9 +263,9 @@ import { type NpmAdvisoryOptions, npmAdvisories, npmCommitTags, npmDownloads, np
|
|
|
260
263
|
import { npmProvenance } from './npm-provenance.ts'
|
|
261
264
|
import { npmReadyScanDownload, npmReadyScanDownloads, npmRisk, npmRiskRemoved } from './npm-risk.ts'
|
|
262
265
|
import { NpmRiskError } from '../risk/index.js'
|
|
263
|
-
import { type PrettyCache, PrettyError, type PrettyRequest, compared, prettyRequest, prettyText } from './pretty-print.ts'
|
|
266
|
+
import { type ComparedSide, type PrettyCache, PrettyError, type PrettyRequest, compared, prettyRequest, prettyText } from './pretty-print.ts'
|
|
264
267
|
import { renameDiffOf, renameDiffRequest, renamedPairs } from './rename-diff.ts'
|
|
265
|
-
import { typeOnlyFiles } from './type-only.ts'
|
|
268
|
+
import { runsAsked, typeOnlyFiles } from './type-only.ts'
|
|
266
269
|
import { comparisonBody, emptySide, npmComparedSide, patchedVersionBody } from './comparison.ts'
|
|
267
270
|
import { isNpmPackageName, isNpmPackageSpec, isPatchHash, npmPackageScope } from '../common/managed/npm-packages.js'
|
|
268
271
|
|
|
@@ -350,6 +353,8 @@ const NPM_PATHS = new Set([NPM_PACKAGE_PATH, NPM_VERSIONS_PATH, NPM_DOWNLOAD_PAT
|
|
|
350
353
|
NPM_RENAME_DIFF_PATH, NPM_TYPE_ONLY_PATH, NPM_RISK_PATH, NPM_COMPARISON_PATH, NPM_DELTA_PATH])
|
|
351
354
|
// How long an npm response may go unread before its connection is dropped.
|
|
352
355
|
const NPM_RESPONSE_IDLE_MS = 60_000
|
|
356
|
+
// `res`'s connection dropped once the response goes NPM_RESPONSE_IDLE_MS unread.
|
|
357
|
+
function dropIdle(res: ServerResponse): void { res.setTimeout(NPM_RESPONSE_IDLE_MS, () => res.destroy()) }
|
|
353
358
|
const MAX_TEAM_NAME = 100
|
|
354
359
|
// Managed data routes, and with them the authentication routes, which an
|
|
355
360
|
// admin's view as another user covers. Other paths fall through to a combined
|
|
@@ -379,10 +384,8 @@ async function handleWorkspaceFixes(res: ServerResponse, deps: ManagedHttpDeps,
|
|
|
379
384
|
const currentUrls = storedFixUrls(await deps.db.listTriageFixes(ids))
|
|
380
385
|
if (await readWorkspaceSession(res, deps, cookie) == null) return
|
|
381
386
|
await recheckTeam(deps.db, s.session.id, snapshot)
|
|
382
|
-
if (JSON.stringify(currentUrls) !== JSON.stringify(manualUrls)
|
|
383
|
-
|
|
384
|
-
}
|
|
385
|
-
if (result.updates.length > 0 && !await deps.db.applyManagedIssueFixes(s.session.id, snapshot, result.updates)) {
|
|
387
|
+
if (JSON.stringify(currentUrls) !== JSON.stringify(manualUrls)
|
|
388
|
+
|| (result.updates.length > 0 && !await deps.db.applyManagedIssueFixes(s.session.id, snapshot, result.updates))) {
|
|
386
389
|
sendJson(res, 404, { error: 'workspace-changed' }); return
|
|
387
390
|
}
|
|
388
391
|
sendJson(res, 200, { fixes: result.fixes })
|
|
@@ -488,10 +491,23 @@ export interface ManagedHttpDeps {
|
|
|
488
491
|
|
|
489
492
|
type Handler = (req: IncomingMessage, res: ServerResponse) => void | Promise<void>
|
|
490
493
|
|
|
494
|
+
// Work going on behind a request's answer: tracked, and on serverless its
|
|
495
|
+
// invocation kept alive till it settles.
|
|
496
|
+
function trackBehind(deps: ManagedHttpDeps, work: Promise<unknown>): void {
|
|
497
|
+
deps.track(work)
|
|
498
|
+
deps.waitUntil?.(work)
|
|
499
|
+
}
|
|
500
|
+
|
|
491
501
|
function send405(res: ServerResponse, allow: string): void {
|
|
492
502
|
sendJson(res, 405, { error: 'method-not-allowed' }, { allow })
|
|
493
503
|
}
|
|
494
504
|
|
|
505
|
+
// A redirect, never kept, setting `setCookie`.
|
|
506
|
+
function sendRedirect(res: ServerResponse, location: string, setCookie: string | string[]): void {
|
|
507
|
+
res.writeHead(302, { location, 'set-cookie': setCookie, 'cache-control': 'no-store' })
|
|
508
|
+
res.end()
|
|
509
|
+
}
|
|
510
|
+
|
|
495
511
|
function firstHeader(v: string | string[] | undefined): string | null {
|
|
496
512
|
if (typeof v === 'string') return v
|
|
497
513
|
if (Array.isArray(v) && v.length > 0) return v[0] ?? null
|
|
@@ -507,7 +523,7 @@ function firstHeader(v: string | string[] | undefined): string | null {
|
|
|
507
523
|
const USER_AVATAR_CACHE = 'private, max-age=300, stale-while-revalidate=86400'
|
|
508
524
|
|
|
509
525
|
// `key` is the image chosen for `id`; one not cached falls back to `id`'s own.
|
|
510
|
-
async function serveAvatar(req: IncomingMessage, res: ServerResponse, avatarStore: AvatarStore, id: string, key
|
|
526
|
+
async function serveAvatar(req: IncomingMessage, res: ServerResponse, avatarStore: AvatarStore, id: string, key: string, cacheControl = USER_AVATAR_CACHE): Promise<void> {
|
|
511
527
|
sendAvatar(req, res, await avatarStore.get(key) ?? (key === id ? null : await avatarStore.get(id)), cacheControl)
|
|
512
528
|
}
|
|
513
529
|
|
|
@@ -563,18 +579,25 @@ async function readBodyBytes(req: IncomingMessage, maxBytes: number): Promise<Bu
|
|
|
563
579
|
|
|
564
580
|
// A file upload's content, opening a body the browser sealed to this session
|
|
565
581
|
// (common/managed/upload-seal.ts). Link reports are never sent in parts; the
|
|
566
|
-
// parts of one sent in them are deleted behind its answer.
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
582
|
+
// parts of one sent in them are deleted behind its answer. Null, answered,
|
|
583
|
+
// where it can't be read: 413 past its size, else 400.
|
|
584
|
+
async function readUploadBody(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, session: ManagedSession, kind: UploadKind | 'links'): Promise<Buffer | null> {
|
|
585
|
+
try {
|
|
586
|
+
const maxBytes = kind === 'bundles' ? deps.config.maxBundleBytes : deps.config.maxReportBytes
|
|
587
|
+
const sealed = req.headers[UPLOAD_SEAL_HEADER] !== undefined
|
|
588
|
+
const limit = sealed ? maxSealedBytes(maxBytes) : maxBytes
|
|
589
|
+
let bytes
|
|
590
|
+
if (kind === 'links' || req.headers['x-upload-id'] == null) bytes = await readBodyBytes(req, limit)
|
|
591
|
+
else if (deps.uploadStore) {
|
|
592
|
+
bytes = await readUpload(deps.uploadStore, req, session.id, kind, limit, cleanup => { trackBehind(deps, cleanup) })
|
|
593
|
+
}
|
|
594
|
+
else throw new Error('bad-upload')
|
|
595
|
+
return sealed ? await openSessionUpload(session.uploadKey, bytes, maxBytes) : bytes
|
|
596
|
+
} catch (err) {
|
|
597
|
+
const tooLarge = err instanceof Error && err.message === 'too-large'
|
|
598
|
+
sendJson(res, tooLarge ? 413 : 400, { error: tooLarge ? 'too-large' : 'bad-body' })
|
|
599
|
+
return null
|
|
575
600
|
}
|
|
576
|
-
else throw new Error('bad-upload')
|
|
577
|
-
return sealed ? await openSessionUpload(session.uploadKey, bytes, maxBytes) : bytes
|
|
578
601
|
}
|
|
579
602
|
|
|
580
603
|
// GET /api/admin/uploads/key — the session's upload public key, created on
|
|
@@ -591,8 +614,8 @@ async function handleUploadKey(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
591
614
|
async function handleUploadPart(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, path: string) {
|
|
592
615
|
const cancel = req.method === 'DELETE'
|
|
593
616
|
if (req.method !== 'POST' && !cancel) { send405(res, 'POST, DELETE'); return }
|
|
594
|
-
const s = await
|
|
595
|
-
if (!s
|
|
617
|
+
const s = await manageMutation(req, res, deps, cookie, { handed: true })
|
|
618
|
+
if (!s) return
|
|
596
619
|
if (!deps.uploadStore) { sendJson(res, 404, { error: 'not-found' }); return }
|
|
597
620
|
const match = /^\/api\/admin\/uploads\/(reports|bundles)\/([^/]+)(?:\/(0|[1-9][0-9]*))?$/u.exec(path)
|
|
598
621
|
if (!match || (cancel ? match[3] !== undefined : match[3] === undefined)) { sendJson(res, 400, { error: 'bad-upload' }); return }
|
|
@@ -627,6 +650,24 @@ async function readJsonBody(req: IncomingMessage, maxBytes = MAX_JSON_BODY_BYTES
|
|
|
627
650
|
return JSON.parse(buf.toString('utf8') || 'null')
|
|
628
651
|
}
|
|
629
652
|
|
|
653
|
+
// A mutation's JSON body (readJsonBody), for the fields it names to be read:
|
|
654
|
+
// none of one that is no object (null, `false`, `0`, `""`, an array), which
|
|
655
|
+
// is answered as one naming none. Null, answered 400, where it can't be read.
|
|
656
|
+
async function readBodyFields(req: IncomingMessage, res: ServerResponse, maxBytes?: number): Promise<Record<string, unknown> | null> {
|
|
657
|
+
let body: unknown
|
|
658
|
+
try { body = await readJsonBody(req, maxBytes) } catch { sendJson(res, 400, { error: 'bad-body' }); return null }
|
|
659
|
+
return plainObject(body) ? body : {}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// A JSON body (readJsonBody) that is an object; null, answered 400, where it
|
|
663
|
+
// is none.
|
|
664
|
+
async function readBodyObject(req: IncomingMessage, res: ServerResponse, maxBytes?: number): Promise<Record<string, unknown> | null> {
|
|
665
|
+
const body = await readJsonBody(req, maxBytes).catch(() => null)
|
|
666
|
+
if (plainObject(body)) return body
|
|
667
|
+
sendJson(res, 400, { error: 'bad-body' })
|
|
668
|
+
return null
|
|
669
|
+
}
|
|
670
|
+
|
|
630
671
|
// The router enforces same-origin for every request. A mutation also needs an
|
|
631
672
|
// authenticated session whose CSRF token matches the X-CSRF-Token header.
|
|
632
673
|
// Returns the session, or null after having already sent the 401/403. An
|
|
@@ -679,12 +720,11 @@ async function handleViewAs(req: IncomingMessage, res: ServerResponse, deps: Man
|
|
|
679
720
|
res.end(); return
|
|
680
721
|
}
|
|
681
722
|
if (method !== 'POST') { send405(res, 'POST, DELETE'); return }
|
|
682
|
-
const s = await
|
|
723
|
+
const s = await adminMutation(req, res, deps, cookie)
|
|
683
724
|
if (s == null) return
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
const userId = (body as { userId?: unknown } | null)?.userId
|
|
725
|
+
const body = await readBodyFields(req, res)
|
|
726
|
+
if (!body) return
|
|
727
|
+
const { userId } = body
|
|
688
728
|
if (typeof userId !== 'string') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
689
729
|
if (userId === s.user.id) { sendJson(res, 400, { error: 'cannot-view-as-self' }); return }
|
|
690
730
|
const target = await deps.db.getUser(userId)
|
|
@@ -710,8 +750,8 @@ async function handleProfile(req: IncomingMessage, res: ServerResponse, deps: Ma
|
|
|
710
750
|
if (method !== 'POST') { send405(res, 'GET, POST'); return }
|
|
711
751
|
const s = await profileMutation(req, res, deps, cookie)
|
|
712
752
|
if (s == null) return
|
|
713
|
-
|
|
714
|
-
|
|
753
|
+
const body = await readBodyFields(req, res)
|
|
754
|
+
if (!body) return
|
|
715
755
|
const choice = parseProfileChoice(body)
|
|
716
756
|
if (choice == null) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
717
757
|
await deps.db.setProfileChoice(s.session.id, choice, Date.now())
|
|
@@ -745,11 +785,11 @@ async function sendProfile(res: ServerResponse, deps: ManagedHttpDeps, userId: s
|
|
|
745
785
|
|
|
746
786
|
// { name?, avatar? }, each a linked account's id or null; at least one.
|
|
747
787
|
function parseProfileChoice(body: unknown): ProfileChoice | null {
|
|
748
|
-
if (
|
|
788
|
+
if (!plainObject(body)) return null
|
|
749
789
|
const choice: ProfileChoice = {}
|
|
750
790
|
for (const key of ['name', 'avatar'] as const) {
|
|
751
791
|
if (!Object.hasOwn(body, key)) continue
|
|
752
|
-
const value =
|
|
792
|
+
const value = body[key]
|
|
753
793
|
if (value !== null && (typeof value !== 'string' || !isBlobId(value))) return null
|
|
754
794
|
choice[key] = value
|
|
755
795
|
}
|
|
@@ -761,13 +801,11 @@ function parseProfileChoice(body: unknown): ProfileChoice | null {
|
|
|
761
801
|
// at least one admin).
|
|
762
802
|
async function handleSetRole(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
763
803
|
if ((req.method ?? 'GET') !== 'POST') { send405(res, 'POST'); return }
|
|
764
|
-
const s = await
|
|
804
|
+
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
765
805
|
if (s == null) return
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
const userId = (body as { userId?: unknown } | null)?.userId
|
|
770
|
-
const role = (body as { role?: unknown } | null)?.role
|
|
806
|
+
const body = await readBodyFields(req, res)
|
|
807
|
+
if (!body) return
|
|
808
|
+
const { userId, role } = body
|
|
771
809
|
if (typeof userId !== 'string' || !isRole(role)) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
772
810
|
if (userId === s.user.id) { sendJson(res, 403, { error: 'cannot-change-own-role' }); return }
|
|
773
811
|
const target = await deps.db.getUser(userId)
|
|
@@ -841,6 +879,13 @@ async function handleListModels(res: ServerResponse, deps: ManagedHttpDeps, cook
|
|
|
841
879
|
sendJson(res, 200, { models: MANAGED_SCAN_MODELS, defaultModel: DEFAULT_MANAGED_SCAN_MODEL })
|
|
842
880
|
}
|
|
843
881
|
|
|
882
|
+
// A repository GitHub lists, as the repository list shows it: `selected`
|
|
883
|
+
// where it is among those connected.
|
|
884
|
+
const listedRepository = (repo: ConnectedRepo, selected: ReadonlySet<number>) => ({
|
|
885
|
+
id: repo.id, fullName: repo.fullName, private: repo.private, visibility: repo.visibility, htmlUrl: repo.htmlUrl,
|
|
886
|
+
installed: repo.installationId != null, selected: selected.has(repo.id),
|
|
887
|
+
})
|
|
888
|
+
|
|
844
889
|
// GET /api/admin/repositories — the connected repositories by default. The
|
|
845
890
|
// potentially large GitHub discovery lists are opt-in (`scope=installed` or
|
|
846
891
|
// `scope=public`). Return the complete catalogue for local search and organization
|
|
@@ -859,10 +904,7 @@ async function handleListRepositories(req: IncomingMessage, res: ServerResponse,
|
|
|
859
904
|
const selected = new Set((await deps.db.listSelectedRepos()).map((repo) => repo.repoId))
|
|
860
905
|
sendJson(res, 200, {
|
|
861
906
|
installUrl: installUrl(deps.config),
|
|
862
|
-
repositories: listing.repositories.map(
|
|
863
|
-
id: repo.id, fullName: repo.fullName, private: repo.private, visibility: repo.visibility, htmlUrl: repo.htmlUrl,
|
|
864
|
-
installed: repo.installationId != null, selected: selected.has(repo.id),
|
|
865
|
-
})),
|
|
907
|
+
repositories: listing.repositories.map(repo => listedRepository(repo, selected)),
|
|
866
908
|
tokenMissing: listing.tokenMissing,
|
|
867
909
|
})
|
|
868
910
|
return
|
|
@@ -895,11 +937,7 @@ async function handleListRepositories(req: IncomingMessage, res: ServerResponse,
|
|
|
895
937
|
return
|
|
896
938
|
}
|
|
897
939
|
tokenMissing = listing.tokenMissing
|
|
898
|
-
repositories = listing.repositories
|
|
899
|
-
.map((r) => ({
|
|
900
|
-
id: r.id, fullName: r.fullName, private: r.private, visibility: r.visibility, htmlUrl: r.htmlUrl,
|
|
901
|
-
installed: r.installationId != null, selected: selected.has(r.id),
|
|
902
|
-
}))
|
|
940
|
+
repositories = listing.repositories.map(repo => listedRepository(repo, selected))
|
|
903
941
|
}
|
|
904
942
|
repositories.sort((a, b) => a.fullName.localeCompare(b.fullName))
|
|
905
943
|
const total = repositories.length
|
|
@@ -968,9 +1006,9 @@ async function handleAddPublicRepository(req: IncomingMessage, res: ServerRespon
|
|
|
968
1006
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
969
1007
|
if (s == null) return
|
|
970
1008
|
if (!canAddAnyPublicRepository(s.user, await deps.db.getUserGithubId(s.user.id))) { sendJson(res, 403, { error: 'forbidden' }); return }
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
const fullName = publicRepositoryName(
|
|
1009
|
+
const body = await readBodyFields(req, res)
|
|
1010
|
+
if (!body) return
|
|
1011
|
+
const fullName = publicRepositoryName(body['repository'])
|
|
974
1012
|
if (fullName == null) { sendJson(res, 400, { error: 'bad-repository' }); return }
|
|
975
1013
|
let repo
|
|
976
1014
|
try { repo = await fetchPublicRepository(fullName) } catch (err) {
|
|
@@ -991,9 +1029,9 @@ async function handleConnectRepositoryApp(req: IncomingMessage, res: ServerRespo
|
|
|
991
1029
|
if ((req.method ?? 'GET') !== 'POST') { send405(res, 'POST'); return }
|
|
992
1030
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
993
1031
|
if (s == null) return
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
const
|
|
1032
|
+
const body = await readBodyFields(req, res)
|
|
1033
|
+
if (!body) return
|
|
1034
|
+
const { repoId } = body
|
|
997
1035
|
if (typeof repoId !== 'number' || !Number.isSafeInteger(repoId) || repoId <= 0) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
998
1036
|
const repo = (await deps.db.listAllRepos()).find(row => row.repoId === repoId)
|
|
999
1037
|
if (repo == null) { sendJson(res, 404, { error: 'repo-not-connected' }); return }
|
|
@@ -1031,10 +1069,9 @@ async function handleSelectRepository(req: IncomingMessage, res: ServerResponse,
|
|
|
1031
1069
|
if ((req.method ?? 'GET') !== 'POST') { send405(res, 'POST'); return }
|
|
1032
1070
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
1033
1071
|
if (s == null) return
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
const
|
|
1037
|
-
const selected = (body as { selected?: unknown } | null)?.selected
|
|
1072
|
+
const body = await readBodyFields(req, res)
|
|
1073
|
+
if (!body) return
|
|
1074
|
+
const { repoId, selected } = body
|
|
1038
1075
|
if (typeof repoId !== 'number' || !Number.isSafeInteger(repoId) || typeof selected !== 'boolean') {
|
|
1039
1076
|
sendJson(res, 400, { error: 'bad-request' }); return
|
|
1040
1077
|
}
|
|
@@ -1060,17 +1097,15 @@ async function handleRepositoryDependencyReview(req: IncomingMessage, res: Serve
|
|
|
1060
1097
|
if ((req.method ?? 'GET') !== 'POST') { send405(res, 'POST'); return }
|
|
1061
1098
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
1062
1099
|
if (s == null) return
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
const repoId = body
|
|
1066
|
-
const
|
|
1067
|
-
const required = body?.['required']
|
|
1068
|
-
const since = body?.['since'] ?? null
|
|
1100
|
+
const body = await readBodyFields(req, res)
|
|
1101
|
+
if (!body) return
|
|
1102
|
+
const { repoId, enabled, required } = body
|
|
1103
|
+
const since = body['since'] ?? null
|
|
1069
1104
|
// The lockfiles it holds to, kept as they are where none is sent.
|
|
1070
|
-
const lockfiles = body
|
|
1105
|
+
const lockfiles = body['lockfiles'] === undefined ? undefined : scopeOf(body['lockfiles'])
|
|
1071
1106
|
if (typeof repoId !== 'number' || !Number.isSafeInteger(repoId) || typeof enabled !== 'boolean'
|
|
1072
1107
|
|| typeof required !== 'number' || !Number.isSafeInteger(required) || required < 1 || required > MAX_REQUIRED_REVIEWS
|
|
1073
|
-
|| (since !== null && (typeof since !== 'string' || !
|
|
1108
|
+
|| (since !== null && (typeof since !== 'string' || !SHA.test(since))) || lockfiles === null) {
|
|
1074
1109
|
sendJson(res, 400, { error: 'bad-request' }); return
|
|
1075
1110
|
}
|
|
1076
1111
|
if (since !== null && deps.reviewedDependencies) { sendJson(res, 400, { error: 'since-unsupported' }); return }
|
|
@@ -1143,15 +1178,11 @@ async function handleRepositoryImpact(req: IncomingMessage, res: ServerResponse,
|
|
|
1143
1178
|
// attached reports/bundles. The exact name + explicit acknowledgement are
|
|
1144
1179
|
// checked server-side too; the UI's dialog is a usability guard, not the policy.
|
|
1145
1180
|
async function handleRemoveRepository(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
1146
|
-
const s = await
|
|
1181
|
+
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
1147
1182
|
if (s == null) return
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
const repoId = (body as { repoId?: unknown } | null)?.repoId
|
|
1152
|
-
const fullName = (body as { fullName?: unknown } | null)?.fullName
|
|
1153
|
-
const acknowledge = (body as { acknowledge?: unknown } | null)?.acknowledge
|
|
1154
|
-
const deleteTriage = (body as { deleteTriage?: unknown } | null)?.deleteTriage
|
|
1183
|
+
const body = await readBodyFields(req, res)
|
|
1184
|
+
if (!body) return
|
|
1185
|
+
const { repoId, fullName, acknowledge, deleteTriage } = body
|
|
1155
1186
|
if (typeof repoId !== 'number' || !Number.isSafeInteger(repoId) || typeof fullName !== 'string' || acknowledge !== true || typeof deleteTriage !== 'boolean') {
|
|
1156
1187
|
sendJson(res, 400, { error: 'confirmation-required' }); return
|
|
1157
1188
|
}
|
|
@@ -1240,11 +1271,11 @@ async function resolveUploadRepoId(req: IncomingMessage, res: ServerResponse, de
|
|
|
1240
1271
|
async function handleSetReportRepo(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
1241
1272
|
const s = await manageMutation(req, res, deps, cookie, { handed: true })
|
|
1242
1273
|
if (s == null) return
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
const
|
|
1246
|
-
const repoId =
|
|
1247
|
-
const directory =
|
|
1274
|
+
const body = await readBodyFields(req, res)
|
|
1275
|
+
if (!body) return
|
|
1276
|
+
const { reportId } = body
|
|
1277
|
+
const repoId = body['repoId'] ?? null
|
|
1278
|
+
const directory = body['directory'] ?? ''
|
|
1248
1279
|
if (typeof reportId !== 'string') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
1249
1280
|
if (repoId !== null && (typeof repoId !== 'number' || !Number.isSafeInteger(repoId))) { sendJson(res, 400, { error: 'bad-repo' }); return }
|
|
1250
1281
|
const normalized = normalizeTeamPath(directory)
|
|
@@ -1261,10 +1292,9 @@ async function handleSetReportRepo(req: IncomingMessage, res: ServerResponse, de
|
|
|
1261
1292
|
async function handleSetReportVisible(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
1262
1293
|
const s = await manageMutation(req, res, deps, cookie, { handed: true })
|
|
1263
1294
|
if (s == null) return
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
const
|
|
1267
|
-
const visible = (body as { visible?: unknown } | null)?.visible
|
|
1295
|
+
const body = await readBodyFields(req, res)
|
|
1296
|
+
if (!body) return
|
|
1297
|
+
const { reportId, visible } = body
|
|
1268
1298
|
if (typeof reportId !== 'string' || typeof visible !== 'boolean') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
1269
1299
|
const { report, user } = await deps.db.mutateReport(s.session.id, reportId, { type: 'visibility', visible })
|
|
1270
1300
|
if (report.visible !== visible) await activity(deps, user, 'visibility', visible ? 'published a report' : 'hid a report', { reportId, report: report.filename, repo: await repositoryName(deps, report.repoId) })
|
|
@@ -1274,10 +1304,9 @@ async function handleSetReportVisible(req: IncomingMessage, res: ServerResponse,
|
|
|
1274
1304
|
async function handleSetBundleVisible(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
1275
1305
|
const s = await manageMutation(req, res, deps, cookie, { handed: true })
|
|
1276
1306
|
if (s == null) return
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
const
|
|
1280
|
-
const visible = (body as { visible?: unknown } | null)?.visible
|
|
1307
|
+
const body = await readBodyFields(req, res)
|
|
1308
|
+
if (!body) return
|
|
1309
|
+
const { bundleId, visible } = body
|
|
1281
1310
|
if (typeof bundleId !== 'string' || typeof visible !== 'boolean') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
1282
1311
|
const { bundle, user } = await deps.db.mutateBundle(s.session.id, bundleId, { type: 'visibility', visible })
|
|
1283
1312
|
if (bundle.visible !== visible) await activity(deps, user, 'visibility', visible ? 'published a bundle' : 'hid a bundle', { bundleId, report: bundle.filename, repo: await repositoryName(deps, bundle.repoId) })
|
|
@@ -1289,11 +1318,11 @@ async function handleSetBundleVisible(req: IncomingMessage, res: ServerResponse,
|
|
|
1289
1318
|
async function handleSetBundleRepo(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
1290
1319
|
const s = await manageMutation(req, res, deps, cookie, { handed: true })
|
|
1291
1320
|
if (s == null) return
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
const
|
|
1295
|
-
const repoId =
|
|
1296
|
-
const normalized = normalizeTeamPath(
|
|
1321
|
+
const body = await readBodyFields(req, res)
|
|
1322
|
+
if (!body) return
|
|
1323
|
+
const { bundleId } = body
|
|
1324
|
+
const repoId = body['repoId'] ?? null
|
|
1325
|
+
const normalized = normalizeTeamPath(body['directory'] ?? '')
|
|
1297
1326
|
if (!normalized.ok) { sendJson(res, 400, { error: 'bad-directory' }); return }
|
|
1298
1327
|
const directory = repoId == null ? '' : normalized.path ?? ''
|
|
1299
1328
|
if (typeof bundleId !== 'string') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
@@ -1328,8 +1357,8 @@ async function resolveReportBundle(deps: ManagedHttpDeps, user: StoredUser, json
|
|
|
1328
1357
|
}
|
|
1329
1358
|
|
|
1330
1359
|
async function sendUploadedReport(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, report: ReportRecord, deduped: boolean): Promise<void> {
|
|
1331
|
-
const current = await
|
|
1332
|
-
if (!current
|
|
1360
|
+
const current = await manageMutation(req, res, deps, cookie)
|
|
1361
|
+
if (!current) return
|
|
1333
1362
|
// Uploading known bytes cannot reveal another team's report or its source
|
|
1334
1363
|
// bundle. The stored location/ownership wins over the upload headers.
|
|
1335
1364
|
if (!(await canViewReport(deps, current.user, report.id))) { sendJson(res, 409, { error: 'report-conflict' }); return }
|
|
@@ -1351,20 +1380,13 @@ async function sendUploadedReport(req: IncomingMessage, res: ServerResponse, dep
|
|
|
1351
1380
|
// insert failure or concurrent duplicate drops the orphan blob; an uncertain
|
|
1352
1381
|
// commit retains it. 413 over the cap, 400 on empty.
|
|
1353
1382
|
async function handleUploadReport(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
1354
|
-
let s = await
|
|
1383
|
+
let s = await manageMutation(req, res, deps, cookie, { handed: true })
|
|
1355
1384
|
if (s == null) return
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
try {
|
|
1359
|
-
bytes = await readUploadBody(req, deps, s.session, 'reports')
|
|
1360
|
-
} catch (err) {
|
|
1361
|
-
const tooLarge = err instanceof Error && err.message === 'too-large'
|
|
1362
|
-
sendJson(res, tooLarge ? 413 : 400, { error: tooLarge ? 'too-large' : 'bad-body' })
|
|
1363
|
-
return
|
|
1364
|
-
}
|
|
1385
|
+
const bytes = await readUploadBody(req, res, deps, s.session, 'reports')
|
|
1386
|
+
if (!bytes) return
|
|
1365
1387
|
// Shared storage reads may outlast a session or role change.
|
|
1366
|
-
s = await
|
|
1367
|
-
if (!s
|
|
1388
|
+
s = await manageMutation(req, res, deps, cookie)
|
|
1389
|
+
if (!s) return
|
|
1368
1390
|
if (bytes.length === 0) { sendJson(res, 400, { error: 'empty' }); return }
|
|
1369
1391
|
const filename = sanitizeFilename(firstHeader(req.headers['x-report-filename']), 'report.json')
|
|
1370
1392
|
const parsed = readManagedReport(bytes.toString('utf8'), filename)
|
|
@@ -1482,9 +1504,8 @@ async function handleGetReport(res: ServerResponse, deps: ManagedHttpDeps, cooki
|
|
|
1482
1504
|
// same-origin + CSRF. Drops the row, then best-effort the bytes; 404 when there
|
|
1483
1505
|
// was no such report.
|
|
1484
1506
|
async function handleDeleteReport(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, id: string): Promise<void> {
|
|
1485
|
-
const s = await
|
|
1507
|
+
const s = await manageMutation(req, res, deps, cookie, { handed: true })
|
|
1486
1508
|
if (s == null) return
|
|
1487
|
-
if (!requireManageRole(res, s.user)) return
|
|
1488
1509
|
const { report, user } = await deps.db.mutateReport(s.session.id, id, { type: 'delete' })
|
|
1489
1510
|
await deps.reportSourcesCache?.deleteReport(report).catch((err) => { console.warn('managed: report sources delete failed:', err) })
|
|
1490
1511
|
await deps.reportStore.delete(id).catch((err) => { console.warn('managed: report bytes delete failed:', err) })
|
|
@@ -1516,6 +1537,12 @@ async function repositoryBrowserUser(deps: ManagedHttpDeps, userId: string) {
|
|
|
1516
1537
|
return { githubUserId, token }
|
|
1517
1538
|
}
|
|
1518
1539
|
|
|
1540
|
+
// The repository browser's reader of `repo` (repository-browser.ts), with
|
|
1541
|
+
// user `userId`'s own GitHub access.
|
|
1542
|
+
async function repositoryReader(deps: ManagedHttpDeps, userId: string, repo: SelectedRepo) {
|
|
1543
|
+
return createRepositoryBrowser(deps.config, await repositoryBrowserUser(deps, userId)).reader(repo)
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1519
1546
|
// After a catalog response: read the commit details it lacked with this
|
|
1520
1547
|
// user's repository access, for the next catalog to send.
|
|
1521
1548
|
async function backfillCatalogCommits(deps: ManagedHttpDeps, userId: string, missing: readonly CatalogCommit[]): Promise<void> {
|
|
@@ -1580,13 +1607,20 @@ function scopeRepositoryContents(contents: RepositoryContents | null, virtualEnt
|
|
|
1580
1607
|
} : {}) }
|
|
1581
1608
|
}
|
|
1582
1609
|
|
|
1610
|
+
// The repository a read's query names by its id (`repoId`); null where it
|
|
1611
|
+
// names none.
|
|
1612
|
+
function askedRepoId(query: URLSearchParams): number | null {
|
|
1613
|
+
const repoId = Number(query.get('repoId'))
|
|
1614
|
+
return Number.isSafeInteger(repoId) && repoId > 0 ? repoId : null
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1583
1617
|
// A browse's repository, revision and directory, as its query names them;
|
|
1584
1618
|
// null, answered, where it names none.
|
|
1585
1619
|
function repositoryQuery(res: ServerResponse, query: URLSearchParams) {
|
|
1586
|
-
const repoId =
|
|
1620
|
+
const repoId = askedRepoId(query)
|
|
1587
1621
|
const normalized = normalizeTeamPath(query.get('path') ?? '')
|
|
1588
1622
|
const ref = query.get('ref') ?? ''
|
|
1589
|
-
if (
|
|
1623
|
+
if (repoId === null || !normalized.ok || ref.length > 1024 || /\p{Cc}/u.test(ref)) {
|
|
1590
1624
|
sendJson(res, 400, { error: 'bad-request' }); return null
|
|
1591
1625
|
}
|
|
1592
1626
|
return { repoId, ref, path: normalized.path ?? '' }
|
|
@@ -1595,17 +1629,31 @@ function repositoryQuery(res: ServerResponse, query: URLSearchParams) {
|
|
|
1595
1629
|
// The repository `repoId` as the reader may browse it at `path`: one of their
|
|
1596
1630
|
// bundle repositories, and what their grants show of that directory
|
|
1597
1631
|
// (`virtualEntries`, null where they reach all of it: scopedDirectory). Null,
|
|
1598
|
-
// answered, where it is none of theirs
|
|
1599
|
-
//
|
|
1600
|
-
//
|
|
1601
|
-
|
|
1632
|
+
// answered, where it is none of theirs, or, `whole`, where they reach only
|
|
1633
|
+
// some of that directory. Every team member (view or above) reads the
|
|
1634
|
+
// repositories their teams reach; the reader then checks their own GitHub
|
|
1635
|
+
// read permission (repository-browser.ts), on each read.
|
|
1636
|
+
async function authorizeRepository(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, repoId: number, path: string, { handed = false, whole = false } = {}) {
|
|
1602
1637
|
const s = await readWorkspaceSession(res, deps, cookie, { handed })
|
|
1603
1638
|
if (!s) return null
|
|
1604
1639
|
const access = repositoryAccessIn(await repositoryGrants(deps, s.user), repoId, path)
|
|
1605
1640
|
if (!access) { sendJson(res, 404, { error: 'no-repository' }); return null }
|
|
1641
|
+
if (whole && access.virtualEntries !== null) { sendJson(res, 404, { error: 'no-directory' }); return null }
|
|
1606
1642
|
return { ...access, user: s.user }
|
|
1607
1643
|
}
|
|
1608
1644
|
|
|
1645
|
+
// What `authorize` answers once `reader` has read the repository `authorized`
|
|
1646
|
+
// names: the reader's GitHub access checked again, then their grants, and it
|
|
1647
|
+
// still the same repository; else null, answered.
|
|
1648
|
+
async function stillAuthorized<T extends { repo: SelectedRepo }>(res: ServerResponse, reader: RepositoryReader, authorize: () => Promise<T | null>,
|
|
1649
|
+
authorized: SelectedRepo): Promise<T | null> {
|
|
1650
|
+
await reader.recheckAccess()
|
|
1651
|
+
const current = await authorize()
|
|
1652
|
+
if (!current) return null
|
|
1653
|
+
if (!sameRepository(current.repo, authorized)) { sendJson(res, 409, { error: 'repository-changed' }); return null }
|
|
1654
|
+
return current
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1609
1657
|
// What a reader's grants let them read of the repositories (bundleRepos's
|
|
1610
1658
|
// reads, the reader's scopes read once for both), for repositoryAccessIn to
|
|
1611
1659
|
// tell of each: read once for as many repositories as a request asks of.
|
|
@@ -1629,7 +1677,12 @@ const sameRepository = (current: SelectedRepo, authorized: SelectedRepo) =>
|
|
|
1629
1677
|
JSON.stringify({ ...current, cachedDefaultBranch: authorized.cachedDefaultBranch }) === JSON.stringify(authorized)
|
|
1630
1678
|
|
|
1631
1679
|
function sendGithubError(res: ServerResponse, err: GithubApiError) {
|
|
1632
|
-
|
|
1680
|
+
sendRefusal(res, githubRefusal(err))
|
|
1681
|
+
}
|
|
1682
|
+
// `err` answered where it is GitHub's failure (sendGithubError), else thrown on.
|
|
1683
|
+
function answerGithubFailure(res: ServerResponse, err: unknown): void {
|
|
1684
|
+
if (!(err instanceof GithubApiError)) throw err
|
|
1685
|
+
sendGithubError(res, err)
|
|
1633
1686
|
}
|
|
1634
1687
|
|
|
1635
1688
|
// Recheck repository/path grants after upstream reads, before returning names.
|
|
@@ -1650,8 +1703,7 @@ async function handleRepositoryBrowser(res: ServerResponse, deps: ManagedHttpDep
|
|
|
1650
1703
|
const access = await authorize(true)
|
|
1651
1704
|
if (!access) return
|
|
1652
1705
|
try {
|
|
1653
|
-
const
|
|
1654
|
-
const reader = await browser.reader(access.repo)
|
|
1706
|
+
const reader = await repositoryReader(deps, access.user.id, access.repo)
|
|
1655
1707
|
// Microseconds, so overlapping browses practically never share a listing time.
|
|
1656
1708
|
const observedUs = Math.round((performance.timeOrigin + performance.now()) * 1000)
|
|
1657
1709
|
const trees = repositoryTreesOf(deps)
|
|
@@ -1667,17 +1719,14 @@ async function handleRepositoryBrowser(res: ServerResponse, deps: ManagedHttpDep
|
|
|
1667
1719
|
if (refs || tags.length > 0) {
|
|
1668
1720
|
await deps.db.refreshGithubTags(access.repo.repoId, tags, refs && tagsComplete, observedUs).catch(err => { console.warn('managed: tag cache refresh failed:', err) })
|
|
1669
1721
|
}
|
|
1670
|
-
await reader.recheckAccess()
|
|
1671
|
-
const current = await authorize()
|
|
1672
|
-
if (!current) return
|
|
1673
1722
|
// This request (or another reader) may have refreshed the shared hint.
|
|
1674
|
-
|
|
1723
|
+
const current = await stillAuthorized(res, reader, authorize, access.repo)
|
|
1724
|
+
if (!current) return
|
|
1675
1725
|
sendJson(res, 200, refs ? { ...listed, tagCommits, ...(withDefault ? {
|
|
1676
1726
|
defaultContents: scopeRepositoryContents(revisions?.defaultContents ?? null, current.virtualEntries),
|
|
1677
1727
|
} : {}) } : commitOnly ? contents : scopeRepositoryContents(contents as RepositoryContents, current.virtualEntries))
|
|
1678
1728
|
} catch (err) {
|
|
1679
|
-
|
|
1680
|
-
throw err
|
|
1729
|
+
answerGithubFailure(res, err)
|
|
1681
1730
|
}
|
|
1682
1731
|
}
|
|
1683
1732
|
|
|
@@ -1707,7 +1756,7 @@ const REPOSITORY_LISTINGS_HELD = 256
|
|
|
1707
1756
|
const LISTING_READ = 1
|
|
1708
1757
|
type TreeFiles = Awaited<ReturnType<typeof repositoryTreeFiles>>
|
|
1709
1758
|
const repositoryTrees = new WeakMap<ManagedDb, { ids: Lru<string>; files: Lru<TreeFiles>; listings: Lru<DirectoryListing> }>()
|
|
1710
|
-
const treeId = (value: unknown): value is string => typeof value === 'string' &&
|
|
1759
|
+
const treeId = (value: unknown): value is string => typeof value === 'string' && SHA.test(value)
|
|
1711
1760
|
const treeFiles = (value: unknown): value is TreeFiles => value === null || (plainObject(value)
|
|
1712
1761
|
&& Number.isSafeInteger(value['files']) && (value['files'] as number) >= 0 && Number.isSafeInteger(value['bytes']) && (value['bytes'] as number) >= 0)
|
|
1713
1762
|
const directoryListing = (value: unknown): value is DirectoryListing => plainObject(value) && Array.isArray(value['entries']) && typeof value['limited'] === 'boolean'
|
|
@@ -1747,38 +1796,25 @@ async function keptTree<T>(memory: Lru<T>, store: KeptStore<T>, key: string, kep
|
|
|
1747
1796
|
function repositoryCodeKeptOf(deps: ManagedHttpDeps): RepositoryCodeKept | null {
|
|
1748
1797
|
if (!deps.repositoryCodeStorage) return null
|
|
1749
1798
|
const active = async (repoId: number) => (await deps.db.listSelectedRepos()).some(row => row.repoId === repoId)
|
|
1750
|
-
return repositoryCodeKept(deps.repositoryCodeStorage, codeHeadStore(deps.db, deps.config.debug), active, work => {
|
|
1751
|
-
deps.track(work)
|
|
1752
|
-
deps.waitUntil?.(work)
|
|
1753
|
-
}, deps.config.debug)
|
|
1799
|
+
return repositoryCodeKept(deps.repositoryCodeStorage, codeHeadStore(deps.db, deps.config.debug), active, work => { trackBehind(deps, work) }, deps.config.debug)
|
|
1754
1800
|
}
|
|
1755
1801
|
|
|
1756
1802
|
async function handleRepositoryCode(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
1757
1803
|
const asked = repositoryQuery(res, query)
|
|
1758
1804
|
if (!asked) return
|
|
1759
1805
|
const { repoId, ref, path } = asked
|
|
1760
|
-
const authorize =
|
|
1761
|
-
const access = await authorizeRepository(res, deps, cookie, repoId, path, { handed })
|
|
1762
|
-
if (access && access.virtualEntries !== null) { sendJson(res, 404, { error: 'no-directory' }); return null }
|
|
1763
|
-
return access
|
|
1764
|
-
}
|
|
1806
|
+
const authorize = (handed = false) => authorizeRepository(res, deps, cookie, repoId, path, { handed, whole: true })
|
|
1765
1807
|
const access = await authorize(true)
|
|
1766
1808
|
if (!access) return
|
|
1767
1809
|
try {
|
|
1768
|
-
const reader = await
|
|
1810
|
+
const reader = await repositoryReader(deps, access.user.id, access.repo)
|
|
1769
1811
|
const commit = await reader.commit(ref)
|
|
1770
1812
|
const repo = access.repo.fullName
|
|
1771
1813
|
const client = createClient({ token: reader.readToken() })
|
|
1772
1814
|
// Access still held, and the same repository, before anything read is sent.
|
|
1773
|
-
const fenced = async () =>
|
|
1774
|
-
await reader.recheckAccess()
|
|
1775
|
-
const current = await authorize()
|
|
1776
|
-
if (!current) return false
|
|
1777
|
-
if (!sameRepository(current.repo, access.repo)) { sendJson(res, 409, { error: 'repository-changed' }); return false }
|
|
1778
|
-
return true
|
|
1779
|
-
}
|
|
1815
|
+
const fenced = async () => await stillAuthorized(res, reader, authorize, access.repo) !== null
|
|
1780
1816
|
const send = (bytes: Buffer) => {
|
|
1781
|
-
|
|
1817
|
+
dropIdle(res)
|
|
1782
1818
|
res.writeHead(200, {
|
|
1783
1819
|
'content-type': 'application/json', 'content-encoding': 'br', 'content-length': String(bytes.byteLength),
|
|
1784
1820
|
'cache-control': 'private, no-store', 'x-content-type-options': 'nosniff',
|
|
@@ -1861,16 +1897,12 @@ async function handleRepositoryHistory(res: ServerResponse, deps: ManagedHttpDep
|
|
|
1861
1897
|
const starts = from === null ? null : historyStarts(from)
|
|
1862
1898
|
if (!Number.isSafeInteger(page) || page < 1 || page > MAX_HISTORY_PAGE || (all && (path !== '' || (page > 1) !== (starts !== null)))
|
|
1863
1899
|
|| (from !== null && (starts === null || path !== '' || page === 1))) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
1864
|
-
const authorize =
|
|
1865
|
-
const access = await authorizeRepository(res, deps, cookie, repoId, path, { handed })
|
|
1866
|
-
if (access && access.virtualEntries !== null) { sendJson(res, 404, { error: 'no-directory' }); return null }
|
|
1867
|
-
return access
|
|
1868
|
-
}
|
|
1900
|
+
const authorize = (handed = false) => authorizeRepository(res, deps, cookie, repoId, path, { handed, whole: true })
|
|
1869
1901
|
const access = await authorize(true)
|
|
1870
1902
|
if (!access) return
|
|
1871
1903
|
let readingPulls: Promise<{ number: number; sha: string }[] | null> = Promise.resolve(null)
|
|
1872
1904
|
try {
|
|
1873
|
-
const reader = await
|
|
1905
|
+
const reader = await repositoryReader(deps, access.user.id, access.repo)
|
|
1874
1906
|
const repo = access.repo.fullName
|
|
1875
1907
|
const token = reader.readToken()
|
|
1876
1908
|
// With a token, as GraphQL reads them.
|
|
@@ -1926,20 +1958,13 @@ async function handleRepositoryHistory(res: ServerResponse, deps: ManagedHttpDep
|
|
|
1926
1958
|
const none = { pulls: [] as SquashedPull[], pending: false }
|
|
1927
1959
|
const [squashed, openPulls] = token && path === '' ? await Promise.all([
|
|
1928
1960
|
pulseMerges(deps, repoId).catch(quiet(null)).then(known => squashedPulls(repo, token, listed, historySquashes(deps, repoId), SQUASH_WAIT_MS, globalThis.fetch, known)).then(read => {
|
|
1929
|
-
if (read.behind)
|
|
1930
|
-
const behind = read.behind.catch(quiet(null))
|
|
1931
|
-
deps.track(behind)
|
|
1932
|
-
deps.waitUntil?.(behind)
|
|
1933
|
-
}
|
|
1961
|
+
if (read.behind) trackBehind(deps, read.behind.catch(quiet(null)))
|
|
1934
1962
|
return read
|
|
1935
1963
|
}, quiet(none)),
|
|
1936
1964
|
readingPulls,
|
|
1937
1965
|
]) : [none, null]
|
|
1938
1966
|
const { pulls } = squashed
|
|
1939
|
-
await reader.
|
|
1940
|
-
const current = await authorize()
|
|
1941
|
-
if (!current) return
|
|
1942
|
-
if (!sameRepository(current.repo, access.repo)) { sendJson(res, 409, { error: 'repository-changed' }); return }
|
|
1967
|
+
if (!await stillAuthorized(res, reader, authorize, access.repo)) return
|
|
1943
1968
|
// Each commit as the tab draws it, its co-authors with it, told by the
|
|
1944
1969
|
// agents the app knows now (coauthorsOf): what Pulse counts of it (its
|
|
1945
1970
|
// lines, its author's time) and the addresses kept not sent.
|
|
@@ -1949,8 +1974,7 @@ async function handleRepositoryHistory(res: ServerResponse, deps: ManagedHttpDep
|
|
|
1949
1974
|
...pulls.length > 0 ? { pulls: pulls.map(pull => ({ ...pull, commits: pull.commits.map(shown) })) } : {}, ...squashed.pending ? { pullsPending: true } : {},
|
|
1950
1975
|
...openPulls?.length ? { openPulls } : {} }))
|
|
1951
1976
|
} catch (err) {
|
|
1952
|
-
|
|
1953
|
-
throw err
|
|
1977
|
+
answerGithubFailure(res, err)
|
|
1954
1978
|
} finally {
|
|
1955
1979
|
// A failed history must not release the request's database lease while
|
|
1956
1980
|
// its independent pull read is still writing to the cache.
|
|
@@ -1980,7 +2004,7 @@ async function handleRepositoryChanges(res: ServerResponse, deps: ManagedHttpDep
|
|
|
1980
2004
|
// reads are (readForReplay).
|
|
1981
2005
|
async function handleRepositoryTree(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
1982
2006
|
const commit = query.get('commit') ?? ''
|
|
1983
|
-
if (
|
|
2007
|
+
if (!SHA.test(commit)) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
1984
2008
|
const store = historyTreeStore<CommitTree>(deps.db, deps.config.debug)
|
|
1985
2009
|
await readForReplay(res, deps, cookie, query, async (fullName, token, repoId, path) => {
|
|
1986
2010
|
const kept = { read: async (sha: string) => {
|
|
@@ -2001,24 +2025,16 @@ async function readForReplay(res: ServerResponse, deps: ManagedHttpDeps, cookie:
|
|
|
2001
2025
|
const asked = repositoryQuery(res, query)
|
|
2002
2026
|
if (!asked) return
|
|
2003
2027
|
const { repoId, path } = asked
|
|
2004
|
-
const authorize =
|
|
2005
|
-
const access = await authorizeRepository(res, deps, cookie, repoId, path, { handed })
|
|
2006
|
-
if (access && access.virtualEntries !== null) { sendJson(res, 404, { error: 'no-directory' }); return null }
|
|
2007
|
-
return access
|
|
2008
|
-
}
|
|
2028
|
+
const authorize = (handed = false) => authorizeRepository(res, deps, cookie, repoId, path, { handed, whole: true })
|
|
2009
2029
|
const access = await authorize(true)
|
|
2010
2030
|
if (!access) return
|
|
2011
2031
|
try {
|
|
2012
|
-
const reader = await
|
|
2032
|
+
const reader = await repositoryReader(deps, access.user.id, access.repo)
|
|
2013
2033
|
const body = await read(access.repo.fullName, reader.readToken(), repoId, path)
|
|
2014
|
-
await reader.
|
|
2015
|
-
const current = await authorize()
|
|
2016
|
-
if (!current) return
|
|
2017
|
-
if (!sameRepository(current.repo, access.repo)) { sendJson(res, 409, { error: 'repository-changed' }); return }
|
|
2034
|
+
if (!await stillAuthorized(res, reader, authorize, access.repo)) return
|
|
2018
2035
|
sendJson(res, 200, body)
|
|
2019
2036
|
} catch (err) {
|
|
2020
|
-
|
|
2021
|
-
throw err
|
|
2037
|
+
answerGithubFailure(res, err)
|
|
2022
2038
|
}
|
|
2023
2039
|
}
|
|
2024
2040
|
|
|
@@ -2125,9 +2141,7 @@ async function keptAnswer<T extends object>(deps: ManagedHttpDeps, key: string,
|
|
|
2125
2141
|
if (held && !now) {
|
|
2126
2142
|
if (age >= REPOSITORY_READ_FRESH_MS && !repositoryRereads.has(key)) {
|
|
2127
2143
|
// Its failure leaves the kept answer sent until it is a day old, so it is said.
|
|
2128
|
-
|
|
2129
|
-
deps.track(behind)
|
|
2130
|
-
deps.waitUntil?.(behind)
|
|
2144
|
+
trackBehind(deps, reread().catch((err: unknown) => { console.warn('managed: repository read failed:', err) }))
|
|
2131
2145
|
}
|
|
2132
2146
|
return { value: held.value as T, kept: true, at: held.at }
|
|
2133
2147
|
}
|
|
@@ -2158,7 +2172,7 @@ const today = () => `\0${Math.floor(Date.now() / (24 * 60 * 60_000))}`
|
|
|
2158
2172
|
// neither), and with `marks`, only those telling the marks agents left on
|
|
2159
2173
|
// its commits by the rules they are read by now (app-agents.ts
|
|
2160
2174
|
// AGENT_MARKS_READ), as the Agents tab reads them; the rest read again.
|
|
2161
|
-
function historyPages(deps: ManagedHttpDeps, repoId: number, graphql
|
|
2175
|
+
function historyPages(deps: ManagedHttpDeps, repoId: number, graphql: boolean, marks = false): HistoryPages {
|
|
2162
2176
|
const store = historyPageStore<HistoryCommit[]>(deps.db, deps.config.debug)
|
|
2163
2177
|
const keyOf = (top: string) => `${repoId}\0${COAUTHORS_READ}\0${top}`
|
|
2164
2178
|
const told = (tops: string[], kept: Map<string, { value: HistoryCommit[] }>) => new Map(tops.flatMap(top => {
|
|
@@ -2271,7 +2285,7 @@ const keptIssues = (deps: ManagedHttpDeps, repoId: number, fullName: string, tok
|
|
|
2271
2285
|
// What is kept by `key` (keptAnswer), read now where it was read
|
|
2272
2286
|
// REPOSITORY_READ_FRESH_MS ago or longer, not behind: for an answer that is
|
|
2273
2287
|
// kept as fresh itself, as told of it (the Agents tab's).
|
|
2274
|
-
async function currentAnswer<T extends object>(deps: ManagedHttpDeps, key: string, read: () => Promise<T>, stamp: Stamp
|
|
2288
|
+
async function currentAnswer<T extends object>(deps: ManagedHttpDeps, key: string, read: () => Promise<T>, stamp: Stamp) {
|
|
2275
2289
|
const stored = await repositoryReadStore(deps.db, deps.config.debug).read(key)
|
|
2276
2290
|
return keptAnswer(deps, key, read, undefined, !stored || Date.now() - stored.at >= REPOSITORY_READ_FRESH_MS, stamp)
|
|
2277
2291
|
}
|
|
@@ -2285,7 +2299,7 @@ async function defaultTip(deps: ManagedHttpDeps, repoId: number, fullName: strin
|
|
|
2285
2299
|
const heads = await repositoryReadStore(deps.db, deps.config.debug).read(`${repoId}\0heads`)
|
|
2286
2300
|
const all = heads && Date.now() - heads.at < REPOSITORY_READ_FRESH_MS ? heads.value as AllHeads : null
|
|
2287
2301
|
const tip = all?.heads.find(head => head.name === all.defaultBranch)?.sha
|
|
2288
|
-
if (typeof tip === 'string' &&
|
|
2302
|
+
if (typeof tip === 'string' && SHA.test(tip)) return { sha: tip, kept: true }
|
|
2289
2303
|
const head = async () => ({ sha: await defaultHead(fullName, token) })
|
|
2290
2304
|
const stamp = stampOf(deps, repoId, fullName, token)
|
|
2291
2305
|
const read = await (current ? currentAnswer(deps, `${repoId}\0pulse-head`, head, stamp) : keptAnswer(deps, `${repoId}\0pulse-head`, head, undefined, false, stamp))
|
|
@@ -2338,10 +2352,9 @@ function historySquashes(deps: ManagedHttpDeps, repoId: number): Squashes {
|
|
|
2338
2352
|
// `readAt`, when it was read from GitHub, one kept as old as it was kept, so
|
|
2339
2353
|
// that a reader holding two reads of the same can tell the later.
|
|
2340
2354
|
async function readWholeRepository(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, repoId: number,
|
|
2341
|
-
read: (fullName: string, token: string) => Promise<object>, key: string
|
|
2355
|
+
read: (fullName: string, token: string) => Promise<object>, key: string, readAt = false, stamped = false): Promise<void> {
|
|
2342
2356
|
await answerWholeRepository(res, deps, cookie, repoId, async (fullName, token) => {
|
|
2343
|
-
const { value, kept, at } =
|
|
2344
|
-
: await keptAnswer(deps, `${repoId}\0${key}`, () => read(fullName, token), undefined, false, stamped ? stampOf(deps, repoId, fullName, token) : null)
|
|
2357
|
+
const { value, kept, at } = await keptAnswer(deps, `${repoId}\0${key}`, () => read(fullName, token), undefined, false, stamped ? stampOf(deps, repoId, fullName, token) : null)
|
|
2345
2358
|
return { value: readAt ? { ...value, readAt: at } : value, kept }
|
|
2346
2359
|
})
|
|
2347
2360
|
}
|
|
@@ -2369,6 +2382,9 @@ const refusal = (status: number, error: string, retryAfter?: number | null): Ref
|
|
|
2369
2382
|
function sendRefusal(res: ServerResponse, { status, error, retryAfter }: Refusal) {
|
|
2370
2383
|
sendJson(res, status, { error }, retryAfter == null ? {} : { 'retry-after': String(retryAfter) })
|
|
2371
2384
|
}
|
|
2385
|
+
// GitHub's failure `err`, as a request is refused for it: a token GitHub
|
|
2386
|
+
// rejects told as GitHub failing (502), never as the reader's session refused.
|
|
2387
|
+
const githubRefusal = (err: GithubApiError) => refusal(err.status === 401 ? 502 : err.status, err.message, err.retryAfter)
|
|
2372
2388
|
// The whole of repository `repoId`, where the session `cookie` names may
|
|
2373
2389
|
// read all of it, and who reads it; else why not: none of it
|
|
2374
2390
|
// (`no-repository`), or only some (`no-directory`).
|
|
@@ -2391,7 +2407,7 @@ function wholeAccessIn(grants: Awaited<ReturnType<typeof repositoryGrants>>, use
|
|
|
2391
2407
|
async function readWholeRepositoryOf<T>(deps: ManagedHttpDeps, access: WholeAccess, answer: (fullName: string, token: string, user: StoredUser) => Promise<{ value: T; kept: boolean }>,
|
|
2392
2408
|
reauthorize: () => Promise<WholeAccess | Refusal>): Promise<{ value: T; kept: boolean } | Refusal> {
|
|
2393
2409
|
try {
|
|
2394
|
-
const reader = await
|
|
2410
|
+
const reader = await repositoryReader(deps, access.user.id, access.repo)
|
|
2395
2411
|
const token = reader.readToken()
|
|
2396
2412
|
if (!token) return refusal(403, 'github-token-required')
|
|
2397
2413
|
const answered = await answer(access.repo.fullName, token, access.user)
|
|
@@ -2402,7 +2418,7 @@ async function readWholeRepositoryOf<T>(deps: ManagedHttpDeps, access: WholeAcce
|
|
|
2402
2418
|
if (!sameRepository(current.repo, access.repo)) return refusal(409, 'repository-changed')
|
|
2403
2419
|
return answered
|
|
2404
2420
|
} catch (err) {
|
|
2405
|
-
if (err instanceof GithubApiError) return
|
|
2421
|
+
if (err instanceof GithubApiError) return githubRefusal(err)
|
|
2406
2422
|
throw err
|
|
2407
2423
|
}
|
|
2408
2424
|
}
|
|
@@ -2430,14 +2446,14 @@ const patchFields = (field: (key: string) => unknown) => requestedPatch({ hash:
|
|
|
2430
2446
|
// open pull requests' commits, which they never tell (teamOpenPulls reads
|
|
2431
2447
|
// them).
|
|
2432
2448
|
async function handleRepositoryIssues(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
2433
|
-
const repoId =
|
|
2449
|
+
const repoId = askedRepoId(query)
|
|
2434
2450
|
const kind = query.get('kind')
|
|
2435
2451
|
const state = query.get('state') ?? 'open'
|
|
2436
2452
|
const after = query.get('after')
|
|
2437
|
-
if (
|
|
2453
|
+
if (repoId === null || (kind !== 'issues' && kind !== 'pulls') || (state !== 'open' && state !== 'closed')
|
|
2438
2454
|
|| (after !== null && !ISSUES_CURSOR.test(after))) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
2439
2455
|
await answerWholeRepository(res, deps, cookie, repoId, async (fullName, token) => {
|
|
2440
|
-
const { value: { commits: _commits, ...page }, kept, at } = await keptAnswer(deps,
|
|
2456
|
+
const { value: { commits: _commits, ...page }, kept, at } = await keptAnswer(deps, issuesKey(repoId, kind, state, after),
|
|
2441
2457
|
async () => ({ kind, state, ...await repositoryIssues(fullName, token, kind, state, after) }), undefined, false,
|
|
2442
2458
|
// An issue's tile tells nothing its update time doesn't move with; a
|
|
2443
2459
|
// pull request's, its checks.
|
|
@@ -2445,6 +2461,11 @@ async function handleRepositoryIssues(res: ServerResponse, deps: ManagedHttpDeps
|
|
|
2445
2461
|
return { value: { ...page, readAt: at }, kept }
|
|
2446
2462
|
})
|
|
2447
2463
|
}
|
|
2464
|
+
// What GET issues keeps a page of a repository's `kind` by, `state` ones on
|
|
2465
|
+
// from the cursor `after` names; those carrying `label` alone, as a team's
|
|
2466
|
+
// Dependencies reads them (teamOpenPulls), apart from the pages of all.
|
|
2467
|
+
const issuesKey = (repoId: number, kind: string, state: string, after: string | null, label: string | null = null) =>
|
|
2468
|
+
`${repoId}\0issues\0${ISSUES_READ_VERSION}\0${kind}\0${state}\0${after ?? ''}${label === null ? '' : `\0label\0${label}`}`
|
|
2448
2469
|
|
|
2449
2470
|
// GET /api/admin/repositories/agents: what the code viewer's Agents tab
|
|
2450
2471
|
// reconstructs agents' sessions from (repository-agents.ts): a page
|
|
@@ -2453,9 +2474,9 @@ async function handleRepositoryIssues(res: ServerResponse, deps: ManagedHttpDeps
|
|
|
2453
2474
|
// `commits`, the first page, naming neither, with issues and branches. They
|
|
2454
2475
|
// are the whole repository's (readWholeRepository).
|
|
2455
2476
|
async function handleRepositoryAgents(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
2456
|
-
const repoId =
|
|
2477
|
+
const repoId = askedRepoId(query)
|
|
2457
2478
|
const cursors = { pulls: query.get('pulls'), commits: query.get('commits') }
|
|
2458
|
-
if (
|
|
2479
|
+
if (repoId === null || (cursors.pulls !== null && !ISSUES_CURSOR.test(cursors.pulls))
|
|
2459
2480
|
|| (cursors.commits !== null && !COMMITS_CURSOR.test(cursors.commits))) {
|
|
2460
2481
|
sendJson(res, 400, { error: 'bad-request' }); return
|
|
2461
2482
|
}
|
|
@@ -2471,17 +2492,17 @@ async function handleRepositoryAgents(res: ServerResponse, deps: ManagedHttpDeps
|
|
|
2471
2492
|
// `number`, as the code viewer's popup for it shows it (repository-issues.ts
|
|
2472
2493
|
// repositoryItem). It is the whole repository's (readWholeRepository).
|
|
2473
2494
|
async function handleRepositoryItem(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
2474
|
-
const repoId =
|
|
2475
|
-
const number = itemNumber(query)
|
|
2476
|
-
if (
|
|
2495
|
+
const repoId = askedRepoId(query)
|
|
2496
|
+
const number = itemNumber(query.get('number'))
|
|
2497
|
+
if (repoId === null || number === null) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
2477
2498
|
await readWholeRepository(res, deps, cookie, repoId, (fullName, token) => repositoryItem(fullName, token, number), `item\0${ISSUES_READ_VERSION}\0${number}`, true)
|
|
2478
2499
|
}
|
|
2479
2500
|
|
|
2480
|
-
// The issue's or pull request's number
|
|
2501
|
+
// The issue's or pull request's number `text` names, as GraphQL takes one
|
|
2481
2502
|
// (an Int, at most 2³¹ − 1); null for none.
|
|
2482
|
-
function itemNumber(
|
|
2483
|
-
const number = Number(
|
|
2484
|
-
return /^[1-9]\d{0,9}$/u.test(
|
|
2503
|
+
function itemNumber(text: string | null): number | null {
|
|
2504
|
+
const number = Number(text)
|
|
2505
|
+
return /^[1-9]\d{0,9}$/u.test(text ?? '') && number <= 2 ** 31 - 1 ? number : null
|
|
2485
2506
|
}
|
|
2486
2507
|
|
|
2487
2508
|
// GET /api/admin/repositories/pull-dependencies: the package versions pull
|
|
@@ -2501,27 +2522,37 @@ function itemNumber(query: URLSearchParams): number | null {
|
|
|
2501
2522
|
const MAX_ASKED_PULLS = 20
|
|
2502
2523
|
const PULLS_AT_ONCE = 3
|
|
2503
2524
|
async function handleRepositoryPullDependencies(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
2504
|
-
const repoId =
|
|
2525
|
+
const repoId = askedRepoId(query)
|
|
2505
2526
|
const review = query.get('review') === '1'
|
|
2506
2527
|
// As an open one's tile on the Pull requests tab asks (`listed=1`): each
|
|
2507
2528
|
// by the commits the page it is of names, where one kept names them
|
|
2508
2529
|
// (keptPullCommits); else by its number, kept a while, as a popup's.
|
|
2509
2530
|
const tiles = query.get('listed') === '1'
|
|
2510
2531
|
const listed = query.get('numbers')
|
|
2511
|
-
const numbers = listed === null ? [itemNumber(query)] : listed.split(',').map(text => itemNumber(
|
|
2512
|
-
if (
|
|
2532
|
+
const numbers = listed === null ? [itemNumber(query.get('number'))] : listed.split(',').map(text => itemNumber(text))
|
|
2533
|
+
if (repoId === null || numbers.length > MAX_ASKED_PULLS || numbers.some(number => number === null) || new Set(numbers).size < numbers.length
|
|
2513
2534
|
|| !['1', null].includes(query.get('review')) || !['1', null].includes(query.get('listed'))) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
2514
2535
|
await answerWholeRepository(res, deps, cookie, repoId, async (fullName, token, user) => {
|
|
2515
2536
|
const commits = tiles ? await keptPullCommits(deps, repoId, numbers as number[]) : new Map<number, PullCommits>()
|
|
2516
2537
|
if (listed === null) return pullDependencyAnswer(deps, fullName, token, user, repoId, numbers[0]!, review, commits.get(numbers[0]!))
|
|
2517
|
-
const answers = await
|
|
2518
|
-
|
|
2538
|
+
const answers = await pullDependencyAnswers(deps, fullName, token, user, repoId, numbers as number[], review, commits)
|
|
2539
|
+
return { value: { pulls: answers.value }, kept: answers.kept }
|
|
2540
|
+
})
|
|
2541
|
+
}
|
|
2542
|
+
|
|
2543
|
+
// Pull requests `numbers`' answers (pullDependencyAnswer), as many read at
|
|
2544
|
+
// once as PULLS_AT_ONCE, by the commits `commits` names of each where it
|
|
2545
|
+
// does, else `{ number, error }` where GitHub fails it; and whether all of
|
|
2546
|
+
// them were kept.
|
|
2547
|
+
async function pullDependencyAnswers(deps: ManagedHttpDeps, fullName: string, token: string, user: StoredUser, repoId: number, numbers: number[], review: boolean,
|
|
2548
|
+
commits: Map<number, PullCommits> | undefined) {
|
|
2549
|
+
const answers = await eachOf(numbers, PULLS_AT_ONCE, number => pullDependencyAnswer(deps, fullName, token, user, repoId, number, review, commits?.get(number))
|
|
2550
|
+
.catch((err: unknown) => {
|
|
2519
2551
|
// GitHub asked, though it failed: its access asked again after.
|
|
2520
2552
|
if (err instanceof GithubApiError) return { value: { number, error: err.message }, kept: false }
|
|
2521
2553
|
throw err
|
|
2522
2554
|
}))
|
|
2523
|
-
|
|
2524
|
-
})
|
|
2555
|
+
return { value: answers.map(({ value }) => value), kept: answers.every(({ kept }) => kept) }
|
|
2525
2556
|
}
|
|
2526
2557
|
|
|
2527
2558
|
// Pull request `number`'s answer, as the endpoint gives it, and whether all
|
|
@@ -2576,8 +2607,8 @@ async function pullDependencyAnswer(deps: ManagedHttpDeps, fullName: string, tok
|
|
|
2576
2607
|
// its access not asked again, where its head was kept and its lockfiles and
|
|
2577
2608
|
// baseline held or kept (lockfileKept), GitHub asked for none of them.
|
|
2578
2609
|
async function handleRepositoryBranchDependencies(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
2579
|
-
const repoId =
|
|
2580
|
-
if (
|
|
2610
|
+
const repoId = askedRepoId(query)
|
|
2611
|
+
if (repoId === null) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
2581
2612
|
await answerWholeRepository(res, deps, cookie, repoId, (fullName, token, user) => branchDependencyAnswer(deps, fullName, token, user, repoId),
|
|
2582
2613
|
async () => (await deps.db.repoDependencyReview(repoId))?.enabled ? null : { review: null })
|
|
2583
2614
|
}
|
|
@@ -2615,8 +2646,8 @@ async function branchDependencyAnswer(deps: ManagedHttpDeps, fullName: string, t
|
|
|
2615
2646
|
// paths, with their formats, at its head, as its pulse reads it, for its
|
|
2616
2647
|
// settings to name those it holds to (lockfile-scope.ts).
|
|
2617
2648
|
async function handleRepositoryLockfiles(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
2618
|
-
const repoId =
|
|
2619
|
-
if (
|
|
2649
|
+
const repoId = askedRepoId(query)
|
|
2650
|
+
if (repoId === null) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
2620
2651
|
await answerWholeRepository(res, deps, cookie, repoId, async (fullName, token) => {
|
|
2621
2652
|
const head = (await defaultTip(deps, repoId, fullName, token)).sha
|
|
2622
2653
|
return { value: { head, lockfiles: head ? (await lockfilesAt(fullName, token, head, lockfileKept(deps, repoId))).map(({ path, format }) => ({ path, format })) : [] }, kept: false }
|
|
@@ -2633,7 +2664,9 @@ async function handleRepositoryLockfiles(res: ServerResponse, deps: ManagedHttpD
|
|
|
2633
2664
|
// effect for the reader, else `{ repoId, branch: null }`, as for one they
|
|
2634
2665
|
// may read only some of, or `{ repoId, error, status }`; then its pull
|
|
2635
2666
|
// requests' dependencies, of those changing a lockfile or that may,
|
|
2636
|
-
// TEAM_PULLS_TOGETHER at a time (`{ repoId, dependencies }`);
|
|
2667
|
+
// TEAM_PULLS_TOGETHER at a time (`{ repoId, dependencies }`); its open pull
|
|
2668
|
+
// requests those carrying its `dependencies` label alone where it has one
|
|
2669
|
+
// (`pulls.label`, its name; teamOpenPulls); each line of
|
|
2637
2670
|
// dependencies with the lines their versions wanting reviews change, where
|
|
2638
2671
|
// they are counted already (`deltas`, npm-delta.ts keptNpmDeltas), told
|
|
2639
2672
|
// before the rows asking for them are drawn. Last, `{ done: true
|
|
@@ -2708,12 +2741,13 @@ async function handleTeamDependencies(res: ServerResponse, deps: ManagedHttpDeps
|
|
|
2708
2741
|
async function teamRepositoryDependencies(deps: ManagedHttpDeps, access: WholeAccess, setting: RepoDependencyReview, deadline: number,
|
|
2709
2742
|
send: (...lines: TeamDependencyLine[]) => Promise<boolean>, reauthorize: () => Promise<WholeAccess | Refusal>): Promise<boolean> {
|
|
2710
2743
|
const repoId = access.repo.repoId
|
|
2711
|
-
type Read = { branch: object | null; pulls?: { items: TeamPull[]; more: boolean }; commits?: Map<number, PullCommits> }
|
|
2744
|
+
type Read = { branch: object | null; pulls?: { items: TeamPull[]; more: boolean; label?: string }; commits?: Map<number, PullCommits> }
|
|
2712
2745
|
const read = await readWholeRepositoryOf<Read>(deps, access, async (fullName, token, user) => {
|
|
2713
2746
|
const branch = await branchDependencyAnswer(deps, fullName, token, user, repoId, setting)
|
|
2714
2747
|
if (!(branch.value as { review?: unknown }).review) return { value: { branch: null }, kept: branch.kept }
|
|
2715
2748
|
const pulls = await teamOpenPulls(deps, repoId, fullName, token)
|
|
2716
|
-
return { value: { branch: branch.value, pulls: { items: pulls.items, more: pulls.more }
|
|
2749
|
+
return { value: { branch: branch.value, pulls: { items: pulls.items, more: pulls.more, ...pulls.label === null ? {} : { label: pulls.label } }, commits: pulls.commits },
|
|
2750
|
+
kept: branch.kept && pulls.kept }
|
|
2717
2751
|
}, reauthorize)
|
|
2718
2752
|
if ('error' in read) return send({ repoId, ...PARTIAL_ACCESS.has(read.error) ? { branch: null } : { error: read.error, status: read.status } })
|
|
2719
2753
|
const { branch, pulls, commits } = read.value
|
|
@@ -2725,14 +2759,8 @@ async function teamRepositoryDependencies(deps: ManagedHttpDeps, access: WholeAc
|
|
|
2725
2759
|
for (let at = 0; at < numbers.length; at += TEAM_PULLS_TOGETHER) {
|
|
2726
2760
|
if (Date.now() > deadline) return false
|
|
2727
2761
|
const batch = numbers.slice(at, at + TEAM_PULLS_TOGETHER)
|
|
2728
|
-
const pulled = await readWholeRepositoryOf(deps, access,
|
|
2729
|
-
|
|
2730
|
-
// GitHub asked, though it failed: its access asked again after.
|
|
2731
|
-
if (err instanceof GithubApiError) return { value: { number, error: err.message }, kept: false }
|
|
2732
|
-
throw err
|
|
2733
|
-
}))
|
|
2734
|
-
return { value: answers.map(({ value }) => value), kept: answers.every(({ kept }) => kept) }
|
|
2735
|
-
}, reauthorize)
|
|
2762
|
+
const pulled = await readWholeRepositoryOf(deps, access, (fullName, token, user) => pullDependencyAnswers(deps, fullName, token, user, repoId, batch, true, commits),
|
|
2763
|
+
reauthorize)
|
|
2736
2764
|
const dependencies = 'error' in pulled ? batch.map(number => ({ number, error: pulled.error })) : pulled.value
|
|
2737
2765
|
if (!await send({ repoId, dependencies, ...await withDeltas(deps, dependencies) })) return false
|
|
2738
2766
|
}
|
|
@@ -2743,37 +2771,40 @@ const withDeltas = async (deps: ManagedHttpDeps, answers: object[]) => {
|
|
|
2743
2771
|
return deltas.length > 0 ? { deltas } : {}
|
|
2744
2772
|
}
|
|
2745
2773
|
|
|
2746
|
-
// A commit's or a blob's id, as GitHub names one.
|
|
2747
|
-
const OBJECT_ID = /^[a-f\d]{40}$/u
|
|
2748
|
-
|
|
2749
2774
|
// A repository's open pull requests, as many pages of them as
|
|
2750
2775
|
// TEAM_PULL_PAGES, each read and kept as GET issues reads it; each's base's
|
|
2751
2776
|
// and head's commits as its page has them (`commits`, by its number), where
|
|
2752
|
-
// it has them; whether it has more, and whether all were kept.
|
|
2777
|
+
// it has them; whether it has more, and whether all were kept. Where the
|
|
2778
|
+
// repository has a label named DEPENDENCIES_LABEL (kept as a page is), those
|
|
2779
|
+
// carrying it alone, by its name as the repository has it (`label`), their
|
|
2780
|
+
// pages kept apart from GET issues', which are of all of them: a repository
|
|
2781
|
+
// of many open pull requests, few of them its dependencies', read in a page.
|
|
2753
2782
|
async function teamOpenPulls(deps: ManagedHttpDeps, repoId: number, fullName: string, token: string) {
|
|
2783
|
+
const labelled = await keptAnswer(deps, `${repoId}\0label\0${DEPENDENCIES_LABEL}`, () => repositoryLabel(fullName, token, DEPENDENCIES_LABEL))
|
|
2784
|
+
const label = typeof labelled.value.label === 'string' && labelled.value.label !== '' ? labelled.value.label : null
|
|
2754
2785
|
const items: TeamPull[] = []
|
|
2755
2786
|
const commits = new Map<number, PullCommits>()
|
|
2756
|
-
let after: string | null = null, kept =
|
|
2787
|
+
let after: string | null = null, kept = labelled.kept
|
|
2757
2788
|
for (let page = 0; page < TEAM_PULL_PAGES; page++) {
|
|
2758
2789
|
const cursor = after
|
|
2759
|
-
const answer = await keptAnswer(deps,
|
|
2790
|
+
const answer = await keptAnswer(deps, issuesKey(repoId, 'pulls', 'open', cursor, label),
|
|
2791
|
+
async () => ({ kind: 'pulls', state: 'open', ...await repositoryIssues(fullName, token, 'pulls', 'open', cursor, undefined, label) }))
|
|
2760
2792
|
kept &&= answer.kept
|
|
2761
2793
|
const value = answer.value as OpenPullsPage
|
|
2762
2794
|
items.push(...(Array.isArray(value.items) ? value.items : []).filter(item => Number.isSafeInteger(item?.number) && item.number > 0))
|
|
2763
2795
|
pageCommits(value, commits)
|
|
2764
|
-
if (value.more !== true || typeof value.after !== 'string') return { items, commits, more: false, kept }
|
|
2796
|
+
if (value.more !== true || typeof value.after !== 'string') return { items, commits, more: false, kept, label }
|
|
2765
2797
|
after = value.after
|
|
2766
2798
|
}
|
|
2767
|
-
return { items, commits, more: true, kept }
|
|
2799
|
+
return { items, commits, more: true, kept, label }
|
|
2768
2800
|
}
|
|
2769
2801
|
type OpenPullsPage = { items?: unknown; more?: unknown; after?: unknown; commits?: unknown }
|
|
2770
|
-
const openPullsKey = (repoId: number, cursor: string | null) => `${repoId}\0issues\0${ISSUES_READ_VERSION}\0pulls\0open\0${cursor ?? ''}`
|
|
2771
2802
|
// Each open pull request's base's and head's commits a page of them names,
|
|
2772
2803
|
// into `commits` by its number.
|
|
2773
2804
|
function pageCommits(page: OpenPullsPage, commits: Map<number, PullCommits>) {
|
|
2774
2805
|
for (const pull of Array.isArray(page.commits) ? page.commits as { number?: unknown; base?: unknown; head?: unknown }[] : []) {
|
|
2775
2806
|
const { number, base, head } = pull ?? {}
|
|
2776
|
-
if (Number.isSafeInteger(number) && typeof base === 'string' &&
|
|
2807
|
+
if (Number.isSafeInteger(number) && typeof base === 'string' && SHA.test(base) && typeof head === 'string' && SHA.test(head)) {
|
|
2777
2808
|
commits.set(number as number, { base, head })
|
|
2778
2809
|
}
|
|
2779
2810
|
}
|
|
@@ -2789,7 +2820,7 @@ async function keptPullCommits(deps: ManagedHttpDeps, repoId: number, numbers: n
|
|
|
2789
2820
|
const commits = new Map<number, PullCommits>()
|
|
2790
2821
|
let after: string | null = null
|
|
2791
2822
|
for (let page = 0; page < TEAM_PULL_PAGES && numbers.some(number => !commits.has(number)); page++) {
|
|
2792
|
-
const stored = await store.read(
|
|
2823
|
+
const stored = await store.read(issuesKey(repoId, 'pulls', 'open', after))
|
|
2793
2824
|
if (!stored || Date.now() - stored.at >= REPOSITORY_READ_KEPT_MS) break
|
|
2794
2825
|
const value = stored.value as OpenPullsPage
|
|
2795
2826
|
pageCommits(value, commits)
|
|
@@ -2824,7 +2855,7 @@ async function teamDeltas(deps: ManagedHttpDeps, answers: object[]) {
|
|
|
2824
2855
|
const integrity = (name: string, version: string) => {
|
|
2825
2856
|
const hit = kept.get(`${name}@${version}`)
|
|
2826
2857
|
const dist = hit && Date.now() - hit.at < VERSION_KEPT_MS ? hit.json['dist'] : null
|
|
2827
|
-
return
|
|
2858
|
+
return plainObject(dist) && typeof dist['integrity'] === 'string' ? dist['integrity'] : null
|
|
2828
2859
|
}
|
|
2829
2860
|
const sides = [...asked.values()].flatMap(([name, version, base]) => {
|
|
2830
2861
|
const against = base === '(empty)' ? null : integrity(name, base), other = integrity(name, version)
|
|
@@ -2833,7 +2864,7 @@ async function teamDeltas(deps: ManagedHttpDeps, answers: object[]) {
|
|
|
2833
2864
|
if (sides.length === 0) return []
|
|
2834
2865
|
const counted = await keptNpmDeltas(sides.map(({ key }) => key), npmDeltaStore<NpmDelta>(deps.db, deps.config.debug))
|
|
2835
2866
|
return sides.flatMap(({ name, version, base, key: [against, other] }) => {
|
|
2836
|
-
const delta = counted.get(
|
|
2867
|
+
const delta = counted.get(deltaKey(against, other))
|
|
2837
2868
|
return delta ? [[name, version, base, delta]] : []
|
|
2838
2869
|
})
|
|
2839
2870
|
}
|
|
@@ -2889,7 +2920,7 @@ function lockfileKept(deps: ManagedHttpDeps, repoId: number): LockfileStore {
|
|
|
2889
2920
|
async read(commit) {
|
|
2890
2921
|
const value: unknown = (await listings.read(keyOf(commit)))?.value
|
|
2891
2922
|
return Array.isArray(value) && value.every(item => typeof item?.path === 'string' && typeof item.format === 'string' && lockfileFormat(item.path) === item.format
|
|
2892
|
-
&& typeof item.sha === 'string' &&
|
|
2923
|
+
&& typeof item.sha === 'string' && SHA.test(item.sha)) ? value : null
|
|
2893
2924
|
},
|
|
2894
2925
|
write: (commit, listed) => listings.write(keyOf(commit), listed, Date.now()),
|
|
2895
2926
|
},
|
|
@@ -2912,9 +2943,9 @@ function lockfileKept(deps: ManagedHttpDeps, repoId: number): LockfileStore {
|
|
|
2912
2943
|
// `pending`, for the client to ask again. They are the whole repository's
|
|
2913
2944
|
// (readWholeRepository).
|
|
2914
2945
|
async function handleRepositoryPulse(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
2915
|
-
const repoId =
|
|
2946
|
+
const repoId = askedRepoId(query)
|
|
2916
2947
|
const weeks = Number(query.get('weeks') ?? '4')
|
|
2917
|
-
if (
|
|
2948
|
+
if (repoId === null || !PULSE_WEEKS.includes(weeks)) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
2918
2949
|
await answerWholeRepository(res, deps, cookie, repoId, async (fullName, token) => {
|
|
2919
2950
|
const year = pulseYearRead(deps, repoId, fullName, token, weeks)
|
|
2920
2951
|
const [period, counted] = await Promise.all([
|
|
@@ -2952,8 +2983,7 @@ function pulseYearRead(deps: ManagedHttpDeps, repoId: number, fullName: string,
|
|
|
2952
2983
|
reads.set(key, year)
|
|
2953
2984
|
const settled = year.reading.catch((err: unknown) => { console.warn('managed: pulse year read failed:', err) })
|
|
2954
2985
|
.finally(() => { if (reads.get(key) === year) reads.delete(key) })
|
|
2955
|
-
deps
|
|
2956
|
-
deps.waitUntil?.(settled)
|
|
2986
|
+
trackBehind(deps, settled)
|
|
2957
2987
|
return year
|
|
2958
2988
|
}
|
|
2959
2989
|
|
|
@@ -2994,10 +3024,7 @@ const PULSE_LAST_MS = 28 * 24 * 60 * 60_000
|
|
|
2994
3024
|
const PULSE_DAY = /^\d{4}-\d{2}-\d{2}$/u
|
|
2995
3025
|
const GITHUB_LOGIN = /^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}(?:\[bot\])?$/iu
|
|
2996
3026
|
const PULSE_AUTHORS = 10
|
|
2997
|
-
const pulseDay = (value: string | null) => {
|
|
2998
|
-
const at = value !== null && PULSE_DAY.test(value) ? Date.parse(`${value}T00:00:00Z`) : Number.NaN
|
|
2999
|
-
return Number.isSafeInteger(at) ? at : null
|
|
3000
|
-
}
|
|
3027
|
+
const pulseDay = (value: string | null) => value !== null && PULSE_DAY.test(value) ? timeOf(`${value}T00:00:00Z`) : null
|
|
3001
3028
|
|
|
3002
3029
|
// The pull requests and issues of a period of `weeks` weeks, narrowed as
|
|
3003
3030
|
// asked (`narrowing`), as the Pulse shows them: of those kept
|
|
@@ -3023,13 +3050,13 @@ async function pulseActivity(deps: ManagedHttpDeps, repoId: number, fullName: st
|
|
|
3023
3050
|
// `from`) and the GitHub accounts a picked contributor committed as
|
|
3024
3051
|
// (`authors`), as repositoryActivity reads them, kept apart for each.
|
|
3025
3052
|
async function handleRepositoryPulseItems(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
|
|
3026
|
-
const repoId =
|
|
3053
|
+
const repoId = askedRepoId(query)
|
|
3027
3054
|
const weeks = Number(query.get('weeks') ?? '4')
|
|
3028
3055
|
const [from, to] = [pulseDay(query.get('from')), query.has('to') ? pulseDay(query.get('to')) : null]
|
|
3029
3056
|
const logins = (query.get('authors') ?? '').split(',').filter(Boolean)
|
|
3030
3057
|
// Each once, whatever its case, as GitHub matches logins.
|
|
3031
3058
|
const authors = [...new Set(logins.map(login => login.toLowerCase()))].toSorted()
|
|
3032
|
-
if (
|
|
3059
|
+
if (repoId === null || !PULSE_WEEKS.includes(weeks) || from === null || (query.has('to') && (to === null || to < from))
|
|
3033
3060
|
|| authors.length > PULSE_AUTHORS || !logins.every(login => GITHUB_LOGIN.test(login))) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
3034
3061
|
await answerWholeRepository(res, deps, cookie, repoId, async (fullName, token) => {
|
|
3035
3062
|
const narrowing = { from, to, authors }
|
|
@@ -3039,7 +3066,7 @@ async function handleRepositoryPulseItems(res: ServerResponse, deps: ManagedHttp
|
|
|
3039
3066
|
})
|
|
3040
3067
|
}
|
|
3041
3068
|
|
|
3042
|
-
async function pulseCommits(deps: ManagedHttpDeps, repoId: number, fullName: string, token: string, weeks
|
|
3069
|
+
async function pulseCommits(deps: ManagedHttpDeps, repoId: number, fullName: string, token: string, weeks: number, progress: { commits: number }) {
|
|
3043
3070
|
const now = Date.now()
|
|
3044
3071
|
const first = pulseSince(52, now)
|
|
3045
3072
|
// As far back as a period of `weeks` weeks needs the year read whole: its
|
|
@@ -3123,7 +3150,7 @@ async function pulseCommits(deps: ManagedHttpDeps, repoId: number, fullName: str
|
|
|
3123
3150
|
if (!tooMany && held && 'tooMany' in held) await store.write(tooManyKey, { within: first }, Date.now())
|
|
3124
3151
|
if (need > tooManyWithin) {
|
|
3125
3152
|
const [year, read] = await Promise.all([yearCommits(fullName, token, sha, first, historyPages(deps, repoId, true), globalThis.fetch, need,
|
|
3126
|
-
commits => {
|
|
3153
|
+
commits => { progress.commits = commits }), attribution(need)])
|
|
3127
3154
|
await store.write(mergesKey, read, Date.now())
|
|
3128
3155
|
if (year.complete) {
|
|
3129
3156
|
if (readTo(read) >= need) return { stats: await last(), reading: null, pulls: read.next?.read ?? 0, pending: false, kept: false }
|
|
@@ -3151,6 +3178,13 @@ function prebuildBundle(deps: ManagedHttpDeps, id: string) {
|
|
|
3151
3178
|
})().catch(err => console.warn('managed: bundle cache build failed:', err)))
|
|
3152
3179
|
}
|
|
3153
3180
|
|
|
3181
|
+
// `stream` as the body of a response whose head is written: none of it for
|
|
3182
|
+
// a HEAD, and the response cut short where it fails midway.
|
|
3183
|
+
async function sendBody(req: IncomingMessage, res: ServerResponse, stream: OpenedBlob['stream']) {
|
|
3184
|
+
if (req.method === 'HEAD') { stream.destroy(); res.end(); return }
|
|
3185
|
+
try { await pipeline(stream, res) } catch { res.destroy() }
|
|
3186
|
+
}
|
|
3187
|
+
|
|
3154
3188
|
// Brotli-encoded bytes as they are: the browser's HTTP stack decompresses
|
|
3155
3189
|
// them without a Brotli JS dependency.
|
|
3156
3190
|
async function sendEncoded(req: IncomingMessage, res: ServerResponse, blob: OpenedBlob, contentType: string, headers: Record<string, string> = {}) {
|
|
@@ -3159,8 +3193,7 @@ async function sendEncoded(req: IncomingMessage, res: ServerResponse, blob: Open
|
|
|
3159
3193
|
...(blob.size == null ? {} : { 'content-length': String(blob.size) }), 'cache-control': 'private, no-store',
|
|
3160
3194
|
'x-content-type-options': 'nosniff',
|
|
3161
3195
|
})
|
|
3162
|
-
|
|
3163
|
-
try { await pipeline(blob.stream, res) } catch { res.destroy() }
|
|
3196
|
+
await sendBody(req, res, blob.stream)
|
|
3164
3197
|
}
|
|
3165
3198
|
|
|
3166
3199
|
|
|
@@ -3334,38 +3367,48 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
|
|
|
3334
3367
|
// was asked for and its source was found to have, for the viewer to check.
|
|
3335
3368
|
const prettySource = ({ hash }: PrettyRequest): Record<string, string> => ({ 'x-source-hash': hash })
|
|
3336
3369
|
|
|
3370
|
+
// A bundle's derivative that failed, answered: as pretty-print.ts refused
|
|
3371
|
+
// it, else as its bundle unreadable.
|
|
3372
|
+
function sendBundleFailure(res: ServerResponse, err: unknown) {
|
|
3373
|
+
sendJson(res, err instanceof PrettyError ? err.status : 422, { error: err instanceof PrettyError ? err.message : 'bundle-unavailable' })
|
|
3374
|
+
}
|
|
3375
|
+
|
|
3337
3376
|
// GET /api/bundles/:id/{metadata,contents,pretty}: what `open` reads of the
|
|
3338
3377
|
// bundle, already encoded; it is absent where its cache is.
|
|
3339
3378
|
async function handleBundleCache(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, session: ManagedSession, id: string,
|
|
3340
3379
|
open: ((rec: ManagedBundle) => Promise<OpenedBlob>) | undefined, contentType = 'application/json', headers: Record<string, string> = {}) {
|
|
3341
|
-
const
|
|
3342
|
-
if (!
|
|
3343
|
-
const rec = access.bundle
|
|
3344
|
-
if (!rec) { sendJson(res, 404, { error: 'no-bundle' }); return }
|
|
3380
|
+
const rec = await readableBundle(res, deps, session, id)
|
|
3381
|
+
if (!rec) return
|
|
3345
3382
|
if (!open) { sendJson(res, 503, { error: 'unavailable' }); return }
|
|
3346
3383
|
let cached
|
|
3347
3384
|
try { cached = await open(rec) }
|
|
3348
|
-
catch (err) {
|
|
3385
|
+
catch (err) { sendBundleFailure(res, err); return }
|
|
3349
3386
|
// A cold build can outlast a session or membership change.
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
cached.stream.destroy()
|
|
3353
|
-
sendJson(res, current ? 404 : 401, { error: current ? 'no-bundle' : 'unauthenticated' })
|
|
3354
|
-
return
|
|
3355
|
-
}
|
|
3356
|
-
await sendEncoded(req, res, cached, contentType, headers)
|
|
3387
|
+
if (await readableBundle(res, deps, session, id)) await sendEncoded(req, res, cached, contentType, headers)
|
|
3388
|
+
else cached.stream.destroy()
|
|
3357
3389
|
}
|
|
3358
3390
|
|
|
3359
|
-
//
|
|
3360
|
-
//
|
|
3361
|
-
// again before it is
|
|
3362
|
-
|
|
3363
|
-
|
|
3391
|
+
// What `work` makes of the pretty-printed copies (503 where none are kept)
|
|
3392
|
+
// of two bundles a reader asks about together, where they may read both,
|
|
3393
|
+
// else told as 401 or 404: asked before it is made and again before it is
|
|
3394
|
+
// sent; its failure answered as a bundle's derivative's is.
|
|
3395
|
+
async function sendOfBothBundles(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, session: ManagedSession, id: string, otherId: string,
|
|
3396
|
+
work: (cache: PrettyCache, records: readonly [ManagedBundle, ManagedBundle]) => Promise<OpenedBlob>) {
|
|
3397
|
+
const readable = async () => {
|
|
3364
3398
|
const [base, other] = await Promise.all([id, otherId].map(bundle => deps.db.getBundleAccessSnapshot(session.id, Date.now(), bundle)))
|
|
3365
3399
|
if (!base || !other) { sendJson(res, 401, { error: 'unauthenticated' }); return null }
|
|
3366
3400
|
if (!base.bundle || !other.bundle) { sendJson(res, 404, { error: 'no-bundle' }); return null }
|
|
3367
3401
|
return [base.bundle, other.bundle] as const
|
|
3368
3402
|
}
|
|
3403
|
+
const records = await readable()
|
|
3404
|
+
if (!records) return
|
|
3405
|
+
const { prettyCache } = deps
|
|
3406
|
+
if (!prettyCache) { sendJson(res, 503, { error: 'unavailable' }); return }
|
|
3407
|
+
let body
|
|
3408
|
+
try { body = await work(prettyCache, records) }
|
|
3409
|
+
catch (err) { sendBundleFailure(res, err); return }
|
|
3410
|
+
if (await readable()) await sendEncoded(req, res, body, 'application/json')
|
|
3411
|
+
else body.stream.destroy()
|
|
3369
3412
|
}
|
|
3370
3413
|
|
|
3371
3414
|
// GET /api/bundles/:id/rename-diff: one of its JavaScript files diffed with
|
|
@@ -3374,20 +3417,8 @@ function bothBundles(res: ServerResponse, deps: ManagedHttpDeps, session: Manage
|
|
|
3374
3417
|
async function handleBundleRenameDiff(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, session: ManagedSession, id: string, params: URLSearchParams) {
|
|
3375
3418
|
const otherId = params.get('other') ?? '', request = renameDiffRequest(params)
|
|
3376
3419
|
if (!request || !/^[a-f\d-]{36}$/iu.test(otherId)) { sendJson(res, 400, { error: 'bad-file' }); return }
|
|
3377
|
-
|
|
3378
|
-
|
|
3379
|
-
if (!records) return
|
|
3380
|
-
const { prettyCache } = deps
|
|
3381
|
-
if (!prettyCache) { sendJson(res, 503, { error: 'unavailable' }); return }
|
|
3382
|
-
let diff
|
|
3383
|
-
try {
|
|
3384
|
-
diff = await renameDiffOf(request, async () => [await prettyText(await prettyCache.bundle(records[0], request.base)),
|
|
3385
|
-
await prettyText(await prettyCache.bundle(records[1], request.other))])
|
|
3386
|
-
} catch (err) {
|
|
3387
|
-
sendJson(res, err instanceof PrettyError ? err.status : 422, { error: err instanceof PrettyError ? err.message : 'bundle-unavailable' }); return
|
|
3388
|
-
}
|
|
3389
|
-
if (await readable()) await sendEncoded(req, res, diff, 'application/json')
|
|
3390
|
-
else diff.stream.destroy()
|
|
3420
|
+
await sendOfBothBundles(req, res, deps, session, id, otherId, (cache, [base, other]) => renameDiffOf(request, async () => [
|
|
3421
|
+
await prettyText(await cache.bundle(base, request.base)), await prettyText(await cache.bundle(other, request.other))]))
|
|
3391
3422
|
}
|
|
3392
3423
|
|
|
3393
3424
|
// GET /api/bundles/:id/comparison?other=: its files paired with the `other`
|
|
@@ -3397,16 +3428,8 @@ async function handleBundleRenameDiff(req: IncomingMessage, res: ServerResponse,
|
|
|
3397
3428
|
async function handleBundleComparison(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, session: ManagedSession, id: string, params: URLSearchParams) {
|
|
3398
3429
|
const otherId = params.get('other') ?? ''
|
|
3399
3430
|
if (!/^[a-f\d-]{36}$/iu.test(otherId)) { sendJson(res, 400, { error: 'bad-bundle' }); return }
|
|
3400
|
-
|
|
3401
|
-
|
|
3402
|
-
if (!records) return
|
|
3403
|
-
const { prettyCache } = deps
|
|
3404
|
-
if (!prettyCache) { sendJson(res, 503, { error: 'unavailable' }); return }
|
|
3405
|
-
let body
|
|
3406
|
-
try { body = await comparisonBody(await prettyCache.bundleDetails(records[0]), await prettyCache.bundleDetails(records[1]), params.get('scope') ?? '') }
|
|
3407
|
-
catch (err) { sendJson(res, err instanceof PrettyError ? err.status : 422, { error: err instanceof PrettyError ? err.message : 'bundle-unavailable' }); return }
|
|
3408
|
-
if (await readable()) await sendEncoded(req, res, body, 'application/json')
|
|
3409
|
-
else body.stream.destroy()
|
|
3431
|
+
await sendOfBothBundles(req, res, deps, session, id, otherId, async (cache, [base, other]) =>
|
|
3432
|
+
comparisonBody(await cache.bundleDetails(base), await cache.bundleDetails(other), params.get('scope') ?? ''))
|
|
3410
3433
|
}
|
|
3411
3434
|
|
|
3412
3435
|
// GET /api/bundles/:id/pretty?other=: the files that changed between it and
|
|
@@ -3426,7 +3449,7 @@ async function handleBundleChanges(res: ServerResponse, deps: ManagedHttpDeps, s
|
|
|
3426
3449
|
if (!deps.prettyCache) { sendJson(res, 503, { error: 'unavailable' }); return }
|
|
3427
3450
|
let lines
|
|
3428
3451
|
try { lines = await linesOf(deps.prettyCache, base.bundle, other.bundle) }
|
|
3429
|
-
catch (err) {
|
|
3452
|
+
catch (err) { sendBundleFailure(res, err); return }
|
|
3430
3453
|
await sendLines(res, lines, async () => (await access()).every(snapshot => snapshot?.bundle))
|
|
3431
3454
|
}
|
|
3432
3455
|
|
|
@@ -3528,7 +3551,7 @@ async function handleBundleDependencyReview(res: ServerResponse, deps: ManagedHt
|
|
|
3528
3551
|
if (inventory === null) { sendJson(res, 413, { error: 'payload-too-large' }); return }
|
|
3529
3552
|
const bundled = (inventory?.packages ?? []).filter(pkg => pkg.ecosystem === 'npm').flatMap(pkg => pkg.versions.map(version => ({ name: pkg.name, version })))
|
|
3530
3553
|
// Its commit as GitHub names one, of SHA-1.
|
|
3531
|
-
if (!commit ||
|
|
3554
|
+
if (!commit || !SHA.test(commit) || bundled.length === 0) { none(); return }
|
|
3532
3555
|
const read = await readWholeRepositoryOf(deps, access, (fullName, token, user) => bundleDependencyAnswer(deps, fullName, token, user, repoId, setting,
|
|
3533
3556
|
{ commit: commit!, directory: record.repoDirectory, bundled }), () => wholeRepositoryAccess(deps, cookie, repoId))
|
|
3534
3557
|
if ('error' in read) { sendRefusal(res, read); return }
|
|
@@ -3625,7 +3648,7 @@ async function bundleValidation(deps: ManagedHttpDeps, cookie: string | undefine
|
|
|
3625
3648
|
const plan = details?.bundle ? validationPlan(details.bundle as PlannedBundle) : null
|
|
3626
3649
|
if (!plan) return refusal(422, 'bundle-unavailable')
|
|
3627
3650
|
const stamp = (details!.bundle as { repo?: { commit?: unknown; directory?: unknown } } | undefined)?.repo
|
|
3628
|
-
const commit = typeof stamp?.commit === 'string' &&
|
|
3651
|
+
const commit = typeof stamp?.commit === 'string' && SHA.test(stamp.commit) ? stamp.commit : null
|
|
3629
3652
|
// Where it was built, as its stamp says, else where it is kept.
|
|
3630
3653
|
const directory = stampedDirectory(typeof stamp?.directory === 'string' ? stamp : { directory: record.repoDirectory })
|
|
3631
3654
|
const options = { deadline: Date.now() + VALIDATION_MS }
|
|
@@ -3698,7 +3721,7 @@ async function handleCreateBundle(req: IncomingMessage, res: ServerResponse, dep
|
|
|
3698
3721
|
const access = await authorize(input.directory)
|
|
3699
3722
|
if (!access) return
|
|
3700
3723
|
await withBundleBuildLease(deps.db, access.user.id, controller.signal, async signal => {
|
|
3701
|
-
const reader = await
|
|
3724
|
+
const reader = await repositoryReader(deps, access.user.id, access.repo)
|
|
3702
3725
|
signal.throwIfAborted()
|
|
3703
3726
|
// Catalogs then show the built bundle's commit details from the cache.
|
|
3704
3727
|
const commitCached = cacheCommitDetails(deps.db, reader, input.repoId, input.commit)
|
|
@@ -3711,9 +3734,7 @@ async function handleCreateBundle(req: IncomingMessage, res: ServerResponse, dep
|
|
|
3711
3734
|
await reader.recheckAccess()
|
|
3712
3735
|
const current = await authorize(built.directory)
|
|
3713
3736
|
if (!current) return
|
|
3714
|
-
if (
|
|
3715
|
-
throw new BundleBuildError(409, 'repository-changed')
|
|
3716
|
-
}
|
|
3737
|
+
if (!sameRepository(current.repo, access.repo)) throw new BundleBuildError(409, 'repository-changed')
|
|
3717
3738
|
signal.throwIfAborted()
|
|
3718
3739
|
await storeUploadedBundle(req, res, deps, cookie, current, built.bytes, input.repoId, built.directory, built.filename, 'build',
|
|
3719
3740
|
bundleIntegrity(built.bytes), input.conditions)
|
|
@@ -3721,11 +3742,7 @@ async function handleCreateBundle(req: IncomingMessage, res: ServerResponse, dep
|
|
|
3721
3742
|
} catch (error) {
|
|
3722
3743
|
if (res.destroyed || controller.signal.aborted) return
|
|
3723
3744
|
if (error instanceof BundleBuildError) { sendJson(res, error.status, { error: error.code }); return }
|
|
3724
|
-
|
|
3725
|
-
sendJson(res, error.status === 401 ? 502 : error.status, { error: error.message }, error.retryAfter == null ? {} : { 'retry-after': String(error.retryAfter) })
|
|
3726
|
-
return
|
|
3727
|
-
}
|
|
3728
|
-
throw error
|
|
3745
|
+
answerGithubFailure(res, error)
|
|
3729
3746
|
} finally { res.off('close', onClose) }
|
|
3730
3747
|
}
|
|
3731
3748
|
|
|
@@ -3739,20 +3756,13 @@ async function handleCreateBundle(req: IncomingMessage, res: ServerResponse, dep
|
|
|
3739
3756
|
// After storing, any reports that declared this integrity but weren't linked yet
|
|
3740
3757
|
// get attached (auto-link). 413 over the cap, 400 on empty.
|
|
3741
3758
|
async function handleUploadBundle(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
3742
|
-
let s = await
|
|
3759
|
+
let s = await manageMutation(req, res, deps, cookie, { handed: true })
|
|
3743
3760
|
if (s == null) return
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
try {
|
|
3747
|
-
bytes = await readUploadBody(req, deps, s.session, 'bundles')
|
|
3748
|
-
} catch (err) {
|
|
3749
|
-
const tooLarge = err instanceof Error && err.message === 'too-large'
|
|
3750
|
-
sendJson(res, tooLarge ? 413 : 400, { error: tooLarge ? 'too-large' : 'bad-body' })
|
|
3751
|
-
return
|
|
3752
|
-
}
|
|
3761
|
+
const bytes = await readUploadBody(req, res, deps, s.session, 'bundles')
|
|
3762
|
+
if (!bytes) return
|
|
3753
3763
|
// Shared storage reads may outlast a session or role change.
|
|
3754
|
-
s = await
|
|
3755
|
-
if (!s
|
|
3764
|
+
s = await manageMutation(req, res, deps, cookie)
|
|
3765
|
+
if (!s) return
|
|
3756
3766
|
if (bytes.length === 0) { sendJson(res, 400, { error: 'empty' }); return }
|
|
3757
3767
|
const repo = await resolveUploadRepoId(req, res, deps)
|
|
3758
3768
|
if (!repo.ok) return
|
|
@@ -3784,8 +3794,8 @@ async function handleUploadBundle(req: IncomingMessage, res: ServerResponse, dep
|
|
|
3784
3794
|
inferredLocation = true
|
|
3785
3795
|
}
|
|
3786
3796
|
}
|
|
3787
|
-
s = await
|
|
3788
|
-
if (!s
|
|
3797
|
+
s = await manageMutation(req, res, deps, cookie)
|
|
3798
|
+
if (!s) return
|
|
3789
3799
|
}
|
|
3790
3800
|
const normalized = normalizeTeamPath(rawDirectory)
|
|
3791
3801
|
if (!normalized.ok) { sendJson(res, 400, { error: 'bad-directory' }); return }
|
|
@@ -3804,7 +3814,7 @@ async function handleUploadBundle(req: IncomingMessage, res: ServerResponse, dep
|
|
|
3804
3814
|
// again, one inserted since meeting the insert's UNIQUE below as a race does.
|
|
3805
3815
|
async function storeUploadedBundle(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined,
|
|
3806
3816
|
s: { session: ManagedSession; user: StoredUser }, bytes: Buffer, repoId: number | null, directory: string, filename: string,
|
|
3807
|
-
provenance: BundleProvenance, integrity
|
|
3817
|
+
provenance: BundleProvenance, integrity: string, buildConditions: BundleBuildConditions | null, absent = false): Promise<void> {
|
|
3808
3818
|
const kind = bundleKind(filename)
|
|
3809
3819
|
const reuse = { provenance, filename, kind, buildConditions }
|
|
3810
3820
|
const existing = absent ? null : await deps.db.getBundleByIntegrity(integrity)
|
|
@@ -3841,10 +3851,8 @@ async function storeUploadedBundle(req: IncomingMessage, res: ServerResponse, de
|
|
|
3841
3851
|
// HTTP Brotli decoding to restore the uploaded .map bytes. 404 no such
|
|
3842
3852
|
// bundle; 503 row-without-bytes (store desync).
|
|
3843
3853
|
async function handleGetBundle(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, session: ManagedSession, id: string): Promise<void> {
|
|
3844
|
-
const
|
|
3845
|
-
if (!
|
|
3846
|
-
const rec = access.bundle
|
|
3847
|
-
if (rec == null) { sendJson(res, 404, { error: 'no-bundle' }); return }
|
|
3854
|
+
const rec = await readableBundle(res, deps, session, id)
|
|
3855
|
+
if (!rec) return
|
|
3848
3856
|
const stored = await deps.bundleStore.open(id, rec.kind)
|
|
3849
3857
|
if (stored == null) { sendJson(res, 503, { error: 'unavailable' }); return }
|
|
3850
3858
|
const current = await deps.db.getBundleAccessSnapshot(session.id, Date.now(), id)
|
|
@@ -3860,8 +3868,7 @@ async function handleGetBundle(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
3860
3868
|
'x-content-type-options': 'nosniff',
|
|
3861
3869
|
'cache-control': 'no-store',
|
|
3862
3870
|
})
|
|
3863
|
-
|
|
3864
|
-
try { await pipeline(stored.stream, res) } catch { res.destroy() }
|
|
3871
|
+
await sendBody(req, res, stored.stream)
|
|
3865
3872
|
}
|
|
3866
3873
|
|
|
3867
3874
|
// GET /api/admin/bundles/<id>/usage — the reports that name a bundle, read
|
|
@@ -3890,9 +3897,8 @@ async function handleBundleUsage(res: ServerResponse, deps: ManagedHttpDeps, coo
|
|
|
3890
3897
|
// the FK; their bundle_integrity stays, so a re-upload re-links), then the bytes
|
|
3891
3898
|
// best-effort. 404 when there was no such bundle.
|
|
3892
3899
|
async function handleDeleteBundle(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, id: string): Promise<void> {
|
|
3893
|
-
const s = await
|
|
3900
|
+
const s = await manageMutation(req, res, deps, cookie, { handed: true })
|
|
3894
3901
|
if (s == null) return
|
|
3895
|
-
if (!requireManageRole(res, s.user)) return
|
|
3896
3902
|
const { bundle, user } = await deps.db.mutateBundle(s.session.id, id, { type: 'delete' })
|
|
3897
3903
|
await deps.bundleCache?.delete(id).catch((err) => { console.warn('managed: bundle cache delete failed:', err) })
|
|
3898
3904
|
await deps.reportSourcesCache?.deleteBundle(id).catch((err) => { console.warn('managed: report sources delete failed:', err) })
|
|
@@ -4000,12 +4006,11 @@ async function handleReportSources(req: IncomingMessage, res: ServerResponse, de
|
|
|
4000
4006
|
...(cached.size == null ? {} : { 'content-length': String(cached.size) }), 'cache-control': 'private, no-store',
|
|
4001
4007
|
'x-content-type-options': 'nosniff',
|
|
4002
4008
|
})
|
|
4003
|
-
|
|
4004
|
-
try { await pipeline(cached.stream, res) } catch { res.destroy() }
|
|
4009
|
+
await sendBody(req, res, cached.stream)
|
|
4005
4010
|
}
|
|
4006
4011
|
|
|
4007
4012
|
async function reportIds(data: unknown): Promise<Set<string>> {
|
|
4008
|
-
const findings = (reportEntries(data) ?? []).flat().filter(
|
|
4013
|
+
const findings = (reportEntries(data) ?? []).flat().filter(plainObject)
|
|
4009
4014
|
await backfillFindingIds(findings)
|
|
4010
4015
|
return new Set(findings.flatMap(f => typeof f['id'] === 'string' ? [f['id']] : []))
|
|
4011
4016
|
}
|
|
@@ -4013,21 +4018,19 @@ async function reportIds(data: unknown): Promise<Set<string>> {
|
|
|
4013
4018
|
async function handleDeduplication(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, id?: string): Promise<void> {
|
|
4014
4019
|
const method = req.method ?? 'GET'
|
|
4015
4020
|
if (!(id ? ['GET', 'PATCH'] : ['GET', 'POST']).includes(method)) { send405(res, id ? 'GET, PATCH' : 'GET, POST'); return }
|
|
4016
|
-
const s = method === 'GET' ? await
|
|
4017
|
-
if (!s)
|
|
4018
|
-
if (s.user.role !== 'admin') { sendJson(res, 403, { error: 'forbidden' }); return }
|
|
4021
|
+
const s = method === 'GET' ? await readAdminSession(res, deps, cookie, { handed: true }) : await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4022
|
+
if (!s) return
|
|
4019
4023
|
if (method === 'GET') { sendJson(res, 200, id ? await deps.db.getLinkReport(s.session.id, id) : { reports: await deps.db.listLinkReports() }); return }
|
|
4020
4024
|
if (id) {
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
const
|
|
4025
|
+
const body = await readBodyFields(req, res, 1024)
|
|
4026
|
+
if (!body) return
|
|
4027
|
+
const { enabled } = body
|
|
4024
4028
|
if (typeof enabled !== 'boolean') { sendJson(res, 400, { error: 'bad-enabled' }); return }
|
|
4025
4029
|
await deps.db.setLinkReportEnabled(s.session.id, id, enabled)
|
|
4026
4030
|
sendJson(res, 200, { ok: true }); return
|
|
4027
4031
|
}
|
|
4028
|
-
|
|
4029
|
-
|
|
4030
|
-
catch (error) { const large = error instanceof Error && error.message === 'too-large'; sendJson(res, large ? 413 : 400, { error: large ? 'too-large' : 'bad-body' }); return }
|
|
4032
|
+
const bytes = await readUploadBody(req, res, deps, s.session, 'links')
|
|
4033
|
+
if (!bytes) return
|
|
4031
4034
|
const filename = sanitizeFilename(firstHeader(req.headers['x-report-filename']), 'report.link.json')
|
|
4032
4035
|
const result = await deps.db.importLinkReport(s.session.id, filename, bytes.toString('utf8'))
|
|
4033
4036
|
sendJson(res, result.reused ? 200 : 201, { ...result.report, deduped: result.reused })
|
|
@@ -4036,9 +4039,8 @@ async function handleDeduplication(req: IncomingMessage, res: ServerResponse, de
|
|
|
4036
4039
|
async function handleRepositoryAliases(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, id?: string): Promise<void> {
|
|
4037
4040
|
const method = req.method ?? 'GET'
|
|
4038
4041
|
if (!(id ? ['PATCH', 'DELETE'] : ['GET', 'POST']).includes(method)) { send405(res, id ? 'PATCH, DELETE' : 'GET, POST'); return }
|
|
4039
|
-
const s = method === 'GET' ? await readAdminSession(res, deps, cookie, { handed: true }) : await
|
|
4042
|
+
const s = method === 'GET' ? await readAdminSession(res, deps, cookie, { handed: true }) : await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4040
4043
|
if (!s) return
|
|
4041
|
-
if (s.user.role !== 'admin') { sendJson(res, 403, { error: 'forbidden' }); return }
|
|
4042
4044
|
if (method === 'GET') {
|
|
4043
4045
|
sendJson(res, 200, { aliases: await deps.db.listRepositoryAliases(), repos: await deps.db.listAllRepos() }); return
|
|
4044
4046
|
}
|
|
@@ -4157,9 +4159,9 @@ const REPORT_QUERY_IN_FLIGHT_BYTES = 64 * 1024 * 1024
|
|
|
4157
4159
|
async function handleQueryReports(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
4158
4160
|
const s = await readManageSession(res, deps, cookie, { handed: true })
|
|
4159
4161
|
if (!s) return
|
|
4160
|
-
|
|
4161
|
-
|
|
4162
|
-
const raw =
|
|
4162
|
+
const body = await readBodyFields(req, res, 1024 * 1024)
|
|
4163
|
+
if (!body) return
|
|
4164
|
+
const raw = body['ids']
|
|
4163
4165
|
if (!Array.isArray(raw) || raw.some(id => typeof id !== 'string' || !id || id.length > 256)) {
|
|
4164
4166
|
sendJson(res, 400, { error: 'bad-ids' }); return
|
|
4165
4167
|
}
|
|
@@ -4273,7 +4275,7 @@ async function canTriageReport(deps: ManagedHttpDeps, user: StoredUser, reportId
|
|
|
4273
4275
|
// workspace. Privileged users retain report-scoped access and the same stable
|
|
4274
4276
|
// ID derivation. Both paths store/read annotations by finding ID alone.
|
|
4275
4277
|
const VISIBLE_IDS_CACHE_MAX = 256
|
|
4276
|
-
const visibleIdsCaches = new WeakMap<ManagedHttpDeps,
|
|
4278
|
+
const visibleIdsCaches = new WeakMap<ManagedHttpDeps, Lru<Set<string>>>()
|
|
4277
4279
|
async function visibleFindingIds(deps: ManagedHttpDeps, user: StoredUser, reportId: string, sessionId: string, teamId: string | null): Promise<Set<string>> {
|
|
4278
4280
|
if (!roleAtLeast(user.role, 'manage')) {
|
|
4279
4281
|
if (!teamId) throw new TeamReportsError(404, 'no-team')
|
|
@@ -4288,9 +4290,9 @@ async function visibleFindingIds(deps: ManagedHttpDeps, user: StoredUser, report
|
|
|
4288
4290
|
async function reportFindingIds(deps: ManagedHttpDeps, rec: { id: string; sha256: string; filename: string }, github: string | null): Promise<Set<string>> {
|
|
4289
4291
|
const key = JSON.stringify([rec.id, rec.sha256, rec.filename, { github }])
|
|
4290
4292
|
let cache = visibleIdsCaches.get(deps)
|
|
4291
|
-
if (cache == null) { cache =
|
|
4293
|
+
if (cache == null) { cache = lru(VISIBLE_IDS_CACHE_MAX); visibleIdsCaches.set(deps, cache) }
|
|
4292
4294
|
const hit = cache.get(key)
|
|
4293
|
-
if (hit != null)
|
|
4295
|
+
if (hit != null) return hit
|
|
4294
4296
|
const bytes = await deps.reportStore.get(rec.id)
|
|
4295
4297
|
if (bytes == null) return new Set()
|
|
4296
4298
|
const { data } = readManagedReport(bytes.toString('utf8'), rec.filename)
|
|
@@ -4298,11 +4300,6 @@ async function reportFindingIds(deps: ManagedHttpDeps, rec: { id: string; sha256
|
|
|
4298
4300
|
// The ids the team workspace derives (teamFindingIds), from the one parse.
|
|
4299
4301
|
const ids = await reportIds(data)
|
|
4300
4302
|
ids.delete('')
|
|
4301
|
-
while (cache.size >= VISIBLE_IDS_CACHE_MAX) {
|
|
4302
|
-
const oldest = cache.keys().next().value
|
|
4303
|
-
if (oldest === undefined) break
|
|
4304
|
-
cache.delete(oldest)
|
|
4305
|
-
}
|
|
4306
4303
|
cache.set(key, ids)
|
|
4307
4304
|
return ids
|
|
4308
4305
|
}
|
|
@@ -4368,10 +4365,10 @@ async function handleSetReportTriage(req: IncomingMessage, res: ServerResponse,
|
|
|
4368
4365
|
const s = await checkMutation(req, res, deps, cookie, { handed: true })
|
|
4369
4366
|
if (s == null) return
|
|
4370
4367
|
if (!(await canTriageReport(deps, s.user, id))) { sendJson(res, 404, { error: 'no-report' }); return }
|
|
4371
|
-
|
|
4372
|
-
|
|
4373
|
-
const raw =
|
|
4374
|
-
if (
|
|
4368
|
+
const body = await readBodyFields(req, res, MAX_TRIAGE_BODY_BYTES)
|
|
4369
|
+
if (!body) return
|
|
4370
|
+
const raw = body['entries']
|
|
4371
|
+
if (!plainObject(raw)) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
4375
4372
|
const pairs = Object.entries(raw)
|
|
4376
4373
|
if (pairs.length > MAX_TRIAGE_ENTRIES) { sendJson(res, 400, { error: 'too-many-entries' }); return }
|
|
4377
4374
|
const parsed: [string, TriageEntryPatch | null][] = []
|
|
@@ -4429,7 +4426,7 @@ async function handleImportTriage(req: IncomingMessage, res: ServerResponse, dep
|
|
|
4429
4426
|
if (!body || typeof body !== 'object') { sendJson(res, 400, { error: 'bad-body' }); return }
|
|
4430
4427
|
const reading = body.entries === undefined
|
|
4431
4428
|
const raw = body.entries
|
|
4432
|
-
if (!reading &&
|
|
4429
|
+
if (!reading && !plainObject(raw)) { sendJson(res, 400, { error: 'bad-entries' }); return }
|
|
4433
4430
|
const ids = reading ? body.findingIds : Object.keys(raw!)
|
|
4434
4431
|
if (!Array.isArray(ids) || ids.length > MAX_TRIAGE_ENTRIES || ids.some(value => typeof value !== 'string' || !value || value.length > MAX_FINDING_ID)) {
|
|
4435
4432
|
sendJson(res, 400, { error: 'bad-finding-ids' }); return
|
|
@@ -4437,7 +4434,7 @@ async function handleImportTriage(req: IncomingMessage, res: ServerResponse, dep
|
|
|
4437
4434
|
const parsed: [string, TriageEntryPatch | null][] = []
|
|
4438
4435
|
const expected = body.expected as Record<string, string> | null
|
|
4439
4436
|
if (!reading) {
|
|
4440
|
-
if (!
|
|
4437
|
+
if (!plainObject(expected)) { sendJson(res, 400, { error: 'bad-expected' }); return }
|
|
4441
4438
|
for (const [findingId, value] of Object.entries(raw!)) {
|
|
4442
4439
|
const patch = parseTriageEntryPatch(value)
|
|
4443
4440
|
if (patch === 'invalid' || !/^[a-f\d]{64}$/u.test(expected[findingId] ?? '')) { sendJson(res, 400, { error: 'bad-entry' }); return }
|
|
@@ -4524,9 +4521,9 @@ async function handleListTeams(res: ServerResponse, deps: ManagedHttpDeps, cooki
|
|
|
4524
4521
|
async function handleCreateTeam(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
4525
4522
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4526
4523
|
if (s == null) return
|
|
4527
|
-
|
|
4528
|
-
|
|
4529
|
-
const rawName =
|
|
4524
|
+
const body = await readBodyFields(req, res)
|
|
4525
|
+
if (!body) return
|
|
4526
|
+
const rawName = body['name']
|
|
4530
4527
|
const name = typeof rawName === 'string' ? rawName.trim() : ''
|
|
4531
4528
|
if (name === '' || name.length > MAX_TEAM_NAME) { sendJson(res, 400, { error: 'bad-name' }); return }
|
|
4532
4529
|
const id = randomUUID()
|
|
@@ -4541,10 +4538,9 @@ async function handleCreateTeam(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
4541
4538
|
async function handleRenameTeam(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
4542
4539
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4543
4540
|
if (s == null) return
|
|
4544
|
-
|
|
4545
|
-
|
|
4546
|
-
const
|
|
4547
|
-
const rawName = (body as { name?: unknown } | null)?.name
|
|
4541
|
+
const body = await readBodyFields(req, res)
|
|
4542
|
+
if (!body) return
|
|
4543
|
+
const { teamId, name: rawName } = body
|
|
4548
4544
|
const name = typeof rawName === 'string' ? rawName.trim() : ''
|
|
4549
4545
|
if (typeof teamId !== 'string' || name === '' || name.length > MAX_TEAM_NAME) { sendJson(res, 400, { error: 'bad-name' }); return }
|
|
4550
4546
|
const team = await deps.db.getTeam(teamId)
|
|
@@ -4560,10 +4556,9 @@ async function handleRenameTeam(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
4560
4556
|
async function handleSetTeamHidden(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
4561
4557
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4562
4558
|
if (s == null) return
|
|
4563
|
-
|
|
4564
|
-
|
|
4565
|
-
const
|
|
4566
|
-
const hidden = (body as { hidden?: unknown } | null)?.hidden
|
|
4559
|
+
const body = await readBodyFields(req, res)
|
|
4560
|
+
if (!body) return
|
|
4561
|
+
const { teamId, hidden } = body
|
|
4567
4562
|
if (typeof teamId !== 'string' || typeof hidden !== 'boolean') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
4568
4563
|
const team = await deps.db.getTeam(teamId)
|
|
4569
4564
|
if (await readAdminSession(res, deps, cookie) == null) return
|
|
@@ -4576,9 +4571,9 @@ async function handleSetTeamHidden(req: IncomingMessage, res: ServerResponse, de
|
|
|
4576
4571
|
async function handleDeleteTeam(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
4577
4572
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4578
4573
|
if (s == null) return
|
|
4579
|
-
|
|
4580
|
-
|
|
4581
|
-
const
|
|
4574
|
+
const body = await readBodyFields(req, res)
|
|
4575
|
+
if (!body) return
|
|
4576
|
+
const { teamId } = body
|
|
4582
4577
|
if (typeof teamId !== 'string') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
4583
4578
|
const team = await deps.db.getTeam(teamId)
|
|
4584
4579
|
if (await readAdminSession(res, deps, cookie) == null) return
|
|
@@ -4593,14 +4588,13 @@ async function handleDeleteTeam(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
4593
4588
|
async function handleSetTeamRepo(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
4594
4589
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4595
4590
|
if (s == null) return
|
|
4596
|
-
|
|
4597
|
-
|
|
4598
|
-
const
|
|
4599
|
-
const repoId = (body as { repoId?: unknown } | null)?.repoId
|
|
4591
|
+
const body = await readBodyFields(req, res)
|
|
4592
|
+
if (!body) return
|
|
4593
|
+
const { teamId, repoId } = body
|
|
4600
4594
|
if (typeof teamId !== 'string' || typeof repoId !== 'number' || !Number.isSafeInteger(repoId)) {
|
|
4601
4595
|
sendJson(res, 400, { error: 'bad-request' }); return
|
|
4602
4596
|
}
|
|
4603
|
-
const path = normalizeTeamPath(
|
|
4597
|
+
const path = normalizeTeamPath(body['path'])
|
|
4604
4598
|
if (!path.ok) { sendJson(res, 400, { error: 'bad-path' }); return }
|
|
4605
4599
|
const team = (await deps.db.listTeams()).find(row => row.id === teamId)
|
|
4606
4600
|
if (team == null) { sendJson(res, 404, { error: 'no-team' }); return }
|
|
@@ -4618,12 +4612,10 @@ async function handleSetTeamRepo(req: IncomingMessage, res: ServerResponse, deps
|
|
|
4618
4612
|
async function handleRemoveTeamRepo(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
4619
4613
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4620
4614
|
if (s == null) return
|
|
4621
|
-
|
|
4622
|
-
|
|
4623
|
-
const teamId
|
|
4624
|
-
const repoId = (body as { repoId?: unknown } | null)?.repoId
|
|
4615
|
+
const body = await readBodyFields(req, res)
|
|
4616
|
+
if (!body) return
|
|
4617
|
+
const { teamId, repoId, path: rawPath } = body
|
|
4625
4618
|
if (typeof teamId !== 'string' || typeof repoId !== 'number' || !Number.isSafeInteger(repoId)) { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
4626
|
-
const rawPath = (body as { path?: unknown }).path
|
|
4627
4619
|
if (rawPath !== undefined && rawPath !== null && typeof rawPath !== 'string') { sendJson(res, 400, { error: 'bad-path' }); return }
|
|
4628
4620
|
const path = normalizeTeamPath(rawPath)
|
|
4629
4621
|
if (!path.ok) { sendJson(res, 400, { error: 'bad-path' }); return }
|
|
@@ -4638,10 +4630,9 @@ async function handleRemoveTeamRepo(req: IncomingMessage, res: ServerResponse, d
|
|
|
4638
4630
|
async function handleSetTeamMember(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
4639
4631
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4640
4632
|
if (s == null) return
|
|
4641
|
-
|
|
4642
|
-
|
|
4643
|
-
const
|
|
4644
|
-
const userId = (body as { userId?: unknown } | null)?.userId
|
|
4633
|
+
const body = await readBodyFields(req, res)
|
|
4634
|
+
if (!body) return
|
|
4635
|
+
const { teamId, userId } = body
|
|
4645
4636
|
if (typeof teamId !== 'string' || typeof userId !== 'string') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
4646
4637
|
const team = (await deps.db.listTeams()).find(row => row.id === teamId)
|
|
4647
4638
|
if (team == null) { sendJson(res, 404, { error: 'no-team' }); return }
|
|
@@ -4661,10 +4652,9 @@ async function handleSetTeamMember(req: IncomingMessage, res: ServerResponse, de
|
|
|
4661
4652
|
async function handleRemoveTeamMember(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
4662
4653
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4663
4654
|
if (s == null) return
|
|
4664
|
-
|
|
4665
|
-
|
|
4666
|
-
const
|
|
4667
|
-
const userId = (body as { userId?: unknown } | null)?.userId
|
|
4655
|
+
const body = await readBodyFields(req, res)
|
|
4656
|
+
if (!body) return
|
|
4657
|
+
const { teamId, userId } = body
|
|
4668
4658
|
if (typeof teamId !== 'string' || typeof userId !== 'string') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
4669
4659
|
if (await readAdminSession(res, deps, cookie) == null) return
|
|
4670
4660
|
if (!(await deps.db.removeTeamMember(teamId, userId))) { sendJson(res, 404, { error: 'not-member' }); return }
|
|
@@ -4677,10 +4667,11 @@ async function handleRemoveTeamMember(req: IncomingMessage, res: ServerResponse,
|
|
|
4677
4667
|
async function handleSetTeamDependencyReview(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
4678
4668
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4679
4669
|
if (!s) return
|
|
4680
|
-
|
|
4681
|
-
|
|
4682
|
-
|
|
4683
|
-
if (
|
|
4670
|
+
const body = await readBodyFields(req, res)
|
|
4671
|
+
if (!body) return
|
|
4672
|
+
const { teamId, enabled } = body
|
|
4673
|
+
if (typeof teamId !== 'string' || typeof enabled !== 'boolean') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
4674
|
+
if (!await deps.db.setTeamDependencyReview(s.session.id, teamId, enabled)) { sendJson(res, 404, { error: 'no-team' }); return }
|
|
4684
4675
|
sendJson(res, 200, { ok: true })
|
|
4685
4676
|
}
|
|
4686
4677
|
|
|
@@ -4689,12 +4680,12 @@ async function handleSetTeamDependencyReview(req: IncomingMessage, res: ServerRe
|
|
|
4689
4680
|
async function handleSetTeamNpmScopes(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined): Promise<void> {
|
|
4690
4681
|
const s = await adminMutation(req, res, deps, cookie, { handed: true })
|
|
4691
4682
|
if (s == null) return
|
|
4692
|
-
|
|
4693
|
-
|
|
4694
|
-
const
|
|
4683
|
+
const body = await readBodyFields(req, res)
|
|
4684
|
+
if (!body) return
|
|
4685
|
+
const { teamId } = body
|
|
4695
4686
|
if (typeof teamId !== 'string') { sendJson(res, 400, { error: 'bad-request' }); return }
|
|
4696
4687
|
const team = await deps.db.getTeam(teamId)
|
|
4697
|
-
const changed = await deps.db.setTeamNpmScopes(s.session.id, teamId,
|
|
4688
|
+
const changed = await deps.db.setTeamNpmScopes(s.session.id, teamId, body['scopes'])
|
|
4698
4689
|
if (changed == null) { sendJson(res, 404, { error: 'no-team' }); return }
|
|
4699
4690
|
const parts = [changed.added.length > 0 ? `added ${changed.added.join(', ')}` : '', changed.removed.length > 0 ? `removed ${changed.removed.join(', ')}` : ''].filter(Boolean)
|
|
4700
4691
|
if (parts.length > 0) await activity(deps, s.user, 'access', `changed team ${team?.name ?? teamId}'s npm scopes: ${parts.join('; ')}`)
|
|
@@ -4731,6 +4722,15 @@ function found<T>(value: T | null | undefined): T {
|
|
|
4731
4722
|
return value
|
|
4732
4723
|
}
|
|
4733
4724
|
|
|
4725
|
+
// The review a page of reviews goes on below (`beforeTime`, `beforeId`):
|
|
4726
|
+
// none for the first page; 'invalid' where the query names it otherwise.
|
|
4727
|
+
function reviewCursor(query: URLSearchParams): { time: number; id: string } | null | 'invalid' {
|
|
4728
|
+
const id = query.get('beforeId'), time = query.get('beforeTime')
|
|
4729
|
+
if (time === null && id === null) return null
|
|
4730
|
+
if (time === null || !/^\d+$/u.test(time) || !Number.isSafeInteger(Number(time)) || !id || id.length > 100) return 'invalid'
|
|
4731
|
+
return { time: Number(time), id }
|
|
4732
|
+
}
|
|
4733
|
+
|
|
4734
4734
|
// Version documents a list of reviews reads at once: each holds a version
|
|
4735
4735
|
// document's room in what npm's reads may hold at once (npm-packages.ts),
|
|
4736
4736
|
// which refuses past thirty-two of them.
|
|
@@ -4738,17 +4738,17 @@ const REVIEW_READS_AT_ONCE = 8
|
|
|
4738
4738
|
|
|
4739
4739
|
// Lists must enforce the same target and base access as the review itself,
|
|
4740
4740
|
// including permission changes while the registry requests are in flight;
|
|
4741
|
-
// first as `session`, the one the request read just now
|
|
4742
|
-
//
|
|
4743
|
-
//
|
|
4741
|
+
// first as `session`, the one the request read just now. A team's
|
|
4742
|
+
// (`teamId`) only to one who still reads its reviews there, asked again
|
|
4743
|
+
// with the rest (npmReviewReader).
|
|
4744
4744
|
async function readableNpmReviews<T extends ReviewContext>(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, user: string, reviews: T[],
|
|
4745
|
-
session
|
|
4745
|
+
session: { id: string; role: NpmReader['role'] }, teamId?: string): Promise<T[] | null> {
|
|
4746
4746
|
const controller = new AbortController()
|
|
4747
4747
|
const onClose = () => { if (!res.writableEnded) controller.abort() }
|
|
4748
4748
|
res.on('close', onClose)
|
|
4749
4749
|
try {
|
|
4750
4750
|
const names = reviews.flatMap(review => [review.package, ...review.basePackage ? [review.basePackage] : []])
|
|
4751
|
-
const reader =
|
|
4751
|
+
const reader = await npmReaderOf(deps, session, names)
|
|
4752
4752
|
if (!reader || reader.userId !== user) { sendJson(res, 401, { error: 'unauthenticated' }); return null }
|
|
4753
4753
|
// Public versions' documents as the viewer keeps them (npm-kept.ts), a
|
|
4754
4754
|
// day, all read of the database at once: a list asks npm for none it read
|
|
@@ -4802,6 +4802,43 @@ async function npmReviewPublicationLimit(deps: ManagedHttpDeps, reader: NpmReade
|
|
|
4802
4802
|
return npmReviewVerdictLimit(doc, list, socket, risk)
|
|
4803
4803
|
}
|
|
4804
4804
|
|
|
4805
|
+
// The change a POST of reviews asks for, as its `body` names it: a review
|
|
4806
|
+
// started, an entry saved, a set published, continued or revoked. Null,
|
|
4807
|
+
// answered 400, where it names none.
|
|
4808
|
+
function reviewChange(res: ServerResponse, body: Record<string, unknown>): ReviewChange | null {
|
|
4809
|
+
const action = body['action'], reviewId = body['reviewId'] ?? null, revision = body['revision'] ?? null
|
|
4810
|
+
if (typeof action !== 'string' || !['start', 'save', 'publish', 'continue', 'revoke'].includes(action)
|
|
4811
|
+
|| (reviewId !== null && (typeof reviewId !== 'string' || reviewId.length === 0 || reviewId.length > 100 || !Number.isSafeInteger(revision) || Number(revision) < 1))
|
|
4812
|
+
|| (!['save', 'start'].includes(action) && reviewId === null) || (action === 'start' && reviewId !== null)) { sendJson(res, 400, { error: 'bad-review' }); return null }
|
|
4813
|
+
if (action === 'start') return { action, reviewId: null, revision: null }
|
|
4814
|
+
if (action === 'publish') {
|
|
4815
|
+
const teamIds = body['teamIds']
|
|
4816
|
+
if (!Array.isArray(teamIds) || teamIds.length === 0 || teamIds.length > 100 || teamIds.some(id => typeof id !== 'string' || id.length > 100)) {
|
|
4817
|
+
sendJson(res, 400, { error: 'bad-review-teams' }); return null
|
|
4818
|
+
}
|
|
4819
|
+
const finalComment = body['finalComment'] ?? '', finalStatus = body['finalStatus'] ?? null
|
|
4820
|
+
if (typeof finalComment !== 'string' || finalComment.length > 20000 || finalStatus !== null
|
|
4821
|
+
&& (typeof finalStatus !== 'string' || !['accept', 'accept-with-nits', 'request-changes', 'reject'].includes(finalStatus))) {
|
|
4822
|
+
sendJson(res, 400, { error: 'bad-final-verdict' }); return null
|
|
4823
|
+
}
|
|
4824
|
+
return { action, reviewId: reviewId as string, revision: revision as number, teamIds, files: [], nonTextFiles: [],
|
|
4825
|
+
final: finalStatus === null ? null : { status: finalStatus as ReviewInput['status'] & string, comment: finalComment } }
|
|
4826
|
+
}
|
|
4827
|
+
if (action === 'continue' || action === 'revoke') return { action, reviewId: reviewId as string, revision: revision as number }
|
|
4828
|
+
const file = body['file']
|
|
4829
|
+
const comment = body['comment']
|
|
4830
|
+
const status = body['status'] ?? null
|
|
4831
|
+
const entryId = body['entryId'] ?? null
|
|
4832
|
+
if (typeof file !== 'string' || !file || file.length > 4096 || file.includes('\0')
|
|
4833
|
+
|| (entryId !== null && (typeof entryId !== 'string' || entryId.length === 0 || entryId.length > 100))
|
|
4834
|
+
|| typeof comment !== 'string' || comment.length > 20000
|
|
4835
|
+
|| (status !== null && (typeof status !== 'string' || !['accept', 'accept-with-nits', 'request-changes', 'reject'].includes(status))) || (status === null && entryId === null)) {
|
|
4836
|
+
sendJson(res, 400, { error: 'bad-review' }); return null
|
|
4837
|
+
}
|
|
4838
|
+
return { action: 'save', reviewId: reviewId as string | null, revision: revision as number | null, entryId: entryId as string | null,
|
|
4839
|
+
entry: { file, comment, status: status as ReviewInput['status'] } }
|
|
4840
|
+
}
|
|
4841
|
+
|
|
4805
4842
|
// Reviews are scoped to the bytes actually displayed, including the base:
|
|
4806
4843
|
// each change but a revocation loads both versions' files, of tarballs held
|
|
4807
4844
|
// to their integrity and to their shasum where npm tells one (npm-loads.ts),
|
|
@@ -4817,14 +4854,8 @@ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
4817
4854
|
const session = mutation ? await checkMutation(req, res, deps, cookie, { handed: true }) : await readSession(deps.config, deps.db, cookie, Date.now(), { handed: true })
|
|
4818
4855
|
if (!session) { if (!mutation) sendJson(res, 401, { error: 'unauthenticated' }); return }
|
|
4819
4856
|
if (!roleAtLeast(session.user.role, mutation ? 'triage' : 'view')) { sendJson(res, 403, { error: 'forbidden' }); return }
|
|
4820
|
-
|
|
4821
|
-
if (
|
|
4822
|
-
try {
|
|
4823
|
-
const raw = await readJsonBody(req, 128 * 1024)
|
|
4824
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('bad-body')
|
|
4825
|
-
body = raw as Record<string, unknown>
|
|
4826
|
-
} catch { sendJson(res, 400, { error: 'bad-body' }); return }
|
|
4827
|
-
}
|
|
4857
|
+
const body: Record<string, unknown> | null = mutation ? await readBodyObject(req, res, 128 * 1024) : {}
|
|
4858
|
+
if (!body) return
|
|
4828
4859
|
const field = (key: string) => mutation ? body[key] : params.get(key)
|
|
4829
4860
|
const name = field('package')
|
|
4830
4861
|
const version = field('version')
|
|
@@ -4846,40 +4877,10 @@ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
4846
4877
|
basePackage: basePackage as string | null, baseVersion: baseVersion as string | null, baseIntegrity: baseIntegrity as string | null }
|
|
4847
4878
|
let change: ReviewChange | null = null
|
|
4848
4879
|
if (mutation) {
|
|
4849
|
-
|
|
4850
|
-
if (
|
|
4851
|
-
|| (reviewId !== null && (typeof reviewId !== 'string' || reviewId.length === 0 || reviewId.length > 100 || !Number.isSafeInteger(revision) || Number(revision) < 1))
|
|
4852
|
-
|| (!['save', 'start'].includes(action) && reviewId === null) || (action === 'start' && reviewId !== null)) { sendJson(res, 400, { error: 'bad-review' }); return }
|
|
4853
|
-
if (action === 'start') change = { action, reviewId: null, revision: null }
|
|
4854
|
-
else if (action === 'publish') {
|
|
4855
|
-
const teamIds = body['teamIds']
|
|
4856
|
-
if (!Array.isArray(teamIds) || teamIds.length === 0 || teamIds.length > 100 || teamIds.some(id => typeof id !== 'string' || id.length > 100)) {
|
|
4857
|
-
sendJson(res, 400, { error: 'bad-review-teams' }); return
|
|
4858
|
-
}
|
|
4859
|
-
const finalComment = body['finalComment'] ?? '', finalStatus = body['finalStatus'] ?? null
|
|
4860
|
-
if (typeof finalComment !== 'string' || finalComment.length > 20000 || finalStatus !== null
|
|
4861
|
-
&& (typeof finalStatus !== 'string' || !['accept', 'accept-with-nits', 'request-changes', 'reject'].includes(finalStatus))) {
|
|
4862
|
-
sendJson(res, 400, { error: 'bad-final-verdict' }); return
|
|
4863
|
-
}
|
|
4864
|
-
change = { action, reviewId: reviewId as string, revision: revision as number, teamIds, files: [], nonTextFiles: [],
|
|
4865
|
-
final: finalStatus === null ? null : { status: finalStatus as ReviewInput['status'] & string, comment: finalComment } }
|
|
4866
|
-
} else if (action === 'continue' || action === 'revoke') change = { action, reviewId: reviewId as string, revision: revision as number }
|
|
4867
|
-
else {
|
|
4868
|
-
const file = body['file']
|
|
4869
|
-
const comment = body['comment']
|
|
4870
|
-
const status = body['status'] ?? null
|
|
4871
|
-
const entryId = body['entryId'] ?? null
|
|
4872
|
-
if (typeof file !== 'string' || !file || file.length > 4096 || file.includes('\0')
|
|
4873
|
-
|| (entryId !== null && (typeof entryId !== 'string' || entryId.length === 0 || entryId.length > 100))
|
|
4874
|
-
|| typeof comment !== 'string' || comment.length > 20000
|
|
4875
|
-
|| (status !== null && (typeof status !== 'string' || !['accept', 'accept-with-nits', 'request-changes', 'reject'].includes(status))) || (status === null && entryId === null)) {
|
|
4876
|
-
sendJson(res, 400, { error: 'bad-review' }); return
|
|
4877
|
-
}
|
|
4878
|
-
change = { action: 'save', reviewId: reviewId as string | null, revision: revision as number | null, entryId: entryId as string | null,
|
|
4879
|
-
entry: { file, comment, status: status as ReviewInput['status'] } }
|
|
4880
|
-
}
|
|
4880
|
+
change = reviewChange(res, body)
|
|
4881
|
+
if (!change) return
|
|
4881
4882
|
// Each change but a revocation reads a patched version's patch.
|
|
4882
|
-
if (patchHash !== null && action !== 'revoke' && !patch) { sendJson(res, 400, { error: 'bad-review-context' }); return }
|
|
4883
|
+
if (patchHash !== null && change.action !== 'revoke' && !patch) { sendJson(res, 400, { error: 'bad-review-context' }); return }
|
|
4883
4884
|
}
|
|
4884
4885
|
const controller = new AbortController()
|
|
4885
4886
|
const onClose = () => { if (!res.writableEnded) controller.abort() }
|
|
@@ -4964,6 +4965,12 @@ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
4964
4965
|
// who may still read it, none told to one whose session is gone.
|
|
4965
4966
|
const MAX_ASKED_DELTAS = 50
|
|
4966
4967
|
const DELTAS_AT_ONCE = 2
|
|
4968
|
+
// A version as npmDelta takes it: its integrity, and its files, loaded as
|
|
4969
|
+
// they are asked for and released once read.
|
|
4970
|
+
const deltaSide = (doc: NpmVersionDocument) => ({ integrity: doc.dist.integrity, files: async () => {
|
|
4971
|
+
const load = loadNpmFiles(doc)
|
|
4972
|
+
try { return await load.result } finally { load.release() }
|
|
4973
|
+
} })
|
|
4967
4974
|
async function handleNpmDeltas(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, params: URLSearchParams): Promise<void> {
|
|
4968
4975
|
if (req.method !== 'GET') { send405(res, 'GET'); return }
|
|
4969
4976
|
let asked: unknown = null
|
|
@@ -4975,7 +4982,7 @@ async function handleNpmDeltas(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
4975
4982
|
if (reader == null) { sendJson(res, 401, { error: 'unauthenticated' }); return }
|
|
4976
4983
|
const controller = new AbortController()
|
|
4977
4984
|
res.once('close', () => { if (!res.writableEnded) controller.abort() })
|
|
4978
|
-
|
|
4985
|
+
dropIdle(res)
|
|
4979
4986
|
const kept = npmDeltaStore<NpmDelta>(deps.db, deps.config.debug), keptVersions = npmVersionStore(deps.db, deps.config.debug)
|
|
4980
4987
|
const out = openLines(res)
|
|
4981
4988
|
let stopped = false
|
|
@@ -4989,11 +4996,7 @@ async function handleNpmDeltas(req: IncomingMessage, res: ServerResponse, deps:
|
|
|
4989
4996
|
const [doc, old] = await Promise.all([readNpmVersion(name, version, privileged, controller.signal, together).then(found),
|
|
4990
4997
|
otherVersion === '(empty)' ? null : readNpmVersion(name, otherVersion, privileged, controller.signal, together).then(found)])
|
|
4991
4998
|
isPrivate = doc.private || old?.private === true
|
|
4992
|
-
|
|
4993
|
-
const load = loadNpmFiles(of)
|
|
4994
|
-
try { return await load.result } finally { load.release() }
|
|
4995
|
-
} })
|
|
4996
|
-
line = { ...asOne, ...await npmDelta(old ? side(old) : null, side(doc), kept) }
|
|
4999
|
+
line = { ...asOne, ...await npmDelta(old ? deltaSide(old) : null, deltaSide(doc), kept) }
|
|
4997
5000
|
} catch (err) {
|
|
4998
5001
|
if (controller.signal.aborted) return
|
|
4999
5002
|
if (!(err instanceof NpmPackageError)) console.warn('managed: a package delta failed:', err)
|
|
@@ -5139,7 +5142,7 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
|
|
|
5139
5142
|
const assessment = await npmRisk(doc, otherSpec === '' ? 'pick' : old, { db: deps.db, npmCache: deps.npmCacheStorage, debug: deps.config.debug, teamScoped, fromEmpty: otherSpec === '(empty)',
|
|
5140
5143
|
ownScope: listed => deps.db.hasTeamNpmScope(listed), privileged, signal: controller.signal })
|
|
5141
5144
|
// What it tells is read of both versions: private where either is.
|
|
5142
|
-
|
|
5145
|
+
dropIdle(res)
|
|
5143
5146
|
await reply(doc.private || old?.private === true, { ...assessment })
|
|
5144
5147
|
return
|
|
5145
5148
|
}
|
|
@@ -5149,12 +5152,8 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
|
|
|
5149
5152
|
// (npm-delta.ts), as a list of versions wanting reviews tells them.
|
|
5150
5153
|
if (path === NPM_DELTA_PATH) {
|
|
5151
5154
|
const old = otherSpec === '(empty)' ? null : await otherDoc()
|
|
5152
|
-
|
|
5153
|
-
const
|
|
5154
|
-
const load = loadNpmFiles(version)
|
|
5155
|
-
try { return await load.result } finally { load.release() }
|
|
5156
|
-
} })
|
|
5157
|
-
const delta = await npmDelta(old ? side(old) : null, side(doc), npmDeltaStore<NpmDelta>(deps.db, deps.config.debug))
|
|
5155
|
+
dropIdle(res)
|
|
5156
|
+
const delta = await npmDelta(old ? deltaSide(old) : null, deltaSide(doc), npmDeltaStore<NpmDelta>(deps.db, deps.config.debug))
|
|
5158
5157
|
await reply(doc.private || old?.private === true, { name, version: doc.version, otherVersion: old?.version ?? null, ...delta })
|
|
5159
5158
|
return
|
|
5160
5159
|
}
|
|
@@ -5169,7 +5168,7 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
|
|
|
5169
5168
|
const old = otherSpec === '(empty)' ? null : await otherDoc()
|
|
5170
5169
|
const patched = patch ? await npmPatchOf(deps, cookie, patch) : null
|
|
5171
5170
|
if (patched && 'error' in patched) { sendRefusal(res, patched); return }
|
|
5172
|
-
|
|
5171
|
+
dropIdle(res)
|
|
5173
5172
|
const loads = [doc, ...old ? [old] : []].map(loadNpmFiles)
|
|
5174
5173
|
let body
|
|
5175
5174
|
try {
|
|
@@ -5210,10 +5209,10 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
|
|
|
5210
5209
|
const other = otherSpec === '' ? null : await otherDoc()
|
|
5211
5210
|
const sides = other && await deps.prettyCache.npmSides(doc, other)
|
|
5212
5211
|
const lines = path === NPM_RENAME_DIFF_PATH ? renamedPairs(sides!, !doc.private && !other!.private)
|
|
5213
|
-
: path === NPM_TYPE_ONLY_PATH ? typeOnlyFiles(sides
|
|
5212
|
+
: path === NPM_TYPE_ONLY_PATH ? typeOnlyFiles(sides!, runsAsked(params)) : sides ? compared(sides) : await deps.prettyCache.npmAll(doc)
|
|
5214
5213
|
const isPrivate = doc.private || other?.private === true
|
|
5215
5214
|
if (!(await recheck(isPrivate))) return
|
|
5216
|
-
|
|
5215
|
+
dropIdle(res)
|
|
5217
5216
|
await sendLines(res, lines, async () => {
|
|
5218
5217
|
const current = await npmReader(deps, cookie, isPrivate ? [name] : [])
|
|
5219
5218
|
return current != null && (!isPrivate || canReadPrivateNpm(current, name))
|
|
@@ -5229,7 +5228,7 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
|
|
|
5229
5228
|
const diff = await renameDiffOf(diffed, async () => [await prettyText(await prettyCache.npm(doc, diffed.base)),
|
|
5230
5229
|
await prettyText(await prettyCache.npm(other, diffed.other))], !doc.private && !other.private)
|
|
5231
5230
|
if (!(await recheck(doc.private || other.private))) { diff.stream.destroy(); return }
|
|
5232
|
-
|
|
5231
|
+
dropIdle(res)
|
|
5233
5232
|
await sendEncoded(req, res, diff, 'application/json')
|
|
5234
5233
|
return
|
|
5235
5234
|
}
|
|
@@ -5243,7 +5242,7 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
|
|
|
5243
5242
|
let body
|
|
5244
5243
|
try { body = await patchedVersionBody(doc, patch, patchedFiles(await load.result, patched.files)) } finally { load.release() }
|
|
5245
5244
|
if (!(await recheck(doc.private))) { body.stream.destroy(); return }
|
|
5246
|
-
|
|
5245
|
+
dropIdle(res)
|
|
5247
5246
|
await sendEncoded(req, res, body, 'application/json')
|
|
5248
5247
|
return
|
|
5249
5248
|
}
|
|
@@ -5276,7 +5275,7 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
|
|
|
5276
5275
|
res.once('close', load.release)
|
|
5277
5276
|
const bytes = await load.result
|
|
5278
5277
|
if (!(await recheck(doc.private))) return
|
|
5279
|
-
|
|
5278
|
+
dropIdle(res)
|
|
5280
5279
|
res.writeHead(200, {
|
|
5281
5280
|
...download
|
|
5282
5281
|
? { 'content-type': 'application/gzip', 'content-disposition': attachmentDisposition(npmTarballFilename(doc.name, doc.version)) }
|
|
@@ -5299,9 +5298,8 @@ async function handleWorkspaceShare(req: IncomingMessage, res: ServerResponse, d
|
|
|
5299
5298
|
const method = req.method ?? 'GET'
|
|
5300
5299
|
const allowed = id ? ['PATCH', 'DELETE'] : ['GET', 'POST', 'DELETE']
|
|
5301
5300
|
if (!allowed.includes(method)) { send405(res, allowed.join(', ')); return }
|
|
5302
|
-
const s = method === 'GET' ? await
|
|
5303
|
-
if (!s)
|
|
5304
|
-
if (!requireManageRole(res, s.user)) return
|
|
5301
|
+
const s = method === 'GET' ? await readManageSession(res, deps, cookie, { handed: true }) : await manageMutation(req, res, deps, cookie, { handed: true })
|
|
5302
|
+
if (!s) return
|
|
5305
5303
|
const { db } = deps
|
|
5306
5304
|
if (method === 'GET') {
|
|
5307
5305
|
const shares = await db.listWorkspaceShares(s.session.id, Date.now(), teamId)
|
|
@@ -5325,12 +5323,21 @@ async function handleWorkspaceShare(req: IncomingMessage, res: ServerResponse, d
|
|
|
5325
5323
|
sendJson(res, 200, method === 'POST' ? { id: shareId, path: `/team/${team.slug}#public=${shareId.slice(0, 8)}.${token}` } : { ok: true })
|
|
5326
5324
|
}
|
|
5327
5325
|
|
|
5326
|
+
// The repositories' reads that are GETs of their query alone, by their paths.
|
|
5327
|
+
const REPOSITORY_QUERY_READS = new Map<string, (res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams) => Promise<void>>([
|
|
5328
|
+
[REPO_RISK_PATH, handleRepositoryRisk], [REPO_CODE_PATH, handleRepositoryCode], [REPO_HISTORY_PATH, handleRepositoryHistory],
|
|
5329
|
+
[REPO_CHANGES_PATH, handleRepositoryChanges], [REPO_TREE_PATH, handleRepositoryTree], [REPO_ISSUES_PATH, handleRepositoryIssues],
|
|
5330
|
+
[REPO_AGENTS_PATH, handleRepositoryAgents], [REPO_ITEM_PATH, handleRepositoryItem], [REPO_PULL_DEPENDENCIES_PATH, handleRepositoryPullDependencies],
|
|
5331
|
+
[REPO_BRANCH_DEPENDENCIES_PATH, handleRepositoryBranchDependencies], [REPO_LOCKFILES_PATH, handleRepositoryLockfiles],
|
|
5332
|
+
[REPO_PULSE_PATH, handleRepositoryPulse], [REPO_PULSE_ITEMS_PATH, handleRepositoryPulseItems],
|
|
5333
|
+
])
|
|
5334
|
+
|
|
5328
5335
|
export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
|
|
5329
5336
|
const { config, db, avatarStore, isShuttingDown, track } = deps
|
|
5330
5337
|
const repositoryDiscovery = new RepositoryDiscovery(config)
|
|
5331
5338
|
// Kept reads' prunes run behind their writes: tracked, so the database
|
|
5332
5339
|
// outlives them, and on serverless kept alive past the answer.
|
|
5333
|
-
ownKeptPrunes(db, prune => {
|
|
5340
|
+
ownKeptPrunes(db, prune => { trackBehind(deps, prune) })
|
|
5334
5341
|
// GitHub's tagged answers kept beyond this process, for an instance
|
|
5335
5342
|
// starting anew to ask again If-None-Match (github-requests.ts).
|
|
5336
5343
|
const tags = githubTagStore<TaggedRead>(db, config.debug)
|
|
@@ -5365,8 +5372,7 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
|
|
|
5365
5372
|
if (path === LOGIN_PATH) {
|
|
5366
5373
|
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5367
5374
|
const { location, setCookie } = buildLoginRedirect(config)
|
|
5368
|
-
res
|
|
5369
|
-
res.end()
|
|
5375
|
+
sendRedirect(res, location, setCookie)
|
|
5370
5376
|
return
|
|
5371
5377
|
}
|
|
5372
5378
|
// OAuth: callback (the GitHub hook) → mint a session, land on the app.
|
|
@@ -5379,43 +5385,31 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
|
|
|
5379
5385
|
if (!s) return
|
|
5380
5386
|
const result = await linkOAuthCallback(config, db, s.session, url.searchParams, cookie, { avatarStore })
|
|
5381
5387
|
if (result.linked != null) await activity(deps, s.user, 'access', `linked GitHub account @${result.linked}`)
|
|
5382
|
-
res
|
|
5383
|
-
res.end(); return
|
|
5388
|
+
sendRedirect(res, result.location, result.setCookie); return
|
|
5384
5389
|
}
|
|
5385
5390
|
if (isIssueOAuthCallback(config, url.searchParams, cookie)) {
|
|
5386
5391
|
if (viewing) { sendViewOnly(res); return }
|
|
5387
5392
|
const s = await readWorkspaceSession(res, deps, cookie)
|
|
5388
5393
|
if (!s) return
|
|
5389
5394
|
const result = await issueOAuthCallback(config, db, s.session, url.searchParams, cookie)
|
|
5390
|
-
res
|
|
5391
|
-
res.end(); return
|
|
5395
|
+
sendRedirect(res, result.location, result.setCookie); return
|
|
5392
5396
|
}
|
|
5393
5397
|
const result = await handleCallback(url.searchParams, cookie, { config, db, avatarStore })
|
|
5394
5398
|
// A new sign-in never resumes an earlier view.
|
|
5395
5399
|
const setCookies = viewing ? [...result.setCookies, clearViewCookie(config)] : result.setCookies
|
|
5396
|
-
res
|
|
5397
|
-
res.end()
|
|
5400
|
+
sendRedirect(res, result.location, setCookies)
|
|
5398
5401
|
} catch (err) {
|
|
5399
5402
|
if (err instanceof OAuthError) sendJson(res, err.status, { error: err.message })
|
|
5400
5403
|
else throw err
|
|
5401
5404
|
}
|
|
5402
5405
|
return
|
|
5403
5406
|
}
|
|
5404
|
-
if (path === ISSUE_LOGIN_PATH) {
|
|
5405
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5406
|
-
const s = await readWorkspaceSession(res, deps, cookie)
|
|
5407
|
-
if (!s) return
|
|
5408
|
-
const result = issueLoginRedirect(config, s.session)
|
|
5409
|
-
res.writeHead(302, { location: result.location, 'set-cookie': result.setCookie, 'cache-control': 'no-store' })
|
|
5410
|
-
res.end(); return
|
|
5411
|
-
}
|
|
5412
|
-
if (path === LINK_LOGIN_PATH) {
|
|
5407
|
+
if (path === ISSUE_LOGIN_PATH || path === LINK_LOGIN_PATH) {
|
|
5413
5408
|
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5414
5409
|
const s = await readWorkspaceSession(res, deps, cookie)
|
|
5415
5410
|
if (!s) return
|
|
5416
|
-
const result = linkLoginRedirect(config, s.session)
|
|
5417
|
-
res
|
|
5418
|
-
res.end(); return
|
|
5411
|
+
const result = path === ISSUE_LOGIN_PATH ? issueLoginRedirect(config, s.session) : linkLoginRedirect(config, s.session)
|
|
5412
|
+
sendRedirect(res, result.location, result.setCookie); return
|
|
5419
5413
|
}
|
|
5420
5414
|
if (path === PROFILE_PATH) { await handleProfile(req, res, deps, cookie); return }
|
|
5421
5415
|
const unlink = /^\/api\/auth\/profile\/accounts\/([a-f\d-]{36})$/iu.exec(path)
|
|
@@ -5495,9 +5489,10 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
|
|
|
5495
5489
|
if (method !== 'POST') { send405(res, 'POST'); return }
|
|
5496
5490
|
await handleRemoveRepository(req, res, deps, cookie); return
|
|
5497
5491
|
}
|
|
5498
|
-
|
|
5492
|
+
const repositoryRead = REPOSITORY_QUERY_READS.get(path)
|
|
5493
|
+
if (repositoryRead) {
|
|
5499
5494
|
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5500
|
-
await
|
|
5495
|
+
await repositoryRead(res, deps, cookie, url.searchParams); return
|
|
5501
5496
|
}
|
|
5502
5497
|
if (path === BROWSABLE_REPOS_PATH) {
|
|
5503
5498
|
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
@@ -5507,54 +5502,6 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
|
|
|
5507
5502
|
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5508
5503
|
await handleRepositoryBrowser(res, deps, cookie, url.searchParams, path === REPO_REFS_PATH); return
|
|
5509
5504
|
}
|
|
5510
|
-
if (path === REPO_CODE_PATH) {
|
|
5511
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5512
|
-
await handleRepositoryCode(res, deps, cookie, url.searchParams); return
|
|
5513
|
-
}
|
|
5514
|
-
if (path === REPO_HISTORY_PATH) {
|
|
5515
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5516
|
-
await handleRepositoryHistory(res, deps, cookie, url.searchParams); return
|
|
5517
|
-
}
|
|
5518
|
-
if (path === REPO_CHANGES_PATH) {
|
|
5519
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5520
|
-
await handleRepositoryChanges(res, deps, cookie, url.searchParams); return
|
|
5521
|
-
}
|
|
5522
|
-
if (path === REPO_TREE_PATH) {
|
|
5523
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5524
|
-
await handleRepositoryTree(res, deps, cookie, url.searchParams); return
|
|
5525
|
-
}
|
|
5526
|
-
if (path === REPO_ISSUES_PATH) {
|
|
5527
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5528
|
-
await handleRepositoryIssues(res, deps, cookie, url.searchParams); return
|
|
5529
|
-
}
|
|
5530
|
-
if (path === REPO_AGENTS_PATH) {
|
|
5531
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5532
|
-
await handleRepositoryAgents(res, deps, cookie, url.searchParams); return
|
|
5533
|
-
}
|
|
5534
|
-
if (path === REPO_ITEM_PATH) {
|
|
5535
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5536
|
-
await handleRepositoryItem(res, deps, cookie, url.searchParams); return
|
|
5537
|
-
}
|
|
5538
|
-
if (path === REPO_PULL_DEPENDENCIES_PATH) {
|
|
5539
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5540
|
-
await handleRepositoryPullDependencies(res, deps, cookie, url.searchParams); return
|
|
5541
|
-
}
|
|
5542
|
-
if (path === REPO_BRANCH_DEPENDENCIES_PATH) {
|
|
5543
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5544
|
-
await handleRepositoryBranchDependencies(res, deps, cookie, url.searchParams); return
|
|
5545
|
-
}
|
|
5546
|
-
if (path === REPO_LOCKFILES_PATH) {
|
|
5547
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5548
|
-
await handleRepositoryLockfiles(res, deps, cookie, url.searchParams); return
|
|
5549
|
-
}
|
|
5550
|
-
if (path === REPO_PULSE_PATH) {
|
|
5551
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5552
|
-
await handleRepositoryPulse(res, deps, cookie, url.searchParams); return
|
|
5553
|
-
}
|
|
5554
|
-
if (path === REPO_PULSE_ITEMS_PATH) {
|
|
5555
|
-
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5556
|
-
await handleRepositoryPulseItems(res, deps, cookie, url.searchParams); return
|
|
5557
|
-
}
|
|
5558
5505
|
if (path === ADMIN_REPOS_PATH) { await handleListRepositories(req, res, deps, cookie, repositoryDiscovery); return }
|
|
5559
5506
|
if (path === SELECT_REPO_PATH) { await handleSelectRepository(req, res, deps, cookie); return }
|
|
5560
5507
|
if (path === REPO_DEPENDENCY_REVIEW_PATH) { await handleRepositoryDependencyReview(req, res, deps, cookie); return }
|
|
@@ -5625,7 +5572,8 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
|
|
|
5625
5572
|
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5626
5573
|
if (part === 'rename-diff' && url.searchParams.has('path')) { await handleBundleRenameDiff(req, res, deps, session, id, url.searchParams); return }
|
|
5627
5574
|
// The pairs a scoped Compare diffs, of the files it compares within its scope.
|
|
5628
|
-
const
|
|
5575
|
+
const typeOnly = (sides: [ComparedSide, ComparedSide]) => typeOnlyFiles(sides, runsAsked(url.searchParams))
|
|
5576
|
+
const [linesOf, scope] = part === 'pretty' ? [compared, ''] : [part === 'type-only' ? typeOnly : renamedPairs, url.searchParams.get('scope') ?? '']
|
|
5629
5577
|
await handleBundleChanges(res, deps, session, id, url.searchParams.get('other') ?? '', async (cache, base, other) => linesOf(await cache.bundleSides(base, other, scope))); return
|
|
5630
5578
|
}
|
|
5631
5579
|
if (method !== 'GET' && method !== 'HEAD') { send405(res, 'GET, HEAD'); return }
|
|
@@ -5778,12 +5726,8 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
|
|
|
5778
5726
|
if (method !== 'POST') { send405(res, 'POST'); return }
|
|
5779
5727
|
const s = await checkMutation(req, res, deps, cookie, { handed: true })
|
|
5780
5728
|
if (!s) return
|
|
5781
|
-
|
|
5782
|
-
|
|
5783
|
-
const raw = await readJsonBody(req, 4096)
|
|
5784
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('bad-body')
|
|
5785
|
-
body = raw as Record<string, unknown>
|
|
5786
|
-
} catch { sendJson(res, 400, { error: 'bad-body' }); return }
|
|
5729
|
+
const body = await readBodyObject(req, res)
|
|
5730
|
+
if (!body) return
|
|
5787
5731
|
const id = body['reviewId'], revision = body['revision']
|
|
5788
5732
|
if (typeof id !== 'string' || !id || id.length > 100 || !Number.isSafeInteger(revision) || Number(revision) < 1) {
|
|
5789
5733
|
sendJson(res, 400, { error: 'bad-review' }); return
|
|
@@ -5794,11 +5738,9 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
|
|
|
5794
5738
|
if (path === '/api/npm/reviews/mine') {
|
|
5795
5739
|
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5796
5740
|
const s = workspaceSession!
|
|
5797
|
-
const
|
|
5798
|
-
if (
|
|
5799
|
-
|
|
5800
|
-
}
|
|
5801
|
-
const page = await deps.db.listOwnDependencyReviews(s.user.id, time !== null && id !== null ? { time: Number(time), id } : null)
|
|
5741
|
+
const cursor = reviewCursor(url.searchParams)
|
|
5742
|
+
if (cursor === 'invalid') { sendJson(res, 400, { error: 'bad-review-cursor' }); return }
|
|
5743
|
+
const page = await deps.db.listOwnDependencyReviews(s.user.id, cursor)
|
|
5802
5744
|
const reviews = await readableNpmReviews(res, deps, cookie, s.user.id, page.reviews, s.user)
|
|
5803
5745
|
if (reviews) sendJson(res, 200, { ...page, reviews: await withFormatted(deps.reviewedDependencies ?? null, s.user.id, reviews) })
|
|
5804
5746
|
return
|
|
@@ -5808,12 +5750,11 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
|
|
|
5808
5750
|
if (path === '/api/npm/reviews/team') {
|
|
5809
5751
|
if (method !== 'GET') { send405(res, 'GET'); return }
|
|
5810
5752
|
const s = workspaceSession!
|
|
5811
|
-
const
|
|
5753
|
+
const teamId = url.searchParams.get('teamId')
|
|
5812
5754
|
if (!teamId || teamId.length > 100) { sendJson(res, 400, { error: 'bad-team' }); return }
|
|
5813
|
-
|
|
5814
|
-
|
|
5815
|
-
|
|
5816
|
-
const page = await deps.db.listTeamDependencyReviews(teamId, s.user.id, time !== null && id !== null ? { time: Number(time), id } : null)
|
|
5755
|
+
const cursor = reviewCursor(url.searchParams)
|
|
5756
|
+
if (cursor === 'invalid') { sendJson(res, 400, { error: 'bad-review-cursor' }); return }
|
|
5757
|
+
const page = await deps.db.listTeamDependencyReviews(teamId, s.user.id, cursor)
|
|
5817
5758
|
if (!page) { sendJson(res, 404, { error: 'no-team' }); return }
|
|
5818
5759
|
// Its access asked again, as it may have been taken while npm was read.
|
|
5819
5760
|
const reviews = await readableNpmReviews(res, deps, cookie, s.user.id, page.reviews, s.user, teamId)
|