@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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/github-app",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -24,5 +24,8 @@
|
|
|
24
24
|
"scripts": {
|
|
25
25
|
"typecheck": "tsc --noEmit",
|
|
26
26
|
"test": "bun test"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"zod": "^3.25.76"
|
|
27
30
|
}
|
|
28
31
|
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { configurationError, requestStatusError, responseError } from './errors'
|
|
2
|
+
import { pemToPkcs8, signAppJwt } from './signing'
|
|
3
|
+
import { createCancellation, GITHUB_ACCEPT, GITHUB_API_VERSION, readBoundedJson } from './transport'
|
|
4
|
+
import type {
|
|
5
|
+
GitHubAppClientConfig,
|
|
6
|
+
GitHubAppFetch,
|
|
7
|
+
GitHubAppIdentity,
|
|
8
|
+
GitHubAppInstallation,
|
|
9
|
+
GitHubAppWebhookConfig,
|
|
10
|
+
GitHubAppWebhookUpdate,
|
|
11
|
+
GitHubInstallationToken,
|
|
12
|
+
GitHubRepositoryTokenRequest,
|
|
13
|
+
} from './types'
|
|
14
|
+
import {
|
|
15
|
+
decodeAppIdentity,
|
|
16
|
+
decodeWebhookConfig,
|
|
17
|
+
installationSchema,
|
|
18
|
+
installationTokenSchema,
|
|
19
|
+
isPositiveSafeInteger,
|
|
20
|
+
normalizeApiBaseUrl,
|
|
21
|
+
normalizeWebhookUrl,
|
|
22
|
+
sameAppIdentity,
|
|
23
|
+
validateRepositoryComponent,
|
|
24
|
+
validateWebhookSecret,
|
|
25
|
+
} from './validation'
|
|
26
|
+
|
|
27
|
+
const DEFAULT_API_BASE_URL = 'https://api.github.com'
|
|
28
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
|
|
29
|
+
const MAX_REQUEST_TIMEOUT_MS = 120_000
|
|
30
|
+
const GITHUB_USER_AGENT = 'vozka'
|
|
31
|
+
const APP_ID_PATTERN = /^[1-9][0-9]*$/
|
|
32
|
+
const NOT_FOUND = Symbol('not-found')
|
|
33
|
+
|
|
34
|
+
/** GitHub App machine identity. Webhook authentication belongs to the receiving service. */
|
|
35
|
+
export class GitHubAppClient {
|
|
36
|
+
private constructor(
|
|
37
|
+
private readonly appId: string,
|
|
38
|
+
private readonly privateKey: CryptoKey,
|
|
39
|
+
private readonly apiBaseUrl: string,
|
|
40
|
+
private readonly fetchImplementation: GitHubAppFetch,
|
|
41
|
+
private readonly clock: () => number,
|
|
42
|
+
private readonly timeoutMs: number,
|
|
43
|
+
) {}
|
|
44
|
+
|
|
45
|
+
/** Validate all configuration and import the RSA key before a credential-owning service boots. */
|
|
46
|
+
static async create(config: GitHubAppClientConfig): Promise<GitHubAppClient> {
|
|
47
|
+
if (!APP_ID_PATTERN.test(config.appId) || config.appId.length > 32) {
|
|
48
|
+
throw configurationError()
|
|
49
|
+
}
|
|
50
|
+
const apiBaseUrl = normalizeApiBaseUrl(config.apiBaseUrl ?? DEFAULT_API_BASE_URL)
|
|
51
|
+
const timeoutMs = config.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
|
|
52
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_REQUEST_TIMEOUT_MS) {
|
|
53
|
+
throw configurationError()
|
|
54
|
+
}
|
|
55
|
+
let privateKey: CryptoKey
|
|
56
|
+
try {
|
|
57
|
+
privateKey = await crypto.subtle.importKey(
|
|
58
|
+
'pkcs8',
|
|
59
|
+
pemToPkcs8(config.privateKeyPem),
|
|
60
|
+
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
|
|
61
|
+
false,
|
|
62
|
+
['sign'],
|
|
63
|
+
)
|
|
64
|
+
} catch {
|
|
65
|
+
throw configurationError()
|
|
66
|
+
}
|
|
67
|
+
return new GitHubAppClient(config.appId, privateKey, apiBaseUrl, config.fetch ?? fetch, config.now ?? Date.now, timeoutMs)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Read and bind the public identity represented by this client's App credentials. */
|
|
71
|
+
async getAuthenticatedApp(signal?: AbortSignal): Promise<GitHubAppIdentity> {
|
|
72
|
+
const body = await this.requestJson('/app', {}, signal, false)
|
|
73
|
+
if (body === NOT_FOUND) throw responseError()
|
|
74
|
+
const identity = decodeAppIdentity(body)
|
|
75
|
+
if (identity === null || String(identity.id) !== this.appId) throw responseError()
|
|
76
|
+
const publicBody = await this.requestJson(`/apps/${identity.slug}`, {}, signal, true, false)
|
|
77
|
+
if (publicBody === NOT_FOUND) return { ...identity, public: false }
|
|
78
|
+
const publicIdentity = decodeAppIdentity(publicBody)
|
|
79
|
+
if (publicIdentity === null || !sameAppIdentity(identity, publicIdentity)) throw responseError()
|
|
80
|
+
return { ...identity, public: true }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Read the App webhook transport settings without exposing GitHub's masked secret field. */
|
|
84
|
+
async getWebhookConfig(signal?: AbortSignal): Promise<GitHubAppWebhookConfig> {
|
|
85
|
+
const body = await this.requestJson('/app/hook/config', {}, signal, false)
|
|
86
|
+
if (body === NOT_FOUND) throw responseError()
|
|
87
|
+
const config = decodeWebhookConfig(body)
|
|
88
|
+
if (config === null) throw responseError()
|
|
89
|
+
return config
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Set the App webhook to JSON over verified TLS and bind GitHub's response to that request. */
|
|
93
|
+
async updateWebhookConfig(input: GitHubAppWebhookUpdate): Promise<GitHubAppWebhookConfig> {
|
|
94
|
+
const webhookUrl = normalizeWebhookUrl(input.url)
|
|
95
|
+
validateWebhookSecret(input.secret)
|
|
96
|
+
const body = await this.requestJson(
|
|
97
|
+
'/app/hook/config',
|
|
98
|
+
{
|
|
99
|
+
method: 'PATCH',
|
|
100
|
+
headers: { 'content-type': 'application/json' },
|
|
101
|
+
body: JSON.stringify({ url: webhookUrl, content_type: 'json', insecure_ssl: '0', secret: input.secret }),
|
|
102
|
+
},
|
|
103
|
+
input.signal,
|
|
104
|
+
false,
|
|
105
|
+
)
|
|
106
|
+
if (body === NOT_FOUND) throw responseError()
|
|
107
|
+
const config = decodeWebhookConfig(body)
|
|
108
|
+
if (config === null || config.url !== webhookUrl || config.contentType !== 'json' || config.insecureSsl !== '0') {
|
|
109
|
+
throw responseError()
|
|
110
|
+
}
|
|
111
|
+
return config
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Resolve the App installation owned by one organization. A 404 is an expected miss. */
|
|
115
|
+
async resolveOrganizationInstallationId(organization: string, signal?: AbortSignal): Promise<number | null> {
|
|
116
|
+
return (await this.resolveOrganizationInstallation(organization, signal))?.id ?? null
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Resolve and strictly bind the installation authority owned by one organization. */
|
|
120
|
+
async resolveOrganizationInstallation(organization: string, signal?: AbortSignal): Promise<GitHubAppInstallation | null> {
|
|
121
|
+
validateRepositoryComponent(organization)
|
|
122
|
+
const body = await this.requestJson(`/orgs/${organization}/installation`, {}, signal, true)
|
|
123
|
+
if (body === NOT_FOUND) return null
|
|
124
|
+
return this.decodeInstallation(body, organization, 'Organization')
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Resolve the App installation for one GitHub repository. A 404 is an expected miss. */
|
|
128
|
+
async resolveInstallationId(owner: string, repository: string, signal?: AbortSignal): Promise<number | null> {
|
|
129
|
+
return (await this.resolveRepositoryInstallation(owner, repository, signal))?.id ?? null
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Resolve and strictly bind the installation authority that grants one repository. */
|
|
133
|
+
async resolveRepositoryInstallation(owner: string, repository: string, signal?: AbortSignal): Promise<GitHubAppInstallation | null> {
|
|
134
|
+
validateRepositoryComponent(owner)
|
|
135
|
+
validateRepositoryComponent(repository)
|
|
136
|
+
const body = await this.requestJson(`/repos/${owner}/${repository}/installation`, {}, signal, true)
|
|
137
|
+
if (body === NOT_FOUND) {
|
|
138
|
+
return null
|
|
139
|
+
}
|
|
140
|
+
return this.decodeInstallation(body, owner)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Mint a read-only token restricted to one repository in the selected installation. */
|
|
144
|
+
async mintRepositoryToken(input: GitHubRepositoryTokenRequest): Promise<GitHubInstallationToken> {
|
|
145
|
+
if (!isPositiveSafeInteger(input.installationId)) {
|
|
146
|
+
throw configurationError()
|
|
147
|
+
}
|
|
148
|
+
validateRepositoryComponent(input.owner)
|
|
149
|
+
validateRepositoryComponent(input.repository)
|
|
150
|
+
const body = await this.requestJson(
|
|
151
|
+
`/app/installations/${input.installationId}/access_tokens`,
|
|
152
|
+
{
|
|
153
|
+
method: 'POST',
|
|
154
|
+
headers: { 'content-type': 'application/json' },
|
|
155
|
+
body: JSON.stringify({ repositories: [input.repository], permissions: { contents: 'read' } }),
|
|
156
|
+
},
|
|
157
|
+
input.signal,
|
|
158
|
+
false,
|
|
159
|
+
)
|
|
160
|
+
if (body === NOT_FOUND) {
|
|
161
|
+
throw responseError()
|
|
162
|
+
}
|
|
163
|
+
const result = installationTokenSchema.safeParse(body)
|
|
164
|
+
if (!result.success) throw responseError()
|
|
165
|
+
const { token, expires_at: expiresAt } = result.data
|
|
166
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= this.now()) {
|
|
167
|
+
throw responseError()
|
|
168
|
+
}
|
|
169
|
+
return { token, expiresAt }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
private async requestJson(
|
|
173
|
+
path: string,
|
|
174
|
+
init: RequestInit,
|
|
175
|
+
callerSignal: AbortSignal | undefined,
|
|
176
|
+
allowNotFound: boolean,
|
|
177
|
+
authenticate = true,
|
|
178
|
+
): Promise<unknown | typeof NOT_FOUND> {
|
|
179
|
+
const cancellation = createCancellation(callerSignal, this.timeoutMs)
|
|
180
|
+
try {
|
|
181
|
+
cancellation.throwIfCancelled()
|
|
182
|
+
const headers = new Headers(init.headers)
|
|
183
|
+
if (authenticate) {
|
|
184
|
+
let jwt: string
|
|
185
|
+
try {
|
|
186
|
+
jwt = await signAppJwt(this.appId, this.privateKey, () => this.now())
|
|
187
|
+
} catch (error) {
|
|
188
|
+
cancellation.throwIfCancelled()
|
|
189
|
+
throw error
|
|
190
|
+
}
|
|
191
|
+
cancellation.throwIfCancelled()
|
|
192
|
+
headers.set('authorization', `Bearer ${jwt}`)
|
|
193
|
+
}
|
|
194
|
+
headers.set('accept', GITHUB_ACCEPT)
|
|
195
|
+
headers.set('x-github-api-version', GITHUB_API_VERSION)
|
|
196
|
+
headers.set('user-agent', GITHUB_USER_AGENT)
|
|
197
|
+
let response: Response
|
|
198
|
+
try {
|
|
199
|
+
response = await this.fetchImplementation(`${this.apiBaseUrl}${path}`, {
|
|
200
|
+
...init,
|
|
201
|
+
headers,
|
|
202
|
+
redirect: 'error',
|
|
203
|
+
signal: cancellation.signal,
|
|
204
|
+
})
|
|
205
|
+
} catch {
|
|
206
|
+
cancellation.throwIfCancelled()
|
|
207
|
+
throw new Error('GitHub App request failed')
|
|
208
|
+
}
|
|
209
|
+
cancellation.throwIfCancelled()
|
|
210
|
+
if (allowNotFound && response.status === 404) {
|
|
211
|
+
return NOT_FOUND
|
|
212
|
+
}
|
|
213
|
+
if (!response.ok) {
|
|
214
|
+
throw requestStatusError(response.status)
|
|
215
|
+
}
|
|
216
|
+
return await readBoundedJson(response, cancellation)
|
|
217
|
+
} finally {
|
|
218
|
+
cancellation.dispose()
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private decodeInstallation(body: unknown, accountLogin: string, requiredType?: 'Organization' | 'User'): GitHubAppInstallation {
|
|
223
|
+
const result = installationSchema.safeParse(body)
|
|
224
|
+
if (!result.success) throw responseError()
|
|
225
|
+
const { id, app_id: appId, target_type: targetType, account: { login, type: accountType }, repository_selection: repositorySelection } = result.data
|
|
226
|
+
if (
|
|
227
|
+
String(appId) !== this.appId || accountType !== targetType
|
|
228
|
+
|| (requiredType !== undefined && targetType !== requiredType)
|
|
229
|
+
|| login.toLowerCase() !== accountLogin.toLowerCase()
|
|
230
|
+
) {
|
|
231
|
+
throw responseError()
|
|
232
|
+
}
|
|
233
|
+
return { id, accountLogin: login, accountType: targetType, repositorySelection }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private now(): number {
|
|
237
|
+
let value: number
|
|
238
|
+
try {
|
|
239
|
+
value = this.clock()
|
|
240
|
+
} catch {
|
|
241
|
+
throw configurationError()
|
|
242
|
+
}
|
|
243
|
+
if (!Number.isFinite(value)) {
|
|
244
|
+
throw configurationError()
|
|
245
|
+
}
|
|
246
|
+
return value
|
|
247
|
+
}
|
|
248
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export function configurationError(): Error {
|
|
2
|
+
return new Error('GitHub App configuration is invalid')
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function requestStatusError(status: number): Error {
|
|
6
|
+
return new Error(`GitHub App request failed with status ${status}`)
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function responseError(): Error {
|
|
10
|
+
return new Error('GitHub App response is invalid')
|
|
11
|
+
}
|