@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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto'
|
|
2
2
|
import { ManagedMutationError } from './management.ts'
|
|
3
3
|
import type { PatchSource } from './npm-patch.ts'
|
|
4
|
-
import type
|
|
4
|
+
import { type ManagedSql, jsonRows } from './sql.ts'
|
|
5
5
|
import { REVIEW_VERDICTS, type ReviewSummary, type ReviewVerdict, allowedReviewVerdicts, needsPackageJsonReview, summarizeReview } from '../common/dependency-reviews.js'
|
|
6
6
|
|
|
7
7
|
// A review is of a version, as npm's registry has it, by its integrity; of
|
|
@@ -146,12 +146,6 @@ async function teams(db: ManagedSql, user: string): Promise<ReviewTeam[]> {
|
|
|
146
146
|
return await db.prepare(`SELECT t.id, t.name FROM managed_team t JOIN managed_user u ON u.id = ?
|
|
147
147
|
WHERE ${reviewsIn(true)} ORDER BY t.name, t.id`).all(user) as ReviewTeam[]
|
|
148
148
|
}
|
|
149
|
-
// A draft is begun or edited by one who publishes to some team; their own
|
|
150
|
-
// published review revoked, or published to more teams, as `publish` checks
|
|
151
|
-
// each, whoever they are now.
|
|
152
|
-
async function requireReviewer(db: ManagedSql, user: string) {
|
|
153
|
-
if ((await teams(db, user)).length === 0) throw new ManagedMutationError(403, 'review-access-required')
|
|
154
|
-
}
|
|
155
149
|
|
|
156
150
|
type ReviewRow = Omit<DependencyReview, 'files' | 'entries' | 'teams' | 'patchSource' | keyof ReviewSummary> & { files: string | null; patchSource: string | null }
|
|
157
151
|
async function expandReviews(db: ManagedSql, rows: unknown[], user: string): Promise<DependencyReview[]> {
|
|
@@ -177,20 +171,22 @@ async function expandReviews(db: ManagedSql, rows: unknown[], user: string): Pro
|
|
|
177
171
|
const [entriesOf, teamsOf] = [byReview(entries), byReview(linked)]
|
|
178
172
|
return reviews.map(review => expanded(review, (entriesOf.get(review.id) ?? []) as ReviewEntry[], (teamsOf.get(review.id) ?? []) as ReviewTeam[]))
|
|
179
173
|
}
|
|
174
|
+
// A review's snapshot of its files, as its row keeps it: its paths, null for
|
|
175
|
+
// a draft's; and its non-text files, none for a draft's, and null for one of
|
|
176
|
+
// paths alone, as kept before they were told.
|
|
177
|
+
export function snapshotOf(stored: string | null): { files: string[] | null; nonTextFiles: string[] | null } {
|
|
178
|
+
const snapshot = stored === null ? null : JSON.parse(stored) as string[] | { paths: string[]; nonTextFiles: string[] }
|
|
179
|
+
return { files: Array.isArray(snapshot) ? snapshot : snapshot?.paths ?? null, nonTextFiles: Array.isArray(snapshot) ? null : snapshot?.nonTextFiles ?? [] }
|
|
180
|
+
}
|
|
180
181
|
// A review as its row, its entries and the teams its reader reads it in
|
|
181
182
|
// tell it: its files' snapshot, its entries a file's each (fileEntries), and
|
|
182
183
|
// what they sum up to; where its patch was read.
|
|
183
184
|
function expanded(review: ReviewRow, entries: ReviewEntry[], readIn: ReviewTeam[]): DependencyReview {
|
|
184
|
-
const
|
|
185
|
-
const files = Array.isArray(snapshot) ? snapshot : snapshot?.paths ?? null
|
|
186
|
-
const nonTextFiles = Array.isArray(snapshot) ? null : snapshot?.nonTextFiles ?? []
|
|
185
|
+
const { files, nonTextFiles } = snapshotOf(review.files)
|
|
187
186
|
const ownEntries = fileEntries(entries)
|
|
188
187
|
return { ...review, patchSource: review.patchSource ? JSON.parse(review.patchSource) as PatchSource : null, files, nonTextFiles, entries: ownEntries,
|
|
189
188
|
...summarizeReview(ownEntries, files, nonTextFiles), teams: readIn }
|
|
190
189
|
}
|
|
191
|
-
// Rows gathered into one JSON array value (json_group_array): its text on
|
|
192
|
-
// SQLite, parsed already on Postgres, where none gather as NULL.
|
|
193
|
-
export const gathered = <T>(value: unknown): T[] => value == null ? [] : (typeof value === 'string' ? JSON.parse(value) : value) as T[]
|
|
194
190
|
|
|
195
191
|
async function publish(db: ManagedSql, current: DependencyReview | undefined, user: string, change: Extract<ReviewChange, { action: 'publish' }>, now: number,
|
|
196
192
|
tarballs: ReviewedTarballs | undefined) {
|
|
@@ -259,7 +255,7 @@ async function listTeam(db: ManagedSql, teamId: string, user: string, before: {
|
|
|
259
255
|
const reviews = rows.filter(row => row.id != null)
|
|
260
256
|
const page = reviews.slice(0, 50)
|
|
261
257
|
const last = page.at(-1)
|
|
262
|
-
return { reviews: page.map(({ reader: _reader, entries, teams: readIn, ...review }) => expanded(review,
|
|
258
|
+
return { reviews: page.map(({ reader: _reader, entries, teams: readIn, ...review }) => expanded(review, jsonRows(entries), jsonRows(readIn))),
|
|
263
259
|
next: reviews.length > 50 && last ? { time: Number(last.publishedAt), id: last.id } : null }
|
|
264
260
|
}
|
|
265
261
|
|
|
@@ -316,7 +312,10 @@ export function dependencyReviewMethods(db: ManagedSql): DependencyReviewStore {
|
|
|
316
312
|
listDependencyReviews: (context, user, allBases = false) => listContext(db, context, user, allBases),
|
|
317
313
|
async changeDependencyReview(context, sessionId, change, now, tarballs) {
|
|
318
314
|
const user = await actor(db, sessionId)
|
|
319
|
-
|
|
315
|
+
// A draft is begun or edited by one who publishes to some team; their own
|
|
316
|
+
// published review revoked, or published to more teams, as `publish` checks
|
|
317
|
+
// each, whoever they are now.
|
|
318
|
+
if (change.action !== 'revoke' && change.action !== 'publish' && (await teams(db, user.id)).length === 0) throw new ManagedMutationError(403, 'review-access-required')
|
|
320
319
|
let id = change.reviewId
|
|
321
320
|
let current: DependencyReview | undefined
|
|
322
321
|
if (id) {
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
// GitHub accounts as GitHub's REST and GraphQL APIs name them, where a
|
|
2
2
|
// repository's activity names its authors (repository-history.ts and the
|
|
3
3
|
// Commits, Issues, Agents and Pulse tabs' readers).
|
|
4
|
-
import { githubGraphql } from './github-graphql.ts'
|
|
5
|
-
|
|
6
|
-
const LOGIN = /^[A-Za-z\d][A-Za-z\d-]{0,38}(?:\[bot\])?$/u
|
|
4
|
+
import { githubGraphql, notFound } from './github-graphql.ts'
|
|
5
|
+
import { LOGIN, isId } from './github-values.ts'
|
|
7
6
|
|
|
8
7
|
// An account as GitHub names it: its login, else null, and its numeric id
|
|
9
8
|
// where GitHub names one with it.
|
|
@@ -11,7 +10,7 @@ export interface NamedAccount { login: string | null; id: number | null }
|
|
|
11
10
|
export function accountOf(account: { login?: unknown; id?: unknown } | null | undefined): NamedAccount {
|
|
12
11
|
const login = typeof account?.login === 'string' && LOGIN.test(account.login) ? account.login : null
|
|
13
12
|
const id = account?.id
|
|
14
|
-
return { login, id: login &&
|
|
13
|
+
return { login, id: login && isId(id) ? id : null }
|
|
15
14
|
}
|
|
16
15
|
|
|
17
16
|
// An actor (the author of an issue or a pull request, one who merged one) as
|
|
@@ -54,7 +53,7 @@ export async function linkNoreplyUsers(actors: (GraphActor | null | undefined)[]
|
|
|
54
53
|
if (logins.length === 0) return
|
|
55
54
|
const query = `query(${logins.map((_, at) => `$l${at}: String!`).join(', ')}) { ${logins.map((_, at) => `u${at}: user(login: $l${at}) { login databaseId }`).join(' ')} }`
|
|
56
55
|
const data = await githubGraphql(query, Object.fromEntries(logins.map((login, at) => [`l${at}`, login])), token, fetchImpl,
|
|
57
|
-
|
|
56
|
+
notFound) as Record<string, GraphAccount> | null
|
|
58
57
|
const users = new Map(logins.map((login, at) => [login, data?.[`u${at}`] ?? null]))
|
|
59
58
|
for (const { actor, login } of unnamed) actor.user = users.get(login) ?? null
|
|
60
59
|
}
|
|
@@ -4,14 +4,14 @@
|
|
|
4
4
|
import { createClient } from '@preventive/upstream/github.js'
|
|
5
5
|
import type { ActionsSource } from '../risk/index.js'
|
|
6
6
|
import { GithubApiError, upstreamGithub } from './github-errors.ts'
|
|
7
|
-
import { githubJson } from './github-
|
|
7
|
+
import { encodedPath, githubJson, repoApi } from './github-requests.ts'
|
|
8
|
+
import { SHA } from './github-values.ts'
|
|
8
9
|
|
|
9
10
|
// How many pages of 100 tags are listed; a repository with more is told by
|
|
10
11
|
// its tags one at a time.
|
|
11
12
|
const MAX_TAG_PAGES = 10
|
|
12
13
|
const BRANCHES_PAGE = 100
|
|
13
14
|
|
|
14
|
-
const api = (name: string, suffix: string) => `https://api.github.com/repos/${name.split('/').map(encodeURIComponent).join('/')}${suffix}`
|
|
15
15
|
|
|
16
16
|
// Whether upstream refused what it was asked before asking GitHub, as a ref
|
|
17
17
|
// git wouldn't take: its arguments' checks say what each must be.
|
|
@@ -48,18 +48,18 @@ export function githubActionsSource(token: string | null, fetchImpl: typeof fetc
|
|
|
48
48
|
tag: async (name, tag) => (await orNone(() => client.getRepoTag({ repo: name, tag })))?.oid ?? null,
|
|
49
49
|
branch: async (name, branch) => (await orNone(() => client.getRepoHead({ repo: name, branch })))?.oid ?? null,
|
|
50
50
|
async branches(name) {
|
|
51
|
-
const listed = await githubJson(
|
|
51
|
+
const listed = await githubJson(`${repoApi(name)}/branches?per_page=${BRANCHES_PAGE}`, token, fetchImpl)
|
|
52
52
|
if (!Array.isArray(listed)) throw new GithubApiError(502, 'github-malformed')
|
|
53
53
|
const branches = (listed as { name?: unknown; commit?: { sha?: unknown } }[]).flatMap(item => typeof item?.name === 'string'
|
|
54
|
-
&& typeof item.commit?.sha === 'string' &&
|
|
54
|
+
&& typeof item.commit?.sha === 'string' && SHA.test(item.commit.sha) ? [{ branch: item.name, oid: item.commit.sha }] : [])
|
|
55
55
|
return { branches, complete: listed.length < BRANCHES_PAGE }
|
|
56
56
|
},
|
|
57
57
|
// `base...sha`: `sha` is `base` or in its history where GitHub tells it
|
|
58
58
|
// behind or identical, a commit of a fork in the same network too.
|
|
59
59
|
async contains(name, base, sha) {
|
|
60
|
-
if (
|
|
60
|
+
if (!SHA.test(sha)) return null
|
|
61
61
|
let compared
|
|
62
|
-
try { compared = await githubJson(
|
|
62
|
+
try { compared = await githubJson(`${repoApi(name)}/compare/${encodedPath(base)}...${sha}?per_page=1`, token, fetchImpl) as { status?: unknown } } catch (error) {
|
|
63
63
|
if (error instanceof GithubApiError && (error.status === 404 || error.message === 'github-status-422')) return null
|
|
64
64
|
throw error
|
|
65
65
|
}
|
|
@@ -7,13 +7,15 @@ import { createHash, createSign } from 'node:crypto'
|
|
|
7
7
|
import { createClient } from '@preventive/upstream/github.js'
|
|
8
8
|
import type { ManagedConfig } from './config.ts'
|
|
9
9
|
import { GithubApiError, upstreamGithub } from './github-errors.ts'
|
|
10
|
-
import { USER_AGENT, githubJson, onTokenRejected } from './github-requests.ts'
|
|
10
|
+
import { GITHUB_API, USER_AGENT, githubJson, onTokenRejected, repoApi } from './github-requests.ts'
|
|
11
|
+
import { isId } from './github-values.ts'
|
|
12
|
+
import { eachOf } from './queue.ts'
|
|
11
13
|
|
|
12
|
-
export { GithubApiError } from './github-errors.ts'
|
|
13
|
-
export { githubJson, onTokenRejected } from './github-requests.ts'
|
|
14
|
-
|
|
15
|
-
const GITHUB_API = 'https://api.github.com'
|
|
16
14
|
const PER_PAGE = 100
|
|
15
|
+
// Bound fan-out while keeping independent installations/permission checks off
|
|
16
|
+
// one long serial critical path. eachOf preserves input order for
|
|
17
|
+
// deterministic merges.
|
|
18
|
+
const GITHUB_REQUESTS_AT_ONCE = 4
|
|
17
19
|
const INSTALLATION_TOKEN_TTL_MS = 5 * 60_000
|
|
18
20
|
const INSTALLATION_TOKEN_EXPIRY_MARGIN_MS = 60_000
|
|
19
21
|
const MAX_INSTALLATION_TOKENS = 256
|
|
@@ -75,7 +77,7 @@ function parseRepo(raw: unknown, installationId: number | null): ConnectedRepo |
|
|
|
75
77
|
if ((raw as { archived?: unknown }).archived === true) return null
|
|
76
78
|
const id = (raw as { id?: unknown }).id
|
|
77
79
|
const fullName = (raw as { full_name?: unknown }).full_name
|
|
78
|
-
if (
|
|
80
|
+
if (!isId(id)) return null
|
|
79
81
|
if (typeof fullName !== 'string' || fullName === '') return null
|
|
80
82
|
const htmlUrl = (raw as { html_url?: unknown }).html_url
|
|
81
83
|
const branch = (raw as { default_branch?: unknown }).default_branch
|
|
@@ -118,13 +120,8 @@ export async function fetchPublicRepository(fullName: string): Promise<Connected
|
|
|
118
120
|
// a short page, deduped + sorted. With an identity-only token this returns the
|
|
119
121
|
// user's PUBLIC repos. READ-ONLY.
|
|
120
122
|
export async function listUserRepos(accessToken: string): Promise<ConnectedRepo[]> {
|
|
121
|
-
const byName = new Map<string, ConnectedRepo>()
|
|
122
123
|
const body = await upstreamGithub(() => createClient({ token: accessToken, userAgent: USER_AGENT }).listUserRepos())
|
|
123
|
-
|
|
124
|
-
const repo = parseRepo(r, null)
|
|
125
|
-
if (repo != null) byName.set(repo.fullName, repo)
|
|
126
|
-
}
|
|
127
|
-
return [...byName.values()].toSorted((a, b) => a.fullName.localeCompare(b.fullName))
|
|
124
|
+
return mergeRepos(body.flatMap(r => parseRepo(r, null) ?? []))
|
|
128
125
|
}
|
|
129
126
|
|
|
130
127
|
// ── PRIVATE: App installations via installation tokens ──
|
|
@@ -152,7 +149,7 @@ async function listInstallationIds(jwt: string, fetchImpl: typeof fetch): Promis
|
|
|
152
149
|
if (!Array.isArray(body)) throw new GithubApiError(502, 'github-malformed')
|
|
153
150
|
for (const inst of body) {
|
|
154
151
|
const id = (inst as { id?: unknown }).id
|
|
155
|
-
if (
|
|
152
|
+
if (isId(id)) ids.push(id)
|
|
156
153
|
}
|
|
157
154
|
if (body.length < PER_PAGE) break
|
|
158
155
|
}
|
|
@@ -203,19 +200,18 @@ export async function repositoryInstallation(config: ManagedConfig, repoId: numb
|
|
|
203
200
|
const { githubAppId, githubAppPrivateKey } = config
|
|
204
201
|
if (githubAppId == null || githubAppPrivateKey == null) throw new GithubApiError(503, 'github-app-not-configured')
|
|
205
202
|
if (publicRepositoryName(fullName) !== fullName) throw new GithubApiError(409, 'repo-identity-changed')
|
|
206
|
-
const path = fullName.split('/').map(encodeURIComponent).join('/')
|
|
207
203
|
const jwt = appJwt(githubAppId, githubAppPrivateKey)
|
|
208
204
|
let raw
|
|
209
|
-
try { raw = await githubJson(`${
|
|
205
|
+
try { raw = await githubJson(`${repoApi(fullName)}/installation`, jwt, fetchImpl) } catch (err) {
|
|
210
206
|
if (err instanceof GithubApiError && err.status === 404) return null
|
|
211
207
|
throw err
|
|
212
208
|
}
|
|
213
209
|
const installation = raw as { id?: unknown; suspended_at?: unknown; permissions?: { contents?: unknown } } | null
|
|
214
210
|
const id = installation?.id
|
|
215
|
-
if (
|
|
211
|
+
if (!isId(id)) throw new GithubApiError(502, 'github-malformed')
|
|
216
212
|
if (installation?.suspended_at != null || !['read', 'write'].includes(String(installation?.permissions?.contents))) return null
|
|
217
213
|
const token = await installationAccessToken(githubAppId, githubAppPrivateKey, id, fetchImpl)
|
|
218
|
-
const repo = parseRepo(await githubJson(
|
|
214
|
+
const repo = parseRepo(await githubJson(repoApi(fullName), token, fetchImpl), id)
|
|
219
215
|
if (repo == null || repo.id !== repoId || repo.fullName.toLowerCase() !== fullName.toLowerCase()) throw new GithubApiError(409, 'repo-identity-changed')
|
|
220
216
|
return id
|
|
221
217
|
}
|
|
@@ -224,13 +220,7 @@ export async function repositoryInstallation(config: ManagedConfig, repoId: numb
|
|
|
224
220
|
// each tagged with the installation id that can read it.
|
|
225
221
|
function repoPage(body: unknown, installationId: number): ConnectedRepo[] {
|
|
226
222
|
const repositories = (body as { repositories?: unknown }).repositories
|
|
227
|
-
|
|
228
|
-
const out: ConnectedRepo[] = []
|
|
229
|
-
for (const r of repositories) {
|
|
230
|
-
const repo = parseRepo(r, installationId)
|
|
231
|
-
if (repo != null) out.push(repo)
|
|
232
|
-
}
|
|
233
|
-
return out
|
|
223
|
+
return Array.isArray(repositories) ? repositories.flatMap(r => parseRepo(r, installationId) ?? []) : []
|
|
234
224
|
}
|
|
235
225
|
|
|
236
226
|
// Every repository one installation can read, paginated by the page count from
|
|
@@ -254,27 +244,13 @@ export async function listInstalledRepos(config: ManagedConfig, fetchImpl: typeo
|
|
|
254
244
|
const { githubAppId, githubAppPrivateKey } = config
|
|
255
245
|
if (githubAppId == null || githubAppPrivateKey == null) return []
|
|
256
246
|
const jwt = appJwt(githubAppId, githubAppPrivateKey)
|
|
257
|
-
const lists = await
|
|
247
|
+
const lists = await eachOf(await listInstallationIds(jwt, fetchImpl), GITHUB_REQUESTS_AT_ONCE, async (id) => {
|
|
258
248
|
const token = await installationAccessToken(githubAppId, githubAppPrivateKey, id, fetchImpl)
|
|
259
249
|
return listInstallationRepos(token, id, fetchImpl)
|
|
260
250
|
})
|
|
261
251
|
return mergeRepos(...lists)
|
|
262
252
|
}
|
|
263
253
|
|
|
264
|
-
// Bound fan-out while keeping independent installations/permission checks off
|
|
265
|
-
// one long serial critical path. Preserve input order for deterministic merges.
|
|
266
|
-
async function mapGithubRequests<T, U>(items: T[], work: (item: T) => Promise<U>): Promise<U[]> {
|
|
267
|
-
const results: U[] = []
|
|
268
|
-
let next = 0
|
|
269
|
-
await Promise.all(Array.from({ length: Math.min(4, items.length) }, async () => {
|
|
270
|
-
while (next < items.length) {
|
|
271
|
-
const index = next++
|
|
272
|
-
results[index] = await work(items[index]!)
|
|
273
|
-
}
|
|
274
|
-
}))
|
|
275
|
-
return results
|
|
276
|
-
}
|
|
277
|
-
|
|
278
254
|
// A GitHub account, as GitHub's /user tells it.
|
|
279
255
|
export interface GithubIdentity { id: number; login: string }
|
|
280
256
|
|
|
@@ -288,16 +264,15 @@ export interface GithubIdentity { id: number; login: string }
|
|
|
288
264
|
// else's access. All repo paths come from GitHub's installation catalogue.
|
|
289
265
|
export async function githubUserIdentity(userToken: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<GithubIdentity> {
|
|
290
266
|
const identity = await githubJson(`${GITHUB_API}/user`, userToken, fetchImpl) as { id?: unknown; login?: unknown }
|
|
291
|
-
if (typeof identity?.login !== 'string' || !identity.login ||
|
|
267
|
+
if (typeof identity?.login !== 'string' || !identity.login || !isId(identity.id)) throw new GithubApiError(502, 'github-malformed')
|
|
292
268
|
return { id: identity.id, login: identity.login }
|
|
293
269
|
}
|
|
294
270
|
|
|
295
271
|
// The permission's level (`admin`, `write`, `read`), as GitHub tells it of
|
|
296
272
|
// `identity` alone; `none` where it tells of none, or of another account.
|
|
297
273
|
export async function githubRepoPermission(fullName: string, token: string, identity: GithubIdentity, fetchImpl: typeof fetch = globalThis.fetch): Promise<string> {
|
|
298
|
-
const path = fullName.split('/').map(encodeURIComponent).join('/')
|
|
299
274
|
try {
|
|
300
|
-
const body = await githubJson(`${
|
|
275
|
+
const body = await githubJson(`${repoApi(fullName)}/collaborators/${encodeURIComponent(identity.login)}/permission`, token, fetchImpl) as { permission?: unknown; user?: { id?: unknown } }
|
|
301
276
|
return body?.user?.id === identity.id && typeof body.permission === 'string' ? body.permission : 'none'
|
|
302
277
|
} catch (err) {
|
|
303
278
|
if (err instanceof GithubApiError && err.status === 404) return 'none'
|
|
@@ -308,14 +283,10 @@ export async function githubRepoPermission(fullName: string, token: string, iden
|
|
|
308
283
|
// The levels that read a repository.
|
|
309
284
|
export const READ_PERMISSIONS: ReadonlySet<string> = new Set(['read', 'write', 'admin'])
|
|
310
285
|
|
|
311
|
-
export async function githubRepoReadPermission(fullName: string, token: string, identity: GithubIdentity, fetchImpl: typeof fetch = globalThis.fetch): Promise<boolean> {
|
|
312
|
-
return READ_PERMISSIONS.has(await githubRepoPermission(fullName, token, identity, fetchImpl))
|
|
313
|
-
}
|
|
314
|
-
|
|
315
286
|
export async function filterInstalledRepos(config: ManagedConfig, repositories: ConnectedRepo[], userToken: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<ConnectedRepo[]> {
|
|
316
287
|
const identity = await githubUserIdentity(userToken, fetchImpl)
|
|
317
288
|
const tokens = new Map<number, Promise<string | null>>()
|
|
318
|
-
const allowed = await
|
|
289
|
+
const allowed = await eachOf(repositories, GITHUB_REQUESTS_AT_ONCE, async (repo) => {
|
|
319
290
|
// Internal repos may have private=false; missing visibility is not proof
|
|
320
291
|
// of public access either. Only explicitly public repositories skip checks.
|
|
321
292
|
if (repo.visibility === 'public') return true
|
|
@@ -327,7 +298,7 @@ export async function filterInstalledRepos(config: ManagedConfig, repositories:
|
|
|
327
298
|
}
|
|
328
299
|
const accessToken = await token
|
|
329
300
|
if (!accessToken) return false
|
|
330
|
-
return
|
|
301
|
+
return READ_PERMISSIONS.has(await githubRepoPermission(repo.fullName, accessToken, identity, fetchImpl))
|
|
331
302
|
})
|
|
332
303
|
return repositories.filter((_, index) => allowed[index])
|
|
333
304
|
}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
// GitHub's GraphQL API, a query at a time, as the repository readers ask it
|
|
2
2
|
// (repository-history.ts, repository-agents.ts, repository-pulse.ts and the rest).
|
|
3
|
-
import { GithubApiError
|
|
3
|
+
import { GithubApiError } from './github-errors.ts'
|
|
4
|
+
import { GITHUB_API, githubJson } from './github-requests.ts'
|
|
4
5
|
|
|
5
6
|
export type GraphqlError = { type?: unknown; path?: unknown; message?: unknown }
|
|
7
|
+
// An error naming what isn't there, for the queries that read past it.
|
|
8
|
+
export const notFound = (error: GraphqlError) => error?.type === 'NOT_FOUND'
|
|
6
9
|
|
|
7
10
|
const NAMED_ERRORS = new Set(['RATE_LIMITED', 'NOT_FOUND', 'FORBIDDEN'])
|
|
8
11
|
// GitHub's own words for a query it stopped past its time (ten seconds):
|
|
@@ -20,7 +23,7 @@ const TIMED_OUT = /\btimeout\b/iu
|
|
|
20
23
|
// are logged, those read past too.
|
|
21
24
|
export async function githubGraphql(query: string, variables: Record<string, unknown>, token: string, fetchImpl: typeof fetch,
|
|
22
25
|
tolerated: (error: GraphqlError) => boolean = () => false) {
|
|
23
|
-
const body = await githubJson(
|
|
26
|
+
const body = await githubJson(`${GITHUB_API}/graphql`, token, fetchImpl, 'POST', { query, variables }, true) as { data?: unknown; errors?: GraphqlError[] } | null
|
|
24
27
|
const all = Array.isArray(body?.errors) ? body.errors : []
|
|
25
28
|
const unnamed = all.filter(error => !NAMED_ERRORS.has(String(error?.type)))
|
|
26
29
|
if (unnamed.length > 0) {
|
|
@@ -3,7 +3,9 @@ import type { ManagedConfig } from './config.ts'
|
|
|
3
3
|
import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
|
|
4
4
|
import type { IssueTracking, ManagedIssue } from './managed-issues.ts'
|
|
5
5
|
import { ensureUserAccessToken } from './github-oauth.ts'
|
|
6
|
-
import {
|
|
6
|
+
import { GITHUB_API, USER_AGENT } from './github-requests.ts'
|
|
7
|
+
import { allowedRepositories, deadlineFetch, lookupFixes } from './github-pulls.ts'
|
|
8
|
+
import { isId } from './github-values.ts'
|
|
7
9
|
|
|
8
10
|
export type IssueFixUpdate = { findingId: string; issueUrl: string; previous: IssueTracking; next: IssueTracking; checkedAt: number }
|
|
9
11
|
type Pull = { number: number; title: string; body: string | null; state: string; isDraft: boolean; createdAt: string;
|
|
@@ -23,6 +25,8 @@ type Duplicate = { repo: Repository; number: number } | null
|
|
|
23
25
|
type Job = { repo: Repository; kind: 'pull' | 'issue'; number: number; aliases: string[];
|
|
24
26
|
linked: boolean; cursor: string | null; pulls: Pull[]; complete: boolean; duplicateOf?: Duplicate | undefined }
|
|
25
27
|
type Metadata = Exclude<GithubFixResult, { error: string }>
|
|
28
|
+
// A batch's answer: each job's repository by its alias (metadataQuery).
|
|
29
|
+
type Page = Record<string, { databaseId: number; nameWithOwner: string; item: Issue | Pull } | null>
|
|
26
30
|
const pullFields = 'number title body state isDraft createdAt repository { databaseId nameWithOwner }'
|
|
27
31
|
// A linked issue's: the issue it was closed as a duplicate of, and a page of
|
|
28
32
|
// the pull requests linked to it.
|
|
@@ -64,9 +68,9 @@ function itemMetadata(item: Issue | Pull, kind: Job['kind']): Omit<Metadata, 'ur
|
|
|
64
68
|
function duplicateOf(issue: Issue, allowed: Map<string, Repository>): Duplicate | undefined {
|
|
65
69
|
if (issue.state !== 'CLOSED' || issue.stateReason !== 'DUPLICATE' || issue.duplicateOf == null) return null
|
|
66
70
|
const { number, repository } = issue.duplicateOf
|
|
67
|
-
if (!
|
|
71
|
+
if (!isId(number) || !isRepositoryReference(repository)) return undefined
|
|
68
72
|
const repo = workspaceRepository(repository, allowed)
|
|
69
|
-
return repo ? { repo, number
|
|
73
|
+
return repo ? { repo, number } : null
|
|
70
74
|
}
|
|
71
75
|
|
|
72
76
|
// `refused`: GitHub answered with an error on the issue's duplicate alone,
|
|
@@ -81,7 +85,7 @@ function readPage(job: Job, item: Issue | Pull, metadata: Map<string, Metadata>,
|
|
|
81
85
|
if (duplicate === undefined) return false
|
|
82
86
|
const connection = (item as Issue).closedByPullRequestsReferences
|
|
83
87
|
if (!connection || !Array.isArray(connection.nodes) || typeof connection.pageInfo?.hasNextPage !== 'boolean'
|
|
84
|
-
|| connection.nodes.some(pr => !pr || !
|
|
88
|
+
|| connection.nodes.some(pr => !pr || !isId(pr.number) || typeof pr.createdAt !== 'string'
|
|
85
89
|
|| !Number.isFinite(Date.parse(pr.createdAt)) || !itemMetadata(pr, 'pull') || typeof pr.isDraft !== 'boolean'
|
|
86
90
|
|| !isRepositoryReference(pr.repository))) return false
|
|
87
91
|
job.duplicateOf = duplicate
|
|
@@ -171,19 +175,13 @@ function issueUpdates(jobs: Map<string, Job>, byIssue: Map<string, ManagedIssue[
|
|
|
171
175
|
return updates
|
|
172
176
|
}
|
|
173
177
|
|
|
174
|
-
//
|
|
175
|
-
//
|
|
176
|
-
//
|
|
177
|
-
//
|
|
178
|
-
//
|
|
179
|
-
|
|
180
|
-
export async function lookupIssueLinks(config: ManagedConfig, db: ManagedDb, snapshot: TeamReportAccessSnapshot,
|
|
181
|
-
urls: string[], issues: ManagedIssue[], fetchImpl: typeof fetch = fetch): Promise<{ fixes: GithubFixResult[]; updates: IssueFixUpdate[] }> {
|
|
182
|
-
const checkedAt = Date.now(), signal = AbortSignal.timeout(10_000)
|
|
183
|
-
const allowed = new Map(snapshot.repositories.filter(repo => isGithubRepoName(repo.github)).map(repo => [repo.github.toLowerCase(), repo]))
|
|
178
|
+
// The jobs of `urls`, one for each pull request or issue of a workspace
|
|
179
|
+
// repository (`allowed`) they name, its URLs its aliases, and the saved
|
|
180
|
+
// `issues` by their issue's key (`byIssue`). Linked jobs are read with their
|
|
181
|
+
// linked pull requests: the saved issues', and the duplicates they were
|
|
182
|
+
// saved with.
|
|
183
|
+
function jobsOf(urls: string[], issues: ManagedIssue[], allowed: Map<string, Repository>) {
|
|
184
184
|
const jobs = new Map<string, Job>()
|
|
185
|
-
// The saved issues by their issue's key, and the issues read with their
|
|
186
|
-
// linked pull requests: theirs, and the duplicates they were saved with.
|
|
187
185
|
const byIssue = new Map<string, ManagedIssue[]>(), linked = new Set<string>()
|
|
188
186
|
for (const issue of issues) {
|
|
189
187
|
const ref = parseGithubIssueUrl(issue.issueUrl)
|
|
@@ -201,41 +199,63 @@ export async function lookupIssueLinks(config: ManagedConfig, db: ManagedDb, sna
|
|
|
201
199
|
if (previous) { previous.aliases.push(url); continue }
|
|
202
200
|
jobs.set(key, { repo, kind: ref.kind, number: ref.number, aliases: [url], linked: linked.has(key), cursor: null, pulls: [], complete: false })
|
|
203
201
|
}
|
|
202
|
+
return { jobs, byIssue }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// GitHub's answer to `batch`'s query, asked with `token`: each job's
|
|
206
|
+
// repository by its alias, and the aliases whose duplicate alone GitHub
|
|
207
|
+
// refused (readPage); null where none was read, or what was is malformed.
|
|
208
|
+
async function readBatch(batch: Job[], token: string, fetchImpl: typeof fetch): Promise<{ data: Page; refused: Set<string> } | null> {
|
|
209
|
+
const query = metadataQuery(batch)
|
|
210
|
+
try {
|
|
211
|
+
const response = await fetchImpl(`${GITHUB_API}/graphql`, {
|
|
212
|
+
method: 'POST', redirect: 'error',
|
|
213
|
+
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': USER_AGENT }, body: JSON.stringify({ query }),
|
|
214
|
+
})
|
|
215
|
+
if (!response.ok) return null
|
|
216
|
+
const body = await response.json() as { data?: Page; errors?: { path?: unknown[] }[] }
|
|
217
|
+
// Errors attached to an alias invalidate that whole job, including its
|
|
218
|
+
// connection. Other aliases can succeed even if one issue was deleted.
|
|
219
|
+
// One on the issue it duplicates alone, which the viewer may be unable
|
|
220
|
+
// to read, leaves its status, and only what it redirects to unknown.
|
|
221
|
+
if (!body?.data || body.errors != null && (!Array.isArray(body.errors)
|
|
222
|
+
|| body.errors.some(error => typeof error?.path?.[0] !== 'string' || !/^r\d+$/u.test(error.path[0])))) return null
|
|
223
|
+
const { data } = body, refused = new Set<string>()
|
|
224
|
+
for (const error of body.errors ?? []) {
|
|
225
|
+
const [alias, field, reference] = error.path! as string[]
|
|
226
|
+
if (field === 'item' && reference === 'duplicateOf') refused.add(alias!)
|
|
227
|
+
else data[alias!] = null
|
|
228
|
+
}
|
|
229
|
+
return { data, refused }
|
|
230
|
+
} catch { return null }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Fetch issue details, linked PR states and manual Fix metadata in one batch.
|
|
234
|
+
// Pagination, workspaces with over 200 distinct links, and issues closed as a
|
|
235
|
+
// duplicate of one not yet read need further batches. A duplicate saved last
|
|
236
|
+
// time is read in the first, as a redirect kept is: its URL among `urls`.
|
|
237
|
+
// Live GraphQL results prove this viewer's access; never publish them into the
|
|
238
|
+
// REST shared cache under an older public-visibility grant.
|
|
239
|
+
export async function lookupIssueLinks(config: ManagedConfig, db: ManagedDb, snapshot: TeamReportAccessSnapshot,
|
|
240
|
+
urls: string[], issues: ManagedIssue[], fetchImpl: typeof fetch = fetch): Promise<{ fixes: GithubFixResult[]; updates: IssueFixUpdate[] }> {
|
|
241
|
+
const checkedAt = Date.now(), signal = AbortSignal.timeout(10_000)
|
|
242
|
+
const allowed = allowedRepositories(snapshot)
|
|
243
|
+
const { jobs, byIssue } = jobsOf(urls, issues, allowed)
|
|
204
244
|
if (jobs.size === 0) return { fixes: [], updates: [] }
|
|
205
|
-
const withinDeadline
|
|
245
|
+
const withinDeadline = deadlineFetch(fetchImpl, signal)
|
|
206
246
|
const token = await ensureUserAccessToken(config, db, snapshot.user.id, checkedAt, withinDeadline)
|
|
207
247
|
if (!token) return { fixes: await lookupFixes(config, db, snapshot, urls, withinDeadline), updates: [] }
|
|
208
248
|
const metadata = new Map<string, Metadata>()
|
|
209
249
|
let pending = [...jobs.values()]
|
|
210
250
|
for (let page = 0; pending.length > 0 && page < 100 && !signal.aborted; page++) {
|
|
211
|
-
const batch = pending.slice(0, 200)
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
try {
|
|
215
|
-
const response = await withinDeadline('https://api.github.com/graphql', {
|
|
216
|
-
method: 'POST', redirect: 'error',
|
|
217
|
-
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'user-agent': 'deepview-triage' }, body: JSON.stringify({ query }),
|
|
218
|
-
})
|
|
219
|
-
if (!response.ok) break
|
|
220
|
-
const body = await response.json() as { data?: typeof data; errors?: { path?: unknown[] }[] }
|
|
221
|
-
// Errors attached to an alias invalidate that whole job, including its
|
|
222
|
-
// connection. Other aliases can succeed even if one issue was deleted.
|
|
223
|
-
// One on the issue it duplicates alone, which the viewer may be unable
|
|
224
|
-
// to read, leaves its status, and only what it redirects to unknown.
|
|
225
|
-
if (!body?.data || body.errors != null && (!Array.isArray(body.errors)
|
|
226
|
-
|| body.errors.some(error => typeof error?.path?.[0] !== 'string' || !/^r\d+$/u.test(error.path[0])))) break
|
|
227
|
-
data = body.data
|
|
228
|
-
for (const error of body.errors ?? []) {
|
|
229
|
-
const [alias, field, reference] = error.path! as string[]
|
|
230
|
-
if (field === 'item' && reference === 'duplicateOf') refused.add(alias!)
|
|
231
|
-
else data[alias!] = null
|
|
232
|
-
}
|
|
233
|
-
} catch { break }
|
|
251
|
+
const batch = pending.slice(0, 200)
|
|
252
|
+
const answer = await readBatch(batch, token, withinDeadline)
|
|
253
|
+
if (!answer) break
|
|
234
254
|
pending = pending.slice(batch.length)
|
|
235
255
|
for (const [index, job] of batch.entries()) {
|
|
236
|
-
const repository = data[`r${index}`]
|
|
256
|
+
const repository = answer.data[`r${index}`]
|
|
237
257
|
if (repository?.databaseId !== job.repo.repoId || typeof repository.nameWithOwner !== 'string' || repository.nameWithOwner.toLowerCase() !== job.repo.github.toLowerCase()) continue
|
|
238
|
-
if (readPage(job, repository.item, metadata, allowed, refused.has(`r${index}`))) pending.push(job)
|
|
258
|
+
if (readPage(job, repository.item, metadata, allowed, answer.refused.has(`r${index}`))) pending.push(job)
|
|
239
259
|
}
|
|
240
260
|
for (const job of duplicateJobs(jobs, byIssue.keys())) if (!pending.includes(job)) pending.push(job)
|
|
241
261
|
}
|
|
@@ -1,38 +1,25 @@
|
|
|
1
1
|
import type { ManagedConfig } from './config.ts'
|
|
2
2
|
import type { ManagedDb, ManagedSession } from './db.ts'
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { OAuthError, ensureUserAccessToken, exchangeCode, fetchIdentity } from './github-oauth.ts'
|
|
3
|
+
import { ISSUE_STATE_COOKIE, clearCookie, cookieName } from './session.ts'
|
|
4
|
+
import { OAuthError, exchangeCode, fetchIdentity, sessionAuthorization, sessionStateValid, stateCookieMatches } from './github-oauth.ts'
|
|
6
5
|
|
|
7
6
|
export const ISSUE_LOGIN_PATH = '/api/oauth/github/issues/login'
|
|
8
7
|
|
|
9
8
|
export function isIssueOAuthCallback(config: ManagedConfig, query: URLSearchParams, cookie: string | undefined): boolean {
|
|
10
|
-
|
|
11
|
-
return !!expected && safeEqual(query.get('state') ?? '', expected)
|
|
9
|
+
return stateCookieMatches(config, ISSUE_STATE_COOKIE, query, cookie)
|
|
12
10
|
}
|
|
13
11
|
|
|
14
12
|
export function issueLoginRedirect(config: ManagedConfig, session: ManagedSession, now = Date.now()) {
|
|
15
|
-
const state = randomToken()
|
|
16
|
-
const url = new URL('https://github.com/login/oauth/authorize')
|
|
17
|
-
url.searchParams.set('client_id', config.githubClientId)
|
|
18
|
-
url.searchParams.set('redirect_uri', config.oauthCallbackUrl)
|
|
19
|
-
url.searchParams.set('state', state)
|
|
20
|
-
url.searchParams.set('allow_signup', 'false')
|
|
21
13
|
// Reauthorize the same app for the current account, without replacing the
|
|
22
14
|
// DeepView session or permitting an OAuth account switch during creation.
|
|
23
|
-
const
|
|
24
|
-
return { location: url.href, setCookie
|
|
25
|
-
{ secure: config.cookieSecure, maxAgeS: 600, sameSite: 'Lax' }) }
|
|
15
|
+
const { url, setCookie } = sessionAuthorization(config, ISSUE_STATE_COOKIE, session, now)
|
|
16
|
+
return { location: url.href, setCookie }
|
|
26
17
|
}
|
|
27
18
|
|
|
28
19
|
export async function issueOAuthCallback(config: ManagedConfig, db: ManagedDb, session: ManagedSession,
|
|
29
20
|
query: URLSearchParams, cookie: string | undefined, fetchImpl: typeof fetch = fetch, now = Date.now()) {
|
|
30
|
-
const
|
|
31
|
-
|
|
32
|
-
if (!code || !state || !expected || !safeEqual(state, expected) || sessionId !== session.id
|
|
33
|
-
|| !timestamp || !Number.isFinite(Number(timestamp)) || now < Number(timestamp) || now - Number(timestamp) > 600_000) {
|
|
34
|
-
throw new OAuthError(400, 'invalid-oauth-state')
|
|
35
|
-
}
|
|
21
|
+
const code = query.get('code')
|
|
22
|
+
if (!code || !sessionStateValid(config, ISSUE_STATE_COOKIE, session, query, cookie, now)) throw new OAuthError(400, 'invalid-oauth-state')
|
|
36
23
|
const tokens = await exchangeCode(config, code, now, fetchImpl)
|
|
37
24
|
const identity = await fetchIdentity(tokens.accessToken, fetchImpl)
|
|
38
25
|
if (identity.githubUserId !== await db.getUserGithubId(session.userId)) throw new OAuthError(403, 'github-account-mismatch')
|
|
@@ -41,7 +28,3 @@ export async function issueOAuthCallback(config: ManagedConfig, db: ManagedDb, s
|
|
|
41
28
|
await db.setUserTokens(session.userId, tokens)
|
|
42
29
|
return { location: '/github-issue-authorized.html', setCookie: clearCookie(cookieName(config, ISSUE_STATE_COOKIE), config.cookieSecure) }
|
|
43
30
|
}
|
|
44
|
-
|
|
45
|
-
export function issueUserToken(config: ManagedConfig, db: ManagedDb, userId: string, fetchImpl: typeof fetch = fetch) {
|
|
46
|
-
return ensureUserAccessToken(config, db, userId, Date.now(), fetchImpl)
|
|
47
|
-
}
|
|
@@ -8,7 +8,10 @@ import { reportEntries, reportRepoGithub } from '@preventive/report'
|
|
|
8
8
|
import { newIssueLabels } from '../common/github-issue-labels.js'
|
|
9
9
|
import { ignoresOwnRepo } from '../common/finding-repo.js'
|
|
10
10
|
import { appJwt, githubAppConfigured, installUrl, publicRepositoryName } from './github-app.ts'
|
|
11
|
-
import { ISSUE_LOGIN_PATH
|
|
11
|
+
import { ISSUE_LOGIN_PATH } from './github-issue-oauth.ts'
|
|
12
|
+
import { ensureUserAccessToken } from './github-oauth.ts'
|
|
13
|
+
import { GITHUB_API, encodedPath, githubHeaders } from './github-requests.ts'
|
|
14
|
+
import { isId } from './github-values.ts'
|
|
12
15
|
import { TeamReportsError, loadTeamReports, recheckTeam, teamSnapshot } from './team-reports.ts'
|
|
13
16
|
|
|
14
17
|
export const MAX_ISSUE_BODY_BYTES = 512_000
|
|
@@ -29,10 +32,9 @@ export function parseIssueContext(raw: unknown): Context {
|
|
|
29
32
|
async function github(path: string, token: string, fetchImpl: typeof fetch, payload?: unknown) {
|
|
30
33
|
let response: Response
|
|
31
34
|
try {
|
|
32
|
-
response = await fetchImpl(
|
|
35
|
+
response = await fetchImpl(`${GITHUB_API}${path}`, {
|
|
33
36
|
method: payload === undefined ? 'GET' : 'POST', redirect: 'error', signal: AbortSignal.timeout(15_000),
|
|
34
|
-
headers: {
|
|
35
|
-
'user-agent': 'deepview-triage', 'x-github-api-version': '2022-11-28', 'content-type': 'application/json' },
|
|
37
|
+
headers: { ...githubHeaders(token), 'content-type': 'application/json' },
|
|
36
38
|
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
|
37
39
|
})
|
|
38
40
|
} catch { throw new IssueError(502, payload === undefined ? 'github-unavailable' : 'github-create-uncertain') }
|
|
@@ -84,14 +86,14 @@ export async function prepareGithubIssue(config: ManagedConfig, db: ManagedDb, s
|
|
|
84
86
|
if (!targetRepository || targetRepository.toLowerCase() !== context.repository.toLowerCase()) throw new IssueError(400, 'bad-issue-repository')
|
|
85
87
|
const repository = snapshot.repositories.find(repo => repo.github.toLowerCase() === targetRepository.toLowerCase())
|
|
86
88
|
if (!repository || !githubAppConfigured(config)) return { mode: 'form' as const, labels, recheck }
|
|
87
|
-
const path = `/repos/${targetRepository
|
|
89
|
+
const path = `/repos/${encodedPath(targetRepository)}`
|
|
88
90
|
const installation = await github(`${path}/installation`, appJwt(config.githubAppId!, config.githubAppPrivateKey!), fetchImpl)
|
|
89
91
|
if (installation.status === 404) return { mode: 'form' as const, labels, recheck }
|
|
90
92
|
if (!installation.ok) throw new IssueError(502, 'github-unavailable')
|
|
91
93
|
let installed: { permissions?: { issues?: string } }
|
|
92
94
|
try { installed = await installation.json() } catch { throw new IssueError(502, 'github-unavailable') }
|
|
93
95
|
if (installed?.permissions?.issues !== 'write') return { mode: 'permissions' as const, authorizationPath: installUrl(config), labels, recheck }
|
|
94
|
-
const token = await
|
|
96
|
+
const token = await ensureUserAccessToken(config, db, session.userId, Date.now(), fetchImpl)
|
|
95
97
|
if (!token) return { mode: 'authorize' as const, authorizationPath: ISSUE_LOGIN_PATH, labels, recheck }
|
|
96
98
|
// All requested labels are optional, including security and operator labels.
|
|
97
99
|
// Omit missing names rather than rejecting issue creation or creating labels.
|
|
@@ -133,7 +135,7 @@ export async function createGithubIssue(prepared: Awaited<ReturnType<typeof prep
|
|
|
133
135
|
if (!response.ok) throw new IssueError(response.status === 422 ? 422 : 502, response.status >= 500 ? 'github-create-uncertain' : 'github-create-failed')
|
|
134
136
|
let issue: { number?: unknown }
|
|
135
137
|
try { issue = await response.json() } catch { throw new IssueError(502, 'github-create-uncertain') }
|
|
136
|
-
if (!
|
|
138
|
+
if (!isId(issue?.number)) throw new IssueError(502, 'github-create-uncertain')
|
|
137
139
|
// Construct the URL from validated inputs, never an upstream redirect target.
|
|
138
140
|
const number = Number(issue.number), url = `https://github.com${prepared.path.slice('/repos'.length)}/issues/${issue.number}`
|
|
139
141
|
if (!await db.finishManagedIssue(findingId, requestId, url)) throw new IssueError(502, 'github-create-uncertain')
|