@preventive/triage 1.0.0-alpha.60 → 1.0.0-alpha.61
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 +1 -1
- package/out/chunk-6CCSTJWB.js +1 -0
- package/out/{chunk-VZJIHHTQ.js → chunk-B3FNMHOE.js} +1 -1
- package/out/chunk-BNH52UHC.js +2 -0
- package/out/chunk-BRO77PQY.js +42 -0
- package/out/chunk-GRGIZOTP.js +4 -0
- package/out/chunk-JJK5OZG2.js +15 -0
- package/out/chunk-OFZYEWBH.js +244 -0
- package/out/{chunk-YGRRXC2L.js → chunk-OIERSXON.js} +1 -1
- package/out/{chunk-TZS7KERJ.js → chunk-QCOGVL37.js} +1 -1
- package/out/{chunk-6VDDCFHT.js → chunk-W3QFV4SP.js} +1 -1
- package/out/chunk-W6VOKW2N.js +12 -0
- package/out/chunk-ZQNEWVGG.js +1 -0
- package/out/client-managed.js +2 -2
- 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/scan.js +1 -1
- package/out/terminal.js +12 -12
- package/out/view.css +1 -1
- package/out/view.js +4 -4
- package/package.json +9 -6
- 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 +18 -10
- 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 +72 -62
- 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/out/chunk-2SY4PYUQ.js +0 -4
- package/out/chunk-4HI2MSAV.js +0 -17
- package/out/chunk-4TQKM3JC.js +0 -42
- 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-YTO6AQZM.js +0 -2
|
@@ -14,13 +14,11 @@
|
|
|
14
14
|
// file's mode is left out, as the files it reads have none.
|
|
15
15
|
import { Buffer } from 'node:buffer'
|
|
16
16
|
import { createHash } from 'node:crypto'
|
|
17
|
-
import { createClient } from '@preventive/upstream/github.js'
|
|
18
17
|
import { isPatchHash, isPatchPath } from '../common/managed/npm-packages.js'
|
|
19
|
-
import {
|
|
20
|
-
import { upstreamGithub } from './github-errors.ts'
|
|
18
|
+
import { SHA } from './github-values.ts'
|
|
21
19
|
import { type Lru, lru } from './lru.ts'
|
|
22
|
-
import { NpmPackageError, type NpmPackageFile, npmFileText } from './npm-packages.ts'
|
|
23
|
-
import type
|
|
20
|
+
import { NpmPackageError, type NpmPackageFile, npmFileText, pathOrder } from './npm-packages.ts'
|
|
21
|
+
import { type GithubAsked, repositoryFile } from './pull-dependencies.ts'
|
|
24
22
|
|
|
25
23
|
// Where a patch is read: its file in a repository (by its id) at a commit,
|
|
26
24
|
// from the repository's root; and the patch, by its hash besides.
|
|
@@ -29,10 +27,9 @@ export interface NpmPatch extends PatchSource { hash: string }
|
|
|
29
27
|
|
|
30
28
|
// The most a patch's file may hold, and how many lines either side of where a
|
|
31
29
|
// hunk says its lines are they are looked for.
|
|
32
|
-
|
|
30
|
+
const MAX_PATCH_BYTES = 8 * 1024 * 1024
|
|
33
31
|
const FUZZ = 20
|
|
34
32
|
|
|
35
|
-
const COMMIT = /^[\da-f]{40}$/u
|
|
36
33
|
|
|
37
34
|
// The patch a request names, by its hash (`hash`), its repository's id
|
|
38
35
|
// (`repoId`, a number or its digits), the commit and its file's path; null
|
|
@@ -41,7 +38,7 @@ const COMMIT = /^[\da-f]{40}$/u
|
|
|
41
38
|
export function requestedPatch({ hash, repoId, commit, path }: { hash: unknown; repoId: unknown; commit: unknown; path: unknown }): NpmPatch | null | 'invalid' {
|
|
42
39
|
if ([repoId, commit, path].every(field => field == null)) return null
|
|
43
40
|
const id = typeof repoId === 'string' && /^[1-9]\d{0,15}$/u.test(repoId) ? Number(repoId) : repoId
|
|
44
|
-
if (!isPatchHash(hash) || !Number.isSafeInteger(id) || (id as number) <= 0 || typeof commit !== 'string' || !
|
|
41
|
+
if (!isPatchHash(hash) || !Number.isSafeInteger(id) || (id as number) <= 0 || typeof commit !== 'string' || !SHA.test(commit)
|
|
45
42
|
|| !isPatchPath(path)) return 'invalid'
|
|
46
43
|
return { hash, repoId: id as number, commit, path }
|
|
47
44
|
}
|
|
@@ -283,7 +280,7 @@ export function patchedFiles(files: NpmPackageFile[], patch: PatchedFile[]): Npm
|
|
|
283
280
|
}
|
|
284
281
|
byPath.set(file.path, next)
|
|
285
282
|
}
|
|
286
|
-
return [...byPath].map(([path, bytes]) => ({ path, bytes })).toSorted((a, b) => a.path
|
|
283
|
+
return [...byPath].map(([path, bytes]) => ({ path, bytes })).toSorted((a, b) => pathOrder(a.path, b.path))
|
|
287
284
|
}
|
|
288
285
|
|
|
289
286
|
// About the bytes a patch read takes: the characters of its paths and of the
|
|
@@ -310,13 +307,8 @@ export async function readPatch(fullName: string, token: string, patch: NpmPatch
|
|
|
310
307
|
const known = patches.get(key)
|
|
311
308
|
if (known) return known
|
|
312
309
|
if (asked) asked.github = true
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
text = await upstreamGithub(() => createClient({ token, userAgent: 'deepview-triage' }).getRepoFile({ repo: fullName, path: patch.path, ref: patch.commit }))
|
|
316
|
-
} catch (err) {
|
|
317
|
-
if (err instanceof GithubApiError && err.message === 'github-not-found') throw new NpmPackageError(404, 'patch-not-found')
|
|
318
|
-
throw err
|
|
319
|
-
}
|
|
310
|
+
const text = await repositoryFile(fullName, token, patch.path, patch.commit)
|
|
311
|
+
if (text === null) throw new NpmPackageError(404, 'patch-not-found')
|
|
320
312
|
if (Buffer.byteLength(text) > MAX_PATCH_BYTES) throw new NpmPackageError(413, 'patch-too-large')
|
|
321
313
|
if (!isPatchOf(text, patch.hash)) throw new NpmPackageError(409, 'patch-mismatch')
|
|
322
314
|
const files = parsePatch(text)
|
|
@@ -8,14 +8,15 @@
|
|
|
8
8
|
// without the server's token, and only about a version it answers for
|
|
9
9
|
// without one (http.ts), each answer kept as npm-insights.ts keeps its own.
|
|
10
10
|
import { Buffer } from 'node:buffer'
|
|
11
|
+
import { SHA } from './github-values.ts'
|
|
11
12
|
import { kept } from './kept.ts'
|
|
12
|
-
import {
|
|
13
|
+
import { plainObject } from './npm-manifest.ts'
|
|
14
|
+
import { NPM_REGISTRY, askUpstreamJson } from './npm-packages.ts'
|
|
13
15
|
|
|
14
16
|
const ATTESTATIONS_API = `${NPM_REGISTRY}/-/npm/v1/attestations`
|
|
15
17
|
const ATTESTATIONS_BYTES = 1024 * 1024
|
|
16
18
|
// SLSA's v1 statement, as npm writes it now, and v0.2, as it first did.
|
|
17
19
|
const SLSA = /^https:\/\/slsa\.dev\/provenance\/v(?:1|0\.2)$/u
|
|
18
|
-
const COMMIT = /^[0-9a-f]{40}$/u
|
|
19
20
|
const GITHUB_REPOSITORY = /^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)$/u
|
|
20
21
|
|
|
21
22
|
// Where a version was built: its source `repository` (an https URL) and
|
|
@@ -43,6 +44,11 @@ function sourceOf(uri: unknown) {
|
|
|
43
44
|
// What `keys` lead to in `value`, through objects and arrays.
|
|
44
45
|
const field = (value: unknown, ...keys: string[]): unknown =>
|
|
45
46
|
keys.reduce<unknown>((at, key) => plainObject(at) || Array.isArray(at) ? (at as Record<string, unknown>)[key] : undefined, value)
|
|
47
|
+
// The list they lead to, none where it is none.
|
|
48
|
+
const listAt = (value: unknown, ...keys: string[]): unknown[] => {
|
|
49
|
+
const list = field(value, ...keys)
|
|
50
|
+
return Array.isArray(list) ? list : []
|
|
51
|
+
}
|
|
46
52
|
|
|
47
53
|
// What a statement says of the build, as v1 or v0.2 says it; null where it
|
|
48
54
|
// names no source repository.
|
|
@@ -54,7 +60,7 @@ function readStatement(predicateType: string, predicate: unknown): NpmProvenance
|
|
|
54
60
|
if (!repository) return null
|
|
55
61
|
const commit = text(field(source, 'digest', 'gitCommit'))
|
|
56
62
|
return {
|
|
57
|
-
repository, commit: commit &&
|
|
63
|
+
repository, commit: commit && SHA.test(commit) ? commit : null, workflow: text(field(workflow, 'path')),
|
|
58
64
|
ref: text(field(workflow, 'ref')) ?? sourceOf(field(source, 'uri')).ref, builder: https(field(predicate, 'runDetails', 'builder', 'id')),
|
|
59
65
|
run: https(field(predicate, 'runDetails', 'metadata', 'invocationId')), logIndex: null, runner: null,
|
|
60
66
|
}
|
|
@@ -68,7 +74,7 @@ function readStatement(predicateType: string, predicate: unknown): NpmProvenance
|
|
|
68
74
|
const run = /^(\d+)-(\d+)$/u.exec(text(invocation) ?? '')
|
|
69
75
|
const github = GITHUB_REPOSITORY.exec(repository)?.[1]
|
|
70
76
|
return {
|
|
71
|
-
repository, commit: commit &&
|
|
77
|
+
repository, commit: commit && SHA.test(commit) ? commit : null, workflow: text(field(config, 'entryPoint')), ref,
|
|
72
78
|
builder: https(field(predicate, 'builder', 'id')),
|
|
73
79
|
run: https(invocation) ?? (run && github ? `https://github.com/${github}/actions/runs/${run[1]}/attempts/${run[2]}` : null), logIndex: null, runner: null,
|
|
74
80
|
}
|
|
@@ -92,8 +98,7 @@ async function askProvenance(name: string, version: string, integrity: string):
|
|
|
92
98
|
const json = await askUpstreamJson(`${ATTESTATIONS_API}/${name.replace('/', '%2f')}@${encodeURIComponent(version)}`,
|
|
93
99
|
{ headers: { accept: 'application/json' }, limit: ATTESTATIONS_BYTES })
|
|
94
100
|
if (json === null) return null
|
|
95
|
-
const
|
|
96
|
-
const slsa = attestations.find(item => SLSA.test(text(field(item, 'predicateType')) ?? ''))
|
|
101
|
+
const slsa = listAt(json, 'attestations').find(item => SLSA.test(text(field(item, 'predicateType')) ?? ''))
|
|
97
102
|
if (!slsa) return null
|
|
98
103
|
// The statement, whatever its length (the answer is bounded as a whole),
|
|
99
104
|
// unlike the fields read out of it.
|
|
@@ -104,8 +109,7 @@ async function askProvenance(name: string, version: string, integrity: string):
|
|
|
104
109
|
// version's integrity has it.
|
|
105
110
|
const purl = `pkg:npm/${name.replace(/^@/u, '%40')}@${version}`
|
|
106
111
|
const digest = /^sha512-(.+)$/u.exec(integrity)?.[1]
|
|
107
|
-
|
|
108
|
-
if (!digest || !subjects.some(subject => field(subject, 'name') === purl && field(subject, 'digest', 'sha512') === Buffer.from(digest, 'base64').toString('hex'))) return null
|
|
112
|
+
if (!digest || !listAt(statement, 'subject').some(subject => field(subject, 'name') === purl && field(subject, 'digest', 'sha512') === Buffer.from(digest, 'base64').toString('hex'))) return null
|
|
109
113
|
const provenance = readStatement(text(field(slsa, 'predicateType'))!, field(statement, 'predicate'))
|
|
110
114
|
const logIndex = Number(field(slsa, 'bundle', 'verificationMaterial', 'tlogEntries', '0', 'logIndex'))
|
|
111
115
|
return provenance && { ...provenance, logIndex: Number.isSafeInteger(logIndex) && logIndex >= 0 ? logIndex : null, runner: runnerOf(field(slsa, 'bundle')) }
|
|
@@ -38,15 +38,14 @@
|
|
|
38
38
|
// unpacking up to two tarballs: one past them is refused as busy.
|
|
39
39
|
import { Buffer } from 'node:buffer'
|
|
40
40
|
import { createHash } from 'node:crypto'
|
|
41
|
-
import { buffer } from 'node:stream/consumers'
|
|
42
41
|
import type { CacheStore } from '@preventive/upstream/npm.js'
|
|
43
42
|
import { DEFAULT_MINIMUM_RELEASE_AGE, type NpmAssessment, assessNpm, npmReadyDownload, npmReadyDownloads } from '../risk/index.js'
|
|
43
|
+
import { readBytes } from './blob-store.ts'
|
|
44
44
|
import { CacheMissError, type CacheStorage } from './cache-storage.ts'
|
|
45
|
-
import { npmVersionStore } from './npm-kept.ts'
|
|
45
|
+
import { npmVersionStore, pruneKept } from './npm-kept.ts'
|
|
46
46
|
import { loadNpmTarball } from './npm-loads.ts'
|
|
47
47
|
import { NpmPackageError, type NpmVersionDocument, npmTokenReads, readNpmPackument, readNpmVersion } from './npm-packages.ts'
|
|
48
48
|
import { npmPackageScope } from '../common/managed/npm-packages.js'
|
|
49
|
-
import { pruneKept } from './npm-kept.ts'
|
|
50
49
|
import type { UpstreamCacheStore } from './upstream-cache.ts'
|
|
51
50
|
|
|
52
51
|
const MEMORY_ENTRIES = 2000
|
|
@@ -113,6 +112,9 @@ export interface NpmRiskCache extends CacheStore {
|
|
|
113
112
|
// that what is kept of it can be shared.
|
|
114
113
|
export function npmRiskCache({ db, npmCache, debug }: NpmRiskStores, isPublic: boolean): NpmRiskCache {
|
|
115
114
|
const warn = (what: string, error: unknown) => { if (debug) console.warn(`managed: risk cache ${what} failed:`, error) }
|
|
115
|
+
// The rows under `prefix` kept `keptMs` before `at` removed, as rows under
|
|
116
|
+
// it are written (pruneKept).
|
|
117
|
+
const prune = (prefix: string, keptMs: number, at: number) => pruneKept(db, prefix, keptMs, at, error => { warn('prune', error) })
|
|
116
118
|
const memoryKey = (type: string, key: string) => `${isPublic ? '' : 'private\0'}${type}\0${key}`
|
|
117
119
|
// Whether a record of `type` is read of the database: unless it is one
|
|
118
120
|
// kept in memory too (HOURLY) and there.
|
|
@@ -144,12 +146,12 @@ export function npmRiskCache({ db, npmCache, debug }: NpmRiskStores, isPublic: b
|
|
|
144
146
|
if (!isPublic || !IN_DATABASE.has(type)) { for (const [key, value] of entries) await cache.write(type, key, value); return }
|
|
145
147
|
const at = Date.now()
|
|
146
148
|
try { await db.setUpstreamCacheEntries(entries.map(([key, value]) => [`${type}/${key}`, JSON.stringify(value)]), at) } catch (error) { warn('write', error); return }
|
|
147
|
-
if (type === 'risk/npm/downloads') await
|
|
149
|
+
if (type === 'risk/npm/downloads') await prune(`${type}/`, DOWNLOADS_KEPT_MS, at)
|
|
148
150
|
},
|
|
149
151
|
async read(type, key) {
|
|
150
152
|
if (type === 'npm/tarballs') return null
|
|
151
153
|
try {
|
|
152
|
-
if (isPublic && type === 'risk/npm/assessments' && npmCache) return JSON.parse((await
|
|
154
|
+
if (isPublic && type === 'risk/npm/assessments' && npmCache) return JSON.parse((await readBytes(await npmCache.open(hashed(type, key)))).toString('utf8'))
|
|
153
155
|
if (ofDatabase(type, key)) return readOf(type, key, await db.getUpstreamCacheEntry(databaseKey(type, key)))
|
|
154
156
|
} catch (error) { if (!(error instanceof CacheMissError)) warn('read', error); return null }
|
|
155
157
|
return memory.get(memoryKey(type, key))?.value ?? null
|
|
@@ -162,7 +164,7 @@ export function npmRiskCache({ db, npmCache, debug }: NpmRiskStores, isPublic: b
|
|
|
162
164
|
if (isPublic && IN_DATABASE.has(type)) {
|
|
163
165
|
const at = Date.now()
|
|
164
166
|
await db.setUpstreamCacheEntry(databaseKey(type, key), JSON.stringify(value), at)
|
|
165
|
-
if (type === 'risk/npm/downloads') await
|
|
167
|
+
if (type === 'risk/npm/downloads') await prune(`${type}/`, DOWNLOADS_KEPT_MS, at)
|
|
166
168
|
return
|
|
167
169
|
}
|
|
168
170
|
if (isPublic && HOURLY.has(type)) {
|
|
@@ -170,7 +172,7 @@ export function npmRiskCache({ db, npmCache, debug }: NpmRiskStores, isPublic: b
|
|
|
170
172
|
if (json.length > HOURLY_LENGTH) return
|
|
171
173
|
const at = Date.now()
|
|
172
174
|
await db.setUpstreamCacheEntry(databaseKey(type, key), json, at)
|
|
173
|
-
await
|
|
175
|
+
await prune(HOURLY_PREFIX, HOURLY_KEPT_MS, at)
|
|
174
176
|
return
|
|
175
177
|
}
|
|
176
178
|
} catch (error) { warn('write', error); return }
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto'
|
|
2
2
|
import { link, lstat, mkdir, open, readdir, rename, rm, rmdir, stat } from 'node:fs/promises'
|
|
3
3
|
import { dirname, join } from 'node:path'
|
|
4
|
-
import { type ObjectPage, type RawObjectStorage, objectPath } from './object-storage.ts'
|
|
4
|
+
import { type ObjectPage, type RawObjectStorage, objectPath, validateStoragePage } from './object-storage.ts'
|
|
5
5
|
|
|
6
6
|
function missing(err: unknown): boolean { return (err as NodeJS.ErrnoException).code === 'ENOENT' }
|
|
7
7
|
function version(info: { dev: number; ino: number; size: number; mtimeMs: number; ctimeMs: number }): string {
|
|
@@ -62,8 +62,7 @@ async function listFiles(dir: string, prefix: string, cursor: string | null, lim
|
|
|
62
62
|
// inventory can mark the shared migration complete.
|
|
63
63
|
try { await syncDirectory(join(dir, key)) } catch (err) { if (!missing(err)) throw err }
|
|
64
64
|
}
|
|
65
|
-
|
|
66
|
-
objectPath(`${prefix}validate`)
|
|
65
|
+
validateStoragePage(prefix, limit)
|
|
67
66
|
await visit(prefix)
|
|
68
67
|
return { objects: objects.slice(0, limit), cursor: objects.length > limit ? objects[limit - 1]!.key : null }
|
|
69
68
|
}
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { Readable } from 'node:stream'
|
|
2
2
|
import { Buffer } from 'node:buffer'
|
|
3
3
|
import { type VercelBlobSdk, isNotFound, loadVercelBlobSdk } from '../server-common/vercel-blob.ts'
|
|
4
|
-
import { type RawObjectStorage, objectPath } from './object-storage.ts'
|
|
4
|
+
import { type RawObjectStorage, objectPath, validateStoragePage } from './object-storage.ts'
|
|
5
|
+
|
|
6
|
+
// The SDK's abort option, where there is a signal to give it; and when a blob
|
|
7
|
+
// was last written, now where the SDK does not say.
|
|
8
|
+
const abortable = (signal?: AbortSignal) => signal ? { abortSignal: signal } : {}
|
|
9
|
+
const modifiedAt = (uploadedAt?: Date | string | number) => new Date(uploadedAt ?? Date.now()).getTime()
|
|
5
10
|
|
|
6
11
|
export async function openVercelObjectStorage(token: string, sdk?: VercelBlobSdk): Promise<RawObjectStorage> {
|
|
7
12
|
const blobs = sdk ?? await loadVercelBlobSdk()
|
|
@@ -9,9 +14,9 @@ export async function openVercelObjectStorage(token: string, sdk?: VercelBlobSdk
|
|
|
9
14
|
const storage: RawObjectStorage = {
|
|
10
15
|
async head(key, signal) {
|
|
11
16
|
try {
|
|
12
|
-
const meta = await blobs.head(path(key), { token, ...(signal
|
|
17
|
+
const meta = await blobs.head(path(key), { token, ...abortable(signal) })
|
|
13
18
|
if (!meta.etag) throw new Error('Missing object version')
|
|
14
|
-
return { size: meta.size, version: meta.etag, modifiedAt:
|
|
19
|
+
return { size: meta.size, version: meta.etag, modifiedAt: modifiedAt(meta.uploadedAt) }
|
|
15
20
|
} catch (err) { if (isNotFound(err, blobs)) return null; throw err }
|
|
16
21
|
},
|
|
17
22
|
async open(key, signal) {
|
|
@@ -19,21 +24,21 @@ export async function openVercelObjectStorage(token: string, sdk?: VercelBlobSdk
|
|
|
19
24
|
// Read the stored representation: transport compression can weaken its
|
|
20
25
|
// ETag, which cannot satisfy ifMatch, and changes the advertised size.
|
|
21
26
|
const result = await blobs.get(path(key), { token, access: 'private', useCache: false,
|
|
22
|
-
headers: { 'accept-encoding': 'identity' }, ...(signal
|
|
27
|
+
headers: { 'accept-encoding': 'identity' }, ...abortable(signal) })
|
|
23
28
|
if (!result) return null
|
|
24
29
|
if (result.statusCode !== 200 || !result.stream || !result.blob.etag) {
|
|
25
30
|
await result.stream?.cancel()
|
|
26
31
|
throw new Error('Unexpected blob response or missing object version')
|
|
27
32
|
}
|
|
28
33
|
return { size: result.blob.size === 0 ? null : result.blob.size, version: result.blob.etag,
|
|
29
|
-
modifiedAt:
|
|
34
|
+
modifiedAt: modifiedAt(result.blob.uploadedAt),
|
|
30
35
|
stream: Readable.fromWeb(result.stream as Parameters<typeof Readable.fromWeb>[0], signal ? { signal } : {}) }
|
|
31
36
|
} catch (err) { if (isNotFound(err, blobs)) return null; throw err }
|
|
32
37
|
},
|
|
33
38
|
async put(key, bytes, signal, expected, sizeHint) {
|
|
34
39
|
const multipart = (sizeHint ?? (Buffer.isBuffer(bytes) ? bytes.length : Infinity)) >= 5 * 1024 * 1024
|
|
35
40
|
try { await blobs.put(path(key), bytes, { token, access: 'private', addRandomSuffix: false, allowOverwrite: expected !== null,
|
|
36
|
-
...(expected ? { ifMatch: expected } : {}), multipart, contentType: 'application/octet-stream', cacheControlMaxAge: 60, ...(signal
|
|
41
|
+
...(expected ? { ifMatch: expected } : {}), multipart, contentType: 'application/octet-stream', cacheControlMaxAge: 60, ...abortable(signal) })
|
|
37
42
|
return true
|
|
38
43
|
} catch (err) {
|
|
39
44
|
if (blobs.BlobPreconditionFailedError && err instanceof blobs.BlobPreconditionFailedError) return false
|
|
@@ -45,7 +50,7 @@ export async function openVercelObjectStorage(token: string, sdk?: VercelBlobSdk
|
|
|
45
50
|
},
|
|
46
51
|
async delete(key, version, signal) {
|
|
47
52
|
signal?.throwIfAborted()
|
|
48
|
-
try { await blobs.del(path(key), { token, ...(version ? { ifMatch: version } : {}), ...(signal
|
|
53
|
+
try { await blobs.del(path(key), { token, ...(version ? { ifMatch: version } : {}), ...abortable(signal) }); return true }
|
|
49
54
|
catch (err) {
|
|
50
55
|
if (isNotFound(err, blobs)) return true
|
|
51
56
|
if (blobs.BlobPreconditionFailedError && err instanceof blobs.BlobPreconditionFailedError) return false
|
|
@@ -54,12 +59,11 @@ export async function openVercelObjectStorage(token: string, sdk?: VercelBlobSdk
|
|
|
54
59
|
},
|
|
55
60
|
async list(prefix, cursor, limit, signal) {
|
|
56
61
|
signal?.throwIfAborted()
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const page = await blobs.list({ prefix: `.managed/${prefix}`, token, limit, ...(cursor ? { cursor } : {}), ...(signal ? { abortSignal: signal } : {}) })
|
|
62
|
+
validateStoragePage(prefix, limit)
|
|
63
|
+
const page = await blobs.list({ prefix: `.managed/${prefix}`, token, limit, ...(cursor ? { cursor } : {}), ...abortable(signal) })
|
|
60
64
|
if (page.hasMore && (!page.cursor || page.cursor === cursor)) throw new Error('Invalid blob pagination')
|
|
61
65
|
return { objects: page.blobs.filter(blob => blob.pathname.startsWith(`.managed/${prefix}`)).map(blob => ({ key: blob.pathname.slice('.managed/'.length),
|
|
62
|
-
modifiedAt:
|
|
66
|
+
modifiedAt: modifiedAt(blob.uploadedAt) })),
|
|
63
67
|
cursor: page.hasMore ? page.cursor! : null }
|
|
64
68
|
},
|
|
65
69
|
}
|
|
@@ -44,6 +44,13 @@ export function objectPath(key: string): string {
|
|
|
44
44
|
return key
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
// A listing's page: `prefix` a directory of the managed namespace, `limit` a
|
|
48
|
+
// count of at least one.
|
|
49
|
+
export function validateStoragePage(prefix: string, limit: number): void {
|
|
50
|
+
if (!prefix.endsWith('/') || !Number.isInteger(limit) || limit < 1) throw new Error('Invalid storage page')
|
|
51
|
+
objectPath(`${prefix}validate`)
|
|
52
|
+
}
|
|
53
|
+
|
|
47
54
|
// Hash verification and migration may consume a stream before it can be used.
|
|
48
55
|
// Reopen only the same object version, closing any concurrent replacement.
|
|
49
56
|
export async function openObjectVersion(raw: RawObjectStorage, key: string, version: string, signal?: AbortSignal): Promise<RawObject | null> {
|
|
@@ -16,7 +16,7 @@ import { FILE_HASH, computeBundleFileHashes } from '../common/bundle-metadata.js
|
|
|
16
16
|
import { bundleCompareFiles, bundleCompareSideScopes } from '../common/bundle-compare-inputs.js'
|
|
17
17
|
import { bundlePackageDirs, bundleSourcesAsMap } from '../common/bundle-sources.js'
|
|
18
18
|
import { MAX_PRETTY_BYTES, needsPrettyPrint, prettyExtension } from '../common/pretty-print.js'
|
|
19
|
-
import type
|
|
19
|
+
import { type OpenedBlob, readBytes } from './blob-store.ts'
|
|
20
20
|
import { type BundleCacheStorage, readSizedBundleDetails } from './bundle-cache.ts'
|
|
21
21
|
import type { BundleStore } from './bundle-store.ts'
|
|
22
22
|
import { encodeBrotli } from './brotli.ts'
|
|
@@ -24,7 +24,8 @@ import { CacheMissError, type CacheStorage } from './cache-storage.ts'
|
|
|
24
24
|
import type { ManagedBundle, ManagedDb } from './db.ts'
|
|
25
25
|
import { keptBriefly } from './kept-briefly.ts'
|
|
26
26
|
import { loadNpmFiles } from './npm-loads.ts'
|
|
27
|
-
import { type NpmVersionDocument, npmFileText } from './npm-packages.ts'
|
|
27
|
+
import { type NpmVersionDocument, npmFileText, pathOrder } from './npm-packages.ts'
|
|
28
|
+
import { inTurns } from './queue.ts'
|
|
28
29
|
|
|
29
30
|
// Part of every kept copy's name; bumped when what the formatter writes for
|
|
30
31
|
// the same file changes, or what its check lets through, so copies written
|
|
@@ -121,7 +122,7 @@ export async function prettyBody(text: string, extension: string): Promise<Buffe
|
|
|
121
122
|
return encodeBrotli(Buffer.from(result.code))
|
|
122
123
|
}
|
|
123
124
|
|
|
124
|
-
const opened = (body: Buffer): OpenedBlob => ({ size: body.byteLength, stream: Readable.from([body]) })
|
|
125
|
+
export const opened = (body: Buffer): OpenedBlob => ({ size: body.byteLength, stream: Readable.from([body]) })
|
|
125
126
|
|
|
126
127
|
// A version's file's hash, by its bytes: those of a version's files loaded
|
|
127
128
|
// a little while since are the same bytes (npm-loads.ts), hashed once.
|
|
@@ -139,9 +140,7 @@ const decompress = promisify(brotliDecompress)
|
|
|
139
140
|
|
|
140
141
|
// A pretty-printed copy's text, from its Brotli-encoded bytes.
|
|
141
142
|
export async function prettyText(copy: OpenedBlob): Promise<string> {
|
|
142
|
-
|
|
143
|
-
for await (const chunk of copy.stream) chunks.push(chunk as Buffer)
|
|
144
|
-
return (await decompress(Buffer.concat(chunks))).toString()
|
|
143
|
+
return (await decompress(await readBytes(copy))).toString()
|
|
145
144
|
}
|
|
146
145
|
|
|
147
146
|
// Every file of a version that needs pretty-printing (needsPrettyPrint), read
|
|
@@ -157,7 +156,7 @@ async function npmPrintable(doc: NpmVersionDocument): Promise<Array<PrettyReques
|
|
|
157
156
|
if (text !== null && needsPrettyPrint(path, text)) files.push({ path, hash: await npmFileHash(bytes), extension, text })
|
|
158
157
|
}
|
|
159
158
|
} finally { load.release() }
|
|
160
|
-
return files.toSorted((a, b) => (a.path
|
|
159
|
+
return files.toSorted((a, b) => pathOrder(a.path, b.path))
|
|
161
160
|
}
|
|
162
161
|
|
|
163
162
|
// A file's line (PrettyLine): the text of its copy, as `copy` has it, or why
|
|
@@ -210,7 +209,7 @@ export function compared(sides: readonly [ComparedSide, ComparedSide]): AsyncGen
|
|
|
210
209
|
const changed = sides.flatMap((own, i) => {
|
|
211
210
|
const other = sides[1 - i]!.hashes
|
|
212
211
|
return own.files.filter(({ path, hash }) => (other.has(path) ? other.get(path) !== hash : !moved[1 - i]!.has(hash))).map(file => ({ own, file }))
|
|
213
|
-
}).toSorted((a, b) => (a.file.path
|
|
212
|
+
}).toSorted((a, b) => pathOrder(a.file.path, b.file.path))
|
|
214
213
|
return (async function* () {
|
|
215
214
|
const unkept: typeof changed = []
|
|
216
215
|
for await (const [{ own, file }, line] of readAhead(changed, item => keptLine(item.file, () => item.own.kept(item.file)))) {
|
|
@@ -234,16 +233,6 @@ function sharing<T>(): (key: string, make: () => Promise<T>) => Promise<T> {
|
|
|
234
233
|
}
|
|
235
234
|
}
|
|
236
235
|
|
|
237
|
-
// Work done one job at a time, in the order asked.
|
|
238
|
-
function serial(): <T>(work: () => Promise<T>) => Promise<T> {
|
|
239
|
-
let queue = Promise.resolve()
|
|
240
|
-
return work => {
|
|
241
|
-
const job = queue.then(work)
|
|
242
|
-
queue = job.then(() => undefined, () => undefined)
|
|
243
|
-
return job
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
236
|
async function keep(put: () => Promise<void>) {
|
|
248
237
|
try { await put() } catch (err) { console.warn('managed: pretty-print cache write failed:', err) }
|
|
249
238
|
}
|
|
@@ -316,7 +305,7 @@ export function stalePrettyRemover(npm: CacheStorage): (signal?: AbortSignal) =>
|
|
|
316
305
|
// as ever.
|
|
317
306
|
function detailsReader(store: BundleStore) {
|
|
318
307
|
type Details = NonNullable<Awaited<ReturnType<typeof readSizedBundleDetails>>>['details']
|
|
319
|
-
const enqueue =
|
|
308
|
+
const enqueue = inTurns(1), share = sharing<Details>()
|
|
320
309
|
const held = keptBriefly<Details>({ keptMs: DETAILS_KEPT_MS, maxBytes: MAX_KEPT_DETAILS_BYTES, maxEntries: MAX_KEPT_DETAILS })
|
|
321
310
|
return (record: ManagedBundle): Promise<Details> => {
|
|
322
311
|
const key = `${record.id} ${record.integrity}`
|
|
@@ -5,6 +5,7 @@ import type { ManagedHttpDeps } from './http.ts'
|
|
|
5
5
|
import type { ManagedBundle } from './db.ts'
|
|
6
6
|
import type { OpenedBlob } from './blob-store.ts'
|
|
7
7
|
import type { WorkspaceShareSnapshot } from './workspace-shares.ts'
|
|
8
|
+
import type { ManagedComment } from '../common/managed/comments.ts'
|
|
8
9
|
import { sendJson, sendLines, writeResponse } from './http-response.ts'
|
|
9
10
|
import { hashToken } from './crypto.ts'
|
|
10
11
|
import { TeamReportsError, loadTeamAnnotations, loadTeamReportsResponse, teamReportVisibility, teamResponsePart } from './team-reports.ts'
|
|
@@ -16,7 +17,7 @@ import { auditCache, auditedKeys } from './upstream-cache.ts'
|
|
|
16
17
|
import { serveTeamFeed } from './team-feed.ts'
|
|
17
18
|
import { type ComparedSide, PrettyError, compared, prettyRequest, prettyText } from './pretty-print.ts'
|
|
18
19
|
import { renameDiffOf, renameDiffRequest, renamedPairs } from './rename-diff.ts'
|
|
19
|
-
import { typeOnlyFiles } from './type-only.ts'
|
|
20
|
+
import { runsAsked, typeOnlyFiles } from './type-only.ts'
|
|
20
21
|
import { comparisonBody } from './comparison.ts'
|
|
21
22
|
import { sharedTeamApp, withWorkspaceSummary } from './team-app.ts'
|
|
22
23
|
|
|
@@ -24,6 +25,24 @@ function json(res: ServerResponse, status: number, body: unknown): void {
|
|
|
24
25
|
sendJson(res, status, body, { 'cache-control': 'private, no-store', 'referrer-policy': 'no-referrer' })
|
|
25
26
|
}
|
|
26
27
|
|
|
28
|
+
// An answer's comments as a link's readers have them: their authors by login
|
|
29
|
+
// alone. A name is chosen to show to the app's users, and may be a linked
|
|
30
|
+
// account's, which a login doesn't tell of.
|
|
31
|
+
const unnamed = <T extends { comments: ManagedComment[] }>(answer: T): T =>
|
|
32
|
+
({ ...answer, comments: answer.comments.map(comment => ({ ...comment, authorName: null })) })
|
|
33
|
+
|
|
34
|
+
// A blob sent as the response, the link checked again first (handlePublicWorkspace).
|
|
35
|
+
type Stream = (stored: OpenedBlob, encoding: string | null, contentType?: string) => Promise<void>
|
|
36
|
+
|
|
37
|
+
// What `work` answers, or undefined where it fails as a PrettyError, which is
|
|
38
|
+
// answered as its status tells.
|
|
39
|
+
async function prettyOr<T>(res: ServerResponse, work: () => Promise<T>): Promise<T | undefined> {
|
|
40
|
+
try { return await work() } catch (err) {
|
|
41
|
+
if (err instanceof PrettyError) { json(res, err.status, { error: err.message }); return undefined }
|
|
42
|
+
throw err
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
27
46
|
// Called before ALL other routing, including OAuth, discovery, static and the
|
|
28
47
|
// combined server fallback. A supplied capability never inherits cookie auth.
|
|
29
48
|
export async function handlePublicWorkspace(req: IncomingMessage, res: ServerResponse, deps: ManagedHttpDeps, url: URL): Promise<void> {
|
|
@@ -53,7 +72,7 @@ export async function handlePublicWorkspace(req: IncomingMessage, res: ServerRes
|
|
|
53
72
|
} })
|
|
54
73
|
await backfillBundleSummaries(snapshot.team.bundles, deps.bundleCache)
|
|
55
74
|
}
|
|
56
|
-
const stream = async (stored
|
|
75
|
+
const stream: Stream = async (stored, encoding, contentType = 'application/json') => {
|
|
57
76
|
try { await recheck() } catch (error) { stored.stream.destroy(); throw error }
|
|
58
77
|
res.writeHead(200, { 'content-type': contentType, 'cache-control': 'private, no-store',
|
|
59
78
|
'x-content-type-options': 'nosniff', ...(encoding ? { 'content-encoding': encoding } : {}),
|
|
@@ -81,7 +100,7 @@ export async function handlePublicWorkspace(req: IncomingMessage, res: ServerRes
|
|
|
81
100
|
await serveTeamFeed(res, deps, snapshot, recheck, { readState: () => deps.db.getWorkspaceShareFeedState(tokenHash) }); return
|
|
82
101
|
}
|
|
83
102
|
if (teamRoute[2] === 'annotations') {
|
|
84
|
-
await send(await loadTeamAnnotations(deps.db, deps.reportStore, snapshot, url.searchParams.get('reportId'))); return
|
|
103
|
+
await send(unnamed(await loadTeamAnnotations(deps.db, deps.reportStore, snapshot, url.searchParams.get('reportId')))); return
|
|
85
104
|
}
|
|
86
105
|
if (teamRoute[2] === 'shared') { await sendTeam(); return }
|
|
87
106
|
const body = await loadTeamReportsResponse(deps.db, deps.reportStore, snapshot, teamResponsePart(teamRoute[2]!, url))
|
|
@@ -95,18 +114,19 @@ export async function handlePublicWorkspace(req: IncomingMessage, res: ServerRes
|
|
|
95
114
|
const visible = await teamReportVisibility(deps.db, deps.reportStore, snapshot, id)
|
|
96
115
|
await recheck()
|
|
97
116
|
if (part === 'sources') { await sources(res, deps, snapshot, id, visible.sourcePaths, recheck, stream); return }
|
|
98
|
-
if (part === 'comments') { await send({ comments: await deps.db.listComments([...visible.ids]) }); return }
|
|
117
|
+
if (part === 'comments') { await send(unnamed({ comments: await deps.db.listComments([...visible.ids]) })); return }
|
|
99
118
|
const entries = Object.fromEntries((await deps.db.listTriage([...visible.ids])).map(row => [row.findingId, triageWireEntry(row)]))
|
|
100
119
|
await send({ entries }); return
|
|
101
120
|
}
|
|
102
|
-
const
|
|
121
|
+
const id = bundleRoute![1]!, part = bundleRoute![2]!
|
|
122
|
+
const bundle = snapshot.bundles.find(item => item.id === id)
|
|
103
123
|
if (!bundle) { json(res, 404, { error: 'no-bundle' }); return }
|
|
104
|
-
if (
|
|
105
|
-
if (
|
|
124
|
+
if (part === 'advisories' && !snapshot.permissions.security) { json(res, 403, { error: 'security-access-required' }); return }
|
|
125
|
+
if (part === 'rename-diff' || part === 'type-only' || part === 'comparison' || (part === 'pretty' && url.searchParams.has('other'))) {
|
|
106
126
|
if (method !== 'GET') { json(res, 405, { error: 'method-not-allowed' }); return }
|
|
107
|
-
await serveCompared(res, deps, bundle, snapshot.bundles.find(item => item.id === url.searchParams.get('other')),
|
|
127
|
+
await serveCompared(res, deps, bundle, snapshot.bundles.find(item => item.id === url.searchParams.get('other')), part, url, recheck, stream); return
|
|
108
128
|
}
|
|
109
|
-
await serveBundle(res, deps, bundle,
|
|
129
|
+
await serveBundle(res, deps, bundle, part, url, recheck, stream)
|
|
110
130
|
}
|
|
111
131
|
|
|
112
132
|
// What a bundle is compared with `other`, another of the link's bundles, by:
|
|
@@ -114,46 +134,36 @@ export async function handlePublicWorkspace(req: IncomingMessage, res: ServerRes
|
|
|
114
134
|
// with renamed names hidden; or the files that changed between them, or the
|
|
115
135
|
// pairs of those, or those that changed in types alone, a line each.
|
|
116
136
|
function serveCompared(res: ServerResponse, deps: ManagedHttpDeps, bundle: ManagedBundle, other: ManagedBundle | undefined, part: string, url: URL,
|
|
117
|
-
recheck: () => Promise<void>, stream:
|
|
137
|
+
recheck: () => Promise<void>, stream: Stream) {
|
|
118
138
|
if (part === 'comparison') return serveComparison(res, deps, bundle, other, url, stream)
|
|
119
139
|
if (part === 'rename-diff' && url.searchParams.has('path')) return serveRenameDiff(res, deps, bundle, other, url, stream)
|
|
120
|
-
return serveChanges(res, deps, bundle, other, recheck,
|
|
121
|
-
|
|
140
|
+
if (part === 'pretty') return serveChanges(res, deps, bundle, other, recheck, compared, '')
|
|
141
|
+
const typeOnly = (sides: [ComparedSide, ComparedSide]) => typeOnlyFiles(sides, runsAsked(url.searchParams))
|
|
142
|
+
return serveChanges(res, deps, bundle, other, recheck, part === 'type-only' ? typeOnly : renamedPairs, url.searchParams.get('scope') ?? '')
|
|
122
143
|
}
|
|
123
144
|
|
|
124
145
|
// One of a bundle's JavaScript files diffed with one of `other`, another of
|
|
125
146
|
// the link's bundles (rename-diff.ts).
|
|
126
|
-
async function serveRenameDiff(res: ServerResponse, deps: ManagedHttpDeps, bundle: ManagedBundle, other: ManagedBundle | undefined, url: URL,
|
|
127
|
-
stream: (stored: OpenedBlob, encoding: string | null, contentType?: string) => Promise<void>) {
|
|
147
|
+
async function serveRenameDiff(res: ServerResponse, deps: ManagedHttpDeps, bundle: ManagedBundle, other: ManagedBundle | undefined, url: URL, stream: Stream) {
|
|
128
148
|
const request = renameDiffRequest(url.searchParams)
|
|
129
149
|
if (!request) { json(res, 400, { error: 'bad-file' }); return }
|
|
130
150
|
if (!other) { json(res, 404, { error: 'no-bundle' }); return }
|
|
131
151
|
const { prettyCache } = deps
|
|
132
152
|
if (!prettyCache) { json(res, 503, { error: 'unavailable' }); return }
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
await prettyText(await prettyCache.bundle(other, request.other))])
|
|
137
|
-
} catch (err) {
|
|
138
|
-
if (err instanceof PrettyError) { json(res, err.status, { error: err.message }); return }
|
|
139
|
-
throw err
|
|
140
|
-
}
|
|
153
|
+
const diff = await prettyOr(res, () => renameDiffOf(request, async () => [await prettyText(await prettyCache.bundle(bundle, request.base)),
|
|
154
|
+
await prettyText(await prettyCache.bundle(other, request.other))]))
|
|
155
|
+
if (diff === undefined) return
|
|
141
156
|
await stream(diff, 'br')
|
|
142
157
|
}
|
|
143
158
|
|
|
144
159
|
// A bundle's files paired with `other`'s, another of the link's bundles, as
|
|
145
160
|
// Compare pairs them (comparison.ts), within a reason `scope` where given.
|
|
146
|
-
async function serveComparison(res: ServerResponse, deps: ManagedHttpDeps, bundle: ManagedBundle, other: ManagedBundle | undefined, url: URL,
|
|
147
|
-
stream: (stored: OpenedBlob, encoding: string | null, contentType?: string) => Promise<void>) {
|
|
161
|
+
async function serveComparison(res: ServerResponse, deps: ManagedHttpDeps, bundle: ManagedBundle, other: ManagedBundle | undefined, url: URL, stream: Stream) {
|
|
148
162
|
if (!other) { json(res, 404, { error: 'no-bundle' }); return }
|
|
149
163
|
const { prettyCache } = deps
|
|
150
164
|
if (!prettyCache) { json(res, 503, { error: 'unavailable' }); return }
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
catch (err) {
|
|
154
|
-
if (err instanceof PrettyError) { json(res, err.status, { error: err.message }); return }
|
|
155
|
-
throw err
|
|
156
|
-
}
|
|
165
|
+
const body = await prettyOr(res, async () => comparisonBody(await prettyCache.bundleDetails(bundle), await prettyCache.bundleDetails(other), url.searchParams.get('scope') ?? ''))
|
|
166
|
+
if (body === undefined) return
|
|
157
167
|
await stream(body, 'br')
|
|
158
168
|
}
|
|
159
169
|
|
|
@@ -165,19 +175,16 @@ async function serveComparison(res: ServerResponse, deps: ManagedHttpDeps, bundl
|
|
|
165
175
|
async function serveChanges(res: ServerResponse, deps: ManagedHttpDeps, bundle: ManagedBundle, other: ManagedBundle | undefined, recheck: () => Promise<void>,
|
|
166
176
|
linesOf: (sides: [ComparedSide, ComparedSide]) => AsyncIterable<unknown>, scope: string) {
|
|
167
177
|
if (!other) { json(res, 404, { error: 'no-bundle' }); return }
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
if (err instanceof PrettyError) { json(res, err.status, { error: err.message }); return }
|
|
173
|
-
throw err
|
|
174
|
-
}
|
|
178
|
+
const { prettyCache } = deps
|
|
179
|
+
if (!prettyCache) { json(res, 503, { error: 'unavailable' }); return }
|
|
180
|
+
const lines = await prettyOr(res, async () => linesOf(await prettyCache.bundleSides(bundle, other, scope)))
|
|
181
|
+
if (lines === undefined) return
|
|
175
182
|
await recheck()
|
|
176
183
|
await sendLines(res, lines, () => recheck().then(() => true, () => false))
|
|
177
184
|
}
|
|
178
185
|
|
|
179
186
|
async function serveBundle(res: ServerResponse, deps: ManagedHttpDeps, bundle: ManagedBundle, part: string, url: URL,
|
|
180
|
-
recheck: () => Promise<void>, stream:
|
|
187
|
+
recheck: () => Promise<void>, stream: Stream) {
|
|
181
188
|
if (part === 'download') {
|
|
182
189
|
const stored = await deps.bundleStore.open(bundle.id, bundle.kind)
|
|
183
190
|
if (!stored) { json(res, 503, { error: 'unavailable' }); return }
|
|
@@ -186,13 +193,10 @@ async function serveBundle(res: ServerResponse, deps: ManagedHttpDeps, bundle: M
|
|
|
186
193
|
if (part === 'pretty') {
|
|
187
194
|
const file = prettyRequest(url.searchParams)
|
|
188
195
|
if (!file) { json(res, 400, { error: 'bad-file' }); return }
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
if (err instanceof PrettyError) { json(res, err.status, { error: err.message }); return }
|
|
194
|
-
throw err
|
|
195
|
-
}
|
|
196
|
+
const { prettyCache } = deps
|
|
197
|
+
if (!prettyCache) { json(res, 503, { error: 'unavailable' }); return }
|
|
198
|
+
const pretty = await prettyOr(res, () => prettyCache.bundle(bundle, file))
|
|
199
|
+
if (pretty === undefined) return
|
|
196
200
|
await stream(pretty, 'br', 'text/plain; charset=utf-8'); return
|
|
197
201
|
}
|
|
198
202
|
if (!deps.bundleCache) { json(res, 503, { error: 'unavailable' }); return }
|
|
@@ -219,7 +223,7 @@ async function serveBundle(res: ServerResponse, deps: ManagedHttpDeps, bundle: M
|
|
|
219
223
|
}
|
|
220
224
|
|
|
221
225
|
async function sources(res: ServerResponse, deps: ManagedHttpDeps, snapshot: WorkspaceShareSnapshot,
|
|
222
|
-
id: string, paths: Set<string>, recheck: () => Promise<void>, stream:
|
|
226
|
+
id: string, paths: Set<string>, recheck: () => Promise<void>, stream: Stream) {
|
|
223
227
|
const report = await deps.db.getReport(id)
|
|
224
228
|
const bundle = report?.bundleId ? await deps.db.getBundle(report.bundleId) : null
|
|
225
229
|
const empty = async () => { await recheck(); res.writeHead(204, { 'cache-control': 'private, no-store' }); res.end() }
|
|
@@ -12,10 +12,10 @@
|
|
|
12
12
|
// comment's. They count for the pull request alone, never stored.
|
|
13
13
|
import { createHash } from 'node:crypto'
|
|
14
14
|
import { ACTOR, type GraphAccount, actorOf } from './github-accounts.ts'
|
|
15
|
+
import { githubGraphql } from './github-graphql.ts'
|
|
15
16
|
import { type Lru, lru } from './lru.ts'
|
|
16
17
|
import type { CommentReviews } from './pull-dependency-reviews.ts'
|
|
17
18
|
import type { PublishedReview } from './repository-dependency-reviews.ts'
|
|
18
|
-
import { githubGraphql } from './repository-history.ts'
|
|
19
19
|
import type { CommentReview, ParseCommentsInput, ReviewComment, ReviewVerdict, ReviewedDependencies } from './reviewed-dependencies.ts'
|
|
20
20
|
|
|
21
21
|
const MAX_COMMENTS = 1000
|
|
@@ -72,7 +72,7 @@ async function inlineComments(review: Node, room: number, token: string, fetchIm
|
|
|
72
72
|
// Pull request `number`'s comments, its reviews' and those on its diff, each
|
|
73
73
|
// review's all of them, and whether it is open, as kept, else read of GitHub
|
|
74
74
|
// a page at a time.
|
|
75
|
-
|
|
75
|
+
async function pullComments(fullName: string, token: string, number: number, fetchImpl: typeof fetch = globalThis.fetch): Promise<PullComments> {
|
|
76
76
|
const key = `${fullName}\0${number}`
|
|
77
77
|
const known = comments.get(key)
|
|
78
78
|
if (known && Date.now() - known.at < KEPT_MS) return known
|