@fabrika/github-app 0.0.26 → 0.3.1
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/package.json +4 -1
- package/src/client.ts +248 -0
- package/src/errors.ts +11 -0
- package/src/index.ts +16 -905
- package/src/manifest.ts +226 -0
- package/src/signing.ts +87 -0
- package/src/transport.ts +138 -0
- package/src/types.ts +86 -0
- package/src/validation.ts +131 -0
package/src/manifest.ts
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import { GITHUB_ACCEPT, GITHUB_API_VERSION } from './transport'
|
|
3
|
+
import type { CreatedGitHubApp, GitHubAppManifestExchangeOptions, GitHubAppManifestInput } from './types'
|
|
4
|
+
import { appReferenceSchema, hasAsciiControl } from './validation'
|
|
5
|
+
|
|
6
|
+
const GITHUB_MANIFEST_USER_AGENT = 'fabrika'
|
|
7
|
+
const ORGANIZATION_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/
|
|
8
|
+
const MANIFEST_CODE_PATTERN = /^[A-Za-z0-9_-]{1,256}$/
|
|
9
|
+
const MANIFEST_CONVERSION_TIMEOUT_MS = 30_000
|
|
10
|
+
const MAX_MANIFEST_CONVERSION_BYTES = 128 * 1024
|
|
11
|
+
const MAX_MANIFEST_URL_LENGTH = 2048
|
|
12
|
+
|
|
13
|
+
const manifestConversionSchema = appReferenceSchema.extend({
|
|
14
|
+
pem: z.string().min(1).max(64 * 1024),
|
|
15
|
+
webhook_secret: z.string().min(1).max(4096).refine((secret) => !hasAsciiControl(secret)),
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
/** Build the one least-authority App manifest used by Fabrika repository source. */
|
|
19
|
+
export function buildGitHubAppManifest(input: GitHubAppManifestInput): Readonly<Record<string, unknown>> {
|
|
20
|
+
validateManifestInput(input)
|
|
21
|
+
return {
|
|
22
|
+
name: input.appName,
|
|
23
|
+
url: input.homepageUrl,
|
|
24
|
+
hook_attributes: { url: input.webhookUrl, active: true },
|
|
25
|
+
...(input.redirectUrl === undefined ? {} : { redirect_url: input.redirectUrl }),
|
|
26
|
+
public: input.public,
|
|
27
|
+
default_permissions: { contents: 'read' },
|
|
28
|
+
default_events: ['push'],
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Exchange a bounded one-time GitHub manifest code without exposing response details. */
|
|
33
|
+
export async function exchangeGitHubAppManifestCode(
|
|
34
|
+
code: string,
|
|
35
|
+
options: GitHubAppManifestExchangeOptions = {},
|
|
36
|
+
): Promise<CreatedGitHubApp> {
|
|
37
|
+
if (!MANIFEST_CODE_PATTERN.test(code)) throw new Error('GitHub App manifest callback is invalid')
|
|
38
|
+
const timeoutMs = options.timeoutMs ?? MANIFEST_CONVERSION_TIMEOUT_MS
|
|
39
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MANIFEST_CONVERSION_TIMEOUT_MS) {
|
|
40
|
+
throw new Error('GitHub App manifest conversion timeout is invalid')
|
|
41
|
+
}
|
|
42
|
+
const cancellation = createManifestCancellation(options.signal, timeoutMs)
|
|
43
|
+
try {
|
|
44
|
+
cancellation.throwIfCancelled()
|
|
45
|
+
let response: Response
|
|
46
|
+
try {
|
|
47
|
+
response = await (options.fetch ?? fetch)(
|
|
48
|
+
`https://api.github.com/app-manifests/${encodeURIComponent(code)}/conversions`,
|
|
49
|
+
{
|
|
50
|
+
method: 'POST',
|
|
51
|
+
headers: {
|
|
52
|
+
accept: GITHUB_ACCEPT,
|
|
53
|
+
'user-agent': GITHUB_MANIFEST_USER_AGENT,
|
|
54
|
+
'x-github-api-version': GITHUB_API_VERSION,
|
|
55
|
+
},
|
|
56
|
+
redirect: 'error',
|
|
57
|
+
signal: cancellation.signal,
|
|
58
|
+
},
|
|
59
|
+
)
|
|
60
|
+
} catch {
|
|
61
|
+
cancellation.throwIfCancelled()
|
|
62
|
+
throw new Error('GitHub App manifest conversion failed')
|
|
63
|
+
}
|
|
64
|
+
cancellation.throwIfCancelled()
|
|
65
|
+
if (!response.ok) throw new Error('GitHub App manifest conversion failed')
|
|
66
|
+
const app = decodeManifestConversion(await readManifestConversionJson(response, cancellation))
|
|
67
|
+
if (app === null) throw new Error('GitHub App manifest conversion returned an invalid response')
|
|
68
|
+
return app
|
|
69
|
+
} finally {
|
|
70
|
+
cancellation.dispose()
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
interface ManifestCancellation {
|
|
75
|
+
readonly signal: AbortSignal
|
|
76
|
+
throwIfCancelled(): void
|
|
77
|
+
dispose(): void
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function createManifestCancellation(callerSignal: AbortSignal | undefined, timeoutMs: number): ManifestCancellation {
|
|
81
|
+
const controller = new AbortController()
|
|
82
|
+
let timedOut = false
|
|
83
|
+
const abortFromCaller = (): void => controller.abort()
|
|
84
|
+
if (callerSignal?.aborted === true) controller.abort()
|
|
85
|
+
else callerSignal?.addEventListener('abort', abortFromCaller, { once: true })
|
|
86
|
+
const timer = setTimeout(() => {
|
|
87
|
+
timedOut = true
|
|
88
|
+
controller.abort()
|
|
89
|
+
}, timeoutMs)
|
|
90
|
+
return {
|
|
91
|
+
signal: controller.signal,
|
|
92
|
+
throwIfCancelled() {
|
|
93
|
+
if (callerSignal?.aborted === true) throw new DOMException('GitHub App manifest conversion was aborted', 'AbortError')
|
|
94
|
+
if (timedOut) throw new DOMException('GitHub App manifest conversion timed out', 'TimeoutError')
|
|
95
|
+
if (controller.signal.aborted) throw new DOMException('GitHub App manifest conversion was aborted', 'AbortError')
|
|
96
|
+
},
|
|
97
|
+
dispose() {
|
|
98
|
+
clearTimeout(timer)
|
|
99
|
+
callerSignal?.removeEventListener('abort', abortFromCaller)
|
|
100
|
+
},
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function readManifestConversionJson(response: Response, cancellation: ManifestCancellation): Promise<unknown> {
|
|
105
|
+
cancellation.throwIfCancelled()
|
|
106
|
+
const contentLength = response.headers.get('content-length')
|
|
107
|
+
if (contentLength !== null && /^[0-9]+$/.test(contentLength) && Number(contentLength) > MAX_MANIFEST_CONVERSION_BYTES) {
|
|
108
|
+
throw new Error('GitHub App manifest conversion returned an invalid response')
|
|
109
|
+
}
|
|
110
|
+
const reader = response.body?.getReader()
|
|
111
|
+
if (reader === undefined) throw new Error('GitHub App manifest conversion returned an invalid response')
|
|
112
|
+
const chunks: Uint8Array[] = []
|
|
113
|
+
let total = 0
|
|
114
|
+
try {
|
|
115
|
+
while (true) {
|
|
116
|
+
const result = await readManifestChunk(reader, cancellation)
|
|
117
|
+
if (result.done) break
|
|
118
|
+
total += result.value.byteLength
|
|
119
|
+
if (total > MAX_MANIFEST_CONVERSION_BYTES) throw new Error('GitHub App manifest conversion returned an invalid response')
|
|
120
|
+
chunks.push(result.value)
|
|
121
|
+
}
|
|
122
|
+
} catch (error) {
|
|
123
|
+
void reader.cancel().catch(() => {})
|
|
124
|
+
cancellation.throwIfCancelled()
|
|
125
|
+
throw error
|
|
126
|
+
} finally {
|
|
127
|
+
reader.releaseLock()
|
|
128
|
+
}
|
|
129
|
+
const bytes = new Uint8Array(total)
|
|
130
|
+
let offset = 0
|
|
131
|
+
for (const chunk of chunks) {
|
|
132
|
+
bytes.set(chunk, offset)
|
|
133
|
+
offset += chunk.byteLength
|
|
134
|
+
}
|
|
135
|
+
cancellation.throwIfCancelled()
|
|
136
|
+
try {
|
|
137
|
+
return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))
|
|
138
|
+
} catch {
|
|
139
|
+
cancellation.throwIfCancelled()
|
|
140
|
+
throw new Error('GitHub App manifest conversion returned an invalid response')
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function readManifestChunk(
|
|
145
|
+
reader: ReadableStreamDefaultReader<Uint8Array>,
|
|
146
|
+
cancellation: ManifestCancellation,
|
|
147
|
+
): Promise<{ readonly done: true } | { readonly done: false; readonly value: Uint8Array }> {
|
|
148
|
+
cancellation.throwIfCancelled()
|
|
149
|
+
return new Promise((resolve, reject) => {
|
|
150
|
+
const abort = (): void => {
|
|
151
|
+
cleanup()
|
|
152
|
+
try {
|
|
153
|
+
cancellation.throwIfCancelled()
|
|
154
|
+
} catch (error) {
|
|
155
|
+
reject(error)
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const cleanup = (): void => cancellation.signal.removeEventListener('abort', abort)
|
|
159
|
+
cancellation.signal.addEventListener('abort', abort, { once: true })
|
|
160
|
+
reader.read().then(
|
|
161
|
+
(result) => {
|
|
162
|
+
cleanup()
|
|
163
|
+
resolve(result.done ? { done: true } : { done: false, value: result.value })
|
|
164
|
+
},
|
|
165
|
+
() => {
|
|
166
|
+
cleanup()
|
|
167
|
+
try {
|
|
168
|
+
cancellation.throwIfCancelled()
|
|
169
|
+
reject(new Error('GitHub App manifest conversion returned an invalid response'))
|
|
170
|
+
} catch (error) {
|
|
171
|
+
reject(error)
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
)
|
|
175
|
+
})
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function validateManifestInput(input: GitHubAppManifestInput): void {
|
|
179
|
+
if (
|
|
180
|
+
!ORGANIZATION_PATTERN.test(input.organization) || input.appName.length === 0 || input.appName.length > 100
|
|
181
|
+
|| hasAsciiControl(input.appName)
|
|
182
|
+
) {
|
|
183
|
+
throw new Error('GitHub App manifest configuration is invalid')
|
|
184
|
+
}
|
|
185
|
+
validateManifestUrl(input.homepageUrl)
|
|
186
|
+
validateManifestUrl(input.webhookUrl)
|
|
187
|
+
if (input.redirectUrl !== undefined) validateManifestUrl(input.redirectUrl)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function validateManifestUrl(value: string): void {
|
|
191
|
+
if (value.length === 0 || value.length > MAX_MANIFEST_URL_LENGTH || hasAsciiControl(value)) {
|
|
192
|
+
throw new Error('GitHub App manifest configuration is invalid')
|
|
193
|
+
}
|
|
194
|
+
let parsed: URL
|
|
195
|
+
try {
|
|
196
|
+
parsed = new URL(value)
|
|
197
|
+
} catch {
|
|
198
|
+
throw new Error('GitHub App manifest configuration is invalid')
|
|
199
|
+
}
|
|
200
|
+
if (
|
|
201
|
+
parsed.protocol !== 'https:' || parsed.username !== '' || parsed.password !== '' || parsed.hash !== '' || parsed.hostname === ''
|
|
202
|
+
) {
|
|
203
|
+
throw new Error('GitHub App manifest configuration is invalid')
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function decodeManifestConversion(value: unknown): CreatedGitHubApp | null {
|
|
208
|
+
const result = manifestConversionSchema.safeParse(value)
|
|
209
|
+
if (!result.success) return null
|
|
210
|
+
const { id, slug, html_url: htmlUrl, pem, webhook_secret: webhookSecret } = result.data
|
|
211
|
+
let parsedHtmlUrl: URL
|
|
212
|
+
try {
|
|
213
|
+
parsedHtmlUrl = new URL(htmlUrl)
|
|
214
|
+
} catch {
|
|
215
|
+
return null
|
|
216
|
+
}
|
|
217
|
+
if (
|
|
218
|
+
parsedHtmlUrl.protocol !== 'https:' || parsedHtmlUrl.hostname !== 'github.com' || parsedHtmlUrl.port !== ''
|
|
219
|
+
|| parsedHtmlUrl.username !== '' || parsedHtmlUrl.password !== '' || parsedHtmlUrl.search !== '' || parsedHtmlUrl.hash !== ''
|
|
220
|
+
|| parsedHtmlUrl.pathname !== `/apps/${slug}`
|
|
221
|
+
|| !/^-----BEGIN (?:RSA )?PRIVATE KEY-----[\s\S]+-----END (?:RSA )?PRIVATE KEY-----\s*$/.test(pem)
|
|
222
|
+
) {
|
|
223
|
+
return null
|
|
224
|
+
}
|
|
225
|
+
return { id, slug, htmlUrl, pem, webhookSecret }
|
|
226
|
+
}
|
package/src/signing.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { configurationError } from './errors'
|
|
2
|
+
|
|
3
|
+
export async function signAppJwt(appId: string, privateKey: CryptoKey, clock: () => number): Promise<string> {
|
|
4
|
+
const now = Math.floor(clock() / 1000)
|
|
5
|
+
const header = { alg: 'RS256', typ: 'JWT' }
|
|
6
|
+
const payload = { iat: now - 30, exp: now + 9 * 60, iss: appId }
|
|
7
|
+
const encode = (value: unknown): string => base64url(utf8(JSON.stringify(value)))
|
|
8
|
+
const signingInput = `${encode(header)}.${encode(payload)}`
|
|
9
|
+
try {
|
|
10
|
+
const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', privateKey, utf8(signingInput))
|
|
11
|
+
return `${signingInput}.${base64url(new Uint8Array(signature))}`
|
|
12
|
+
} catch {
|
|
13
|
+
throw configurationError()
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Convert a GitHub App PKCS1 or PKCS8 PEM key into PKCS8 DER for WebCrypto. */
|
|
18
|
+
export function pemToPkcs8(pem: string): Uint8Array<ArrayBuffer> {
|
|
19
|
+
const pkcs1 = /^-----BEGIN RSA PRIVATE KEY-----\s+([A-Za-z0-9+/=\s]+)\s+-----END RSA PRIVATE KEY-----\s*$/.exec(pem)
|
|
20
|
+
const pkcs8 = /^-----BEGIN PRIVATE KEY-----\s+([A-Za-z0-9+/=\s]+)\s+-----END PRIVATE KEY-----\s*$/.exec(pem)
|
|
21
|
+
const match = pkcs1 ?? pkcs8
|
|
22
|
+
const body = match?.[1]
|
|
23
|
+
if (body === undefined) {
|
|
24
|
+
throw configurationError()
|
|
25
|
+
}
|
|
26
|
+
let binary: string
|
|
27
|
+
try {
|
|
28
|
+
binary = atob(body.replace(/\s+/g, ''))
|
|
29
|
+
} catch {
|
|
30
|
+
throw configurationError()
|
|
31
|
+
}
|
|
32
|
+
if (binary.length === 0 || binary.charCodeAt(0) !== 0x30) {
|
|
33
|
+
throw configurationError()
|
|
34
|
+
}
|
|
35
|
+
const der = new Uint8Array(binary.length)
|
|
36
|
+
for (let index = 0; index < binary.length; index++) {
|
|
37
|
+
der[index] = binary.charCodeAt(index)
|
|
38
|
+
}
|
|
39
|
+
return pkcs1 === null ? der : wrapPkcs1AsPkcs8(der)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function utf8(text: string): Uint8Array<ArrayBuffer> {
|
|
43
|
+
const encoded = new TextEncoder().encode(text)
|
|
44
|
+
const buffer = new ArrayBuffer(encoded.byteLength)
|
|
45
|
+
const view = new Uint8Array(buffer)
|
|
46
|
+
view.set(encoded)
|
|
47
|
+
return view
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function base64url(bytes: Uint8Array): string {
|
|
51
|
+
let binary = ''
|
|
52
|
+
for (const byte of bytes) {
|
|
53
|
+
binary += String.fromCharCode(byte)
|
|
54
|
+
}
|
|
55
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function derTlv(tag: number, content: Uint8Array): Uint8Array<ArrayBuffer> {
|
|
59
|
+
let lengthBytes: number[]
|
|
60
|
+
if (content.length < 0x80) {
|
|
61
|
+
lengthBytes = [content.length]
|
|
62
|
+
} else {
|
|
63
|
+
const big: number[] = []
|
|
64
|
+
let length = content.length
|
|
65
|
+
while (length > 0) {
|
|
66
|
+
big.unshift(length & 0xff)
|
|
67
|
+
length >>= 8
|
|
68
|
+
}
|
|
69
|
+
lengthBytes = [0x80 | big.length, ...big]
|
|
70
|
+
}
|
|
71
|
+
const out = new Uint8Array(1 + lengthBytes.length + content.length)
|
|
72
|
+
out[0] = tag
|
|
73
|
+
out.set(lengthBytes, 1)
|
|
74
|
+
out.set(content, 1 + lengthBytes.length)
|
|
75
|
+
return out
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function wrapPkcs1AsPkcs8(pkcs1: Uint8Array): Uint8Array<ArrayBuffer> {
|
|
79
|
+
const version = new Uint8Array([0x02, 0x01, 0x00])
|
|
80
|
+
const algorithmId = new Uint8Array([0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00])
|
|
81
|
+
const privateKey = derTlv(0x04, pkcs1)
|
|
82
|
+
const inner = new Uint8Array(version.length + algorithmId.length + privateKey.length)
|
|
83
|
+
inner.set(version, 0)
|
|
84
|
+
inner.set(algorithmId, version.length)
|
|
85
|
+
inner.set(privateKey, version.length + algorithmId.length)
|
|
86
|
+
return derTlv(0x30, inner)
|
|
87
|
+
}
|
package/src/transport.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { responseError } from './errors'
|
|
2
|
+
|
|
3
|
+
export const GITHUB_ACCEPT = 'application/vnd.github+json'
|
|
4
|
+
export const GITHUB_API_VERSION = '2022-11-28'
|
|
5
|
+
const MAX_RESPONSE_BYTES = 64 * 1024
|
|
6
|
+
|
|
7
|
+
interface RequestCancellation {
|
|
8
|
+
readonly signal: AbortSignal
|
|
9
|
+
throwIfCancelled(): void
|
|
10
|
+
dispose(): void
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function createCancellation(callerSignal: AbortSignal | undefined, timeoutMs: number): RequestCancellation {
|
|
14
|
+
const controller = new AbortController()
|
|
15
|
+
let timedOut = false
|
|
16
|
+
const abortFromCaller = (): void => controller.abort()
|
|
17
|
+
if (callerSignal?.aborted === true) {
|
|
18
|
+
controller.abort()
|
|
19
|
+
} else {
|
|
20
|
+
callerSignal?.addEventListener('abort', abortFromCaller, { once: true })
|
|
21
|
+
}
|
|
22
|
+
const timer = setTimeout(() => {
|
|
23
|
+
timedOut = true
|
|
24
|
+
controller.abort()
|
|
25
|
+
}, timeoutMs)
|
|
26
|
+
return {
|
|
27
|
+
signal: controller.signal,
|
|
28
|
+
throwIfCancelled() {
|
|
29
|
+
if (callerSignal?.aborted === true) {
|
|
30
|
+
throw abortError()
|
|
31
|
+
}
|
|
32
|
+
if (timedOut) {
|
|
33
|
+
throw timeoutError()
|
|
34
|
+
}
|
|
35
|
+
if (controller.signal.aborted) {
|
|
36
|
+
throw abortError()
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
dispose() {
|
|
40
|
+
clearTimeout(timer)
|
|
41
|
+
callerSignal?.removeEventListener('abort', abortFromCaller)
|
|
42
|
+
},
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function readBoundedJson(response: Response, cancellation: RequestCancellation): Promise<unknown> {
|
|
47
|
+
cancellation.throwIfCancelled()
|
|
48
|
+
const contentLength = response.headers.get('content-length')
|
|
49
|
+
if (contentLength !== null && /^[0-9]+$/.test(contentLength) && Number(contentLength) > MAX_RESPONSE_BYTES) {
|
|
50
|
+
throw responseError()
|
|
51
|
+
}
|
|
52
|
+
const reader = response.body?.getReader()
|
|
53
|
+
if (reader === undefined) {
|
|
54
|
+
throw responseError()
|
|
55
|
+
}
|
|
56
|
+
const chunks: Uint8Array[] = []
|
|
57
|
+
let total = 0
|
|
58
|
+
try {
|
|
59
|
+
while (true) {
|
|
60
|
+
const result = await readChunk(reader, cancellation)
|
|
61
|
+
if (result.done) {
|
|
62
|
+
break
|
|
63
|
+
}
|
|
64
|
+
total += result.value.byteLength
|
|
65
|
+
if (total > MAX_RESPONSE_BYTES) {
|
|
66
|
+
throw responseError()
|
|
67
|
+
}
|
|
68
|
+
chunks.push(result.value)
|
|
69
|
+
}
|
|
70
|
+
} catch (error) {
|
|
71
|
+
void reader.cancel().catch(() => {})
|
|
72
|
+
cancellation.throwIfCancelled()
|
|
73
|
+
throw error
|
|
74
|
+
} finally {
|
|
75
|
+
reader.releaseLock()
|
|
76
|
+
}
|
|
77
|
+
const bytes = new Uint8Array(total)
|
|
78
|
+
let offset = 0
|
|
79
|
+
for (const chunk of chunks) {
|
|
80
|
+
bytes.set(chunk, offset)
|
|
81
|
+
offset += chunk.byteLength
|
|
82
|
+
}
|
|
83
|
+
cancellation.throwIfCancelled()
|
|
84
|
+
try {
|
|
85
|
+
const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
|
|
86
|
+
const body: unknown = JSON.parse(text)
|
|
87
|
+
cancellation.throwIfCancelled()
|
|
88
|
+
return body
|
|
89
|
+
} catch (error) {
|
|
90
|
+
cancellation.throwIfCancelled()
|
|
91
|
+
if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {
|
|
92
|
+
throw error
|
|
93
|
+
}
|
|
94
|
+
throw responseError()
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function readChunk(
|
|
99
|
+
reader: ReadableStreamDefaultReader<Uint8Array>,
|
|
100
|
+
cancellation: RequestCancellation,
|
|
101
|
+
): Promise<{ done: true } | { done: false; value: Uint8Array }> {
|
|
102
|
+
cancellation.throwIfCancelled()
|
|
103
|
+
return new Promise((resolve, reject) => {
|
|
104
|
+
const aborted = (): void => {
|
|
105
|
+
cleanup()
|
|
106
|
+
try {
|
|
107
|
+
cancellation.throwIfCancelled()
|
|
108
|
+
} catch (error) {
|
|
109
|
+
reject(error)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const cleanup = (): void => cancellation.signal.removeEventListener('abort', aborted)
|
|
113
|
+
cancellation.signal.addEventListener('abort', aborted, { once: true })
|
|
114
|
+
reader.read().then(
|
|
115
|
+
(result) => {
|
|
116
|
+
cleanup()
|
|
117
|
+
resolve(result.done ? { done: true } : { done: false, value: result.value })
|
|
118
|
+
},
|
|
119
|
+
() => {
|
|
120
|
+
cleanup()
|
|
121
|
+
try {
|
|
122
|
+
cancellation.throwIfCancelled()
|
|
123
|
+
reject(responseError())
|
|
124
|
+
} catch (error) {
|
|
125
|
+
reject(error)
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
)
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function abortError(): DOMException {
|
|
133
|
+
return new DOMException('GitHub App request was aborted', 'AbortError')
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function timeoutError(): DOMException {
|
|
137
|
+
return new DOMException('GitHub App request timed out', 'TimeoutError')
|
|
138
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import { configurationError } from './errors'
|
|
3
|
+
import type { GitHubAppIdentity, GitHubAppWebhookConfig } from './types'
|
|
4
|
+
|
|
5
|
+
const REPOSITORY_COMPONENT_PATTERN = /^[A-Za-z0-9_.-]+$/
|
|
6
|
+
export const APP_SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,98}[a-z0-9])?$/
|
|
7
|
+
|
|
8
|
+
export const appReferenceSchema = z.object({
|
|
9
|
+
id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
|
10
|
+
slug: z.string().regex(APP_SLUG_PATTERN),
|
|
11
|
+
html_url: z.string(),
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
const appIdentitySchema = appReferenceSchema.extend({
|
|
15
|
+
// Strict for least privilege: an App granted any permission beyond read-only contents is refused.
|
|
16
|
+
permissions: z.object({ contents: z.literal('read'), metadata: z.literal('read').optional() }).strict(),
|
|
17
|
+
events: z.array(z.string().min(1).max(100)).max(100).refine((events) => events.includes('push')),
|
|
18
|
+
owner: z.object({ login: z.string().min(1).max(100).regex(REPOSITORY_COMPONENT_PATTERN), type: z.enum(['Organization', 'User']) }),
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
const webhookConfigSchema = z.object({
|
|
22
|
+
url: z.string(),
|
|
23
|
+
content_type: z.enum(['json', 'form']),
|
|
24
|
+
insecure_ssl: z.union([z.literal('0'), z.literal('1'), z.literal(0), z.literal(1)]),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
export const installationSchema = z.object({
|
|
28
|
+
id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
|
29
|
+
app_id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
|
30
|
+
target_type: z.enum(['Organization', 'User']),
|
|
31
|
+
account: z.object({ login: z.string(), type: z.enum(['Organization', 'User']) }),
|
|
32
|
+
repository_selection: z.enum(['all', 'selected']),
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
export const installationTokenSchema = z.object({
|
|
36
|
+
token: z.string().min(1).max(4096).refine((token) => !/\s/.test(token)),
|
|
37
|
+
expires_at: z.string().transform((value) => Date.parse(value)),
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
export function normalizeApiBaseUrl(value: string): string {
|
|
41
|
+
let url: URL
|
|
42
|
+
try {
|
|
43
|
+
url = new URL(value)
|
|
44
|
+
} catch {
|
|
45
|
+
throw configurationError()
|
|
46
|
+
}
|
|
47
|
+
if (url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '') {
|
|
48
|
+
throw configurationError()
|
|
49
|
+
}
|
|
50
|
+
return url.toString().replace(/\/$/, '')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function validateRepositoryComponent(value: string): void {
|
|
54
|
+
if (value.length === 0 || value.length > 100 || !REPOSITORY_COMPONENT_PATTERN.test(value) || value === '.' || value === '..') {
|
|
55
|
+
throw configurationError()
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function normalizeWebhookUrl(value: string): string {
|
|
60
|
+
let url: URL
|
|
61
|
+
try {
|
|
62
|
+
url = new URL(value)
|
|
63
|
+
} catch {
|
|
64
|
+
throw configurationError()
|
|
65
|
+
}
|
|
66
|
+
if (
|
|
67
|
+
url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '' || url.hostname === ''
|
|
68
|
+
) {
|
|
69
|
+
throw configurationError()
|
|
70
|
+
}
|
|
71
|
+
return url.toString()
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function validateWebhookSecret(value: string): void {
|
|
75
|
+
if (value.length === 0 || value.length > 4096 || hasAsciiControl(value)) throw configurationError()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function decodeAppIdentity(value: unknown): Omit<GitHubAppIdentity, 'public'> | null {
|
|
79
|
+
const result = appIdentitySchema.safeParse(value)
|
|
80
|
+
if (!result.success) return null
|
|
81
|
+
const { id, slug, html_url: htmlUrl, permissions: { contents }, events, owner: { login, type } } = result.data
|
|
82
|
+
let parsedHtmlUrl: URL
|
|
83
|
+
try {
|
|
84
|
+
parsedHtmlUrl = new URL(htmlUrl)
|
|
85
|
+
} catch {
|
|
86
|
+
return null
|
|
87
|
+
}
|
|
88
|
+
if (
|
|
89
|
+
parsedHtmlUrl.protocol !== 'https:' || parsedHtmlUrl.hostname !== 'github.com' || parsedHtmlUrl.port !== ''
|
|
90
|
+
|| parsedHtmlUrl.username !== '' || parsedHtmlUrl.password !== '' || parsedHtmlUrl.search !== '' || parsedHtmlUrl.hash !== ''
|
|
91
|
+
|| parsedHtmlUrl.pathname !== `/apps/${slug}`
|
|
92
|
+
) {
|
|
93
|
+
return null
|
|
94
|
+
}
|
|
95
|
+
return { id, slug, htmlUrl, permissions: { contents }, events, owner: { login, type } }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function sameAppIdentity(
|
|
99
|
+
left: Omit<GitHubAppIdentity, 'public'>,
|
|
100
|
+
right: Omit<GitHubAppIdentity, 'public'>,
|
|
101
|
+
): boolean {
|
|
102
|
+
return left.id === right.id && left.slug === right.slug && left.htmlUrl === right.htmlUrl
|
|
103
|
+
&& left.owner.login === right.owner.login && left.owner.type === right.owner.type
|
|
104
|
+
&& left.events.length === right.events.length && left.events.every((event, index) => event === right.events[index])
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function decodeWebhookConfig(value: unknown): GitHubAppWebhookConfig | null {
|
|
108
|
+
const result = webhookConfigSchema.safeParse(value)
|
|
109
|
+
if (!result.success) return null
|
|
110
|
+
const { url, content_type: contentType, insecure_ssl: insecureSsl } = result.data
|
|
111
|
+
let normalized: string
|
|
112
|
+
try {
|
|
113
|
+
normalized = normalizeWebhookUrl(url)
|
|
114
|
+
} catch {
|
|
115
|
+
return null
|
|
116
|
+
}
|
|
117
|
+
if (normalized !== url) return null
|
|
118
|
+
return { url, contentType, insecureSsl: String(insecureSsl) === '0' ? '0' : '1' }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function hasAsciiControl(value: string): boolean {
|
|
122
|
+
for (const character of value) {
|
|
123
|
+
const code = character.charCodeAt(0)
|
|
124
|
+
if (code < 32 || code === 127) return true
|
|
125
|
+
}
|
|
126
|
+
return false
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function isPositiveSafeInteger(value: number): boolean {
|
|
130
|
+
return Number.isSafeInteger(value) && value > 0
|
|
131
|
+
}
|