@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
|
@@ -27,17 +27,19 @@
|
|
|
27
27
|
// this instance where its reader keeps it (LockfileStore): what a blob holds
|
|
28
28
|
// never changes either, and a push changing no lockfile changes none.
|
|
29
29
|
import { createClient } from '@preventive/upstream/github.js'
|
|
30
|
-
import { GithubApiError,
|
|
31
|
-
import {
|
|
30
|
+
import { GithubApiError, upstreamGithub } from './github-errors.ts'
|
|
31
|
+
import { USER_AGENT, githubJson, repoApi } from './github-requests.ts'
|
|
32
|
+
import { SHA } from './github-values.ts'
|
|
32
33
|
import { compareVersions, isExactVersion } from '@preventive/upstream/semver.js'
|
|
33
34
|
import { type LockedPackage, isTestFixture, lockedPackages, patchedIn } from './locked-packages.ts'
|
|
34
35
|
import { type Lru, lru } from './lru.ts'
|
|
36
|
+
import { eachOf } from './queue.ts'
|
|
35
37
|
import { type ChangedFile, commitChanges } from './repository-changes.ts'
|
|
36
38
|
|
|
37
39
|
// The files of a pull request read from its own list past those compared,
|
|
38
40
|
// FILES_PAGE a page, as many as GitHub lists (3,000).
|
|
39
41
|
const FILES_PAGE = 100
|
|
40
|
-
|
|
42
|
+
const PULL_FILES = 3000
|
|
41
43
|
// The directories whose lockfiles are read, those past them left out
|
|
42
44
|
// (`cut`), and the packages told new of each, those past them counted.
|
|
43
45
|
export const MAX_DIRECTORIES = 20
|
|
@@ -53,7 +55,6 @@ const READ_PARALLEL = 4
|
|
|
53
55
|
// told or read by others is told or read again, as those read before pnpm's
|
|
54
56
|
// patches' files were.
|
|
55
57
|
export const PULL_DEPENDENCIES_READ = 4
|
|
56
|
-
const SHA = /^[a-f\d]{40}$/u
|
|
57
58
|
|
|
58
59
|
type Format = 'npm' | 'pnpm' | 'yarn' | 'bun'
|
|
59
60
|
|
|
@@ -138,14 +139,12 @@ export interface GithubAsked { github: boolean }
|
|
|
138
139
|
const readKey = (ref: string, { path, format, sha }: { path: string; format: Format; sha?: string }) =>
|
|
139
140
|
sha ? `blob\0${format}\0${sha}` : `commit\0${ref}\0${path}`
|
|
140
141
|
|
|
141
|
-
const api = (fullName: string) => `https://api.github.com/repos/${fullName.split('/').map(encodeURIComponent).join('/')}`
|
|
142
|
-
|
|
143
142
|
// The pull request's base's and head's commits, as GitHub has them now: its
|
|
144
143
|
// base's moving on as it does, its head's with each push, both kept once it
|
|
145
144
|
// is merged or closed.
|
|
146
145
|
export interface PullCommits { base: string; head: string }
|
|
147
146
|
async function pullCommits(fullName: string, token: string, number: number, fetchImpl: typeof fetch): Promise<PullCommits> {
|
|
148
|
-
const pull = await githubJson(`${
|
|
147
|
+
const pull = await githubJson(`${repoApi(fullName)}/pulls/${number}`, token, fetchImpl) as
|
|
149
148
|
{ number?: unknown; base?: { sha?: unknown; repo?: { full_name?: unknown } | null }; head?: { sha?: unknown } } | null
|
|
150
149
|
const base = pull?.base?.sha, head = pull?.head?.sha, repo = pull?.base?.repo?.full_name
|
|
151
150
|
if (pull?.number !== number || typeof base !== 'string' || !SHA.test(base) || typeof head !== 'string' || !SHA.test(head)
|
|
@@ -160,7 +159,7 @@ async function pullCommits(fullName: string, token: string, number: number, fetc
|
|
|
160
159
|
// now: null where they are no longer `base` and `head` (`current`).
|
|
161
160
|
async function pullFiles(fullName: string, token: string, number: number, base: string, head: string, fetchImpl: typeof fetch,
|
|
162
161
|
current: () => Promise<boolean>) {
|
|
163
|
-
const compared = await githubJson(`${
|
|
162
|
+
const compared = await githubJson(`${repoApi(fullName)}/compare/${base}...${head}?per_page=1`, token, fetchImpl) as { merge_base_commit?: { sha?: unknown } } | null
|
|
164
163
|
const mergeBase = compared?.merge_base_commit?.sha
|
|
165
164
|
if (typeof mergeBase !== 'string' || !SHA.test(mergeBase)) throw new GithubApiError(502, 'github-malformed')
|
|
166
165
|
const { files, more } = commitChanges(compared)
|
|
@@ -168,7 +167,7 @@ async function pullFiles(fullName: string, token: string, number: number, base:
|
|
|
168
167
|
if (!await current()) return null
|
|
169
168
|
const listed: ChangedFile[] = []
|
|
170
169
|
for (let page = 1; listed.length < PULL_FILES; page++) {
|
|
171
|
-
const data = await githubJson(`${
|
|
170
|
+
const data = await githubJson(`${repoApi(fullName)}/pulls/${number}/files?per_page=${FILES_PAGE}&page=${page}`, token, fetchImpl)
|
|
172
171
|
if (!Array.isArray(data)) throw new GithubApiError(502, 'github-malformed')
|
|
173
172
|
listed.push(...commitChanges({ files: data }).files)
|
|
174
173
|
if (data.length < FILES_PAGE) return { mergeBase, files: listed, cut: false }
|
|
@@ -201,6 +200,15 @@ function lockfilesChanged(files: ChangedFile[]) {
|
|
|
201
200
|
omitted: all.slice(MAX_DIRECTORIES).flatMap(([, directory]) => [...directory.paths]).toSorted() }
|
|
202
201
|
}
|
|
203
202
|
|
|
203
|
+
// The text of the file at `path` of repository `fullName` at `ref`; null
|
|
204
|
+
// where GitHub has none there.
|
|
205
|
+
export async function repositoryFile(fullName: string, token: string, path: string, ref: string): Promise<string | null> {
|
|
206
|
+
try { return await upstreamGithub(() => createClient({ token, userAgent: USER_AGENT }).getRepoFile({ repo: fullName, path, ref })) } catch (err) {
|
|
207
|
+
if (err instanceof GithubApiError && err.message === 'github-not-found') return null
|
|
208
|
+
throw err
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
204
212
|
// A lockfile's packages at `ref`, as read in this instance, else as kept
|
|
205
213
|
// beyond it (`kept`), else shared with a read of it with the same token still
|
|
206
214
|
// under way, else of GitHub, and kept; a lockfile its reader refuses, why,
|
|
@@ -230,13 +238,8 @@ async function readOf(fullName: string, token: string, ref: string, { path, form
|
|
|
230
238
|
kept: LockfileStore | null): Promise<{ read: LockfileRead; github: boolean }> {
|
|
231
239
|
const stored = await kept?.lockfiles.read(key)
|
|
232
240
|
if (stored) { lockfileReads.set(`${fullName}\0${key}`, stored); return { read: stored, github: false } }
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
text = await upstreamGithub(() => createClient({ token, userAgent: 'deepview-triage' }).getRepoFile({ repo: fullName, path, ref }))
|
|
236
|
-
} catch (err) {
|
|
237
|
-
if (err instanceof GithubApiError && err.message === 'github-not-found') return { read: { error: 'github-not-found' }, github: true }
|
|
238
|
-
throw err
|
|
239
|
-
}
|
|
241
|
+
const text = await repositoryFile(fullName, token, path, ref)
|
|
242
|
+
if (text === null) return { read: { error: 'github-not-found' }, github: true }
|
|
240
243
|
let read: LockfileRead
|
|
241
244
|
try { read = { packages: lockedPackages(format, text, { review: true }) } } catch (error) {
|
|
242
245
|
read = { error: 'lockfile-unreadable', ...error instanceof Error ? { detail: error.message.slice(0, 500) } : {} }
|
|
@@ -246,20 +249,6 @@ async function readOf(fullName: string, token: string, ref: string, { path, form
|
|
|
246
249
|
return { read, github: true }
|
|
247
250
|
}
|
|
248
251
|
|
|
249
|
-
// Runs `run` for each of `items`, as many at once as `parallel`, each's
|
|
250
|
-
// result in its place.
|
|
251
|
-
export async function eachOf<T, R>(items: T[], parallel: number, run: (item: T) => Promise<R>): Promise<R[]> {
|
|
252
|
-
const results: R[] = []
|
|
253
|
-
let next = 0
|
|
254
|
-
await Promise.all(Array.from({ length: Math.min(parallel, items.length) }, async () => {
|
|
255
|
-
while (next < items.length) {
|
|
256
|
-
const at = next++
|
|
257
|
-
results[at] = await run(items[at]!)
|
|
258
|
-
}
|
|
259
|
-
}))
|
|
260
|
-
return results
|
|
261
|
-
}
|
|
262
|
-
|
|
263
252
|
// Versions by semver, the highest first, any semver can't read after them.
|
|
264
253
|
function byVersion(a: string, b: string) {
|
|
265
254
|
const [exactA, exactB] = [isExactVersion(a), isExactVersion(b)]
|
|
@@ -283,7 +272,7 @@ export const lockedWith = (pkg: LockedPackage) => `${lockedAs(pkg)}\0${pkg.integ
|
|
|
283
272
|
// them.
|
|
284
273
|
function addedIn(paths: string[], before: LockfileRead[], after: LockfileRead[]): DirectoryDependencies {
|
|
285
274
|
const failed = [...before, ...after].find(read => 'error' in read)
|
|
286
|
-
if (failed
|
|
275
|
+
if (failed) return { paths, error: failed.error, ...failed.detail ? { detail: failed.detail } : {} }
|
|
287
276
|
const known = new Set<string>()
|
|
288
277
|
const versions = new Map<string, Set<string>>()
|
|
289
278
|
for (const pkg of before.flatMap(read => 'packages' in read ? read.packages : [])) {
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
// (pull-dependencies.ts), and kept by the commit (`baselines` in this
|
|
28
28
|
// instance, `kept` beyond it), never stored as reviews.
|
|
29
29
|
import { lockedAt, lockedIn } from './commit-lockfiles.ts'
|
|
30
|
-
import { GithubApiError } from './github-
|
|
30
|
+
import { GithubApiError } from './github-errors.ts'
|
|
31
31
|
import type { LockedPackage } from './locked-packages.ts'
|
|
32
32
|
import { EVERY_LOCKFILE, type LockfileScope, heldTo, isEvery, reviewedIn } from './lockfile-scope.ts'
|
|
33
33
|
import { type Lru, lru } from './lru.ts'
|
|
@@ -79,27 +79,26 @@ export async function reviewBaseline(fullName: string, token: string, repoId: nu
|
|
|
79
79
|
const stored = await kept.read(key)
|
|
80
80
|
if (stored) { const baseline = { versions: new Set(stored.versions), unread: stored.unread }; baselines.set(key, baseline); return baseline }
|
|
81
81
|
const read = await lockedAt(fullName, token, since, reads, () => true, asked)
|
|
82
|
-
const
|
|
83
|
-
const
|
|
84
|
-
for (const pkg of packages) if (reviewedAs(pkg) === 'version') for (const held of baselineKeys(pkg)) versions.add(held)
|
|
85
|
-
const baseline = { versions, unread }
|
|
82
|
+
const versions = new Set(lockedIn(read).packages.filter(pkg => reviewedAs(pkg) === 'version').flatMap(pkg => baselineKeys(pkg)))
|
|
83
|
+
const baseline = { versions, unread: read.unread }
|
|
86
84
|
baselines.set(key, baseline)
|
|
87
|
-
await kept.write(key, { versions: [...versions], unread:
|
|
85
|
+
await kept.write(key, { versions: [...versions], unread: read.unread })
|
|
88
86
|
return baseline
|
|
89
87
|
}
|
|
90
88
|
|
|
91
89
|
// Passing reviews by the version they are of, its name and version.
|
|
92
90
|
type ReviewsOf = Map<string, PublishedReview[]>
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
else by.set(key, [review])
|
|
100
|
-
}
|
|
101
|
-
return by
|
|
91
|
+
export const reviewsByVersion = (reviews: PublishedReview[]): ReviewsOf => Map.groupBy(reviews, review => `${review.package}@${review.version}`)
|
|
92
|
+
// Of those, `pkg`'s: of its version, of an integrity it is locked with, and
|
|
93
|
+
// of its patch.
|
|
94
|
+
export function reviewsOf(pkg: LockedPackage, reviews: ReviewsOf): PublishedReview[] {
|
|
95
|
+
const hashes = hashesOf(pkg)
|
|
96
|
+
return (reviews.get(`${pkg.name}@${pkg.version}`) ?? []).filter(review => hashes.includes(review.integrity) && (review.patchHash ?? '') === (pkg.patchHash ?? ''))
|
|
102
97
|
}
|
|
98
|
+
// Whether `review` is of `pkg` whole, or compared with one of `bases` of its
|
|
99
|
+
// package (any, for `any`).
|
|
100
|
+
export const comparedWith = (review: PublishedReview, pkg: LockedPackage, bases: string[] | 'any') => review.basePackage === null
|
|
101
|
+
|| (review.basePackage === pkg.name && (bases === 'any' || bases.includes(review.baseVersion ?? '')))
|
|
103
102
|
|
|
104
103
|
const ACCEPTING = new Set(['accept', 'accept-with-nits'])
|
|
105
104
|
// Where `pkg`'s reviewers stand on it among `reviews`, those of its version,
|
|
@@ -113,14 +112,8 @@ const ACCEPTING = new Set(['accept', 'accept-with-nits'])
|
|
|
113
112
|
// their login, their latest verdict, whether they pass it, and whether that
|
|
114
113
|
// verdict is its comments' (`comment`), which counts for it alone.
|
|
115
114
|
function stancesOf(pkg: LockedPackage, reviews: ReviewsOf, bases: string[] | 'any') {
|
|
116
|
-
const
|
|
117
|
-
const
|
|
118
|
-
for (const review of reviews.get(`${pkg.name}@${pkg.version}`) ?? []) {
|
|
119
|
-
if (!hashes.includes(review.integrity) || (review.patchHash ?? '') !== (pkg.patchHash ?? '')) continue
|
|
120
|
-
by.set(review.reviewer, [...by.get(review.reviewer) ?? [], review])
|
|
121
|
-
}
|
|
122
|
-
const qualifies = (review: PublishedReview) => review.full && ACCEPTING.has(review.status)
|
|
123
|
-
&& (review.basePackage === null || (review.basePackage === pkg.name && (bases === 'any' || bases.includes(review.baseVersion ?? ''))))
|
|
115
|
+
const by = Map.groupBy(reviewsOf(pkg, reviews), review => review.reviewer)
|
|
116
|
+
const qualifies = (review: PublishedReview) => review.full && ACCEPTING.has(review.status) && comparedWith(review, pkg, bases)
|
|
124
117
|
let commented = 0, passing = 0, rejected = false
|
|
125
118
|
const reviewers: Reviewer[] = []
|
|
126
119
|
for (const theirs of by.values()) {
|
|
@@ -303,7 +296,7 @@ export async function reviewedDependencies(told: PullDependencies, state: RepoRe
|
|
|
303
296
|
return judged.wants && passed.has(askedOf(pkg)[0]) ? { review: { reviewed: true }, wants: false } : judged
|
|
304
297
|
}))
|
|
305
298
|
const unread = baselineUnread.filter(path => heldTo(scope, path))
|
|
306
|
-
const listed = dirs.
|
|
299
|
+
const listed = dirs.filter(dir => 'unreviewed' in dir)
|
|
307
300
|
return { ...answered, cut, lockfiles: dirs.map(dir => 'unreviewed' in dir ? capped(dir) : dir), review: { required: state.required,
|
|
308
301
|
since: reviewed ? null : state.since, canReview: state.canReview, ...reviewed ? { reviewedDependencies: true } : {},
|
|
309
302
|
toReview: distinct(listed.map(dir => dir.toReview), versionKey), unreviewed: distinct(listed.map(dir => dir.unreviewed), versionKey),
|
|
@@ -15,6 +15,8 @@
|
|
|
15
15
|
// the popup, which reads reviews' bodies.
|
|
16
16
|
import { githubAgent } from '../common/managed/github-agents.ts'
|
|
17
17
|
import { ACTOR, type GraphAccount, actorOf } from './github-accounts.ts'
|
|
18
|
+
import type { GraphqlError } from './github-graphql.ts'
|
|
19
|
+
import { SHA, timeOf } from './github-values.ts'
|
|
18
20
|
|
|
19
21
|
const REVIEWERS = 20
|
|
20
22
|
const REQUESTS = 10
|
|
@@ -28,7 +30,6 @@ const FIRST_COMMENTS = 5
|
|
|
28
30
|
const LAST_COMMENTS = 20
|
|
29
31
|
const MAX_TITLE = 200
|
|
30
32
|
const MAX_PATH = 1000
|
|
31
|
-
const COMMIT = /^[a-f\d]{40}$/u
|
|
32
33
|
|
|
33
34
|
// The fields a pull request's reviews are read by, its threads' places and
|
|
34
35
|
// links with them for its popup (`detail`). A team requested is no reviewer
|
|
@@ -48,7 +49,7 @@ export const reviewFields = (threads: number, detail: boolean) => `headRefOid
|
|
|
48
49
|
// The fields read for reviews that GitHub may refuse alone, as it refuses an
|
|
49
50
|
// App a pull request's checks: their pull request then shows no reviews.
|
|
50
51
|
const REVIEW_PATHS = new Set(['latestReviews', 'reviewRequests', 'reviewThreads', 'firstComments', 'lastComments'])
|
|
51
|
-
export const reviewsRefused = (error:
|
|
52
|
+
export const reviewsRefused = (error: GraphqlError) => error?.type === 'FORBIDDEN' && Array.isArray(error.path)
|
|
52
53
|
&& error.path.some(part => REVIEW_PATHS.has(part as string))
|
|
53
54
|
|
|
54
55
|
type Comment = { author?: GraphAccount; body?: unknown; updatedAt?: unknown; createdAt?: unknown } | null
|
|
@@ -72,11 +73,7 @@ const ASKED = /^@codex\s+review\b/iu
|
|
|
72
73
|
const FAILED = /^Codex Review: Something went wrong/u
|
|
73
74
|
const WORKFLOW = /<!--\s*gh-aw-workflow-id:\s*([\w.-]{1,100})\s*-->/u
|
|
74
75
|
|
|
75
|
-
const
|
|
76
|
-
const at = typeof value === 'string' ? Date.parse(value) : Number.NaN
|
|
77
|
-
return Number.isSafeInteger(at) ? at : null
|
|
78
|
-
}
|
|
79
|
-
const commitOf = (value: unknown) => typeof value === 'string' && COMMIT.test(value.toLowerCase()) ? value.toLowerCase() : null
|
|
76
|
+
const commitOf = (value: unknown) => typeof value === 'string' && SHA.test(value.toLowerCase()) ? value.toLowerCase() : null
|
|
80
77
|
const textOf = (value: unknown) => typeof value === 'string' ? value : ''
|
|
81
78
|
const isCodex = (account: GraphAccount) => {
|
|
82
79
|
const { login, id } = actorOf(account)
|
package/server-managed/queue.ts
CHANGED
|
@@ -37,3 +37,17 @@ export function inTurns(count: number): <T>(work: () => Promise<T>) => Promise<T
|
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
|
+
|
|
41
|
+
// Runs `run` for each of `items`, as many at once as `parallel`, each's
|
|
42
|
+
// result in its place.
|
|
43
|
+
export async function eachOf<T, R>(items: T[], parallel: number, run: (item: T) => Promise<R>): Promise<R[]> {
|
|
44
|
+
const results: R[] = []
|
|
45
|
+
let next = 0
|
|
46
|
+
await Promise.all(Array.from({ length: Math.min(parallel, items.length) }, async () => {
|
|
47
|
+
while (next < items.length) {
|
|
48
|
+
const at = next++
|
|
49
|
+
results[at] = await run(items[at]!)
|
|
50
|
+
}
|
|
51
|
+
}))
|
|
52
|
+
return results
|
|
53
|
+
}
|
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
// leave one. What each commit changes is read as Replay reads it, kept by
|
|
7
7
|
// the commit (repository-changes.ts repositoryChanges).
|
|
8
8
|
import { type ChangesStore, type CommitChanges, repositoryChanges } from './repository-changes.ts'
|
|
9
|
-
import { githubGraphql } from './
|
|
9
|
+
import { githubGraphql } from './github-graphql.ts'
|
|
10
|
+
import { SHA, timeOf } from './github-values.ts'
|
|
11
|
+
import { type Connection, nextCursor } from './repository-history.ts'
|
|
10
12
|
|
|
11
13
|
// The tags read, a page a query, the latest commits' first, as many pages as
|
|
12
14
|
// TAG_PAGES; of the commits they name, as many as RELEASES_READ have their
|
|
@@ -17,7 +19,6 @@ const RELEASES_READ = 200
|
|
|
17
19
|
// An annotated tag's target, its own target in turn, through as many as
|
|
18
20
|
// TAG_DEPTH annotated tags.
|
|
19
21
|
const TAG_DEPTH = 3
|
|
20
|
-
const SHA = /^[a-f\d]{40}$/u
|
|
21
22
|
const RELEASE_LOCKFILES = new Set(['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock', 'bun.lockb'])
|
|
22
23
|
const RELEASE_CHANGELOG = /^(?:changelog|changes|history|news|releases?)(?:[._-][^/]*)?\.(?:md|markdown)$/iu
|
|
23
24
|
const CHANGESET = /(?:^|\/)\.changeset\/[^/]+\.md$/iu
|
|
@@ -32,19 +33,19 @@ const TAGS_QUERY = `query($owner: String!, $name: String!, $after: String) {
|
|
|
32
33
|
}
|
|
33
34
|
}`
|
|
34
35
|
type TagTarget = { __typename?: unknown; oid?: unknown; committedDate?: unknown; target?: TagTarget | null } | null | undefined
|
|
35
|
-
type TagsPage = { repository?: { refs?: {
|
|
36
|
+
type TagsPage = { repository?: { refs?: Connection<{ target?: TagTarget }> | null } | null }
|
|
36
37
|
|
|
37
38
|
// The commit a tag names, through its annotated tags, and when it was
|
|
38
39
|
// committed; null for one naming no commit (a tree, a blob).
|
|
39
40
|
function taggedCommit(target: TagTarget, depth = TAG_DEPTH): { oid: string; at: number } | null {
|
|
40
41
|
if (target?.__typename === 'Tag' && depth > 0) return taggedCommit(target.target, depth - 1)
|
|
41
|
-
const at =
|
|
42
|
-
return target?.__typename === 'Commit' && typeof target.oid === 'string' && SHA.test(target.oid) &&
|
|
42
|
+
const at = timeOf(target?.committedDate)
|
|
43
|
+
return target?.__typename === 'Commit' && typeof target.oid === 'string' && SHA.test(target.oid) && at !== null ? { oid: target.oid, at } : null
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
// The commits the repository's tags name committed since `since`, the
|
|
46
47
|
// latest first, as many pages of them as TAG_PAGES.
|
|
47
|
-
|
|
48
|
+
async function taggedCommits(fullName: string, token: string, since: number, fetchImpl: typeof fetch = globalThis.fetch): Promise<Set<string>> {
|
|
48
49
|
const [owner, name] = fullName.split('/') as [string, string]
|
|
49
50
|
const tagged = new Set<string>()
|
|
50
51
|
let after: string | null = null
|
|
@@ -53,8 +54,8 @@ export async function taggedCommits(fullName: string, token: string, since: numb
|
|
|
53
54
|
const refs = page?.repository?.refs
|
|
54
55
|
const commits = (refs?.nodes ?? []).flatMap(node => taggedCommit(node?.target) ?? [])
|
|
55
56
|
for (const commit of commits) if (commit.at >= since) tagged.add(commit.oid)
|
|
56
|
-
|
|
57
|
-
after
|
|
57
|
+
after = nextCursor(refs?.pageInfo)
|
|
58
|
+
if (after === null || commits.some(commit => commit.at < since)) break
|
|
58
59
|
}
|
|
59
60
|
return tagged
|
|
60
61
|
}
|
|
@@ -14,9 +14,7 @@
|
|
|
14
14
|
// again through the pretty-print cache first, which checks that its source
|
|
15
15
|
// holds a file of that hash. Access is the caller's to check.
|
|
16
16
|
import { Buffer } from 'node:buffer'
|
|
17
|
-
import { Readable } from 'node:stream'
|
|
18
17
|
import { promisify } from 'node:util'
|
|
19
|
-
import { Worker } from 'node:worker_threads'
|
|
20
18
|
import { brotliDecompress } from 'node:zlib'
|
|
21
19
|
import { layoutPackageDirs, treeLayout } from '@preventive/compare'
|
|
22
20
|
import { computeFileHash } from '@preventive/report'
|
|
@@ -27,7 +25,9 @@ import { needsPrettyPrint, prettyExtension } from '../common/pretty-print.js'
|
|
|
27
25
|
import { type ChangeBlock, blocksHold, textLines } from '../common/line-diff.js'
|
|
28
26
|
import type { OpenedBlob } from './blob-store.ts'
|
|
29
27
|
import { encodeBrotli } from './brotli.ts'
|
|
30
|
-
import {
|
|
28
|
+
import { pathOrder } from './npm-packages.ts'
|
|
29
|
+
import { type ComparedSide, PrettyError, type PrettyRequest, opened, prettyText } from './pretty-print.ts'
|
|
30
|
+
import { workerTurns } from './worker-turns.ts'
|
|
31
31
|
|
|
32
32
|
// What a minifier renames: JavaScript, as the viewer offers it for.
|
|
33
33
|
const RENAMABLE = new Set(['js', 'mjs', 'cjs'])
|
|
@@ -67,35 +67,11 @@ export function renameDiffRequest(params: URLSearchParams): RenameDiffRequest |
|
|
|
67
67
|
return base && other ? { base, other } : null
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
|
|
71
|
-
|
|
70
|
+
const workers = workerTurns({ what: 'rename diff', active: MAX_ACTIVE_DIFFS, waiting: MAX_WAITING_DIFFS, error: PrettyError,
|
|
71
|
+
busy: 'diff-busy', timeout: 'diff-timeout', failed: 'undiffable' })
|
|
72
72
|
const kept = new Map<string, Buffer>()
|
|
73
73
|
const pending = new Map<string, Promise<Buffer>>()
|
|
74
74
|
|
|
75
|
-
// A worker's turn, waited for behind those running until `deadline`; given
|
|
76
|
-
// up, it goes to the next one waiting.
|
|
77
|
-
async function turn(deadline: number): Promise<void> {
|
|
78
|
-
if (activeDiffs < MAX_ACTIVE_DIFFS) { activeDiffs++; return }
|
|
79
|
-
if (waiting.length >= MAX_WAITING_DIFFS) throw new PrettyError(429, 'diff-busy')
|
|
80
|
-
await new Promise<void>((resolve, reject) => {
|
|
81
|
-
const next = () => { clearTimeout(timer); resolve() }
|
|
82
|
-
const timer = setTimeout(() => {
|
|
83
|
-
waiting.splice(waiting.indexOf(next), 1)
|
|
84
|
-
reject(new PrettyError(504, 'diff-timeout'))
|
|
85
|
-
}, deadline - Date.now())
|
|
86
|
-
waiting.push(next)
|
|
87
|
-
})
|
|
88
|
-
}
|
|
89
|
-
function done() {
|
|
90
|
-
const next = waiting.shift()
|
|
91
|
-
if (next) next()
|
|
92
|
-
else activeDiffs--
|
|
93
|
-
}
|
|
94
|
-
async function inTurn<T>(deadline: number, work: () => Promise<T>): Promise<T> {
|
|
95
|
-
await turn(deadline)
|
|
96
|
-
try { return await work() } finally { done() }
|
|
97
|
-
}
|
|
98
|
-
|
|
99
75
|
// Whether a worker's answer is one as rename-diff-worker.js gives it, its
|
|
100
76
|
// blocks taking the old side it answered to the new one asked of, whitespace
|
|
101
77
|
// changes shown and hidden: checked again here, apart from the worker, as an
|
|
@@ -125,35 +101,17 @@ function marksFit(before: string, after: string, marks: unknown): boolean {
|
|
|
125
101
|
return true
|
|
126
102
|
}
|
|
127
103
|
|
|
128
|
-
//
|
|
104
|
+
// The two sides diffed in a worker, its answer checked (answers).
|
|
129
105
|
function inWorker(before: string, after: string, { base, other }: RenameDiffRequest, deadline: number): Promise<RenameDiff> {
|
|
130
106
|
if (before.length + after.length > MAX_DIFF_CHARS) throw new PrettyError(413, 'diff-too-large')
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
throw new PrettyError(503, 'unavailable')
|
|
140
|
-
}
|
|
141
|
-
return new Promise<RenameDiff>((resolve, reject) => {
|
|
142
|
-
let diff: RenameDiff | null = null, failure = new PrettyError(422, 'undiffable')
|
|
143
|
-
const timer = setTimeout(() => { failure = new PrettyError(504, 'diff-timeout'); void worker.terminate() }, deadline - Date.now())
|
|
144
|
-
worker.once('message', (answer: unknown) => {
|
|
145
|
-
if (answers(answer, before, after)) diff = answer
|
|
146
|
-
else console.warn('managed: a rename diff answered what does not take its old side to the new')
|
|
147
|
-
void worker.terminate()
|
|
148
|
-
})
|
|
149
|
-
worker.once('error', err => { console.warn('managed: a rename diff failed:', err) })
|
|
150
|
-
// Gone: answered, run out of memory, or terminated.
|
|
151
|
-
worker.once('exit', () => {
|
|
152
|
-
clearTimeout(timer)
|
|
153
|
-
if (diff) resolve(diff)
|
|
154
|
-
else reject(failure)
|
|
155
|
-
})
|
|
156
|
-
})
|
|
107
|
+
return workers.run(new URL('./rename-diff-worker.js', import.meta.url), {
|
|
108
|
+
workerData: { before, after, extension: base.extension, otherExtension: other.extension }, execArgv: [],
|
|
109
|
+
resourceLimits: { maxOldGenerationSizeMb: 1024 },
|
|
110
|
+
}, answer => {
|
|
111
|
+
if (answers(answer, before, after)) return answer
|
|
112
|
+
console.warn('managed: a rename diff answered what does not take its old side to the new')
|
|
113
|
+
return null
|
|
114
|
+
}, deadline)
|
|
157
115
|
}
|
|
158
116
|
|
|
159
117
|
// `work` given until `deadline`: past it, answered 504 and left to finish on its own.
|
|
@@ -169,7 +127,6 @@ async function encoded(diff: RenameDiff, { base, other }: RenameDiffRequest, [be
|
|
|
169
127
|
const [prettyHash, otherPrettyHash] = await Promise.all([computeFileHash(before), computeFileHash(after)])
|
|
170
128
|
return encodeBrotli(Buffer.from(JSON.stringify({ ...diff, hash: base.hash, otherHash: other.hash, prettyHash, otherPrettyHash })))
|
|
171
129
|
}
|
|
172
|
-
const opened = (body: Buffer): OpenedBlob => ({ size: body.byteLength, stream: Readable.from([body]) })
|
|
173
130
|
|
|
174
131
|
// The answer for the two files a request names, Brotli-encoded, `texts`
|
|
175
132
|
// reading both sides pretty-printed (and so checking each is its source's):
|
|
@@ -190,7 +147,7 @@ async function answerOf(request: RenameDiffRequest, texts: () => Promise<[string
|
|
|
190
147
|
if (!keep) {
|
|
191
148
|
const deadline = Date.now() + DIFF_TIMEOUT_MS
|
|
192
149
|
let sides: [string, string] = ['', '']
|
|
193
|
-
const diff = await inTurn(deadline, async () => {
|
|
150
|
+
const diff = await workers.inTurn(deadline, async () => {
|
|
194
151
|
sides = await byDeadline(texts(), deadline)
|
|
195
152
|
return inWorker(sides[0], sides[1], request, deadline)
|
|
196
153
|
})
|
|
@@ -212,7 +169,7 @@ async function answerOf(request: RenameDiffRequest, texts: () => Promise<[string
|
|
|
212
169
|
answer = held()
|
|
213
170
|
if (!answer) {
|
|
214
171
|
const deadline = Date.now() + DIFF_TIMEOUT_MS
|
|
215
|
-
const job = inTurn(deadline, () => inWorker(before, after, request, deadline)).then(diff => encoded(diff, request, [before, after])).finally(() => pending.delete(key))
|
|
172
|
+
const job = workers.inTurn(deadline, () => inWorker(before, after, request, deadline)).then(diff => encoded(diff, request, [before, after])).finally(() => pending.delete(key))
|
|
216
173
|
pending.set(key, answer = job)
|
|
217
174
|
}
|
|
218
175
|
}
|
|
@@ -260,7 +217,7 @@ export function renamedPairs([base, other]: readonly [ComparedSide, ComparedSide
|
|
|
260
217
|
const pairs = comparedFiles([base, other]).changed.flatMap(({ path, basePath = path }) => {
|
|
261
218
|
const [from, to] = [olds.get(basePath), news.get(path)]
|
|
262
219
|
return from && to && from.hash !== to.hash && [from, to].every(file => renamable(file) && needsPrettyPrint(file.path, file.text)) ? [[from, to] as const] : []
|
|
263
|
-
}).toSorted(([, a], [, b]) => (a.path
|
|
220
|
+
}).toSorted(([, a], [, b]) => pathOrder(a.path, b.path))
|
|
264
221
|
return (async function* () {
|
|
265
222
|
for (const [from, to] of pairs) {
|
|
266
223
|
const request = { base: { path: from.path, hash: from.hash, extension: from.extension }, other: { path: to.path, hash: to.hash, extension: to.extension } }
|
|
@@ -7,19 +7,20 @@ import type { DatabaseSync } from 'node:sqlite'
|
|
|
7
7
|
import { reportRepoGithub } from '@preventive/report'
|
|
8
8
|
import { readManagedReport } from '../common/managed/report-content.ts'
|
|
9
9
|
import { normalizeTeamPath } from './repo-path.ts'
|
|
10
|
+
import { isBlobId } from './object-storage.ts'
|
|
11
|
+
import { sqliteTransaction } from './sql.ts'
|
|
10
12
|
|
|
11
13
|
export function migrateReportLocations(db: DatabaseSync, reportDir: string): void {
|
|
12
14
|
const columns = db.prepare('PRAGMA table_info(managed_report)').all() as { name: string }[]
|
|
13
15
|
if (columns.some((column) => column.name === 'repo_directory')) return
|
|
14
|
-
db
|
|
15
|
-
try {
|
|
16
|
+
sqliteTransaction(db, 'BEGIN IMMEDIATE', () => {
|
|
16
17
|
db.exec("ALTER TABLE managed_report ADD COLUMN repo_directory TEXT NOT NULL DEFAULT ''")
|
|
17
18
|
const update = db.prepare('UPDATE managed_report SET repo_directory = ?, repo_embedded = ? WHERE id = ?')
|
|
18
19
|
const reports = db.prepare('SELECT id, filename FROM managed_report').all() as { id: string, filename: string }[]
|
|
19
20
|
for (const { id, filename } of reports) {
|
|
20
21
|
// Same opaque UUID boundary as the blob store; never splice arbitrary
|
|
21
22
|
// database text into a filesystem path during an upgrade.
|
|
22
|
-
if (
|
|
23
|
+
if (!isBlobId(id)) throw new Error(`Invalid legacy report id: ${id}`)
|
|
23
24
|
const { data } = readManagedReport(readFileSync(join(reportDir, id), 'utf8'), filename)
|
|
24
25
|
if (data == null) throw new Error(`Cannot migrate location of unreadable report ${id}`)
|
|
25
26
|
const embedded = reportRepoGithub(data) != null
|
|
@@ -27,9 +28,5 @@ export function migrateReportLocations(db: DatabaseSync, reportDir: string): voi
|
|
|
27
28
|
if (!directory.ok) throw new Error(`Cannot migrate invalid directory of report ${id}`)
|
|
28
29
|
update.run(directory.path ?? '', embedded ? 1 : 0, id)
|
|
29
30
|
}
|
|
30
|
-
|
|
31
|
-
} catch (err) {
|
|
32
|
-
db.exec('ROLLBACK')
|
|
33
|
-
throw err
|
|
34
|
-
}
|
|
31
|
+
})
|
|
35
32
|
}
|
|
@@ -14,6 +14,7 @@ import { readBundleDetails } from './bundle-cache.ts'
|
|
|
14
14
|
import type { BlobStore } from './blob-store.ts'
|
|
15
15
|
import type { BundleStore } from './bundle-store.ts'
|
|
16
16
|
import type { ManagedBundle, ManagedDb, ReportRecord } from './db.ts'
|
|
17
|
+
import { inTurns } from './queue.ts'
|
|
17
18
|
|
|
18
19
|
const compress = promisify(gzip)
|
|
19
20
|
const reportFormat = (filename: string) => extname(filename).toLowerCase()
|
|
@@ -81,24 +82,19 @@ async function lendSourcemapEdges(details: BundleDetails, bundle: ManagedBundle,
|
|
|
81
82
|
if (edges) details.edges = edges
|
|
82
83
|
}
|
|
83
84
|
|
|
84
|
-
// Immutable report hashes share a derivative across duplicate uploads. Bundle
|
|
85
|
-
// identity and visibility are part of the key: a broader viewer's sources must
|
|
86
|
-
// never populate a restricted response. Group derivatives by hash and filename
|
|
87
|
-
// format so each format's permissions can be removed after its last deletion.
|
|
88
85
|
// The repositories that are ours, so that a finding's `repo` none of them is
|
|
89
86
|
// left out (common/finding-repo.js isStrayRepo).
|
|
90
87
|
async function oursFor(db: ManagedDb, repo: { github: string | null }): Promise<Set<string>> {
|
|
91
88
|
return ourRepoSlugs([...(await db.listSelectedRepos()).map(selected => selected.fullName), repo.github])
|
|
92
89
|
}
|
|
93
90
|
|
|
91
|
+
// Immutable report hashes share a derivative across duplicate uploads. Bundle
|
|
92
|
+
// identity and visibility are part of the key: a broader viewer's sources must
|
|
93
|
+
// never populate a restricted response. Group derivatives by hash and filename
|
|
94
|
+
// format so each format's permissions can be removed after its last deletion.
|
|
94
95
|
export function createReportSourcesCache(storage: CacheStorage, db: ManagedDb, reports: BlobStore, bundles: BundleStore, sourcemapEdges?: SourcemapEdges) {
|
|
95
96
|
const pending = new Map<string, { reportId: string; job: Promise<boolean> }>()
|
|
96
|
-
|
|
97
|
-
function enqueue<T>(work: () => Promise<T>): Promise<T> {
|
|
98
|
-
const job = queue.then(work)
|
|
99
|
-
queue = job.then(() => undefined, () => undefined)
|
|
100
|
-
return job
|
|
101
|
-
}
|
|
97
|
+
const enqueue = inTurns(1)
|
|
102
98
|
async function referenced(report: ReportRecord, bundle: ManagedBundle) {
|
|
103
99
|
const names = await db.listReportFilenamesWithBundleHash(bundle.id, report.sha256)
|
|
104
100
|
return names.some(name => reportFormat(name) === reportFormat(report.filename)) && await db.getBundle(bundle.id) != null
|
|
@@ -1,20 +1,12 @@
|
|
|
1
1
|
// Compress before the object-storage encryption boundary. Separate paths let
|
|
2
2
|
// legacy arbitrary report bytes remain readable without format sniffing.
|
|
3
|
-
import { Buffer } from 'node:buffer'
|
|
3
|
+
import type { Buffer } from 'node:buffer'
|
|
4
4
|
import { Readable } from 'node:stream'
|
|
5
5
|
import { pipeline } from 'node:stream/promises'
|
|
6
6
|
import { createBrotliDecompress } from 'node:zlib'
|
|
7
|
-
import type
|
|
7
|
+
import { type BlobStore, type OpenedBlob, readBytes } from './blob-store.ts'
|
|
8
8
|
import { encodeBrotli } from './brotli.ts'
|
|
9
9
|
|
|
10
|
-
async function readBytes(stored: OpenedBlob): Promise<Buffer> {
|
|
11
|
-
const parts: Buffer[] = []
|
|
12
|
-
try {
|
|
13
|
-
for await (const part of stored.stream) parts.push(Buffer.from(part))
|
|
14
|
-
return Buffer.concat(parts)
|
|
15
|
-
} finally { stored.stream.destroy() }
|
|
16
|
-
}
|
|
17
|
-
|
|
18
10
|
// Ids whose original copy is known gone, at most this many.
|
|
19
11
|
const COMPRESSED_ONLY_MAX = 16_384
|
|
20
12
|
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
// every scan, as many repositories use the same few actions.
|
|
6
6
|
import { type ActionsSource, type ResolvedAction, type ScanOptions, type WorkflowScan, dockerfileFindings, keptSource, ownFilesOf, resolveAction,
|
|
7
7
|
scanWorkflow, usesOfKey } from '../risk/index.js'
|
|
8
|
+
import { SHA } from './github-values.ts'
|
|
8
9
|
import type { OpenedRepository } from './repository-risk-read.ts'
|
|
9
10
|
import type { Lru } from './lru.ts'
|
|
10
11
|
import type { KeptStore } from './npm-kept.ts'
|
|
@@ -22,7 +23,7 @@ const MAX_DEPTH = 4
|
|
|
22
23
|
const RESOLVERS = 4
|
|
23
24
|
|
|
24
25
|
// A file of a repository's Actions: its text, or why it couldn't be had.
|
|
25
|
-
|
|
26
|
+
type ActionsFile = { path: string; kind: 'workflow' | 'action' | 'dockerfile' } & ({ text: string } | RiskFailure)
|
|
26
27
|
export type WorkflowsRead = { files: ActionsFile[] } | RiskFailure
|
|
27
28
|
|
|
28
29
|
// What a scan tells of them: the workflows' paths, each file's scan, and
|
|
@@ -35,7 +36,7 @@ export type ActionLine = { type: 'action' } & (ResolvedAction | { key: string }
|
|
|
35
36
|
export interface ActionRef { key: string; owner: string | null; depth: number }
|
|
36
37
|
|
|
37
38
|
// What reading a repository's Actions asks of it.
|
|
38
|
-
|
|
39
|
+
type ActionsReading = Required<Pick<OpenedRepository, 'workflows' | 'file'>>
|
|
39
40
|
|
|
40
41
|
// A file's text, or why not: one GitHub hasn't, or larger than read.
|
|
41
42
|
async function readFile(reading: ActionsReading, path: string): Promise<{ text: string } | RiskFailure> {
|
|
@@ -107,13 +108,11 @@ export type ActionAnswers = Lru<{ at: number; answer: unknown }>
|
|
|
107
108
|
export const answerWeight = ({ answer }: { at: number; answer: unknown }) => Array.isArray(answer) ? answer.length + 1
|
|
108
109
|
: typeof answer === 'string' ? Math.ceil(answer.length / 1024) + 1 : ((answer as { branches?: unknown[] } | null)?.branches?.length ?? 0) + 1
|
|
109
110
|
|
|
110
|
-
const isCommit = (text: string) => /^[\da-f]{40}$/u.test(text)
|
|
111
|
-
|
|
112
111
|
// `source`, what it answers of a public repository kept for every scan, the
|
|
113
112
|
// same whoever asks: of a commit while kept (but none, as one can be pushed
|
|
114
113
|
// later), the rest, its advisories too, for RISK_KEPT_MS. A private one's,
|
|
115
114
|
// or one missing, never.
|
|
116
|
-
|
|
115
|
+
function sharedSource(source: ActionsSource, answers: ActionAnswers): ActionsSource {
|
|
117
116
|
const keyOf = (what: string, name: string, ...more: string[]) => [what, name.toLowerCase(), ...more].join('\0')
|
|
118
117
|
const kept = (key: string, lasting = false) => {
|
|
119
118
|
const at = answers.get(key)
|
|
@@ -139,14 +138,14 @@ export function sharedSource(source: ActionsSource, answers: ActionAnswers): Act
|
|
|
139
138
|
tag: (name, tag) => shared(name, keyOf('tag', name, tag), false, () => source.tag(name, tag)),
|
|
140
139
|
branch: (name, branch) => shared(name, keyOf('branch', name, branch), false, () => source.branch(name, branch)),
|
|
141
140
|
branches: name => shared(name, keyOf('branches', name), false, () => source.branches(name)),
|
|
142
|
-
contains: (name, base, sha) => shared(name, keyOf('contains', name, base, sha),
|
|
143
|
-
file: (name, path, commit) => shared(name, keyOf('file', name, path, commit),
|
|
141
|
+
contains: (name, base, sha) => shared(name, keyOf('contains', name, base, sha), SHA.test(base), () => source.contains(name, base, sha)),
|
|
142
|
+
file: (name, path, commit) => shared(name, keyOf('file', name, path, commit), SHA.test(commit), () => source.file(name, path, commit)),
|
|
144
143
|
...source.advisories && { advisories: (name: string, versions: string[], internal: boolean) =>
|
|
145
144
|
shared(name, keyOf('advisories', name, ...versions), false, () => source.advisories!(name, versions, internal)) },
|
|
146
145
|
}
|
|
147
146
|
}
|
|
148
147
|
|
|
149
|
-
|
|
148
|
+
interface ActionsResolving {
|
|
150
149
|
source: ActionsSource
|
|
151
150
|
signal: AbortSignal
|
|
152
151
|
tell(line: ActionLine): void
|