-
Notifications
You must be signed in to change notification settings - Fork 731
Expand file tree
/
Copy pathfetchLightRepo.ts
More file actions
276 lines (248 loc) · 9.32 KB
/
Copy pathfetchLightRepo.ts
File metadata and controls
276 lines (248 loc) · 9.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import { getServiceChildLogger } from '@crowd/logging'
import { FetchError, LightRepoResult } from './types'
import {
RepoTrees,
TreeEntryNode,
classifyWellKnownFiles,
deriveSecurityFileEnabled,
} from './wellKnownFiles'
const log = getServiceChildLogger('fetch-light-repo')
const GITHUB_API_URL = 'https://api.github.com'
const REPO_QUERY = `
query($owner: String!, $name: String!) {
rateLimit { limit cost remaining resetAt }
repository(owner: $owner, name: $name) {
description
primaryLanguage { name }
repositoryTopics(first: 25) { nodes { topic { name } } }
stargazerCount
forkCount
watchers { totalCount }
issues(states: OPEN) { totalCount }
pushedAt
isArchived
isDisabled
isFork
createdAt
isSecurityPolicyEnabled
defaultBranchRef { name }
rootTree: object(expression: "HEAD:") {
... on Tree { entries { name type oid } }
}
githubTree: object(expression: "HEAD:.github") {
... on Tree { entries { name type oid } }
}
docsTree: object(expression: "HEAD:docs") {
... on Tree { entries { name type oid } }
}
}
}
`
export function parseGithubUrl(url: string): { owner: string; name: string } {
const match = url.match(/https?:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/)
if (!match) throw new FetchError('MALFORMED', `Cannot parse GitHub URL: ${url}`)
return { owner: match[1], name: match[2] }
}
interface BranchProtection {
enabled: boolean | null
requiredReviews: number | null
requiresStatusChecks: boolean | null
allowsForcePush: boolean | null
}
const UNKNOWN_PROTECTION: BranchProtection = {
enabled: null,
requiredReviews: null,
requiresStatusChecks: null,
allowsForcePush: null,
}
interface BranchRule {
type: string
parameters?: { required_approving_review_count?: number }
}
async function restGet(path: string, token: string, timeoutMs: number): Promise<Response> {
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), timeoutMs)
try {
const response = await fetch(`${GITHUB_API_URL}${path}`, {
headers: { Authorization: `bearer ${token}`, Accept: 'application/vnd.github+json' },
signal: controller.signal,
})
if (response.status === 403) {
const body = await response.text()
if (body.toLowerCase().includes('rate limit')) {
const retryAfterSec = parseInt(response.headers.get('retry-after') ?? '0', 10)
const resetSec = parseInt(response.headers.get('x-ratelimit-reset') ?? '0', 10)
const resetMs = retryAfterSec
? Date.now() + retryAfterSec * 1000
: resetSec
? resetSec * 1000 + 5_000
: Date.now() + 65_000
throw new FetchError('RATE_LIMIT', `Rate limited on ${path}`, resetMs)
}
}
return response
} finally {
clearTimeout(timeoutId)
}
}
async function fetchBranchProtection(
url: string,
owner: string,
name: string,
branch: string,
token: string,
timeoutMs: number,
): Promise<BranchProtection> {
try {
const branchResp = await restGet(
`/repos/${owner}/${name}/branches/${encodeURIComponent(branch)}`,
token,
timeoutMs,
)
if (branchResp.status !== 200) return UNKNOWN_PROTECTION
const { protected: isProtected } = (await branchResp.json()) as { protected?: boolean }
if (!isProtected) {
return {
enabled: false,
requiredReviews: 0,
requiresStatusChecks: false,
allowsForcePush: true,
}
}
const rulesResp = await restGet(
`/repos/${owner}/${name}/rules/branches/${encodeURIComponent(branch)}?per_page=100`,
token,
timeoutMs,
)
if (rulesResp.status !== 200) return { ...UNKNOWN_PROTECTION, enabled: true }
const rules = (await rulesResp.json()) as BranchRule[]
if (rules.length === 0) return { ...UNKNOWN_PROTECTION, enabled: true }
const pullRequestRule = rules.find((r) => r.type === 'pull_request')
// Absent rule types stay null, not false: classic protection can coexist with rulesets
// on the same branch and its rules are invisible without admin access
return {
enabled: true,
requiredReviews: pullRequestRule?.parameters?.required_approving_review_count ?? null,
requiresStatusChecks: rules.some((r) => r.type === 'required_status_checks') ? true : null,
allowsForcePush: rules.some((r) => r.type === 'non_fast_forward') ? false : null,
}
} catch (err) {
if (err instanceof FetchError && err.kind === 'RATE_LIMIT') throw err
log.warn(
{ url, errName: (err as Error).name, errMsg: (err as Error).message },
'Branch protection check failed — fields will be null',
)
return UNKNOWN_PROTECTION
}
}
interface RepoGraphqlResponse {
data?: {
rateLimit: { limit: number; cost: number; remaining: number; resetAt: string }
repository: {
description: string | null
primaryLanguage: { name: string } | null
repositoryTopics: { nodes: Array<{ topic: { name: string } }> }
stargazerCount: number
forkCount: number
watchers: { totalCount: number }
issues: { totalCount: number }
pushedAt: string | null
isArchived: boolean
isDisabled: boolean
isFork: boolean
createdAt: string
isSecurityPolicyEnabled: boolean
defaultBranchRef: { name: string } | null
rootTree: { entries?: TreeEntryNode[] } | null
githubTree: { entries?: TreeEntryNode[] } | null
docsTree: { entries?: TreeEntryNode[] } | null
} | null
}
errors?: Array<{ type?: string; message?: string }>
}
export async function fetchLightRepo(
url: string,
token: string,
timeoutMs: number,
): Promise<LightRepoResult> {
const { owner, name } = parseGithubUrl(url)
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), timeoutMs)
let response: Response
try {
response = await fetch(`${GITHUB_API_URL}/graphql`, {
method: 'POST',
headers: {
Authorization: `bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query: REPO_QUERY, variables: { owner, name } }),
signal: controller.signal,
})
} catch (err) {
throw new FetchError('TRANSIENT', `Network error for ${url}: ${(err as Error).message}`)
} finally {
clearTimeout(timeoutId)
}
const resetSec = parseInt(response.headers.get('x-ratelimit-reset') ?? '0', 10)
const resetMs = resetSec ? resetSec * 1000 + 5_000 : Date.now() + 65_000
// 401 is requester/platform-side (bad token, GitHub auth incident) — never a repo signal
if (response.status === 401) throw new FetchError('TRANSIENT', `401 Unauthorized for ${url}`)
if (response.status === 403) {
const body = await response.text()
if (body.toLowerCase().includes('rate limit'))
throw new FetchError('RATE_LIMIT', `Rate limited on ${url}`, resetMs)
throw new FetchError('AUTH', `403 Forbidden for ${url}`)
}
if (response.status === 404) throw new FetchError('NOT_FOUND', `404 for ${url}`)
if (response.status >= 500) throw new FetchError('TRANSIENT', `${response.status} for ${url}`)
const json = (await response.json()) as RepoGraphqlResponse
if (json.errors?.length) {
const err = json.errors[0]
if (err.type === 'RATE_LIMITED' || err.message?.toLowerCase().includes('rate limit'))
throw new FetchError('RATE_LIMIT', `RATE_LIMITED for ${url}`, resetMs)
if (err.type === 'NOT_FOUND') throw new FetchError('NOT_FOUND', `NOT_FOUND for ${url}`)
if (err.message?.toLowerCase().includes('ip allow list'))
throw new FetchError('AUTH', `IP allowlist blocks access to ${url}`)
throw new FetchError('TRANSIENT', `GraphQL error for ${url}: ${err.message ?? err.type}`)
}
const repo = json.data?.repository
if (!repo) throw new FetchError('NOT_FOUND', `No repository data for ${url}`)
const trees: RepoTrees = {
root: repo.rootTree?.entries ?? null,
github: repo.githubTree?.entries ?? null,
docs: repo.docsTree?.entries ?? null,
}
const defaultBranch = repo.defaultBranchRef?.name ?? null
const branchProtection = defaultBranch
? await fetchBranchProtection(url, owner, name, defaultBranch, token, timeoutMs)
: UNKNOWN_PROTECTION
return {
url,
host: 'github',
owner,
name,
description: repo.description ?? null,
primaryLanguage: repo.primaryLanguage?.name ?? null,
topics: (repo.repositoryTopics?.nodes ?? []).map(
(n: { topic: { name: string } }) => n.topic.name,
),
stars: repo.stargazerCount ?? null,
forks: repo.forkCount ?? null,
watchers: repo.watchers?.totalCount ?? null,
openIssues: repo.issues?.totalCount ?? null,
lastCommitAt: repo.pushedAt ?? null,
archived: repo.isArchived ?? null,
disabled: repo.isDisabled ?? null,
isFork: repo.isFork ?? null,
createdAt: repo.createdAt ?? null,
securityPolicyEnabled: repo.isSecurityPolicyEnabled ?? null,
securityFileEnabled: deriveSecurityFileEnabled(trees),
wellKnownFiles: classifyWellKnownFiles(trees),
branchProtectionEnabled: branchProtection.enabled,
branchProtectionRequiredReviews: branchProtection.requiredReviews,
branchProtectionRequiresStatusChecks: branchProtection.requiresStatusChecks,
branchProtectionAllowsForcePush: branchProtection.allowsForcePush,
rateLimit: json.data?.rateLimit ?? null,
}
}