@fabrika/github-app 0.2.0 → 0.3.2

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/src/index.ts CHANGED
@@ -1,905 +1,16 @@
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
- const publicBody = await this.requestJson(`/apps/${identity.slug}`, {}, signal, true, false)
205
- if (publicBody === NOT_FOUND) return { ...identity, public: false }
206
- const publicIdentity = decodeAppIdentity(publicBody)
207
- if (publicIdentity === null || !sameAppIdentity(identity, publicIdentity)) throw responseError()
208
- return { ...identity, public: true }
209
- }
210
-
211
- /** Read the App webhook transport settings without exposing GitHub's masked secret field. */
212
- async getWebhookConfig(signal?: AbortSignal): Promise<GitHubAppWebhookConfig> {
213
- const body = await this.requestJson('/app/hook/config', {}, signal, false)
214
- if (body === NOT_FOUND) throw responseError()
215
- const config = decodeWebhookConfig(body)
216
- if (config === null) throw responseError()
217
- return config
218
- }
219
-
220
- /** Set the App webhook to JSON over verified TLS and bind GitHub's response to that request. */
221
- async updateWebhookConfig(input: GitHubAppWebhookUpdate): Promise<GitHubAppWebhookConfig> {
222
- const webhookUrl = normalizeWebhookUrl(input.url)
223
- validateWebhookSecret(input.secret)
224
- const body = await this.requestJson(
225
- '/app/hook/config',
226
- {
227
- method: 'PATCH',
228
- headers: { 'content-type': 'application/json' },
229
- body: JSON.stringify({ url: webhookUrl, content_type: 'json', insecure_ssl: '0', secret: input.secret }),
230
- },
231
- input.signal,
232
- false,
233
- )
234
- if (body === NOT_FOUND) throw responseError()
235
- const config = decodeWebhookConfig(body)
236
- if (config === null || config.url !== webhookUrl || config.contentType !== 'json' || config.insecureSsl !== '0') {
237
- throw responseError()
238
- }
239
- return config
240
- }
241
-
242
- /** Resolve the App installation owned by one organization. A 404 is an expected miss. */
243
- async resolveOrganizationInstallationId(organization: string, signal?: AbortSignal): Promise<number | null> {
244
- return (await this.resolveOrganizationInstallation(organization, signal))?.id ?? null
245
- }
246
-
247
- /** Resolve and strictly bind the installation authority owned by one organization. */
248
- async resolveOrganizationInstallation(organization: string, signal?: AbortSignal): Promise<GitHubAppInstallation | null> {
249
- validateRepositoryComponent(organization)
250
- const body = await this.requestJson(`/orgs/${organization}/installation`, {}, signal, true)
251
- if (body === NOT_FOUND) return null
252
- return this.decodeInstallation(body, organization, 'Organization')
253
- }
254
-
255
- /** Resolve the App installation for one GitHub repository. A 404 is an expected miss. */
256
- async resolveInstallationId(owner: string, repository: string, signal?: AbortSignal): Promise<number | null> {
257
- return (await this.resolveRepositoryInstallation(owner, repository, signal))?.id ?? null
258
- }
259
-
260
- /** Resolve and strictly bind the installation authority that grants one repository. */
261
- async resolveRepositoryInstallation(owner: string, repository: string, signal?: AbortSignal): Promise<GitHubAppInstallation | null> {
262
- validateRepositoryComponent(owner)
263
- validateRepositoryComponent(repository)
264
- const body = await this.requestJson(`/repos/${owner}/${repository}/installation`, {}, signal, true)
265
- if (body === NOT_FOUND) {
266
- return null
267
- }
268
- return this.decodeInstallation(body, owner)
269
- }
270
-
271
- /** Mint a read-only token restricted to one repository in the selected installation. */
272
- async mintRepositoryToken(input: GitHubRepositoryTokenRequest): Promise<GitHubInstallationToken> {
273
- if (!isPositiveSafeInteger(input.installationId)) {
274
- throw configurationError()
275
- }
276
- validateRepositoryComponent(input.owner)
277
- validateRepositoryComponent(input.repository)
278
- const body = await this.requestJson(
279
- `/app/installations/${input.installationId}/access_tokens`,
280
- {
281
- method: 'POST',
282
- headers: { 'content-type': 'application/json' },
283
- body: JSON.stringify({ repositories: [input.repository], permissions: { contents: 'read' } }),
284
- },
285
- input.signal,
286
- false,
287
- )
288
- if (body === NOT_FOUND) {
289
- throw responseError()
290
- }
291
- const token = objectField(body, 'token')
292
- const expiresAtValue = objectField(body, 'expires_at')
293
- const expiresAt = typeof expiresAtValue === 'string' ? Date.parse(expiresAtValue) : Number.NaN
294
- if (
295
- typeof token !== 'string' || token.length === 0 || token.length > 4096 || /\s/.test(token) || !Number.isFinite(expiresAt)
296
- || expiresAt <= this.now()
297
- ) {
298
- throw responseError()
299
- }
300
- return { token, expiresAt }
301
- }
302
-
303
- private async requestJson(
304
- path: string,
305
- init: RequestInit,
306
- callerSignal: AbortSignal | undefined,
307
- allowNotFound: boolean,
308
- authenticate = true,
309
- ): Promise<unknown | typeof NOT_FOUND> {
310
- const cancellation = createCancellation(callerSignal, this.timeoutMs)
311
- try {
312
- cancellation.throwIfCancelled()
313
- const headers = new Headers(init.headers)
314
- if (authenticate) {
315
- let jwt: string
316
- try {
317
- jwt = await this.signAppJwt()
318
- } catch (error) {
319
- cancellation.throwIfCancelled()
320
- throw error
321
- }
322
- cancellation.throwIfCancelled()
323
- headers.set('authorization', `Bearer ${jwt}`)
324
- }
325
- headers.set('accept', GITHUB_ACCEPT)
326
- headers.set('x-github-api-version', GITHUB_API_VERSION)
327
- headers.set('user-agent', GITHUB_USER_AGENT)
328
- let response: Response
329
- try {
330
- response = await this.fetchImplementation(`${this.apiBaseUrl}${path}`, {
331
- ...init,
332
- headers,
333
- redirect: 'error',
334
- signal: cancellation.signal,
335
- })
336
- } catch {
337
- cancellation.throwIfCancelled()
338
- throw new Error('GitHub App request failed')
339
- }
340
- cancellation.throwIfCancelled()
341
- if (allowNotFound && response.status === 404) {
342
- return NOT_FOUND
343
- }
344
- if (!response.ok) {
345
- throw requestStatusError(response.status)
346
- }
347
- return await readBoundedJson(response, cancellation)
348
- } finally {
349
- cancellation.dispose()
350
- }
351
- }
352
-
353
- private async signAppJwt(): Promise<string> {
354
- const now = Math.floor(this.now() / 1000)
355
- const header = { alg: 'RS256', typ: 'JWT' }
356
- const payload = { iat: now - 30, exp: now + 9 * 60, iss: this.appId }
357
- const encode = (value: unknown): string => base64url(utf8(JSON.stringify(value)))
358
- const signingInput = `${encode(header)}.${encode(payload)}`
359
- try {
360
- const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', this.privateKey, utf8(signingInput))
361
- return `${signingInput}.${base64url(new Uint8Array(signature))}`
362
- } catch {
363
- throw configurationError()
364
- }
365
- }
366
-
367
- private decodeInstallation(body: unknown, accountLogin: string, requiredType?: 'Organization' | 'User'): GitHubAppInstallation {
368
- const id = objectField(body, 'id')
369
- const appId = objectField(body, 'app_id')
370
- const targetType = objectField(body, 'target_type')
371
- const account = objectField(body, 'account')
372
- const login = objectField(account, 'login')
373
- const accountType = objectField(account, 'type')
374
- const repositorySelection = objectField(body, 'repository_selection')
375
- if (
376
- typeof id !== 'number' || !isPositiveSafeInteger(id) || typeof appId !== 'number' || !isPositiveSafeInteger(appId)
377
- || String(appId) !== this.appId || (targetType !== 'Organization' && targetType !== 'User') || accountType !== targetType
378
- || (requiredType !== undefined && targetType !== requiredType) || typeof login !== 'string'
379
- || login.toLowerCase() !== accountLogin.toLowerCase()
380
- || (repositorySelection !== 'all' && repositorySelection !== 'selected')
381
- ) {
382
- throw responseError()
383
- }
384
- return { id, accountLogin: login, accountType: targetType, repositorySelection }
385
- }
386
-
387
- private now(): number {
388
- let value: number
389
- try {
390
- value = this.clock()
391
- } catch {
392
- throw configurationError()
393
- }
394
- if (!Number.isFinite(value)) {
395
- throw configurationError()
396
- }
397
- return value
398
- }
399
- }
400
-
401
- interface RequestCancellation {
402
- readonly signal: AbortSignal
403
- throwIfCancelled(): void
404
- dispose(): void
405
- }
406
-
407
- interface ManifestCancellation {
408
- readonly signal: AbortSignal
409
- throwIfCancelled(): void
410
- dispose(): void
411
- }
412
-
413
- function createManifestCancellation(callerSignal: AbortSignal | undefined, timeoutMs: number): ManifestCancellation {
414
- const controller = new AbortController()
415
- let timedOut = false
416
- const abortFromCaller = (): void => controller.abort()
417
- if (callerSignal?.aborted === true) controller.abort()
418
- else callerSignal?.addEventListener('abort', abortFromCaller, { once: true })
419
- const timer = setTimeout(() => {
420
- timedOut = true
421
- controller.abort()
422
- }, timeoutMs)
423
- return {
424
- signal: controller.signal,
425
- throwIfCancelled() {
426
- if (callerSignal?.aborted === true) throw new DOMException('GitHub App manifest conversion was aborted', 'AbortError')
427
- if (timedOut) throw new DOMException('GitHub App manifest conversion timed out', 'TimeoutError')
428
- if (controller.signal.aborted) throw new DOMException('GitHub App manifest conversion was aborted', 'AbortError')
429
- },
430
- dispose() {
431
- clearTimeout(timer)
432
- callerSignal?.removeEventListener('abort', abortFromCaller)
433
- },
434
- }
435
- }
436
-
437
- async function readManifestConversionJson(response: Response, cancellation: ManifestCancellation): Promise<unknown> {
438
- cancellation.throwIfCancelled()
439
- const contentLength = response.headers.get('content-length')
440
- if (contentLength !== null && /^[0-9]+$/.test(contentLength) && Number(contentLength) > MAX_MANIFEST_CONVERSION_BYTES) {
441
- throw new Error('GitHub App manifest conversion returned an invalid response')
442
- }
443
- const reader = response.body?.getReader()
444
- if (reader === undefined) throw new Error('GitHub App manifest conversion returned an invalid response')
445
- const chunks: Uint8Array[] = []
446
- let total = 0
447
- try {
448
- while (true) {
449
- const result = await readManifestChunk(reader, cancellation)
450
- if (result.done) break
451
- total += result.value.byteLength
452
- if (total > MAX_MANIFEST_CONVERSION_BYTES) throw new Error('GitHub App manifest conversion returned an invalid response')
453
- chunks.push(result.value)
454
- }
455
- } catch (error) {
456
- void reader.cancel().catch(() => {})
457
- cancellation.throwIfCancelled()
458
- throw error
459
- } finally {
460
- reader.releaseLock()
461
- }
462
- const bytes = new Uint8Array(total)
463
- let offset = 0
464
- for (const chunk of chunks) {
465
- bytes.set(chunk, offset)
466
- offset += chunk.byteLength
467
- }
468
- cancellation.throwIfCancelled()
469
- try {
470
- return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))
471
- } catch {
472
- cancellation.throwIfCancelled()
473
- throw new Error('GitHub App manifest conversion returned an invalid response')
474
- }
475
- }
476
-
477
- function readManifestChunk(
478
- reader: ReadableStreamDefaultReader<Uint8Array>,
479
- cancellation: ManifestCancellation,
480
- ): Promise<{ readonly done: true } | { readonly done: false; readonly value: Uint8Array }> {
481
- cancellation.throwIfCancelled()
482
- return new Promise((resolve, reject) => {
483
- const abort = (): void => {
484
- cleanup()
485
- try {
486
- cancellation.throwIfCancelled()
487
- } catch (error) {
488
- reject(error)
489
- }
490
- }
491
- const cleanup = (): void => cancellation.signal.removeEventListener('abort', abort)
492
- cancellation.signal.addEventListener('abort', abort, { once: true })
493
- reader.read().then(
494
- (result) => {
495
- cleanup()
496
- resolve(result.done ? { done: true } : { done: false, value: result.value })
497
- },
498
- () => {
499
- cleanup()
500
- try {
501
- cancellation.throwIfCancelled()
502
- reject(new Error('GitHub App manifest conversion returned an invalid response'))
503
- } catch (error) {
504
- reject(error)
505
- }
506
- },
507
- )
508
- })
509
- }
510
-
511
- function createCancellation(callerSignal: AbortSignal | undefined, timeoutMs: number): RequestCancellation {
512
- const controller = new AbortController()
513
- let timedOut = false
514
- const abortFromCaller = (): void => controller.abort()
515
- if (callerSignal?.aborted === true) {
516
- controller.abort()
517
- } else {
518
- callerSignal?.addEventListener('abort', abortFromCaller, { once: true })
519
- }
520
- const timer = setTimeout(() => {
521
- timedOut = true
522
- controller.abort()
523
- }, timeoutMs)
524
- return {
525
- signal: controller.signal,
526
- throwIfCancelled() {
527
- if (callerSignal?.aborted === true) {
528
- throw abortError()
529
- }
530
- if (timedOut) {
531
- throw timeoutError()
532
- }
533
- if (controller.signal.aborted) {
534
- throw abortError()
535
- }
536
- },
537
- dispose() {
538
- clearTimeout(timer)
539
- callerSignal?.removeEventListener('abort', abortFromCaller)
540
- },
541
- }
542
- }
543
-
544
- async function readBoundedJson(response: Response, cancellation: RequestCancellation): Promise<unknown> {
545
- cancellation.throwIfCancelled()
546
- const contentLength = response.headers.get('content-length')
547
- if (contentLength !== null && /^[0-9]+$/.test(contentLength) && Number(contentLength) > MAX_RESPONSE_BYTES) {
548
- throw responseError()
549
- }
550
- const reader = response.body?.getReader()
551
- if (reader === undefined) {
552
- throw responseError()
553
- }
554
- const chunks: Uint8Array[] = []
555
- let total = 0
556
- try {
557
- while (true) {
558
- const result = await readChunk(reader, cancellation)
559
- if (result.done) {
560
- break
561
- }
562
- total += result.value.byteLength
563
- if (total > MAX_RESPONSE_BYTES) {
564
- throw responseError()
565
- }
566
- chunks.push(result.value)
567
- }
568
- } catch (error) {
569
- void reader.cancel().catch(() => {})
570
- cancellation.throwIfCancelled()
571
- throw error
572
- } finally {
573
- reader.releaseLock()
574
- }
575
- const bytes = new Uint8Array(total)
576
- let offset = 0
577
- for (const chunk of chunks) {
578
- bytes.set(chunk, offset)
579
- offset += chunk.byteLength
580
- }
581
- cancellation.throwIfCancelled()
582
- try {
583
- const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
584
- const body: unknown = JSON.parse(text)
585
- cancellation.throwIfCancelled()
586
- return body
587
- } catch (error) {
588
- cancellation.throwIfCancelled()
589
- if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {
590
- throw error
591
- }
592
- throw responseError()
593
- }
594
- }
595
-
596
- function readChunk(
597
- reader: ReadableStreamDefaultReader<Uint8Array>,
598
- cancellation: RequestCancellation,
599
- ): Promise<{ done: true } | { done: false; value: Uint8Array }> {
600
- cancellation.throwIfCancelled()
601
- return new Promise((resolve, reject) => {
602
- const aborted = (): void => {
603
- cleanup()
604
- try {
605
- cancellation.throwIfCancelled()
606
- } catch (error) {
607
- reject(error)
608
- }
609
- }
610
- const cleanup = (): void => cancellation.signal.removeEventListener('abort', aborted)
611
- cancellation.signal.addEventListener('abort', aborted, { once: true })
612
- reader.read().then(
613
- (result) => {
614
- cleanup()
615
- resolve(result.done ? { done: true } : { done: false, value: result.value })
616
- },
617
- () => {
618
- cleanup()
619
- try {
620
- cancellation.throwIfCancelled()
621
- reject(responseError())
622
- } catch (error) {
623
- reject(error)
624
- }
625
- },
626
- )
627
- })
628
- }
629
-
630
- /** Convert a GitHub App PKCS1 or PKCS8 PEM key into PKCS8 DER for WebCrypto. */
631
- export function pemToPkcs8(pem: string): Uint8Array<ArrayBuffer> {
632
- const pkcs1 = /^-----BEGIN RSA PRIVATE KEY-----\s+([A-Za-z0-9+/=\s]+)\s+-----END RSA PRIVATE KEY-----\s*$/.exec(pem)
633
- const pkcs8 = /^-----BEGIN PRIVATE KEY-----\s+([A-Za-z0-9+/=\s]+)\s+-----END PRIVATE KEY-----\s*$/.exec(pem)
634
- const match = pkcs1 ?? pkcs8
635
- const body = match?.[1]
636
- if (body === undefined) {
637
- throw configurationError()
638
- }
639
- let binary: string
640
- try {
641
- binary = atob(body.replace(/\s+/g, ''))
642
- } catch {
643
- throw configurationError()
644
- }
645
- if (binary.length === 0 || binary.charCodeAt(0) !== 0x30) {
646
- throw configurationError()
647
- }
648
- const der = new Uint8Array(binary.length)
649
- for (let index = 0; index < binary.length; index++) {
650
- der[index] = binary.charCodeAt(index)
651
- }
652
- return pkcs1 === null ? der : wrapPkcs1AsPkcs8(der)
653
- }
654
-
655
- function normalizeApiBaseUrl(value: string): string {
656
- let url: URL
657
- try {
658
- url = new URL(value)
659
- } catch {
660
- throw configurationError()
661
- }
662
- if (url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '') {
663
- throw configurationError()
664
- }
665
- return url.toString().replace(/\/$/, '')
666
- }
667
-
668
- function validateRepositoryComponent(value: string): void {
669
- if (value.length === 0 || value.length > 100 || !REPOSITORY_COMPONENT_PATTERN.test(value) || value === '.' || value === '..') {
670
- throw configurationError()
671
- }
672
- }
673
-
674
- function normalizeWebhookUrl(value: string): string {
675
- let url: URL
676
- try {
677
- url = new URL(value)
678
- } catch {
679
- throw configurationError()
680
- }
681
- if (
682
- url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '' || url.hostname === ''
683
- ) {
684
- throw configurationError()
685
- }
686
- return url.toString()
687
- }
688
-
689
- function validateManifestInput(input: GitHubAppManifestInput): void {
690
- if (
691
- !ORGANIZATION_PATTERN.test(input.organization) || input.appName.length === 0 || input.appName.length > 100
692
- || hasAsciiControl(input.appName)
693
- ) {
694
- throw new Error('GitHub App manifest configuration is invalid')
695
- }
696
- validateManifestUrl(input.homepageUrl)
697
- validateManifestUrl(input.webhookUrl)
698
- if (input.redirectUrl !== undefined) validateManifestUrl(input.redirectUrl)
699
- }
700
-
701
- function validateManifestUrl(value: string): void {
702
- if (value.length === 0 || value.length > MAX_MANIFEST_URL_LENGTH || hasAsciiControl(value)) {
703
- throw new Error('GitHub App manifest configuration is invalid')
704
- }
705
- let parsed: URL
706
- try {
707
- parsed = new URL(value)
708
- } catch {
709
- throw new Error('GitHub App manifest configuration is invalid')
710
- }
711
- if (
712
- parsed.protocol !== 'https:' || parsed.username !== '' || parsed.password !== '' || parsed.hash !== '' || parsed.hostname === ''
713
- ) {
714
- throw new Error('GitHub App manifest configuration is invalid')
715
- }
716
- }
717
-
718
- function decodeManifestConversion(value: unknown): CreatedGitHubApp | null {
719
- const id = objectField(value, 'id')
720
- const slug = objectField(value, 'slug')
721
- const htmlUrl = objectField(value, 'html_url')
722
- const pem = objectField(value, 'pem')
723
- const webhookSecret = objectField(value, 'webhook_secret')
724
- if (
725
- typeof id !== 'number' || !isPositiveSafeInteger(id) || typeof slug !== 'string' || !APP_SLUG_PATTERN.test(slug)
726
- || typeof htmlUrl !== 'string' || typeof pem !== 'string' || typeof webhookSecret !== 'string'
727
- || pem.length === 0 || pem.length > 64 * 1024 || webhookSecret.length === 0 || webhookSecret.length > 4096
728
- || hasAsciiControl(webhookSecret)
729
- ) {
730
- return null
731
- }
732
- let parsedHtmlUrl: URL
733
- try {
734
- parsedHtmlUrl = new URL(htmlUrl)
735
- } catch {
736
- return null
737
- }
738
- if (
739
- parsedHtmlUrl.protocol !== 'https:' || parsedHtmlUrl.hostname !== 'github.com' || parsedHtmlUrl.port !== ''
740
- || parsedHtmlUrl.username !== '' || parsedHtmlUrl.password !== '' || parsedHtmlUrl.search !== '' || parsedHtmlUrl.hash !== ''
741
- || parsedHtmlUrl.pathname !== `/apps/${slug}`
742
- || !/^-----BEGIN (?:RSA )?PRIVATE KEY-----[\s\S]+-----END (?:RSA )?PRIVATE KEY-----\s*$/.test(pem)
743
- ) {
744
- return null
745
- }
746
- return { id, slug, htmlUrl, pem, webhookSecret }
747
- }
748
-
749
- function validateWebhookSecret(value: string): void {
750
- if (value.length === 0 || value.length > 4096 || hasAsciiControl(value)) throw configurationError()
751
- }
752
-
753
- function decodeAppIdentity(value: unknown): Omit<GitHubAppIdentity, 'public'> | null {
754
- const id = objectField(value, 'id')
755
- const slug = objectField(value, 'slug')
756
- const htmlUrl = objectField(value, 'html_url')
757
- const permissions = objectField(value, 'permissions')
758
- const contents = objectField(permissions, 'contents')
759
- const events = objectField(value, 'events')
760
- const owner = objectField(value, 'owner')
761
- const login = objectField(owner, 'login')
762
- const type = objectField(owner, 'type')
763
- if (
764
- typeof id !== 'number' || !isPositiveSafeInteger(id) || typeof slug !== 'string' || !APP_SLUG_PATTERN.test(slug)
765
- || typeof htmlUrl !== 'string' || typeof login !== 'string' || login.length === 0 || login.length > 100
766
- || !REPOSITORY_COMPONENT_PATTERN.test(login) || (type !== 'Organization' && type !== 'User')
767
- || contents !== 'read' || !hasExactAppPermissions(permissions) || !isStringArray(events) || !events.includes('push')
768
- ) {
769
- return null
770
- }
771
- let parsedHtmlUrl: URL
772
- try {
773
- parsedHtmlUrl = new URL(htmlUrl)
774
- } catch {
775
- return null
776
- }
777
- if (
778
- parsedHtmlUrl.protocol !== 'https:' || parsedHtmlUrl.hostname !== 'github.com' || parsedHtmlUrl.port !== ''
779
- || parsedHtmlUrl.username !== '' || parsedHtmlUrl.password !== '' || parsedHtmlUrl.search !== '' || parsedHtmlUrl.hash !== ''
780
- || parsedHtmlUrl.pathname !== `/apps/${slug}`
781
- ) {
782
- return null
783
- }
784
- return { id, slug, htmlUrl, permissions: { contents }, events, owner: { login, type } }
785
- }
786
-
787
- function sameAppIdentity(
788
- left: Omit<GitHubAppIdentity, 'public'>,
789
- right: Omit<GitHubAppIdentity, 'public'>,
790
- ): boolean {
791
- return left.id === right.id && left.slug === right.slug && left.htmlUrl === right.htmlUrl
792
- && left.owner.login === right.owner.login && left.owner.type === right.owner.type
793
- && left.events.length === right.events.length && left.events.every((event, index) => event === right.events[index])
794
- }
795
-
796
- function decodeWebhookConfig(value: unknown): GitHubAppWebhookConfig | null {
797
- const url = objectField(value, 'url')
798
- const contentType = objectField(value, 'content_type')
799
- const insecureSsl = objectField(value, 'insecure_ssl')
800
- if (typeof url !== 'string' || (contentType !== 'json' && contentType !== 'form')) return null
801
- let normalized: string
802
- try {
803
- normalized = normalizeWebhookUrl(url)
804
- } catch {
805
- return null
806
- }
807
- if (normalized !== url) return null
808
- if (insecureSsl !== '0' && insecureSsl !== '1' && insecureSsl !== 0 && insecureSsl !== 1) return null
809
- return { url, contentType, insecureSsl: String(insecureSsl) === '0' ? '0' : '1' }
810
- }
811
-
812
- function hasAsciiControl(value: string): boolean {
813
- for (const character of value) {
814
- const code = character.charCodeAt(0)
815
- if (code < 32 || code === 127) return true
816
- }
817
- return false
818
- }
819
-
820
- function isStringArray(value: unknown): value is string[] {
821
- return Array.isArray(value) && value.length <= 100 && value.every((item) => typeof item === 'string' && item.length > 0 && item.length <= 100)
822
- }
823
-
824
- function hasExactAppPermissions(value: unknown): boolean {
825
- if (typeof value !== 'object' || value === null || objectField(value, 'contents') !== 'read') return false
826
- const keys = Object.keys(value)
827
- if (keys.some((key) => key !== 'contents' && key !== 'metadata')) return false
828
- const metadata = objectField(value, 'metadata')
829
- return metadata === undefined || metadata === 'read'
830
- }
831
-
832
- function isPositiveSafeInteger(value: number): boolean {
833
- return Number.isSafeInteger(value) && value > 0
834
- }
835
-
836
- function objectField(value: unknown, key: string): unknown {
837
- return typeof value === 'object' && value !== null ? Reflect.get(value, key) : undefined
838
- }
839
-
840
- function configurationError(): Error {
841
- return new Error('GitHub App configuration is invalid')
842
- }
843
-
844
- function requestStatusError(status: number): Error {
845
- return new Error(`GitHub App request failed with status ${status}`)
846
- }
847
-
848
- function responseError(): Error {
849
- return new Error('GitHub App response is invalid')
850
- }
851
-
852
- function abortError(): DOMException {
853
- return new DOMException('GitHub App request was aborted', 'AbortError')
854
- }
855
-
856
- function timeoutError(): DOMException {
857
- return new DOMException('GitHub App request timed out', 'TimeoutError')
858
- }
859
-
860
- function utf8(text: string): Uint8Array<ArrayBuffer> {
861
- const encoded = new TextEncoder().encode(text)
862
- const buffer = new ArrayBuffer(encoded.byteLength)
863
- const view = new Uint8Array(buffer)
864
- view.set(encoded)
865
- return view
866
- }
867
-
868
- function base64url(bytes: Uint8Array): string {
869
- let binary = ''
870
- for (const byte of bytes) {
871
- binary += String.fromCharCode(byte)
872
- }
873
- return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
874
- }
875
-
876
- function derTlv(tag: number, content: Uint8Array): Uint8Array<ArrayBuffer> {
877
- let lengthBytes: number[]
878
- if (content.length < 0x80) {
879
- lengthBytes = [content.length]
880
- } else {
881
- const big: number[] = []
882
- let length = content.length
883
- while (length > 0) {
884
- big.unshift(length & 0xff)
885
- length >>= 8
886
- }
887
- lengthBytes = [0x80 | big.length, ...big]
888
- }
889
- const out = new Uint8Array(1 + lengthBytes.length + content.length)
890
- out[0] = tag
891
- out.set(lengthBytes, 1)
892
- out.set(content, 1 + lengthBytes.length)
893
- return out
894
- }
895
-
896
- function wrapPkcs1AsPkcs8(pkcs1: Uint8Array): Uint8Array<ArrayBuffer> {
897
- const version = new Uint8Array([0x02, 0x01, 0x00])
898
- const algorithmId = new Uint8Array([0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00])
899
- const privateKey = derTlv(0x04, pkcs1)
900
- const inner = new Uint8Array(version.length + algorithmId.length + privateKey.length)
901
- inner.set(version, 0)
902
- inner.set(algorithmId, version.length)
903
- inner.set(privateKey, version.length + algorithmId.length)
904
- return derTlv(0x30, inner)
905
- }
1
+ export { GitHubAppClient } from './client'
2
+ export { buildGitHubAppManifest, exchangeGitHubAppManifestCode } from './manifest'
3
+ export { pemToPkcs8 } from './signing'
4
+ export type {
5
+ CreatedGitHubApp,
6
+ GitHubAppClientConfig,
7
+ GitHubAppFetch,
8
+ GitHubAppIdentity,
9
+ GitHubAppInstallation,
10
+ GitHubAppManifestExchangeOptions,
11
+ GitHubAppManifestInput,
12
+ GitHubAppWebhookConfig,
13
+ GitHubAppWebhookUpdate,
14
+ GitHubInstallationToken,
15
+ GitHubRepositoryTokenRequest,
16
+ } from './types'