@fabrika/github-app 0.9.0-cloudflare.2 → 0.9.0-cloudflare.3
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 +1 -1
- package/src/client.ts +41 -6
- package/src/errors.ts +36 -2
- package/src/index.ts +1 -1
- package/src/manifest.ts +7 -2
- package/src/repository.ts +2 -1
- package/src/transport.ts +16 -0
- package/src/types.ts +6 -0
- package/types/src/client.d.ts +7 -0
- package/types/src/errors.d.ts +18 -1
- package/types/src/index.d.ts +1 -1
- package/types/src/transport.d.ts +2 -0
- package/types/src/types.d.ts +6 -0
package/package.json
CHANGED
package/src/client.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { configurationError, requestStatusError, responseError } from './errors'
|
|
1
|
+
import { configurationError, GitHubRateLimitError, requestStatusError, responseError } from './errors'
|
|
2
2
|
import { createRepositoryClient } from './repository'
|
|
3
3
|
import type { GitHubRepositoryClient, GitHubRepositoryOpenRequest } from './repository-types'
|
|
4
4
|
import { pemToPkcs8, signAppJwt } from './signing'
|
|
5
|
-
import { createCancellation, GITHUB_ACCEPT, GITHUB_API_VERSION, GITHUB_USER_AGENT, readBoundedJson } from './transport'
|
|
5
|
+
import { createCancellation, GITHUB_ACCEPT, GITHUB_API_VERSION, GITHUB_USER_AGENT, pause, readBoundedJson } from './transport'
|
|
6
6
|
import type {
|
|
7
7
|
GitHubAppClientConfig,
|
|
8
8
|
GitHubAppFetch,
|
|
@@ -26,6 +26,12 @@ import {
|
|
|
26
26
|
validateWebhookSecret,
|
|
27
27
|
} from './validation'
|
|
28
28
|
|
|
29
|
+
/** The most anonymous reads of the App's public page a client may make before a rate limit is the caller's answer. */
|
|
30
|
+
const MAX_PUBLIC_APP_ATTEMPTS = 4
|
|
31
|
+
/** The wait before the next anonymous read when GitHub names none; it doubles with each read. */
|
|
32
|
+
const PUBLIC_APP_BACKOFF_MS = 500
|
|
33
|
+
/** A `retry-after` longer than this is GitHub's answer: the read is not tried again. */
|
|
34
|
+
const MAX_PUBLIC_APP_WAIT_MS = 5_000
|
|
29
35
|
const DEFAULT_API_BASE_URL = 'https://api.github.com'
|
|
30
36
|
const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
|
|
31
37
|
const MAX_REQUEST_TIMEOUT_MS = 120_000
|
|
@@ -41,6 +47,7 @@ export class GitHubAppClient {
|
|
|
41
47
|
private readonly fetchImplementation: GitHubAppFetch,
|
|
42
48
|
private readonly clock: () => number,
|
|
43
49
|
private readonly timeoutMs: number,
|
|
50
|
+
private readonly publicAppAttempts: number,
|
|
44
51
|
) {}
|
|
45
52
|
|
|
46
53
|
/** Validate all configuration and import the RSA key before a credential-owning service boots. */
|
|
@@ -53,6 +60,10 @@ export class GitHubAppClient {
|
|
|
53
60
|
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_REQUEST_TIMEOUT_MS) {
|
|
54
61
|
throw configurationError()
|
|
55
62
|
}
|
|
63
|
+
const publicAppAttempts = config.publicAppAttempts ?? 1
|
|
64
|
+
if (!Number.isSafeInteger(publicAppAttempts) || publicAppAttempts < 1 || publicAppAttempts > MAX_PUBLIC_APP_ATTEMPTS) {
|
|
65
|
+
throw configurationError()
|
|
66
|
+
}
|
|
56
67
|
let privateKey: CryptoKey
|
|
57
68
|
try {
|
|
58
69
|
privateKey = await crypto.subtle.importKey(
|
|
@@ -65,7 +76,10 @@ export class GitHubAppClient {
|
|
|
65
76
|
} catch {
|
|
66
77
|
throw configurationError()
|
|
67
78
|
}
|
|
68
|
-
|
|
79
|
+
// The global `fetch` is wrapped: a Worker refuses it with any other `this` ("Illegal invocation"), and the client calls
|
|
80
|
+
// it as its own property, and hands it to the repository client.
|
|
81
|
+
const fetchImplementation = config.fetch ?? ((input, init) => fetch(input, init))
|
|
82
|
+
return new GitHubAppClient(config.appId, privateKey, apiBaseUrl, fetchImplementation, config.now ?? Date.now, timeoutMs, publicAppAttempts)
|
|
69
83
|
}
|
|
70
84
|
|
|
71
85
|
/** Read and bind the public identity represented by this client's App credentials. */
|
|
@@ -74,13 +88,31 @@ export class GitHubAppClient {
|
|
|
74
88
|
if (body === NOT_FOUND) throw responseError()
|
|
75
89
|
const identity = decodeAppIdentity(body)
|
|
76
90
|
if (identity === null || String(identity.id) !== this.appId) throw responseError()
|
|
77
|
-
const publicBody = await this.
|
|
91
|
+
const publicBody = await this.publicApp(identity.slug, signal)
|
|
78
92
|
if (publicBody === NOT_FOUND) return { ...identity, public: false }
|
|
79
93
|
const publicIdentity = decodeAppIdentity(publicBody)
|
|
80
94
|
if (publicIdentity === null || !sameAppIdentity(identity, publicIdentity)) throw responseError()
|
|
81
95
|
return { ...identity, public: true }
|
|
82
96
|
}
|
|
83
97
|
|
|
98
|
+
/**
|
|
99
|
+
* The App's public page, read without credentials: GitHub answers it only for a public App. The read is anonymous,
|
|
100
|
+
* so it spends the caller's address's limit. Where the next read may leave from another address (a Worker on a cloud's
|
|
101
|
+
* shared egress), the client is configured to try a rate-limited read again after a short wait.
|
|
102
|
+
*/
|
|
103
|
+
private async publicApp(slug: string, signal?: AbortSignal): Promise<unknown | typeof NOT_FOUND> {
|
|
104
|
+
for (let attempt = 1;; attempt++) {
|
|
105
|
+
try {
|
|
106
|
+
return await this.requestJson(`/apps/${slug}`, {}, signal, true, false)
|
|
107
|
+
} catch (error) {
|
|
108
|
+
if (!(error instanceof GitHubRateLimitError) || attempt >= this.publicAppAttempts) throw error
|
|
109
|
+
const wait = error.retryAfterMs ?? PUBLIC_APP_BACKOFF_MS * 2 ** (attempt - 1)
|
|
110
|
+
if (wait > MAX_PUBLIC_APP_WAIT_MS) throw error
|
|
111
|
+
await pause(wait, signal)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
84
116
|
/** Read the App webhook transport settings without exposing GitHub's masked secret field. */
|
|
85
117
|
async getWebhookConfig(signal?: AbortSignal): Promise<GitHubAppWebhookConfig> {
|
|
86
118
|
const body = await this.requestJson('/app/hook/config', {}, signal, false)
|
|
@@ -224,7 +256,8 @@ export class GitHubAppClient {
|
|
|
224
256
|
response = await this.fetchImplementation(`${this.apiBaseUrl}${path}`, {
|
|
225
257
|
...init,
|
|
226
258
|
headers,
|
|
227
|
-
redirect: 'error'
|
|
259
|
+
// Workers refuse `redirect: 'error'`; a redirect is a response that is not `ok` and fails below.
|
|
260
|
+
redirect: 'manual',
|
|
228
261
|
signal: cancellation.signal,
|
|
229
262
|
})
|
|
230
263
|
} catch {
|
|
@@ -236,7 +269,9 @@ export class GitHubAppClient {
|
|
|
236
269
|
return NOT_FOUND
|
|
237
270
|
}
|
|
238
271
|
if (!response.ok) {
|
|
239
|
-
|
|
272
|
+
// An unread body holds its connection open on workerd, and a retried read would hold another.
|
|
273
|
+
void response.body?.cancel().catch(() => {})
|
|
274
|
+
throw requestStatusError(response.status, response.headers, !authenticate, () => this.now())
|
|
240
275
|
}
|
|
241
276
|
return await readBoundedJson(response, cancellation)
|
|
242
277
|
} finally {
|
package/src/errors.ts
CHANGED
|
@@ -10,8 +10,42 @@ export class GitHubRequestError extends Error {
|
|
|
10
10
|
}
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
/**
|
|
14
|
+
* GitHub refused a request for its rate limit: a 429, or a 403 that says the limit is spent (`x-ratelimit-remaining: 0`)
|
|
15
|
+
* or when to come back (`retry-after`, GitHub's secondary limit). An anonymous read spends the caller's address's limit,
|
|
16
|
+
* which every tenant of a cloud's shared egress spends with it.
|
|
17
|
+
*/
|
|
18
|
+
export class GitHubRateLimitError extends GitHubRequestError {
|
|
19
|
+
constructor(
|
|
20
|
+
status: number,
|
|
21
|
+
readonly anonymous: boolean,
|
|
22
|
+
/** When GitHub admits the next request: `retry-after` when it sends one, else `x-ratelimit-reset`. */
|
|
23
|
+
readonly resetAt: Date | undefined,
|
|
24
|
+
/** GitHub's `retry-after`, in milliseconds; only the secondary limit sends it. */
|
|
25
|
+
readonly retryAfterMs: number | undefined,
|
|
26
|
+
) {
|
|
27
|
+
super(status)
|
|
28
|
+
this.name = 'GitHubRateLimitError'
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function requestStatusError(
|
|
33
|
+
status: number,
|
|
34
|
+
headers?: Headers,
|
|
35
|
+
anonymous = false,
|
|
36
|
+
now: () => number = Date.now,
|
|
37
|
+
): GitHubRequestError {
|
|
38
|
+
const retryAfter = headers?.get('retry-after') ?? null
|
|
39
|
+
const limited = status === 429 || (status === 403 && (headers?.get('x-ratelimit-remaining') === '0' || retryAfter !== null))
|
|
40
|
+
if (!limited) return new GitHubRequestError(status)
|
|
41
|
+
const retryAfterMs = retryAfter !== null && /^\d{1,6}$/.test(retryAfter) ? Number(retryAfter) * 1000 : undefined
|
|
42
|
+
const reset = headers?.get('x-ratelimit-reset') ?? null
|
|
43
|
+
const resetAt = retryAfterMs !== undefined
|
|
44
|
+
? new Date(now() + retryAfterMs)
|
|
45
|
+
: reset !== null && /^\d{1,12}$/.test(reset)
|
|
46
|
+
? new Date(Number(reset) * 1000)
|
|
47
|
+
: undefined
|
|
48
|
+
return new GitHubRateLimitError(status, anonymous, resetAt, retryAfterMs)
|
|
15
49
|
}
|
|
16
50
|
|
|
17
51
|
export function responseError(): Error {
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { GitHubAppClient } from './client'
|
|
2
|
-
export { GitHubBranchConflictError, GitHubNotFoundError, GitHubRequestError, GitHubStaleHeadError } from './errors'
|
|
2
|
+
export { GitHubBranchConflictError, GitHubNotFoundError, GitHubRateLimitError, GitHubRequestError, GitHubStaleHeadError } from './errors'
|
|
3
3
|
export { buildGitHubAppManifest, exchangeGitHubAppManifestCode } from './manifest'
|
|
4
4
|
export type {
|
|
5
5
|
GitHubBlobRead,
|
package/src/manifest.ts
CHANGED
|
@@ -57,7 +57,8 @@ export async function exchangeGitHubAppManifestCode(
|
|
|
57
57
|
'user-agent': GITHUB_MANIFEST_USER_AGENT,
|
|
58
58
|
'x-github-api-version': GITHUB_API_VERSION,
|
|
59
59
|
},
|
|
60
|
-
redirect: 'error'
|
|
60
|
+
// Workers refuse `redirect: 'error'`; a redirect is a response that is not `ok` and fails below.
|
|
61
|
+
redirect: 'manual',
|
|
61
62
|
signal: cancellation.signal,
|
|
62
63
|
},
|
|
63
64
|
)
|
|
@@ -66,7 +67,10 @@ export async function exchangeGitHubAppManifestCode(
|
|
|
66
67
|
throw new Error('GitHub App manifest conversion failed')
|
|
67
68
|
}
|
|
68
69
|
cancellation.throwIfCancelled()
|
|
69
|
-
if (!response.ok)
|
|
70
|
+
if (!response.ok) {
|
|
71
|
+
void response.body?.cancel().catch(() => {})
|
|
72
|
+
throw new Error('GitHub App manifest conversion failed')
|
|
73
|
+
}
|
|
70
74
|
const app = decodeManifestConversion(await readManifestConversionJson(response, cancellation))
|
|
71
75
|
if (app === null) throw new Error('GitHub App manifest conversion returned an invalid response')
|
|
72
76
|
return app
|
|
@@ -109,6 +113,7 @@ async function readManifestConversionJson(response: Response, cancellation: Mani
|
|
|
109
113
|
cancellation.throwIfCancelled()
|
|
110
114
|
const contentLength = response.headers.get('content-length')
|
|
111
115
|
if (contentLength !== null && /^[0-9]+$/.test(contentLength) && Number(contentLength) > MAX_MANIFEST_CONVERSION_BYTES) {
|
|
116
|
+
void response.body?.cancel().catch(() => {})
|
|
112
117
|
throw new Error('GitHub App manifest conversion returned an invalid response')
|
|
113
118
|
}
|
|
114
119
|
const reader = response.body?.getReader()
|
package/src/repository.ts
CHANGED
|
@@ -373,7 +373,8 @@ class RepositoryClient implements GitHubRepositoryClient {
|
|
|
373
373
|
method: options.method ?? 'GET',
|
|
374
374
|
headers,
|
|
375
375
|
...(options.body === undefined ? {} : { body: JSON.stringify(options.body) }),
|
|
376
|
-
redirect: 'error'
|
|
376
|
+
// Workers refuse `redirect: 'error'`; a redirect is a response that is not `ok` and fails below.
|
|
377
|
+
redirect: 'manual',
|
|
377
378
|
signal: cancellation.signal,
|
|
378
379
|
})
|
|
379
380
|
} catch {
|
package/src/transport.ts
CHANGED
|
@@ -135,6 +135,22 @@ function readChunk(
|
|
|
135
135
|
})
|
|
136
136
|
}
|
|
137
137
|
|
|
138
|
+
/** Wait `milliseconds`, or reject as soon as the caller aborts. */
|
|
139
|
+
export function pause(milliseconds: number, signal: AbortSignal | undefined): Promise<void> {
|
|
140
|
+
if (signal?.aborted === true) return Promise.reject(abortError())
|
|
141
|
+
return new Promise((resolve, reject) => {
|
|
142
|
+
const abort = (): void => {
|
|
143
|
+
clearTimeout(timer)
|
|
144
|
+
reject(abortError())
|
|
145
|
+
}
|
|
146
|
+
const timer = setTimeout(() => {
|
|
147
|
+
signal?.removeEventListener('abort', abort)
|
|
148
|
+
resolve()
|
|
149
|
+
}, milliseconds)
|
|
150
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
|
|
138
154
|
function abortError(): DOMException {
|
|
139
155
|
return new DOMException('GitHub App request was aborted', 'AbortError')
|
|
140
156
|
}
|
package/src/types.ts
CHANGED
|
@@ -11,6 +11,12 @@ export interface GitHubAppClientConfig {
|
|
|
11
11
|
now?: () => number
|
|
12
12
|
/** Upper bound for each GitHub API request, including its response body. */
|
|
13
13
|
timeoutMs?: number
|
|
14
|
+
/**
|
|
15
|
+
* Anonymous reads of the App's public page before a rate limit is the answer, 1–4; 1 by default. Raise it only where
|
|
16
|
+
* each read may leave from another address (a Worker on a cloud's shared egress): from one fixed address a spent limit
|
|
17
|
+
* stays spent until it resets.
|
|
18
|
+
*/
|
|
19
|
+
publicAppAttempts?: number
|
|
14
20
|
}
|
|
15
21
|
|
|
16
22
|
export interface GitHubInstallationToken {
|
package/types/src/client.d.ts
CHANGED
|
@@ -8,11 +8,18 @@ export declare class GitHubAppClient {
|
|
|
8
8
|
private readonly fetchImplementation;
|
|
9
9
|
private readonly clock;
|
|
10
10
|
private readonly timeoutMs;
|
|
11
|
+
private readonly publicAppAttempts;
|
|
11
12
|
private constructor();
|
|
12
13
|
/** Validate all configuration and import the RSA key before a credential-owning service boots. */
|
|
13
14
|
static create(config: GitHubAppClientConfig): Promise<GitHubAppClient>;
|
|
14
15
|
/** Read and bind the public identity represented by this client's App credentials. */
|
|
15
16
|
getAuthenticatedApp(signal?: AbortSignal): Promise<GitHubAppIdentity>;
|
|
17
|
+
/**
|
|
18
|
+
* The App's public page, read without credentials: GitHub answers it only for a public App. The read is anonymous,
|
|
19
|
+
* so it spends the caller's address's limit. Where the next read may leave from another address (a Worker on a cloud's
|
|
20
|
+
* shared egress), the client is configured to try a rate-limited read again after a short wait.
|
|
21
|
+
*/
|
|
22
|
+
private publicApp;
|
|
16
23
|
/** Read the App webhook transport settings without exposing GitHub's masked secret field. */
|
|
17
24
|
getWebhookConfig(signal?: AbortSignal): Promise<GitHubAppWebhookConfig>;
|
|
18
25
|
/** Set the App webhook to JSON over verified TLS and bind GitHub's response to that request. */
|
package/types/src/errors.d.ts
CHANGED
|
@@ -4,7 +4,24 @@ export declare class GitHubRequestError extends Error {
|
|
|
4
4
|
readonly status: number;
|
|
5
5
|
constructor(status: number);
|
|
6
6
|
}
|
|
7
|
-
|
|
7
|
+
/**
|
|
8
|
+
* GitHub refused a request for its rate limit: a 429, or a 403 that says the limit is spent (`x-ratelimit-remaining: 0`)
|
|
9
|
+
* or when to come back (`retry-after`, GitHub's secondary limit). An anonymous read spends the caller's address's limit,
|
|
10
|
+
* which every tenant of a cloud's shared egress spends with it.
|
|
11
|
+
*/
|
|
12
|
+
export declare class GitHubRateLimitError extends GitHubRequestError {
|
|
13
|
+
readonly anonymous: boolean;
|
|
14
|
+
/** When GitHub admits the next request: `retry-after` when it sends one, else `x-ratelimit-reset`. */
|
|
15
|
+
readonly resetAt: Date | undefined;
|
|
16
|
+
/** GitHub's `retry-after`, in milliseconds; only the secondary limit sends it. */
|
|
17
|
+
readonly retryAfterMs: number | undefined;
|
|
18
|
+
constructor(status: number, anonymous: boolean,
|
|
19
|
+
/** When GitHub admits the next request: `retry-after` when it sends one, else `x-ratelimit-reset`. */
|
|
20
|
+
resetAt: Date | undefined,
|
|
21
|
+
/** GitHub's `retry-after`, in milliseconds; only the secondary limit sends it. */
|
|
22
|
+
retryAfterMs: number | undefined);
|
|
23
|
+
}
|
|
24
|
+
export declare function requestStatusError(status: number, headers?: Headers, anonymous?: boolean, now?: () => number): GitHubRequestError;
|
|
8
25
|
export declare function responseError(): Error;
|
|
9
26
|
/** The branch moved since the caller read it; re-read the head and retry the change on top of it. */
|
|
10
27
|
export declare class GitHubStaleHeadError extends Error {
|
package/types/src/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { GitHubAppClient } from './client';
|
|
2
|
-
export { GitHubBranchConflictError, GitHubNotFoundError, GitHubRequestError, GitHubStaleHeadError } from './errors';
|
|
2
|
+
export { GitHubBranchConflictError, GitHubNotFoundError, GitHubRateLimitError, GitHubRequestError, GitHubStaleHeadError } from './errors';
|
|
3
3
|
export { buildGitHubAppManifest, exchangeGitHubAppManifestCode } from './manifest';
|
|
4
4
|
export type { GitHubBlobRead, GitHubBlobRef, GitHubChangedFile, GitHubChangedFileStatus, GitHubCommit, GitHubCommitFilesInput, GitHubComparison, GitHubCreateBranchInput, GitHubFileChange, GitHubFileRead, GitHubOpenPullRequestInput, GitHubPullRequestRef, GitHubRef, GitHubRepositoryClient, GitHubRepositoryOpenRequest, GitHubTextFile, GitHubTreeEntry, GitHubTreeListing, GitHubUnreadablePath, GitHubUnreadableReason, } from './repository-types';
|
|
5
5
|
export { pemToPkcs8 } from './signing';
|
package/types/src/transport.d.ts
CHANGED
|
@@ -8,4 +8,6 @@ interface RequestCancellation {
|
|
|
8
8
|
}
|
|
9
9
|
export declare function createCancellation(callerSignal: AbortSignal | undefined, timeoutMs: number): RequestCancellation;
|
|
10
10
|
export declare function readBoundedJson(response: Response, cancellation: RequestCancellation, maxResponseBytes?: number): Promise<unknown>;
|
|
11
|
+
/** Wait `milliseconds`, or reject as soon as the caller aborts. */
|
|
12
|
+
export declare function pause(milliseconds: number, signal: AbortSignal | undefined): Promise<void>;
|
|
11
13
|
export {};
|
package/types/src/types.d.ts
CHANGED
|
@@ -11,6 +11,12 @@ export interface GitHubAppClientConfig {
|
|
|
11
11
|
now?: () => number;
|
|
12
12
|
/** Upper bound for each GitHub API request, including its response body. */
|
|
13
13
|
timeoutMs?: number;
|
|
14
|
+
/**
|
|
15
|
+
* Anonymous reads of the App's public page before a rate limit is the answer, 1–4; 1 by default. Raise it only where
|
|
16
|
+
* each read may leave from another address (a Worker on a cloud's shared egress): from one fixed address a spent limit
|
|
17
|
+
* stays spent until it resets.
|
|
18
|
+
*/
|
|
19
|
+
publicAppAttempts?: number;
|
|
14
20
|
}
|
|
15
21
|
export interface GitHubInstallationToken {
|
|
16
22
|
token: string;
|