@fabrika/github-app 0.0.5

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.
Files changed (2) hide show
  1. package/package.json +28 -0
  2. package/src/index.ts +890 -0
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@fabrika/github-app",
3
+ "version": "0.0.5",
4
+ "type": "module",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/contember/fabrika-platform.git",
8
+ "directory": "packages/github-app"
9
+ },
10
+ "files": [
11
+ "src",
12
+ "!src/**/__tests__/**"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "bun": "./src/index.ts",
17
+ "types": "./src/index.ts",
18
+ "default": "./src/index.ts"
19
+ }
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "scripts": {
25
+ "typecheck": "tsc --noEmit",
26
+ "test": "bun test"
27
+ }
28
+ }
package/src/index.ts ADDED
@@ -0,0 +1,890 @@
1
+ export interface GitHubAppClientConfig {
2
+ /** Numeric GitHub App id, kept as a string because it is the JWT issuer. */
3
+ appId: string
4
+ /** GitHub App RSA private key in PKCS1 or PKCS8 PEM form. */
5
+ privateKeyPem: string
6
+ /** GitHub API base URL. Defaults to the public GitHub API. */
7
+ apiBaseUrl?: string
8
+ /** HTTP implementation for the current runtime. */
9
+ fetch?: GitHubAppFetch
10
+ /** Millisecond Unix clock. */
11
+ now?: () => number
12
+ /** Upper bound for each GitHub API request, including its response body. */
13
+ timeoutMs?: number
14
+ }
15
+
16
+ export interface GitHubInstallationToken {
17
+ token: string
18
+ expiresAt: number
19
+ }
20
+
21
+ export interface GitHubAppInstallation {
22
+ readonly id: number
23
+ readonly accountLogin: string
24
+ readonly accountType: 'Organization' | 'User'
25
+ readonly repositorySelection: 'all' | 'selected'
26
+ }
27
+
28
+ export interface GitHubAppIdentity {
29
+ readonly id: number
30
+ readonly slug: string
31
+ readonly htmlUrl: string
32
+ readonly public: boolean
33
+ readonly permissions: {
34
+ readonly contents: 'read'
35
+ }
36
+ readonly events: readonly string[]
37
+ readonly owner: {
38
+ readonly login: string
39
+ readonly type: 'Organization' | 'User'
40
+ }
41
+ }
42
+
43
+ export interface GitHubAppWebhookConfig {
44
+ readonly url: string
45
+ readonly contentType: 'json' | 'form'
46
+ readonly insecureSsl: '0' | '1'
47
+ }
48
+
49
+ export interface GitHubAppWebhookUpdate {
50
+ readonly url: string
51
+ readonly secret: string
52
+ readonly signal?: AbortSignal
53
+ }
54
+
55
+ export interface GitHubRepositoryTokenRequest {
56
+ installationId: number
57
+ owner: string
58
+ repository: string
59
+ signal?: AbortSignal
60
+ }
61
+
62
+ export type GitHubAppFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>
63
+
64
+ export interface CreatedGitHubApp {
65
+ readonly id: number
66
+ readonly slug: string
67
+ readonly htmlUrl: string
68
+ readonly pem: string
69
+ readonly webhookSecret: string
70
+ }
71
+
72
+ export interface GitHubAppManifestInput {
73
+ readonly organization: string
74
+ readonly appName: string
75
+ readonly homepageUrl: string
76
+ readonly webhookUrl: string
77
+ readonly redirectUrl?: string
78
+ /** GitHub requires a public App when repositories outside its owner organization need it. */
79
+ readonly public: boolean
80
+ }
81
+
82
+ export interface GitHubAppManifestExchangeOptions {
83
+ readonly fetch?: GitHubAppFetch
84
+ readonly signal?: AbortSignal
85
+ readonly timeoutMs?: number
86
+ }
87
+
88
+ const DEFAULT_API_BASE_URL = 'https://api.github.com'
89
+ const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
90
+ const MAX_REQUEST_TIMEOUT_MS = 120_000
91
+ const MAX_RESPONSE_BYTES = 64 * 1024
92
+ const GITHUB_ACCEPT = 'application/vnd.github+json'
93
+ const GITHUB_API_VERSION = '2022-11-28'
94
+ const GITHUB_USER_AGENT = 'vozka'
95
+ const GITHUB_MANIFEST_USER_AGENT = 'fabrika'
96
+ const APP_ID_PATTERN = /^[1-9][0-9]*$/
97
+ const REPOSITORY_COMPONENT_PATTERN = /^[A-Za-z0-9_.-]+$/
98
+ const APP_SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,98}[a-z0-9])?$/
99
+ const ORGANIZATION_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/
100
+ const MANIFEST_CODE_PATTERN = /^[A-Za-z0-9_-]{1,256}$/
101
+ const MANIFEST_CONVERSION_TIMEOUT_MS = 30_000
102
+ const MAX_MANIFEST_CONVERSION_BYTES = 128 * 1024
103
+ const MAX_MANIFEST_URL_LENGTH = 2048
104
+ const NOT_FOUND = Symbol('not-found')
105
+
106
+ /** Build the one least-authority App manifest used by Fabrika repository source. */
107
+ export function buildGitHubAppManifest(input: GitHubAppManifestInput): Readonly<Record<string, unknown>> {
108
+ validateManifestInput(input)
109
+ return {
110
+ name: input.appName,
111
+ url: input.homepageUrl,
112
+ hook_attributes: { url: input.webhookUrl, active: true },
113
+ ...(input.redirectUrl === undefined ? {} : { redirect_url: input.redirectUrl }),
114
+ public: input.public,
115
+ default_permissions: { contents: 'read' },
116
+ default_events: ['push'],
117
+ }
118
+ }
119
+
120
+ /** Exchange a bounded one-time GitHub manifest code without exposing response details. */
121
+ export async function exchangeGitHubAppManifestCode(
122
+ code: string,
123
+ options: GitHubAppManifestExchangeOptions = {},
124
+ ): Promise<CreatedGitHubApp> {
125
+ if (!MANIFEST_CODE_PATTERN.test(code)) throw new Error('GitHub App manifest callback is invalid')
126
+ const timeoutMs = options.timeoutMs ?? MANIFEST_CONVERSION_TIMEOUT_MS
127
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MANIFEST_CONVERSION_TIMEOUT_MS) {
128
+ throw new Error('GitHub App manifest conversion timeout is invalid')
129
+ }
130
+ const cancellation = createManifestCancellation(options.signal, timeoutMs)
131
+ try {
132
+ cancellation.throwIfCancelled()
133
+ let response: Response
134
+ try {
135
+ response = await (options.fetch ?? fetch)(
136
+ `https://api.github.com/app-manifests/${encodeURIComponent(code)}/conversions`,
137
+ {
138
+ method: 'POST',
139
+ headers: {
140
+ accept: GITHUB_ACCEPT,
141
+ 'user-agent': GITHUB_MANIFEST_USER_AGENT,
142
+ 'x-github-api-version': GITHUB_API_VERSION,
143
+ },
144
+ redirect: 'error',
145
+ signal: cancellation.signal,
146
+ },
147
+ )
148
+ } catch {
149
+ cancellation.throwIfCancelled()
150
+ throw new Error('GitHub App manifest conversion failed')
151
+ }
152
+ cancellation.throwIfCancelled()
153
+ if (!response.ok) throw new Error('GitHub App manifest conversion failed')
154
+ const app = decodeManifestConversion(await readManifestConversionJson(response, cancellation))
155
+ if (app === null) throw new Error('GitHub App manifest conversion returned an invalid response')
156
+ return app
157
+ } finally {
158
+ cancellation.dispose()
159
+ }
160
+ }
161
+
162
+ /** GitHub App machine identity. Webhook authentication belongs to the receiving service. */
163
+ export class GitHubAppClient {
164
+ private constructor(
165
+ private readonly appId: string,
166
+ private readonly privateKey: CryptoKey,
167
+ private readonly apiBaseUrl: string,
168
+ private readonly fetchImplementation: GitHubAppFetch,
169
+ private readonly clock: () => number,
170
+ private readonly timeoutMs: number,
171
+ ) {}
172
+
173
+ /** Validate all configuration and import the RSA key before a credential-owning service boots. */
174
+ static async create(config: GitHubAppClientConfig): Promise<GitHubAppClient> {
175
+ if (!APP_ID_PATTERN.test(config.appId) || config.appId.length > 32) {
176
+ throw configurationError()
177
+ }
178
+ const apiBaseUrl = normalizeApiBaseUrl(config.apiBaseUrl ?? DEFAULT_API_BASE_URL)
179
+ const timeoutMs = config.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
180
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_REQUEST_TIMEOUT_MS) {
181
+ throw configurationError()
182
+ }
183
+ let privateKey: CryptoKey
184
+ try {
185
+ privateKey = await crypto.subtle.importKey(
186
+ 'pkcs8',
187
+ pemToPkcs8(config.privateKeyPem),
188
+ { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
189
+ false,
190
+ ['sign'],
191
+ )
192
+ } catch {
193
+ throw configurationError()
194
+ }
195
+ return new GitHubAppClient(config.appId, privateKey, apiBaseUrl, config.fetch ?? fetch, config.now ?? Date.now, timeoutMs)
196
+ }
197
+
198
+ /** Read and bind the public identity represented by this client's App credentials. */
199
+ async getAuthenticatedApp(signal?: AbortSignal): Promise<GitHubAppIdentity> {
200
+ const body = await this.requestJson('/app', {}, signal, false)
201
+ if (body === NOT_FOUND) throw responseError()
202
+ const identity = decodeAppIdentity(body)
203
+ if (identity === null || String(identity.id) !== this.appId) throw responseError()
204
+ return identity
205
+ }
206
+
207
+ /** Read the App webhook transport settings without exposing GitHub's masked secret field. */
208
+ async getWebhookConfig(signal?: AbortSignal): Promise<GitHubAppWebhookConfig> {
209
+ const body = await this.requestJson('/app/hook/config', {}, signal, false)
210
+ if (body === NOT_FOUND) throw responseError()
211
+ const config = decodeWebhookConfig(body)
212
+ if (config === null) throw responseError()
213
+ return config
214
+ }
215
+
216
+ /** Set the App webhook to JSON over verified TLS and bind GitHub's response to that request. */
217
+ async updateWebhookConfig(input: GitHubAppWebhookUpdate): Promise<GitHubAppWebhookConfig> {
218
+ const webhookUrl = normalizeWebhookUrl(input.url)
219
+ validateWebhookSecret(input.secret)
220
+ const body = await this.requestJson(
221
+ '/app/hook/config',
222
+ {
223
+ method: 'PATCH',
224
+ headers: { 'content-type': 'application/json' },
225
+ body: JSON.stringify({ url: webhookUrl, content_type: 'json', insecure_ssl: '0', secret: input.secret }),
226
+ },
227
+ input.signal,
228
+ false,
229
+ )
230
+ if (body === NOT_FOUND) throw responseError()
231
+ const config = decodeWebhookConfig(body)
232
+ if (config === null || config.url !== webhookUrl || config.contentType !== 'json' || config.insecureSsl !== '0') {
233
+ throw responseError()
234
+ }
235
+ return config
236
+ }
237
+
238
+ /** Resolve the App installation owned by one organization. A 404 is an expected miss. */
239
+ async resolveOrganizationInstallationId(organization: string, signal?: AbortSignal): Promise<number | null> {
240
+ return (await this.resolveOrganizationInstallation(organization, signal))?.id ?? null
241
+ }
242
+
243
+ /** Resolve and strictly bind the installation authority owned by one organization. */
244
+ async resolveOrganizationInstallation(organization: string, signal?: AbortSignal): Promise<GitHubAppInstallation | null> {
245
+ validateRepositoryComponent(organization)
246
+ const body = await this.requestJson(`/orgs/${organization}/installation`, {}, signal, true)
247
+ if (body === NOT_FOUND) return null
248
+ return this.decodeInstallation(body, organization, 'Organization')
249
+ }
250
+
251
+ /** Resolve the App installation for one GitHub repository. A 404 is an expected miss. */
252
+ async resolveInstallationId(owner: string, repository: string, signal?: AbortSignal): Promise<number | null> {
253
+ return (await this.resolveRepositoryInstallation(owner, repository, signal))?.id ?? null
254
+ }
255
+
256
+ /** Resolve and strictly bind the installation authority that grants one repository. */
257
+ async resolveRepositoryInstallation(owner: string, repository: string, signal?: AbortSignal): Promise<GitHubAppInstallation | null> {
258
+ validateRepositoryComponent(owner)
259
+ validateRepositoryComponent(repository)
260
+ const body = await this.requestJson(`/repos/${owner}/${repository}/installation`, {}, signal, true)
261
+ if (body === NOT_FOUND) {
262
+ return null
263
+ }
264
+ return this.decodeInstallation(body, owner)
265
+ }
266
+
267
+ /** Mint a read-only token restricted to one repository in the selected installation. */
268
+ async mintRepositoryToken(input: GitHubRepositoryTokenRequest): Promise<GitHubInstallationToken> {
269
+ if (!isPositiveSafeInteger(input.installationId)) {
270
+ throw configurationError()
271
+ }
272
+ validateRepositoryComponent(input.owner)
273
+ validateRepositoryComponent(input.repository)
274
+ const body = await this.requestJson(
275
+ `/app/installations/${input.installationId}/access_tokens`,
276
+ {
277
+ method: 'POST',
278
+ headers: { 'content-type': 'application/json' },
279
+ body: JSON.stringify({ repositories: [input.repository], permissions: { contents: 'read' } }),
280
+ },
281
+ input.signal,
282
+ false,
283
+ )
284
+ if (body === NOT_FOUND) {
285
+ throw responseError()
286
+ }
287
+ const token = objectField(body, 'token')
288
+ const expiresAtValue = objectField(body, 'expires_at')
289
+ const expiresAt = typeof expiresAtValue === 'string' ? Date.parse(expiresAtValue) : Number.NaN
290
+ if (
291
+ typeof token !== 'string' || token.length === 0 || token.length > 4096 || /\s/.test(token) || !Number.isFinite(expiresAt)
292
+ || expiresAt <= this.now()
293
+ ) {
294
+ throw responseError()
295
+ }
296
+ return { token, expiresAt }
297
+ }
298
+
299
+ private async requestJson(
300
+ path: string,
301
+ init: RequestInit,
302
+ callerSignal: AbortSignal | undefined,
303
+ allowNotFound: boolean,
304
+ ): Promise<unknown | typeof NOT_FOUND> {
305
+ const cancellation = createCancellation(callerSignal, this.timeoutMs)
306
+ try {
307
+ cancellation.throwIfCancelled()
308
+ let jwt: string
309
+ try {
310
+ jwt = await this.signAppJwt()
311
+ } catch (error) {
312
+ cancellation.throwIfCancelled()
313
+ throw error
314
+ }
315
+ cancellation.throwIfCancelled()
316
+ const headers = new Headers(init.headers)
317
+ headers.set('authorization', `Bearer ${jwt}`)
318
+ headers.set('accept', GITHUB_ACCEPT)
319
+ headers.set('x-github-api-version', GITHUB_API_VERSION)
320
+ headers.set('user-agent', GITHUB_USER_AGENT)
321
+ let response: Response
322
+ try {
323
+ response = await this.fetchImplementation(`${this.apiBaseUrl}${path}`, {
324
+ ...init,
325
+ headers,
326
+ redirect: 'error',
327
+ signal: cancellation.signal,
328
+ })
329
+ } catch {
330
+ cancellation.throwIfCancelled()
331
+ throw new Error('GitHub App request failed')
332
+ }
333
+ cancellation.throwIfCancelled()
334
+ if (allowNotFound && response.status === 404) {
335
+ return NOT_FOUND
336
+ }
337
+ if (!response.ok) {
338
+ throw requestStatusError(response.status)
339
+ }
340
+ return await readBoundedJson(response, cancellation)
341
+ } finally {
342
+ cancellation.dispose()
343
+ }
344
+ }
345
+
346
+ private async signAppJwt(): Promise<string> {
347
+ const now = Math.floor(this.now() / 1000)
348
+ const header = { alg: 'RS256', typ: 'JWT' }
349
+ const payload = { iat: now - 30, exp: now + 9 * 60, iss: this.appId }
350
+ const encode = (value: unknown): string => base64url(utf8(JSON.stringify(value)))
351
+ const signingInput = `${encode(header)}.${encode(payload)}`
352
+ try {
353
+ const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', this.privateKey, utf8(signingInput))
354
+ return `${signingInput}.${base64url(new Uint8Array(signature))}`
355
+ } catch {
356
+ throw configurationError()
357
+ }
358
+ }
359
+
360
+ private decodeInstallation(body: unknown, accountLogin: string, requiredType?: 'Organization' | 'User'): GitHubAppInstallation {
361
+ const id = objectField(body, 'id')
362
+ const appId = objectField(body, 'app_id')
363
+ const targetType = objectField(body, 'target_type')
364
+ const account = objectField(body, 'account')
365
+ const login = objectField(account, 'login')
366
+ const accountType = objectField(account, 'type')
367
+ const repositorySelection = objectField(body, 'repository_selection')
368
+ if (
369
+ typeof id !== 'number' || !isPositiveSafeInteger(id) || typeof appId !== 'number' || !isPositiveSafeInteger(appId)
370
+ || String(appId) !== this.appId || (targetType !== 'Organization' && targetType !== 'User') || accountType !== targetType
371
+ || (requiredType !== undefined && targetType !== requiredType) || typeof login !== 'string'
372
+ || login.toLowerCase() !== accountLogin.toLowerCase()
373
+ || (repositorySelection !== 'all' && repositorySelection !== 'selected')
374
+ ) {
375
+ throw responseError()
376
+ }
377
+ return { id, accountLogin: login, accountType: targetType, repositorySelection }
378
+ }
379
+
380
+ private now(): number {
381
+ let value: number
382
+ try {
383
+ value = this.clock()
384
+ } catch {
385
+ throw configurationError()
386
+ }
387
+ if (!Number.isFinite(value)) {
388
+ throw configurationError()
389
+ }
390
+ return value
391
+ }
392
+ }
393
+
394
+ interface RequestCancellation {
395
+ readonly signal: AbortSignal
396
+ throwIfCancelled(): void
397
+ dispose(): void
398
+ }
399
+
400
+ interface ManifestCancellation {
401
+ readonly signal: AbortSignal
402
+ throwIfCancelled(): void
403
+ dispose(): void
404
+ }
405
+
406
+ function createManifestCancellation(callerSignal: AbortSignal | undefined, timeoutMs: number): ManifestCancellation {
407
+ const controller = new AbortController()
408
+ let timedOut = false
409
+ const abortFromCaller = (): void => controller.abort()
410
+ if (callerSignal?.aborted === true) controller.abort()
411
+ else callerSignal?.addEventListener('abort', abortFromCaller, { once: true })
412
+ const timer = setTimeout(() => {
413
+ timedOut = true
414
+ controller.abort()
415
+ }, timeoutMs)
416
+ return {
417
+ signal: controller.signal,
418
+ throwIfCancelled() {
419
+ if (callerSignal?.aborted === true) throw new DOMException('GitHub App manifest conversion was aborted', 'AbortError')
420
+ if (timedOut) throw new DOMException('GitHub App manifest conversion timed out', 'TimeoutError')
421
+ if (controller.signal.aborted) throw new DOMException('GitHub App manifest conversion was aborted', 'AbortError')
422
+ },
423
+ dispose() {
424
+ clearTimeout(timer)
425
+ callerSignal?.removeEventListener('abort', abortFromCaller)
426
+ },
427
+ }
428
+ }
429
+
430
+ async function readManifestConversionJson(response: Response, cancellation: ManifestCancellation): Promise<unknown> {
431
+ cancellation.throwIfCancelled()
432
+ const contentLength = response.headers.get('content-length')
433
+ if (contentLength !== null && /^[0-9]+$/.test(contentLength) && Number(contentLength) > MAX_MANIFEST_CONVERSION_BYTES) {
434
+ throw new Error('GitHub App manifest conversion returned an invalid response')
435
+ }
436
+ const reader = response.body?.getReader()
437
+ if (reader === undefined) throw new Error('GitHub App manifest conversion returned an invalid response')
438
+ const chunks: Uint8Array[] = []
439
+ let total = 0
440
+ try {
441
+ while (true) {
442
+ const result = await readManifestChunk(reader, cancellation)
443
+ if (result.done) break
444
+ total += result.value.byteLength
445
+ if (total > MAX_MANIFEST_CONVERSION_BYTES) throw new Error('GitHub App manifest conversion returned an invalid response')
446
+ chunks.push(result.value)
447
+ }
448
+ } catch (error) {
449
+ void reader.cancel().catch(() => {})
450
+ cancellation.throwIfCancelled()
451
+ throw error
452
+ } finally {
453
+ reader.releaseLock()
454
+ }
455
+ const bytes = new Uint8Array(total)
456
+ let offset = 0
457
+ for (const chunk of chunks) {
458
+ bytes.set(chunk, offset)
459
+ offset += chunk.byteLength
460
+ }
461
+ cancellation.throwIfCancelled()
462
+ try {
463
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))
464
+ } catch {
465
+ cancellation.throwIfCancelled()
466
+ throw new Error('GitHub App manifest conversion returned an invalid response')
467
+ }
468
+ }
469
+
470
+ function readManifestChunk(
471
+ reader: ReadableStreamDefaultReader<Uint8Array>,
472
+ cancellation: ManifestCancellation,
473
+ ): Promise<{ readonly done: true } | { readonly done: false; readonly value: Uint8Array }> {
474
+ cancellation.throwIfCancelled()
475
+ return new Promise((resolve, reject) => {
476
+ const abort = (): void => {
477
+ cleanup()
478
+ try {
479
+ cancellation.throwIfCancelled()
480
+ } catch (error) {
481
+ reject(error)
482
+ }
483
+ }
484
+ const cleanup = (): void => cancellation.signal.removeEventListener('abort', abort)
485
+ cancellation.signal.addEventListener('abort', abort, { once: true })
486
+ reader.read().then(
487
+ (result) => {
488
+ cleanup()
489
+ resolve(result.done ? { done: true } : { done: false, value: result.value })
490
+ },
491
+ () => {
492
+ cleanup()
493
+ try {
494
+ cancellation.throwIfCancelled()
495
+ reject(new Error('GitHub App manifest conversion returned an invalid response'))
496
+ } catch (error) {
497
+ reject(error)
498
+ }
499
+ },
500
+ )
501
+ })
502
+ }
503
+
504
+ function createCancellation(callerSignal: AbortSignal | undefined, timeoutMs: number): RequestCancellation {
505
+ const controller = new AbortController()
506
+ let timedOut = false
507
+ const abortFromCaller = (): void => controller.abort()
508
+ if (callerSignal?.aborted === true) {
509
+ controller.abort()
510
+ } else {
511
+ callerSignal?.addEventListener('abort', abortFromCaller, { once: true })
512
+ }
513
+ const timer = setTimeout(() => {
514
+ timedOut = true
515
+ controller.abort()
516
+ }, timeoutMs)
517
+ return {
518
+ signal: controller.signal,
519
+ throwIfCancelled() {
520
+ if (callerSignal?.aborted === true) {
521
+ throw abortError()
522
+ }
523
+ if (timedOut) {
524
+ throw timeoutError()
525
+ }
526
+ if (controller.signal.aborted) {
527
+ throw abortError()
528
+ }
529
+ },
530
+ dispose() {
531
+ clearTimeout(timer)
532
+ callerSignal?.removeEventListener('abort', abortFromCaller)
533
+ },
534
+ }
535
+ }
536
+
537
+ async function readBoundedJson(response: Response, cancellation: RequestCancellation): Promise<unknown> {
538
+ cancellation.throwIfCancelled()
539
+ const contentLength = response.headers.get('content-length')
540
+ if (contentLength !== null && /^[0-9]+$/.test(contentLength) && Number(contentLength) > MAX_RESPONSE_BYTES) {
541
+ throw responseError()
542
+ }
543
+ const reader = response.body?.getReader()
544
+ if (reader === undefined) {
545
+ throw responseError()
546
+ }
547
+ const chunks: Uint8Array[] = []
548
+ let total = 0
549
+ try {
550
+ while (true) {
551
+ const result = await readChunk(reader, cancellation)
552
+ if (result.done) {
553
+ break
554
+ }
555
+ total += result.value.byteLength
556
+ if (total > MAX_RESPONSE_BYTES) {
557
+ throw responseError()
558
+ }
559
+ chunks.push(result.value)
560
+ }
561
+ } catch (error) {
562
+ void reader.cancel().catch(() => {})
563
+ cancellation.throwIfCancelled()
564
+ throw error
565
+ } finally {
566
+ reader.releaseLock()
567
+ }
568
+ const bytes = new Uint8Array(total)
569
+ let offset = 0
570
+ for (const chunk of chunks) {
571
+ bytes.set(chunk, offset)
572
+ offset += chunk.byteLength
573
+ }
574
+ cancellation.throwIfCancelled()
575
+ try {
576
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
577
+ const body: unknown = JSON.parse(text)
578
+ cancellation.throwIfCancelled()
579
+ return body
580
+ } catch (error) {
581
+ cancellation.throwIfCancelled()
582
+ if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {
583
+ throw error
584
+ }
585
+ throw responseError()
586
+ }
587
+ }
588
+
589
+ function readChunk(
590
+ reader: ReadableStreamDefaultReader<Uint8Array>,
591
+ cancellation: RequestCancellation,
592
+ ): Promise<{ done: true } | { done: false; value: Uint8Array }> {
593
+ cancellation.throwIfCancelled()
594
+ return new Promise((resolve, reject) => {
595
+ const aborted = (): void => {
596
+ cleanup()
597
+ try {
598
+ cancellation.throwIfCancelled()
599
+ } catch (error) {
600
+ reject(error)
601
+ }
602
+ }
603
+ const cleanup = (): void => cancellation.signal.removeEventListener('abort', aborted)
604
+ cancellation.signal.addEventListener('abort', aborted, { once: true })
605
+ reader.read().then(
606
+ (result) => {
607
+ cleanup()
608
+ resolve(result.done ? { done: true } : { done: false, value: result.value })
609
+ },
610
+ () => {
611
+ cleanup()
612
+ try {
613
+ cancellation.throwIfCancelled()
614
+ reject(responseError())
615
+ } catch (error) {
616
+ reject(error)
617
+ }
618
+ },
619
+ )
620
+ })
621
+ }
622
+
623
+ /** Convert a GitHub App PKCS1 or PKCS8 PEM key into PKCS8 DER for WebCrypto. */
624
+ export function pemToPkcs8(pem: string): Uint8Array<ArrayBuffer> {
625
+ const pkcs1 = /^-----BEGIN RSA PRIVATE KEY-----\s+([A-Za-z0-9+/=\s]+)\s+-----END RSA PRIVATE KEY-----\s*$/.exec(pem)
626
+ const pkcs8 = /^-----BEGIN PRIVATE KEY-----\s+([A-Za-z0-9+/=\s]+)\s+-----END PRIVATE KEY-----\s*$/.exec(pem)
627
+ const match = pkcs1 ?? pkcs8
628
+ const body = match?.[1]
629
+ if (body === undefined) {
630
+ throw configurationError()
631
+ }
632
+ let binary: string
633
+ try {
634
+ binary = atob(body.replace(/\s+/g, ''))
635
+ } catch {
636
+ throw configurationError()
637
+ }
638
+ if (binary.length === 0 || binary.charCodeAt(0) !== 0x30) {
639
+ throw configurationError()
640
+ }
641
+ const der = new Uint8Array(binary.length)
642
+ for (let index = 0; index < binary.length; index++) {
643
+ der[index] = binary.charCodeAt(index)
644
+ }
645
+ return pkcs1 === null ? der : wrapPkcs1AsPkcs8(der)
646
+ }
647
+
648
+ function normalizeApiBaseUrl(value: string): string {
649
+ let url: URL
650
+ try {
651
+ url = new URL(value)
652
+ } catch {
653
+ throw configurationError()
654
+ }
655
+ if (url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '') {
656
+ throw configurationError()
657
+ }
658
+ return url.toString().replace(/\/$/, '')
659
+ }
660
+
661
+ function validateRepositoryComponent(value: string): void {
662
+ if (value.length === 0 || value.length > 100 || !REPOSITORY_COMPONENT_PATTERN.test(value) || value === '.' || value === '..') {
663
+ throw configurationError()
664
+ }
665
+ }
666
+
667
+ function normalizeWebhookUrl(value: string): string {
668
+ let url: URL
669
+ try {
670
+ url = new URL(value)
671
+ } catch {
672
+ throw configurationError()
673
+ }
674
+ if (
675
+ url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '' || url.hostname === ''
676
+ ) {
677
+ throw configurationError()
678
+ }
679
+ return url.toString()
680
+ }
681
+
682
+ function validateManifestInput(input: GitHubAppManifestInput): void {
683
+ if (
684
+ !ORGANIZATION_PATTERN.test(input.organization) || input.appName.length === 0 || input.appName.length > 100
685
+ || hasAsciiControl(input.appName)
686
+ ) {
687
+ throw new Error('GitHub App manifest configuration is invalid')
688
+ }
689
+ validateManifestUrl(input.homepageUrl)
690
+ validateManifestUrl(input.webhookUrl)
691
+ if (input.redirectUrl !== undefined) validateManifestUrl(input.redirectUrl)
692
+ }
693
+
694
+ function validateManifestUrl(value: string): void {
695
+ if (value.length === 0 || value.length > MAX_MANIFEST_URL_LENGTH || hasAsciiControl(value)) {
696
+ throw new Error('GitHub App manifest configuration is invalid')
697
+ }
698
+ let parsed: URL
699
+ try {
700
+ parsed = new URL(value)
701
+ } catch {
702
+ throw new Error('GitHub App manifest configuration is invalid')
703
+ }
704
+ if (
705
+ parsed.protocol !== 'https:' || parsed.username !== '' || parsed.password !== '' || parsed.hash !== '' || parsed.hostname === ''
706
+ ) {
707
+ throw new Error('GitHub App manifest configuration is invalid')
708
+ }
709
+ }
710
+
711
+ function decodeManifestConversion(value: unknown): CreatedGitHubApp | null {
712
+ const id = objectField(value, 'id')
713
+ const slug = objectField(value, 'slug')
714
+ const htmlUrl = objectField(value, 'html_url')
715
+ const pem = objectField(value, 'pem')
716
+ const webhookSecret = objectField(value, 'webhook_secret')
717
+ if (
718
+ typeof id !== 'number' || !isPositiveSafeInteger(id) || typeof slug !== 'string' || !APP_SLUG_PATTERN.test(slug)
719
+ || typeof htmlUrl !== 'string' || typeof pem !== 'string' || typeof webhookSecret !== 'string'
720
+ || pem.length === 0 || pem.length > 64 * 1024 || webhookSecret.length === 0 || webhookSecret.length > 4096
721
+ || hasAsciiControl(webhookSecret)
722
+ ) {
723
+ return null
724
+ }
725
+ let parsedHtmlUrl: URL
726
+ try {
727
+ parsedHtmlUrl = new URL(htmlUrl)
728
+ } catch {
729
+ return null
730
+ }
731
+ if (
732
+ parsedHtmlUrl.protocol !== 'https:' || parsedHtmlUrl.hostname !== 'github.com' || parsedHtmlUrl.port !== ''
733
+ || parsedHtmlUrl.username !== '' || parsedHtmlUrl.password !== '' || parsedHtmlUrl.search !== '' || parsedHtmlUrl.hash !== ''
734
+ || parsedHtmlUrl.pathname !== `/apps/${slug}`
735
+ || !/^-----BEGIN (?:RSA )?PRIVATE KEY-----[\s\S]+-----END (?:RSA )?PRIVATE KEY-----\s*$/.test(pem)
736
+ ) {
737
+ return null
738
+ }
739
+ return { id, slug, htmlUrl, pem, webhookSecret }
740
+ }
741
+
742
+ function validateWebhookSecret(value: string): void {
743
+ if (value.length === 0 || value.length > 4096 || hasAsciiControl(value)) throw configurationError()
744
+ }
745
+
746
+ function decodeAppIdentity(value: unknown): GitHubAppIdentity | null {
747
+ const id = objectField(value, 'id')
748
+ const slug = objectField(value, 'slug')
749
+ const htmlUrl = objectField(value, 'html_url')
750
+ const publicApp = objectField(value, 'public')
751
+ const permissions = objectField(value, 'permissions')
752
+ const contents = objectField(permissions, 'contents')
753
+ const events = objectField(value, 'events')
754
+ const owner = objectField(value, 'owner')
755
+ const login = objectField(owner, 'login')
756
+ const type = objectField(owner, 'type')
757
+ if (
758
+ typeof id !== 'number' || !isPositiveSafeInteger(id) || typeof slug !== 'string' || !APP_SLUG_PATTERN.test(slug)
759
+ || typeof htmlUrl !== 'string' || typeof login !== 'string' || login.length === 0 || login.length > 100
760
+ || !REPOSITORY_COMPONENT_PATTERN.test(login) || (type !== 'Organization' && type !== 'User') || typeof publicApp !== 'boolean'
761
+ || contents !== 'read' || !hasExactAppPermissions(permissions) || !isStringArray(events) || !events.includes('push')
762
+ ) {
763
+ return null
764
+ }
765
+ let parsedHtmlUrl: URL
766
+ try {
767
+ parsedHtmlUrl = new URL(htmlUrl)
768
+ } catch {
769
+ return null
770
+ }
771
+ if (
772
+ parsedHtmlUrl.protocol !== 'https:' || parsedHtmlUrl.hostname !== 'github.com' || parsedHtmlUrl.port !== ''
773
+ || parsedHtmlUrl.username !== '' || parsedHtmlUrl.password !== '' || parsedHtmlUrl.search !== '' || parsedHtmlUrl.hash !== ''
774
+ || parsedHtmlUrl.pathname !== `/apps/${slug}`
775
+ ) {
776
+ return null
777
+ }
778
+ return { id, slug, htmlUrl, public: publicApp, permissions: { contents }, events, owner: { login, type } }
779
+ }
780
+
781
+ function decodeWebhookConfig(value: unknown): GitHubAppWebhookConfig | null {
782
+ const url = objectField(value, 'url')
783
+ const contentType = objectField(value, 'content_type')
784
+ const insecureSsl = objectField(value, 'insecure_ssl')
785
+ if (typeof url !== 'string' || (contentType !== 'json' && contentType !== 'form')) return null
786
+ let normalized: string
787
+ try {
788
+ normalized = normalizeWebhookUrl(url)
789
+ } catch {
790
+ return null
791
+ }
792
+ if (normalized !== url) return null
793
+ if (insecureSsl !== '0' && insecureSsl !== '1' && insecureSsl !== 0 && insecureSsl !== 1) return null
794
+ return { url, contentType, insecureSsl: String(insecureSsl) === '0' ? '0' : '1' }
795
+ }
796
+
797
+ function hasAsciiControl(value: string): boolean {
798
+ for (const character of value) {
799
+ const code = character.charCodeAt(0)
800
+ if (code < 32 || code === 127) return true
801
+ }
802
+ return false
803
+ }
804
+
805
+ function isStringArray(value: unknown): value is string[] {
806
+ return Array.isArray(value) && value.length <= 100 && value.every((item) => typeof item === 'string' && item.length > 0 && item.length <= 100)
807
+ }
808
+
809
+ function hasExactAppPermissions(value: unknown): boolean {
810
+ if (typeof value !== 'object' || value === null || objectField(value, 'contents') !== 'read') return false
811
+ const keys = Object.keys(value)
812
+ if (keys.some((key) => key !== 'contents' && key !== 'metadata')) return false
813
+ const metadata = objectField(value, 'metadata')
814
+ return metadata === undefined || metadata === 'read'
815
+ }
816
+
817
+ function isPositiveSafeInteger(value: number): boolean {
818
+ return Number.isSafeInteger(value) && value > 0
819
+ }
820
+
821
+ function objectField(value: unknown, key: string): unknown {
822
+ return typeof value === 'object' && value !== null ? Reflect.get(value, key) : undefined
823
+ }
824
+
825
+ function configurationError(): Error {
826
+ return new Error('GitHub App configuration is invalid')
827
+ }
828
+
829
+ function requestStatusError(status: number): Error {
830
+ return new Error(`GitHub App request failed with status ${status}`)
831
+ }
832
+
833
+ function responseError(): Error {
834
+ return new Error('GitHub App response is invalid')
835
+ }
836
+
837
+ function abortError(): DOMException {
838
+ return new DOMException('GitHub App request was aborted', 'AbortError')
839
+ }
840
+
841
+ function timeoutError(): DOMException {
842
+ return new DOMException('GitHub App request timed out', 'TimeoutError')
843
+ }
844
+
845
+ function utf8(text: string): Uint8Array<ArrayBuffer> {
846
+ const encoded = new TextEncoder().encode(text)
847
+ const buffer = new ArrayBuffer(encoded.byteLength)
848
+ const view = new Uint8Array(buffer)
849
+ view.set(encoded)
850
+ return view
851
+ }
852
+
853
+ function base64url(bytes: Uint8Array): string {
854
+ let binary = ''
855
+ for (const byte of bytes) {
856
+ binary += String.fromCharCode(byte)
857
+ }
858
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
859
+ }
860
+
861
+ function derTlv(tag: number, content: Uint8Array): Uint8Array<ArrayBuffer> {
862
+ let lengthBytes: number[]
863
+ if (content.length < 0x80) {
864
+ lengthBytes = [content.length]
865
+ } else {
866
+ const big: number[] = []
867
+ let length = content.length
868
+ while (length > 0) {
869
+ big.unshift(length & 0xff)
870
+ length >>= 8
871
+ }
872
+ lengthBytes = [0x80 | big.length, ...big]
873
+ }
874
+ const out = new Uint8Array(1 + lengthBytes.length + content.length)
875
+ out[0] = tag
876
+ out.set(lengthBytes, 1)
877
+ out.set(content, 1 + lengthBytes.length)
878
+ return out
879
+ }
880
+
881
+ function wrapPkcs1AsPkcs8(pkcs1: Uint8Array): Uint8Array<ArrayBuffer> {
882
+ const version = new Uint8Array([0x02, 0x01, 0x00])
883
+ const algorithmId = new Uint8Array([0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00])
884
+ const privateKey = derTlv(0x04, pkcs1)
885
+ const inner = new Uint8Array(version.length + algorithmId.length + privateKey.length)
886
+ inner.set(version, 0)
887
+ inner.set(algorithmId, version.length)
888
+ inner.set(privateKey, version.length + algorithmId.length)
889
+ return derTlv(0x30, inner)
890
+ }