@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
|
@@ -6,33 +6,24 @@
|
|
|
6
6
|
import type { AvatarStore } from './avatar-store.ts'
|
|
7
7
|
import type { ManagedConfig } from './config.ts'
|
|
8
8
|
import type { ManagedDb, ManagedSession } from './db.ts'
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { OAuthError, cacheAvatar, exchangeCode, fetchIdentity } from './github-oauth.ts'
|
|
9
|
+
import { LINK_STATE_COOKIE, clearCookie, cookieName } from './session.ts'
|
|
10
|
+
import { OAuthError, cacheAvatar, exchangeCode, fetchIdentity, sessionAuthorization, sessionStateValid, stateCookieMatches } from './github-oauth.ts'
|
|
12
11
|
import { ManagedMutationError } from './management.ts'
|
|
13
12
|
|
|
14
13
|
export const LINK_LOGIN_PATH = '/api/oauth/github/link'
|
|
15
14
|
// The profile page, where linking starts and its callback lands.
|
|
16
15
|
const PROFILE_PATH = '/my/profile'
|
|
17
|
-
const STATE_TTL_MS = 600_000
|
|
18
16
|
|
|
19
17
|
export function isLinkOAuthCallback(config: ManagedConfig, query: URLSearchParams, cookie: string | undefined): boolean {
|
|
20
|
-
|
|
21
|
-
return !!expected && safeEqual(query.get('state') ?? '', expected)
|
|
18
|
+
return stateCookieMatches(config, LINK_STATE_COOKIE, query, cookie)
|
|
22
19
|
}
|
|
23
20
|
|
|
24
21
|
// The state is bound to the session that started linking, so the account
|
|
25
22
|
// links to the user who asked, never to whoever is signed in on return.
|
|
26
23
|
export function linkLoginRedirect(config: ManagedConfig, session: ManagedSession, now = Date.now()): { location: string; setCookie: string } {
|
|
27
|
-
const
|
|
28
|
-
const url = new URL('https://github.com/login/oauth/authorize')
|
|
29
|
-
url.searchParams.set('client_id', config.githubClientId)
|
|
30
|
-
url.searchParams.set('redirect_uri', config.oauthCallbackUrl)
|
|
31
|
-
url.searchParams.set('state', state)
|
|
32
|
-
url.searchParams.set('allow_signup', 'false')
|
|
24
|
+
const { url, setCookie } = sessionAuthorization(config, LINK_STATE_COOKIE, session, now)
|
|
33
25
|
url.searchParams.set('prompt', 'select_account')
|
|
34
|
-
return { location: url.href, setCookie
|
|
35
|
-
{ secure: config.cookieSecure, maxAgeS: STATE_TTL_MS / 1000, sameSite: 'Lax' }) }
|
|
26
|
+
return { location: url.href, setCookie }
|
|
36
27
|
}
|
|
37
28
|
|
|
38
29
|
// Back from GitHub: link the account that authorized, then land on the
|
|
@@ -44,12 +35,8 @@ export async function linkOAuthCallback(config: ManagedConfig, db: ManagedDb, se
|
|
|
44
35
|
): Promise<{ location: string; setCookie: string; linked: string | null }> {
|
|
45
36
|
const setCookie = clearCookie(cookieName(config, LINK_STATE_COOKIE), config.cookieSecure)
|
|
46
37
|
try {
|
|
47
|
-
|
|
48
|
-
const code = query.get('code')
|
|
49
|
-
if (!state || !expected || !safeEqual(state, expected) || sessionId !== session.id
|
|
50
|
-
|| !timestamp || !Number.isFinite(started) || now < started || now - started > STATE_TTL_MS) {
|
|
51
|
-
throw new OAuthError(400, 'invalid-oauth-state')
|
|
52
|
-
}
|
|
38
|
+
if (!sessionStateValid(config, LINK_STATE_COOKIE, session, query, cookie, now)) throw new OAuthError(400, 'invalid-oauth-state')
|
|
39
|
+
const code = query.get('code')
|
|
53
40
|
// Declined on GitHub's side, which sends an error in place of a code.
|
|
54
41
|
if (!code) throw new OAuthError(400, query.get('error') ? 'github-authorization-declined' : 'invalid-oauth-state')
|
|
55
42
|
const tokens = await exchangeCode(config, code, now, fetchImpl)
|
|
@@ -4,14 +4,15 @@
|
|
|
4
4
|
import { Buffer } from 'node:buffer'
|
|
5
5
|
import type { AvatarStore } from './avatar-store.ts'
|
|
6
6
|
import type { ManagedConfig } from './config.ts'
|
|
7
|
-
import type { ManagedDb, ManagedUser, UserTokens } from './db.ts'
|
|
7
|
+
import type { ManagedDb, ManagedSession, ManagedUser, UserTokens } from './db.ts'
|
|
8
8
|
import { randomToken, safeEqual } from './crypto.ts'
|
|
9
|
+
import { GITHUB_API, githubHeaders } from './github-requests.ts'
|
|
9
10
|
import { STATE_COOKIE, buildCookie, clearCookie, cookieName, createSession, parseCookies } from './session.ts'
|
|
10
11
|
import { isViewing } from './view-as.ts'
|
|
11
12
|
|
|
12
13
|
const GITHUB_AUTHORIZE_URL = 'https://github.com/login/oauth/authorize'
|
|
13
14
|
const GITHUB_TOKEN_URL = 'https://github.com/login/oauth/access_token'
|
|
14
|
-
const GITHUB_USER_URL =
|
|
15
|
+
const GITHUB_USER_URL = `${GITHUB_API}/user`
|
|
15
16
|
const STATE_TTL_S = 600
|
|
16
17
|
|
|
17
18
|
export const LOGIN_PATH = '/api/oauth/github/login'
|
|
@@ -36,15 +37,45 @@ export interface CallbackDeps { config: ManagedConfig; db: ManagedDb; avatarStor
|
|
|
36
37
|
// grants are approved separately when installing the App.
|
|
37
38
|
export function buildLoginRedirect(config: ManagedConfig): { location: string; setCookie: string } {
|
|
38
39
|
const state = randomToken()
|
|
40
|
+
const setCookie = buildCookie(cookieName(config, STATE_COOKIE), state, {
|
|
41
|
+
maxAgeS: STATE_TTL_S, secure: config.cookieSecure, sameSite: 'Lax',
|
|
42
|
+
})
|
|
43
|
+
return { location: authorizeUrl(config, state).toString(), setCookie }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// GitHub's page authorizing the App, which sends `state` back to the callback.
|
|
47
|
+
function authorizeUrl(config: ManagedConfig, state: string): URL {
|
|
39
48
|
const u = new URL(GITHUB_AUTHORIZE_URL)
|
|
40
49
|
u.searchParams.set('client_id', config.githubClientId)
|
|
41
50
|
u.searchParams.set('redirect_uri', config.oauthCallbackUrl)
|
|
42
51
|
u.searchParams.set('state', state)
|
|
43
52
|
u.searchParams.set('allow_signup', 'false')
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
53
|
+
return u
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// An authorization a signed-in session starts (github-issue-oauth.ts,
|
|
57
|
+
// github-link-oauth.ts): GitHub's page, and the cookie `name` keeping its
|
|
58
|
+
// state bound to that session, `<state>.<session id>.<when set>`.
|
|
59
|
+
export function sessionAuthorization(config: ManagedConfig, name: string, session: ManagedSession, now: number): { url: URL; setCookie: string } {
|
|
60
|
+
const state = randomToken()
|
|
61
|
+
return { url: authorizeUrl(config, state), setCookie: buildCookie(cookieName(config, name), `${state}.${session.id}.${now}`,
|
|
62
|
+
{ secure: config.cookieSecure, maxAgeS: STATE_TTL_S, sameSite: 'Lax' }) }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Whether the `state` GitHub sent back is the one cookie `name` keeps: the
|
|
66
|
+
// callback is that authorization's.
|
|
67
|
+
export function stateCookieMatches(config: ManagedConfig, name: string, query: URLSearchParams, cookie: string | undefined): boolean {
|
|
68
|
+
const expected = parseCookies(cookie).get(cookieName(config, name))?.split('.')[0]
|
|
69
|
+
return !!expected && safeEqual(query.get('state') ?? '', expected)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Whether cookie `name` keeps the `state` GitHub sent back, bound to
|
|
73
|
+
// `session` (sessionAuthorization) no longer than STATE_TTL_S ago.
|
|
74
|
+
export function sessionStateValid(config: ManagedConfig, name: string, session: ManagedSession, query: URLSearchParams, cookie: string | undefined, now: number): boolean {
|
|
75
|
+
const [expected, sessionId, timestamp] = (parseCookies(cookie).get(cookieName(config, name)) ?? '').split('.')
|
|
76
|
+
const started = Number(timestamp), state = query.get('state')
|
|
77
|
+
return !!state && !!expected && safeEqual(state, expected) && sessionId === session.id
|
|
78
|
+
&& !!timestamp && Number.isFinite(started) && now >= started && now - started <= STATE_TTL_S * 1000
|
|
48
79
|
}
|
|
49
80
|
|
|
50
81
|
// GET /api/oauth/github/callback?code&state — the GitHub OAuth hook.
|
|
@@ -186,12 +217,7 @@ async function refreshStoredToken(
|
|
|
186
217
|
export async function fetchIdentity(token: string, fetchImpl: typeof fetch): Promise<ManagedUser> {
|
|
187
218
|
let res: Response
|
|
188
219
|
try {
|
|
189
|
-
res = await fetchImpl(GITHUB_USER_URL, {
|
|
190
|
-
headers: {
|
|
191
|
-
'authorization': `Bearer ${token}`, 'accept': 'application/vnd.github+json',
|
|
192
|
-
'user-agent': 'deepview-triage', 'x-github-api-version': '2022-11-28',
|
|
193
|
-
},
|
|
194
|
-
})
|
|
220
|
+
res = await fetchImpl(GITHUB_USER_URL, { headers: githubHeaders(token) })
|
|
195
221
|
} catch { throw new OAuthError(502, 'github-user-unreachable') }
|
|
196
222
|
if (!res.ok) throw new OAuthError(502, `github-user-status-${res.status}`)
|
|
197
223
|
let body: unknown
|
|
@@ -3,6 +3,7 @@ import type { ManagedConfig } from './config.ts'
|
|
|
3
3
|
import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
|
|
4
4
|
import type { GithubMetadata, GithubRepositoryVisibility } from './github-metadata.ts'
|
|
5
5
|
import { ensureUserAccessToken } from './github-oauth.ts'
|
|
6
|
+
import { GITHUB_API, githubHeaders, repoApi } from './github-requests.ts'
|
|
6
7
|
|
|
7
8
|
type Metadata = Pick<GithubMetadata, 'title' | 'description' | 'status' | 'stateReason'>
|
|
8
9
|
const MAX_GITHUB_LOOKUPS = 200
|
|
@@ -12,7 +13,7 @@ const CLOSED_RECHECK_EVERY = 10
|
|
|
12
13
|
const GITHUB_LOOKUP_TIMEOUT_MS = 10_000
|
|
13
14
|
const GITHUB_METADATA_TTL_MS = 60_000
|
|
14
15
|
const GITHUB_PUBLIC_VISIBILITY_TTL_MS = 60_000
|
|
15
|
-
const GITHUB_PRIVATE_REPOSITORIES_URL =
|
|
16
|
+
const GITHUB_PRIVATE_REPOSITORIES_URL = `${GITHUB_API}/user/repos?visibility=private&per_page=100&page=1`
|
|
16
17
|
|
|
17
18
|
type Repository = TeamReportAccessSnapshot['repositories'][number]
|
|
18
19
|
type RepositoryPayload = { id?: unknown; full_name?: unknown; private?: unknown; visibility?: unknown; permissions?: { pull?: unknown } }
|
|
@@ -28,16 +29,32 @@ type RepositoryAccessContext = {
|
|
|
28
29
|
includePrivateList?: boolean
|
|
29
30
|
}
|
|
30
31
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
32
|
+
// The workspace's repositories GitHub can name, by their lowercased names.
|
|
33
|
+
export function allowedRepositories(snapshot: TeamReportAccessSnapshot): Map<string, Repository> {
|
|
34
|
+
return new Map(snapshot.repositories.filter(repo => isGithubRepoName(repo.github)).map(repo => [repo.github.toLowerCase(), repo]))
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// `fetchImpl`, each request of it cut short at `signal`, and none started past it.
|
|
38
|
+
export function deadlineFetch(fetchImpl: typeof fetch, signal: AbortSignal): typeof fetch {
|
|
39
|
+
return (input, init) => {
|
|
40
|
+
signal.throwIfAborted()
|
|
41
|
+
return fetchImpl(input, { ...init, signal })
|
|
38
42
|
}
|
|
39
43
|
}
|
|
40
44
|
|
|
45
|
+
function githubRequest(token: string | null): RequestInit {
|
|
46
|
+
return { headers: githubHeaders(token || null), redirect: 'error' }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The repositories of `byId` that `visibility` found public, by the name they
|
|
50
|
+
// have still: one renamed since is not known public.
|
|
51
|
+
function foundPublic(visibility: GithubRepositoryVisibility[], byId: Map<number, Repository>): Repository[] {
|
|
52
|
+
return visibility.flatMap(entry => {
|
|
53
|
+
const repo = byId.get(entry.repoId)
|
|
54
|
+
return entry.public && repo?.github.toLowerCase() === entry.github.toLowerCase() ? [repo] : []
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
|
|
41
58
|
function repositoryMatches(repo: Repository, body: RepositoryPayload | null): boolean {
|
|
42
59
|
return body?.id === repo.repoId && typeof body.full_name === 'string' && body.full_name.toLowerCase() === repo.github.toLowerCase()
|
|
43
60
|
}
|
|
@@ -73,8 +90,7 @@ async function readableRepositories(repositories: Repository[], { db, visibility
|
|
|
73
90
|
if (repo && !readable.has(repo.github) && repositoryMatches(repo, entry) && entry?.permissions?.pull === true) grant(repo, entry, checkedAt)
|
|
74
91
|
}
|
|
75
92
|
}
|
|
76
|
-
const formerlyPublic = new Set(visibility.
|
|
77
|
-
&& byId.get(entry.repoId)?.github.toLowerCase() === entry.github.toLowerCase()).map(entry => entry.repoId))
|
|
93
|
+
const formerlyPublic = new Set(foundPublic(visibility, byId).map(repo => repo.repoId))
|
|
78
94
|
const pending = unverified.filter(repo => !readable.has(repo.github) && (token || formerlyPublic.has(repo.repoId))).slice(0, checks.remaining)
|
|
79
95
|
checks.remaining -= pending.length
|
|
80
96
|
for (let i = 0; i < pending.length && !signal.aborted; i += 4) {
|
|
@@ -82,7 +98,7 @@ async function readableRepositories(repositories: Repository[], { db, visibility
|
|
|
82
98
|
if (signal.aborted) return
|
|
83
99
|
const checkedAt = Date.now()
|
|
84
100
|
try {
|
|
85
|
-
const response = await fetchImpl(
|
|
101
|
+
const response = await fetchImpl(repoApi(repo.github), githubRequest(token))
|
|
86
102
|
if (!response.ok) return
|
|
87
103
|
const body = await response.json() as RepositoryPayload | null
|
|
88
104
|
if (!signal.aborted && body && repositoryMatches(repo, body)
|
|
@@ -112,7 +128,7 @@ async function verifyPublicRefreshes(config: ManagedConfig, userId: string, repo
|
|
|
112
128
|
// owner/repo/path taken from a Fix URL. Redirects cannot move the user token.
|
|
113
129
|
async function fetchMetadata(ref: GithubFixRef, token: string | null, fetchImpl: typeof fetch): Promise<Metadata | null> {
|
|
114
130
|
try {
|
|
115
|
-
const response = await fetchImpl(
|
|
131
|
+
const response = await fetchImpl(`${repoApi(ref.repo)}/${ref.kind === 'pull' ? 'pulls' : 'issues'}/${ref.number}`, githubRequest(token))
|
|
116
132
|
if (!response.ok) return null
|
|
117
133
|
const body = await response.json() as { number?: unknown; title?: unknown; body?: unknown; state?: unknown; merged?: unknown;
|
|
118
134
|
draft?: unknown; base?: { repo?: { full_name?: unknown } }; repository_url?: unknown; pull_request?: unknown; state_reason?: unknown } | null
|
|
@@ -127,7 +143,7 @@ async function fetchMetadata(ref: GithubFixRef, token: string | null, fetchImpl:
|
|
|
127
143
|
// The issues API also accepts PR numbers. Do not cache a PR as a closed
|
|
128
144
|
// ordinary issue: only the pulls API can establish its merged state.
|
|
129
145
|
if (body.pull_request != null || typeof body.repository_url !== 'string'
|
|
130
|
-
|| body.repository_url.toLowerCase() !==
|
|
146
|
+
|| body.repository_url.toLowerCase() !== repoApi(ref.repo).toLowerCase()) return null
|
|
131
147
|
status = body.state === 'closed' ? 'closed' : 'open'
|
|
132
148
|
}
|
|
133
149
|
const stateReason = ref.kind === 'issue' && status === 'closed' ? githubIssueClosedReason(body.state_reason) : null
|
|
@@ -165,7 +181,7 @@ function readsOf<Entry extends [string, GithubFixRef]>(entries: Entry[], metadat
|
|
|
165
181
|
// Shared private metadata also requires this viewer's live GitHub access,
|
|
166
182
|
// including for admins. Only recently verified public repos skip that check.
|
|
167
183
|
export async function lookupFixes(config: ManagedConfig, db: ManagedDb, snapshot: TeamReportAccessSnapshot, urls: string[], fetchImpl: typeof fetch = globalThis.fetch): Promise<GithubFixResult[]> {
|
|
168
|
-
const allowed =
|
|
184
|
+
const allowed = allowedRepositories(snapshot)
|
|
169
185
|
const parsed = urls.map(parseGithubFixUrl)
|
|
170
186
|
const jobs = new Map<string, GithubFixRef>()
|
|
171
187
|
const keys = parsed.map(ref => {
|
|
@@ -178,19 +194,15 @@ export async function lookupFixes(config: ManagedConfig, db: ManagedDb, snapshot
|
|
|
178
194
|
if (jobs.size === 0) return []
|
|
179
195
|
const now = Date.now()
|
|
180
196
|
const signal = AbortSignal.timeout(GITHUB_LOOKUP_TIMEOUT_MS)
|
|
181
|
-
const fetchWithinDeadline
|
|
182
|
-
|
|
183
|
-
return fetchImpl(input, { ...init, signal })
|
|
184
|
-
}
|
|
185
|
-
const repositories = [...new Map([...jobs.values()].map(ref => {
|
|
197
|
+
const fetchWithinDeadline = deadlineFetch(fetchImpl, signal)
|
|
198
|
+
const byId = new Map([...jobs.values()].map(ref => {
|
|
186
199
|
const repo = allowed.get(ref.repo.toLowerCase())!
|
|
187
200
|
return [repo.repoId, repo] as const
|
|
188
|
-
}))
|
|
201
|
+
}))
|
|
202
|
+
const repositories = [...byId.values()]
|
|
189
203
|
const visibility = await db.listGithubRepositoryVisibility(repositories.map(repo => repo.repoId))
|
|
190
|
-
const
|
|
191
|
-
|
|
192
|
-
&& entry.checkedAt + GITHUB_PUBLIC_VISIBILITY_TTL_MS > now
|
|
193
|
-
&& byId.get(entry.repoId)?.github.toLowerCase() === entry.github.toLowerCase()).map(entry => byId.get(entry.repoId)!.github))
|
|
204
|
+
const publicRepos = new Set(foundPublic(visibility.filter(entry => entry.checkedAt <= now
|
|
205
|
+
&& entry.checkedAt + GITHUB_PUBLIC_VISIBILITY_TTL_MS > now), byId).map(repo => repo.github))
|
|
194
206
|
let token = repositories.some(repo => !publicRepos.has(repo.github))
|
|
195
207
|
? await ensureUserAccessToken(config, db, snapshot.user.id, now, fetchWithinDeadline) : null
|
|
196
208
|
const checks: RepositoryChecks = { remaining: MAX_GITHUB_LOOKUPS, verified: new Set() }
|
|
@@ -228,8 +240,7 @@ export async function lookupFixes(config: ManagedConfig, db: ManagedDb, snapshot
|
|
|
228
240
|
// Another request may already have discovered a public -> private change
|
|
229
241
|
// and written new private metadata. Honor that newer visibility observation.
|
|
230
242
|
const current = await db.listGithubRepositoryVisibility(repositories.filter(repo => publicRepos.has(repo.github)).map(repo => repo.repoId))
|
|
231
|
-
const stillPublic = new Set(current.
|
|
232
|
-
&& byId.get(entry.repoId)?.github.toLowerCase() === entry.github.toLowerCase()).map(entry => byId.get(entry.repoId)!.github))
|
|
243
|
+
const stillPublic = new Set(foundPublic(current, byId).map(repo => repo.github))
|
|
233
244
|
for (const [key, ref] of authorized) if (publicRepos.has(ref.repo) && !stillPublic.has(ref.repo)) metadata.delete(key)
|
|
234
245
|
}
|
|
235
246
|
// The handler rechecks workspace access and saved Fix links before returning.
|
|
@@ -2,15 +2,25 @@ import { createHash } from 'node:crypto'
|
|
|
2
2
|
import { GithubApiError, githubUnreachable, throwGithubResponseError } from './github-errors.ts'
|
|
3
3
|
import { timed } from './request-timing.ts'
|
|
4
4
|
|
|
5
|
-
const
|
|
5
|
+
export const GITHUB_API = 'https://api.github.com'
|
|
6
|
+
export const API_VERSION = '2022-11-28'
|
|
6
7
|
export const USER_AGENT = 'deepview-triage'
|
|
7
8
|
|
|
9
|
+
// What GitHub's REST API is asked with: its media type and version, as
|
|
10
|
+
// USER_AGENT, and `token` as Bearer where there is one (githubJson and the
|
|
11
|
+
// readers that ask GitHub themselves).
|
|
12
|
+
export const githubHeaders = (token: string | null) => ({
|
|
13
|
+
...(token == null ? {} : { authorization: `Bearer ${token}` }), 'accept': 'application/vnd.github+json',
|
|
14
|
+
'user-agent': USER_AGENT, 'x-github-api-version': API_VERSION,
|
|
15
|
+
})
|
|
16
|
+
|
|
8
17
|
// Only outstanding reads: a completed answer (or failure) is never reused.
|
|
9
18
|
// Keep transports and credentials separate, including anonymous reads. When
|
|
10
19
|
// full, new reads proceed normally rather than waiting for an unrelated one.
|
|
11
20
|
const MAX_PENDING_READS = 1000
|
|
12
21
|
type PendingRead = { promise: Promise<unknown>; shared: boolean }
|
|
13
22
|
const pendingReads = new WeakMap<typeof fetch, Map<string, PendingRead>>()
|
|
23
|
+
const requestKey = (request: string) => createHash('sha256').update(request).digest('hex')
|
|
14
24
|
|
|
15
25
|
// Invalidate installation credentials and access verdicts when GitHub rejects
|
|
16
26
|
// a token, including when several callers share the rejected request.
|
|
@@ -18,7 +28,7 @@ const rejectedTokenListeners = new Set<(token: string, fetchImpl: typeof fetch)
|
|
|
18
28
|
export function onTokenRejected(listener: (token: string, fetchImpl: typeof fetch) => void): void {
|
|
19
29
|
rejectedTokenListeners.add(listener)
|
|
20
30
|
}
|
|
21
|
-
|
|
31
|
+
function tokenRejected(token: string, fetchImpl: typeof fetch): void {
|
|
22
32
|
for (const listener of rejectedTokenListeners) listener(token, fetchImpl)
|
|
23
33
|
}
|
|
24
34
|
|
|
@@ -26,7 +36,7 @@ export async function shareGithubRead<T>(fetchImpl: typeof fetch, request: strin
|
|
|
26
36
|
let pending = pendingReads.get(fetchImpl)
|
|
27
37
|
if (!pending) { pending = new Map(); pendingReads.set(fetchImpl, pending) }
|
|
28
38
|
// The request includes credentials and query variables. Retain only its hash.
|
|
29
|
-
const key =
|
|
39
|
+
const key = requestKey(request)
|
|
30
40
|
const held = pending.get(key)
|
|
31
41
|
if (held) {
|
|
32
42
|
held.shared = true
|
|
@@ -65,7 +75,6 @@ const taggedOf = (fetchImpl: typeof fetch) => {
|
|
|
65
75
|
if (!tagged) taggedReads.set(fetchImpl, tagged = { reads: new Map(), bytes: 0 })
|
|
66
76
|
return tagged
|
|
67
77
|
}
|
|
68
|
-
const requestKey = (request: string) => createHash('sha256').update(request).digest('hex')
|
|
69
78
|
// A GET's request as its answer is kept by: its URL and credential.
|
|
70
79
|
const taggedRequest = (url: string, token: string | null) => JSON.stringify([url, token?.startsWith('ghs_') ? { installation: true } : token])
|
|
71
80
|
|
|
@@ -79,7 +88,7 @@ export function keepTaggedReadsIn(store: TaggedStore | null): void { taggedStore
|
|
|
79
88
|
// The answer kept to `request`, its ETag and body as GitHub wrote it: as
|
|
80
89
|
// this process holds it, else, where a store is kept beyond it, as that
|
|
81
90
|
// keeps it.
|
|
82
|
-
|
|
91
|
+
function taggedRead(fetchImpl: typeof fetch, request: string): TaggedRead | undefined | Promise<TaggedRead | undefined> {
|
|
83
92
|
const { reads } = taggedOf(fetchImpl)
|
|
84
93
|
const key = requestKey(request)
|
|
85
94
|
const read = reads.get(key)
|
|
@@ -94,7 +103,7 @@ async function storedTaggedRead(fetchImpl: typeof fetch, key: string, store: Tag
|
|
|
94
103
|
}
|
|
95
104
|
|
|
96
105
|
// `text` kept as GitHub's answer to `request`, by its ETag.
|
|
97
|
-
|
|
106
|
+
async function keepTaggedRead(fetchImpl: typeof fetch, request: string, etag: string, text: string): Promise<void> {
|
|
98
107
|
const key = requestKey(request)
|
|
99
108
|
holdTaggedRead(fetchImpl, key, { etag, text })
|
|
100
109
|
if (text.length <= MAX_STORED_READ_BYTES) await taggedStore?.write(key, { etag, text }).catch(() => {})
|
|
@@ -113,6 +122,11 @@ function holdTaggedRead(fetchImpl: typeof fetch, key: string, read: TaggedRead)
|
|
|
113
122
|
}
|
|
114
123
|
}
|
|
115
124
|
|
|
125
|
+
// `path` (a repository's full name, a branch, a file's path) with each of its
|
|
126
|
+
// segments URL-encoded, and the REST API's URL of the repository `fullName`.
|
|
127
|
+
export const encodedPath = (path: string) => path.split('/').map(encodeURIComponent).join('/')
|
|
128
|
+
export const repoApi = (fullName: string) => `${GITHUB_API}/repos/${encodedPath(fullName)}`
|
|
129
|
+
|
|
116
130
|
// One GitHub API call returning parsed JSON, optionally Bearer-authed by a
|
|
117
131
|
// user token, App JWT, or installation token, `body` sent as JSON (a GraphQL
|
|
118
132
|
// query's, given longer to answer). Network / non-2xx / malformed fold into a
|
|
@@ -137,8 +151,7 @@ export function githubJson(url: string, token: string | null, fetchImpl: typeof
|
|
|
137
151
|
signal: AbortSignal.timeout(body === undefined ? 10_000 : 20_000),
|
|
138
152
|
redirect: 'error',
|
|
139
153
|
headers: {
|
|
140
|
-
...(token
|
|
141
|
-
...(body === undefined ? {} : { 'content-type': 'application/json' }), 'user-agent': USER_AGENT, 'x-github-api-version': API_VERSION,
|
|
154
|
+
...githubHeaders(token), ...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
|
142
155
|
...(tagged ? { 'if-none-match': tagged.etag } : {}),
|
|
143
156
|
},
|
|
144
157
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Values as GitHub's REST and GraphQL APIs answer them, as the repository
|
|
2
|
+
// readers keep them (repository-history.ts, commit-coauthors.ts, pull-reviews.ts
|
|
3
|
+
// and the Issues, Agents and Pulse tabs' readers): any other value none.
|
|
4
|
+
|
|
5
|
+
export const MAX_NAME = 256
|
|
6
|
+
// A login of GitHub's: a user's, an organization's or a GitHub App's bot's.
|
|
7
|
+
export const LOGIN = /^[A-Za-z\d][A-Za-z\d-]{0,38}(?:\[bot\])?$/u
|
|
8
|
+
// A commit's or a blob's id, as GitHub names one.
|
|
9
|
+
export const SHA = /^[a-f\d]{40}$/u
|
|
10
|
+
|
|
11
|
+
// A time GitHub names as an ISO 8601 date, in milliseconds since the epoch.
|
|
12
|
+
export const timeOf = (value: unknown) => {
|
|
13
|
+
const at = typeof value === 'string' ? Date.parse(value) : Number.NaN
|
|
14
|
+
return Number.isSafeInteger(at) ? at : null
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// An id or a number GitHub gives (an account's, a repository's, an issue's):
|
|
18
|
+
// a positive integer.
|
|
19
|
+
export const isId = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) > 0
|
|
20
|
+
|
|
21
|
+
// A count GitHub gives, 0 where it gives none.
|
|
22
|
+
export const count = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0 ? value as number : 0
|
|
23
|
+
|
|
24
|
+
// A name or text GitHub gives, trimmed, as much of it as `max` characters;
|
|
25
|
+
// null where it is empty.
|
|
26
|
+
export const nameOf = (value: unknown, max = MAX_NAME) => typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : null
|
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
// walk later, from a head moved on or in the Commits tab, reads them kept.
|
|
8
8
|
import { linkNoreplyUsers } from './github-accounts.ts'
|
|
9
9
|
import { githubGraphql } from './github-graphql.ts'
|
|
10
|
-
import { COMMIT_FRAGMENT, type GraphCommit, HISTORY_PAGE, type HistoryCommit, type HistoryPages, PAGES_PARALLEL, PAGES_PER_QUERY, commitActors, graphCommit,
|
|
11
|
-
inBatches, variablesOf } from './repository-history.ts'
|
|
10
|
+
import { COMMIT_FRAGMENT, type Connection, type GraphCommit, HISTORY_PAGE, type HistoryCommit, type HistoryPages, PAGES_PARALLEL, PAGES_PER_QUERY, commitActors, graphCommit,
|
|
11
|
+
inBatches, nextCursor, variablesOf } from './repository-history.ts'
|
|
12
12
|
|
|
13
13
|
// Windows a read is split into at most, each meant to hold as many commits
|
|
14
14
|
// as WINDOW_COMMITS, a page's worth with room to spare, as often as the
|
|
@@ -39,7 +39,7 @@ const windowsQuery = (count: number) => `query($owner: String!, $name: String!,
|
|
|
39
39
|
${COMMIT_FRAGMENT}`
|
|
40
40
|
|
|
41
41
|
type Window = { since: number | null; until: number; after: string | null; oldest?: number }
|
|
42
|
-
type WindowPage =
|
|
42
|
+
type WindowPage = Connection<GraphCommit> | null
|
|
43
43
|
type Windows = { repository?: { object?: Record<string, WindowPage> | null } | null } | null
|
|
44
44
|
// A time as GitHub takes it, to the second: a window's start rounded down,
|
|
45
45
|
// its end up, so that those beside each other overlap rather than part.
|
|
@@ -55,7 +55,7 @@ const stamp = (at: number, up: boolean) => new Date((up ? Math.ceil : Math.floor
|
|
|
55
55
|
// made of those it read, as GitHub lists them the latest made first, those
|
|
56
56
|
// made together left out; or its end, none read), and how many pages were
|
|
57
57
|
// read (`read`).
|
|
58
|
-
|
|
58
|
+
async function readWindows(fullName: string, token: string, head: string, low: number, high: number, perMs: number, fetchImpl: typeof fetch) {
|
|
59
59
|
const [owner, name] = fullName.split('/') as [string, string]
|
|
60
60
|
const bottom = Math.max(low, high - MAX_WINDOWS * WINDOW_COMMITS / perMs)
|
|
61
61
|
const count = Math.min(MAX_WINDOWS, Math.max(1, Math.ceil((high - bottom) * perMs / WINDOW_COMMITS)))
|
|
@@ -79,8 +79,8 @@ export async function readWindows(fullName: string, token: string, head: string,
|
|
|
79
79
|
if (!commits.has(commit.sha)) commits.set(commit.sha, commit)
|
|
80
80
|
oldest = Math.min(oldest, commit.committedAt ?? Number.POSITIVE_INFINITY)
|
|
81
81
|
}
|
|
82
|
-
const
|
|
83
|
-
if (window.since !== null &&
|
|
82
|
+
const after = nextCursor(pages[at]?.pageInfo)
|
|
83
|
+
if (window.since !== null && after !== null) next.push({ ...window, after, oldest })
|
|
84
84
|
}
|
|
85
85
|
})
|
|
86
86
|
open = [...next, ...open.slice(wave.length)]
|
|
@@ -122,7 +122,7 @@ export function gitLogPage(top: string, known: Map<string, HistoryCommit>, low:
|
|
|
122
122
|
// parents of those they list that none of `listed` is nor any kept lists, on
|
|
123
123
|
// till none is left, as many as MAX_KEPT: as a walk reading pages goes on to
|
|
124
124
|
// them.
|
|
125
|
-
|
|
125
|
+
async function keepPages(tops: string[], known: Map<string, HistoryCommit>, listed: Set<string>, low: number, pages: HistoryPages) {
|
|
126
126
|
const covered = new Set(listed)
|
|
127
127
|
const kept: [string, HistoryCommit[]][] = []
|
|
128
128
|
const waiting = [...tops]
|