-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathgithub.mts
More file actions
646 lines (590 loc) · 18.8 KB
/
github.mts
File metadata and controls
646 lines (590 loc) · 18.8 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
/**
* GitHub utilities for Socket CLI.
* Provides GitHub API integration for repository operations and GHSA vulnerability data.
*
* Authentication:
* - getGitHubToken: Retrieve GitHub token from env/git config
* - getOctokit: Get authenticated Octokit instance
* - getOctokitGraphql: Get authenticated GraphQL client
*
* Caching:
* - 5-minute TTL for API responses
* - Automatic cache invalidation
* - Persistent cache in node_modules/.cache
*
* GHSA Operations:
* - cacheFetch: Cache API responses with TTL
* - fetchGhsaDetails: Fetch GitHub Security Advisory details
* - getGhsaUrl: Generate GHSA advisory URL
* - readCache/writeCache: Persistent cache operations
*
* Repository Operations:
* - GraphQL queries for complex operations
* - Integration with Octokit REST API
* - Support for GitHub Actions environment variables
*/
import { promises as fs } from 'node:fs'
import path from 'node:path'
import {
GraphqlResponseError,
graphql as OctokitGraphql,
} from '@octokit/graphql'
import { RequestError } from '@octokit/request-error'
import { Octokit } from '@octokit/rest'
import { LRUCache } from 'lru-cache'
import { debugDirNs, debugNs, isDebugNs } from '@socketsecurity/lib/debug'
import { readJson, safeMkdir, writeJson } from '@socketsecurity/lib/fs'
import { spawn } from '@socketsecurity/lib/spawn'
import { parseUrl } from '@socketsecurity/lib/url'
import { DISABLE_GITHUB_CACHE } from '../../env/disable-github-cache.mts'
import { GITHUB_API_URL } from '../../env/github-api-url.mts'
import { GITHUB_SERVER_URL } from '../../env/github-server-url.mts'
import { SOCKET_CLI_GITHUB_TOKEN } from '../../env/socket-cli-github-token.mts'
import { getGithubCachePath } from '../../constants/paths.mts'
import { formatErrorWithDetail } from '../error/errors.mts'
import type { CResult } from '../../types.mts'
import type { components } from '@octokit/openapi-types'
import type { JsonContent } from '@socketsecurity/lib/fs'
import type { SpawnOptions } from '@socketsecurity/lib/spawn'
export type Pr = components['schemas']['pull-request']
// Canonical `message` values returned by `handleGitHubApiError` /
// `handleGraphqlError`. Exported so callers can short-circuit on
// blocking conditions without matching free-form strings.
export const GITHUB_ERR_ABUSE_DETECTION = 'GitHub abuse detection triggered'
export const GITHUB_ERR_AUTH_FAILED = 'GitHub authentication failed'
export const GITHUB_ERR_GRAPHQL_RATE_LIMIT =
'GitHub GraphQL rate limit exceeded'
export const GITHUB_ERR_RATE_LIMIT = 'GitHub rate limit exceeded'
interface CacheEntry {
timestamp: number
data: JsonContent
}
async function readCache(
key: string,
// 5 minute in milliseconds time to live (TTL).
ttlMs = 5 * 60 * 1000,
): Promise<JsonContent | undefined> {
const githubCachePath = getGithubCachePath()
const cacheJsonPath = path.join(githubCachePath, `${key}.json`)
try {
const entry = (await readJson(cacheJsonPath)) as CacheEntry | JsonContent
// Handle both new format (with timestamp) and legacy format (without).
if (
entry &&
typeof entry === 'object' &&
'timestamp' in entry &&
'data' in entry
) {
const isExpired = Date.now() - (entry.timestamp as number) > ttlMs
if (!isExpired) {
return entry.data
}
} else {
// Legacy format without timestamp - treat as expired.
return undefined
}
} catch {
return undefined
}
return undefined
}
export async function writeCache(
key: string,
data: JsonContent,
): Promise<void> {
const githubCachePath = getGithubCachePath()
const cacheJsonPath = path.join(githubCachePath, `${key}.json`)
// Create directory with recursive flag that doesn't fail if exists.
await safeMkdir(githubCachePath, { recursive: true })
const entry: CacheEntry = {
timestamp: Date.now(),
data,
}
// Use atomic write pattern to prevent multi-process race conditions.
const tmpPath = `${cacheJsonPath}.tmp.${process.pid}`
await writeJson(tmpPath, entry)
await fs.rename(tmpPath, cacheJsonPath)
}
// In-memory promise cache to prevent concurrent fetches for the same key.
// LRU cache with max size to prevent unbounded memory growth.
const inflightRequests = new LRUCache<string, Promise<unknown>>({ max: 100 })
export async function cacheFetch<T>(
key: string,
fetcher: () => Promise<T>,
ttlMs?: number | undefined,
): Promise<T> {
// Optionally disable cache.
if (DISABLE_GITHUB_CACHE) {
return await fetcher()
}
// Check if already fetching this key to prevent TOCTOU race.
const inflight = inflightRequests.get(key)
if (inflight) {
return inflight as Promise<T>
}
try {
let data = (await readCache(key, ttlMs)) as T
if (!data) {
// Re-check inflight after async readCache to prevent race.
const inflightAfterRead = inflightRequests.get(key)
if (inflightAfterRead) {
return inflightAfterRead as Promise<T>
}
const fetchPromise = (async () => {
try {
const result = await fetcher()
await writeCache(key, result as JsonContent)
return result
} finally {
inflightRequests.delete(key)
}
})()
inflightRequests.set(key, fetchPromise)
data = await fetchPromise
}
return data
} catch (e) {
// Fetch promise's finally block handles cleanup - no action needed here.
throw e
}
}
export type GhsaDetails = {
ghsaId: string
cveId?: string | undefined
summary: string
severity: string
publishedAt: string
withdrawnAt?: string | undefined
references: Array<{
url: string
}>
vulnerabilities: {
nodes: Array<{
package: {
ecosystem: string
name: string
}
vulnerableVersionRange: string
}>
}
}
export async function fetchGhsaDetails(
ids: string[],
): Promise<Map<string, GhsaDetails>> {
const results = new Map<string, GhsaDetails>()
if (!ids.length) {
return results
}
const octokitGraphql = getOctokitGraphql()
try {
// Use '::' delimiter to avoid collisions (GHSA IDs contain hyphens).
const gqlCacheKey = `${ids.join('::')}-graphql-snapshot`
const aliases = ids
.map(
(id, index) =>
`advisory${index}: securityAdvisory(ghsaId: "${id}") {
ghsaId
summary
severity
publishedAt
withdrawnAt
vulnerabilities(first: 10) {
nodes {
package {
ecosystem
name
}
vulnerableVersionRange
}
}
}`,
)
.join('\n')
const gqlResp = await cacheFetch(gqlCacheKey, () =>
octokitGraphql(`
query {
${aliases}
}
`),
)
for (let i = 0, { length } = ids; i < length; i += 1) {
const id = ids[i]!
const advisoryKey = `advisory${i}`
const advisory = (gqlResp as any)?.[advisoryKey]
if (advisory?.ghsaId) {
results.set(id, advisory as GhsaDetails)
} else {
debugNs('notice', `miss: no advisory found for ${id}`)
}
}
} catch (e) {
debugNs('error', formatErrorWithDetail('Failed to fetch GHSA details', e))
debugDirNs('error', e)
}
return results
}
let _octokit: Octokit | undefined
export function getOctokit(): Octokit {
if (_octokit === undefined) {
if (!SOCKET_CLI_GITHUB_TOKEN) {
debugNs('notice', 'miss: SOCKET_CLI_GITHUB_TOKEN env var')
}
const octokitOptions = {
...(SOCKET_CLI_GITHUB_TOKEN ? { auth: SOCKET_CLI_GITHUB_TOKEN } : {}),
...(GITHUB_API_URL ? { baseUrl: GITHUB_API_URL } : {}),
}
debugDirNs('inspect', { octokitOptions })
_octokit = new Octokit(octokitOptions)
}
return _octokit
}
let _octokitGraphql: typeof OctokitGraphql | undefined
export function getOctokitGraphql(): typeof OctokitGraphql {
if (!_octokitGraphql) {
if (!SOCKET_CLI_GITHUB_TOKEN) {
debugNs('notice', 'miss: SOCKET_CLI_GITHUB_TOKEN env var')
}
_octokitGraphql = OctokitGraphql.defaults({
headers: {
authorization: `token ${SOCKET_CLI_GITHUB_TOKEN}`,
},
})
}
return _octokitGraphql
}
export type PrAutoMergeState = {
enabled: boolean
details?: string[] | undefined
}
export async function enablePrAutoMerge({
node_id: prId,
}: Pr): Promise<PrAutoMergeState> {
const octokitGraphql = getOctokitGraphql()
try {
const gqlResp = await octokitGraphql(
`
mutation EnableAutoMerge($pullRequestId: ID!) {
enablePullRequestAutoMerge(input: {
pullRequestId: $pullRequestId,
mergeMethod: SQUASH
}) {
pullRequest {
number
}
}
}`,
{ pullRequestId: prId },
)
const respPrNumber = (gqlResp as any)?.enablePullRequestAutoMerge
?.pullRequest?.number
if (respPrNumber) {
return { enabled: true }
}
} catch (e) {
if (
e instanceof GraphqlResponseError &&
Array.isArray(e.errors) &&
e.errors.length
) {
const details = e.errors.map(({ message: m }) => m.trim())
return { enabled: false, details }
}
}
return { enabled: false }
}
export async function prExistForBranch(
owner: string,
repo: string,
branch: string,
): Promise<boolean> {
const octokit = getOctokit()
try {
const { data: prs } = await octokit.pulls.list({
owner,
repo,
head: `${owner}:${branch}`,
state: 'all',
per_page: 1,
})
return prs.length > 0
} catch {}
return false
}
export async function setGitRemoteGithubRepoUrl(
owner: string,
repo: string,
token: string,
cwd = process.cwd(),
): Promise<boolean> {
const urlObj = parseUrl(GITHUB_SERVER_URL || '')
const host = urlObj?.host
if (!host) {
debugNs('error', 'invalid: GITHUB_SERVER_URL env var')
debugDirNs('inspect', { GITHUB_SERVER_URL })
return false
}
const url = `https://x-access-token:${token}@${host}/${owner}/${repo}`
const stdioIgnoreOptions: SpawnOptions = {
cwd,
stdio: isDebugNs('stdio') ? 'inherit' : 'ignore',
}
const quotedCmd = `\`git remote set-url origin ${url}\``
debugNs('stdio', `spawn: ${quotedCmd}`)
try {
await spawn('git', ['remote', 'set-url', 'origin', url], stdioIgnoreOptions)
return true
} catch (e) {
debugNs('error', `Git command failed: ${quotedCmd}`)
debugDirNs('inspect', { cmd: quotedCmd })
debugDirNs('error', e)
}
return false
}
/**
* Check if a GraphQL error is a rate limit error.
*/
export function isGraphqlRateLimitError(e: unknown): boolean {
if (e instanceof GraphqlResponseError && Array.isArray(e.errors)) {
return e.errors.some(
err =>
err.type === 'RATE_LIMITED' ||
err.message?.toLowerCase().includes('rate limit'),
)
}
return false
}
/**
* Convert GraphQL errors to user-friendly CResult failures.
* Handles rate limits and authentication errors with actionable messages.
*/
export function handleGraphqlError(
e: unknown,
context: string,
): CResult<never> {
debugNs('error', formatErrorWithDetail(`GraphQL error: ${context}`, e))
debugDirNs('error', e)
if (e instanceof GraphqlResponseError) {
const errorMessages = Array.isArray(e.errors)
? e.errors.map(err => err.message).filter(Boolean)
: []
// Check for rate limit errors.
if (isGraphqlRateLimitError(e)) {
return {
ok: false,
message: GITHUB_ERR_GRAPHQL_RATE_LIMIT,
cause:
`GitHub GraphQL rate limit exceeded while ${context}. ` +
'Try again in a few minutes.\n\n' +
'To increase your rate limit:\n' +
'- Set GITHUB_TOKEN environment variable with a valid token\n' +
'- In GitHub Actions, GITHUB_TOKEN is automatically available',
}
}
// Return the GraphQL error details.
return {
ok: false,
message: 'GitHub GraphQL error',
cause:
`GitHub GraphQL error while ${context}` +
(errorMessages.length ? `:\n- ${errorMessages.join('\n- ')}` : ''),
}
}
// Fall back to REST error handler for non-GraphQL errors.
return handleGitHubApiError(e, context)
}
/**
* Convert GitHub API errors to user-friendly CResult failures.
* Handles rate limits, authentication, and network errors with actionable messages.
*/
export function handleGitHubApiError(
e: unknown,
context: string,
): CResult<never> {
debugNs('error', formatErrorWithDetail(`GitHub API error: ${context}`, e))
debugDirNs('error', e)
if (e instanceof RequestError) {
const { status } = e
// Abuse detection rate limit - check first since it's more specific than standard rate limit.
if (status === 403 && e.message.includes('secondary rate limit')) {
return {
ok: false,
message: GITHUB_ERR_ABUSE_DETECTION,
cause:
`GitHub abuse detection triggered while ${context}. ` +
'This happens when making too many requests in a short period. ' +
'Wait a few minutes before retrying.\n\n' +
'To avoid this:\n' +
'- Reduce the number of concurrent operations\n' +
'- Add delays between bulk operations',
}
}
// Standard rate limit errors (403 with rate limit message or 429).
if (
status === 429 ||
(status === 403 && e.message.includes('rate limit'))
) {
const retryAfter = e.response?.headers?.['retry-after']
const resetHeader = e.response?.headers?.['x-ratelimit-reset']
let waitTime: number | undefined
if (retryAfter) {
waitTime = Number.parseInt(String(retryAfter), 10)
if (Number.isNaN(waitTime) || waitTime < 0) {
waitTime = undefined
}
} else if (resetHeader) {
const resetTimestamp = Number.parseInt(String(resetHeader), 10)
if (!Number.isNaN(resetTimestamp)) {
waitTime = Math.max(0, resetTimestamp - Math.floor(Date.now() / 1000))
}
}
return {
ok: false,
message: GITHUB_ERR_RATE_LIMIT,
cause:
`GitHub API rate limit exceeded while ${context}. ` +
(waitTime
? `Try again in ${waitTime} seconds.`
: 'Try again in a few minutes.') +
'\n\n' +
'To increase your rate limit:\n' +
'- Set GITHUB_TOKEN environment variable with a valid token\n' +
'- In GitHub Actions, GITHUB_TOKEN is automatically available\n' +
'- Personal access tokens provide higher rate limits than unauthenticated requests',
}
}
// Authentication errors.
if (status === 401) {
return {
ok: false,
message: GITHUB_ERR_AUTH_FAILED,
cause:
`GitHub authentication failed while ${context}. ` +
'Your token may be invalid, expired, or missing required permissions.\n\n' +
'To resolve:\n' +
'- Verify your GitHub token is valid and not expired\n' +
'- Set GITHUB_TOKEN environment variable\n' +
'- Ensure the token has required scopes (repo, read:org)',
}
}
// Permission denied (valid token but insufficient permissions).
if (status === 403 && !e.message.includes('rate limit')) {
return {
ok: false,
message: 'GitHub permission denied',
cause:
`GitHub permission denied while ${context}. ` +
'Your token does not have access to this resource.\n\n' +
'Ensure your token has the required scopes:\n' +
'- repo: Full control of private repositories\n' +
'- read:org: Read org membership (for org repos)',
}
}
// Not found errors.
if (status === 404) {
return {
ok: false,
message: 'GitHub resource not found',
cause:
`GitHub resource not found while ${context}. ` +
'The repository, branch, or file may not exist, or you may not have access to it.\n\n' +
'Verify:\n' +
'- The repository name and owner are correct\n' +
'- The branch exists\n' +
'- Your token has access to the repository',
}
}
// Server errors (5xx).
if (status >= 500) {
return {
ok: false,
message: 'GitHub server error',
cause:
`GitHub server error (${status}) while ${context}. ` +
'GitHub may be experiencing issues.\n\n' +
'To resolve:\n' +
'- Check https://www.githubstatus.com for service status\n' +
'- Try again in a few moments',
}
}
// Other request errors.
return {
ok: false,
message: `GitHub API error (${status})`,
cause: `GitHub API error while ${context}: ${e.message}`,
}
}
// Network errors (ECONNREFUSED, ETIMEDOUT, etc.).
if (e instanceof Error) {
const code = (e as NodeJS.ErrnoException).code
if (
code === 'ECONNREFUSED' ||
code === 'ETIMEDOUT' ||
code === 'ENOTFOUND'
) {
return {
ok: false,
message: 'Network error connecting to GitHub',
cause:
`Network error while ${context}: ${e.message}\n\n` +
'To resolve:\n' +
'- Check your internet connection\n' +
'- Verify GitHub API is accessible from your network\n' +
'- Check if a proxy or firewall is blocking the connection',
}
}
}
// Generic fallback.
return {
ok: false,
message: 'GitHub API error',
cause: `Unexpected error while ${context}: ${e instanceof Error ? e.message : String(e)}`,
}
}
/**
* Execute a GitHub API call with retry logic for transient failures.
* Retries on 5xx errors and network failures with exponential backoff.
*/
export async function withGitHubRetry<T>(
operation: () => Promise<T>,
context: string,
maxRetries = 3,
): Promise<CResult<T>> {
let lastError: unknown
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
// eslint-disable-next-line no-await-in-loop
const result = await operation()
return { ok: true, data: result }
} catch (e) {
lastError = e
debugNs(
'notice',
`GitHub API attempt ${attempt}/${maxRetries} failed for ${context}`,
)
debugDirNs('error', e)
// Don't retry on client errors (4xx) except rate limits.
if (e instanceof RequestError) {
const { status } = e
// Rate limits: return immediately with helpful message.
if (
status === 429 ||
(status === 403 && e.message.includes('rate limit'))
) {
return handleGitHubApiError(e, context)
}
// Don't retry other 4xx errors.
if (status >= 400 && status < 500) {
return handleGitHubApiError(e, context)
}
}
// Retry on 5xx or network errors.
if (attempt < maxRetries) {
const delay = Math.min(1000 * 2 ** (attempt - 1), 10_000)
debugNs('notice', `Retrying in ${delay}ms...`)
// eslint-disable-next-line no-await-in-loop
await new Promise(resolve => setTimeout(resolve, delay))
}
}
}
return handleGitHubApiError(lastError, context)
}