@catamorphic/github 0.0.0-stage → 0.1.0-alpha.31
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/LICENSE.txt +202 -0
- package/NOTICE.txt +32 -0
- package/README.md +143 -2
- package/dist/api.d.ts +366 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/app-auth.d.ts +84 -0
- package/dist/app-auth.d.ts.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1371 -0
- package/dist/index.js.map +15 -0
- package/dist/manifest.d.ts +83 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/oauth.d.ts +74 -0
- package/dist/oauth.d.ts.map +1 -0
- package/dist/rest.d.ts +57 -0
- package/dist/rest.d.ts.map +1 -0
- package/dist/types.d.ts +307 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +47 -4
- package/src/api.ts +1580 -0
- package/src/app-auth.ts +412 -0
- package/src/index.ts +74 -0
- package/src/manifest.ts +197 -0
- package/src/oauth.ts +272 -0
- package/src/rest.ts +170 -0
- package/src/types.ts +355 -0
package/src/app-auth.ts
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createHash,
|
|
3
|
+
createPrivateKey,
|
|
4
|
+
type KeyObject,
|
|
5
|
+
sign,
|
|
6
|
+
} from "node:crypto";
|
|
7
|
+
import {
|
|
8
|
+
type FetchLike,
|
|
9
|
+
GithubApiError,
|
|
10
|
+
type GithubAppCredentials,
|
|
11
|
+
GithubAuthError,
|
|
12
|
+
type GithubInstallation,
|
|
13
|
+
type GithubInstallationToken,
|
|
14
|
+
type GithubPermissions,
|
|
15
|
+
} from "./types.js";
|
|
16
|
+
|
|
17
|
+
const API_BASE = "https://api.github.com";
|
|
18
|
+
/** GitHub rejects app JWTs that live longer than ten minutes. */
|
|
19
|
+
const JWT_LIFETIME_SECONDS = 9 * 60;
|
|
20
|
+
/** Backdated issue time, tolerating clock drift against GitHub. */
|
|
21
|
+
const JWT_BACKDATE_SECONDS = 60;
|
|
22
|
+
const DEFAULT_REFRESH_SKEW_MS = 5 * 60_000;
|
|
23
|
+
|
|
24
|
+
/** How long one call to GitHub as the App may take. */
|
|
25
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
26
|
+
|
|
27
|
+
/** Parse and check a GitHub App private key (PKCS#1 or PKCS#8 PEM). */
|
|
28
|
+
export function parseGithubAppPrivateKey(privateKey: string): KeyObject {
|
|
29
|
+
let key: KeyObject;
|
|
30
|
+
try {
|
|
31
|
+
key = createPrivateKey(privateKey.trim());
|
|
32
|
+
} catch {
|
|
33
|
+
throw new GithubAuthError(
|
|
34
|
+
"invalid_private_key",
|
|
35
|
+
"The GitHub App private key is not a readable PEM key",
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
if (key.asymmetricKeyType !== "rsa") {
|
|
39
|
+
throw new GithubAuthError(
|
|
40
|
+
"invalid_private_key",
|
|
41
|
+
"A GitHub App private key must be an RSA key",
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
return key;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Sign a GitHub App JWT (RS256): issued a minute in the past, expiring nine
|
|
49
|
+
* minutes from now, with the app ID (or client ID) as issuer. App JWTs only
|
|
50
|
+
* authenticate `/app/...` endpoints, chiefly minting installation tokens.
|
|
51
|
+
*/
|
|
52
|
+
export function createGithubAppJwt(
|
|
53
|
+
args: GithubAppCredentials & { now?: number },
|
|
54
|
+
): string {
|
|
55
|
+
const seconds = Math.floor((args.now ?? Date.now()) / 1000);
|
|
56
|
+
const appId = args.appId.trim();
|
|
57
|
+
if (!appId) {
|
|
58
|
+
throw new GithubAuthError("invalid_app_id", "A GitHub App ID is required");
|
|
59
|
+
}
|
|
60
|
+
const header = { alg: "RS256", typ: "JWT" };
|
|
61
|
+
const payload = {
|
|
62
|
+
iat: seconds - JWT_BACKDATE_SECONDS,
|
|
63
|
+
exp: seconds + JWT_LIFETIME_SECONDS,
|
|
64
|
+
iss: /^\d+$/.test(appId) ? Number(appId) : appId,
|
|
65
|
+
};
|
|
66
|
+
const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(payload))}`;
|
|
67
|
+
const signature = sign(
|
|
68
|
+
"sha256",
|
|
69
|
+
Buffer.from(signingInput),
|
|
70
|
+
parseGithubAppPrivateKey(args.privateKey),
|
|
71
|
+
);
|
|
72
|
+
return `${signingInput}.${signature.toString("base64url")}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface GithubAppAuthOptions {
|
|
76
|
+
fetch?: FetchLike;
|
|
77
|
+
/** REST API base; GitHub Enterprise Server uses `https://HOST/api/v3`. */
|
|
78
|
+
apiBaseUrl?: string;
|
|
79
|
+
/** Clock, for tests. */
|
|
80
|
+
now?: () => number;
|
|
81
|
+
/** Tokens closer than this to expiry are minted again. Default 5 minutes. */
|
|
82
|
+
refreshSkewMs?: number;
|
|
83
|
+
/**
|
|
84
|
+
* How long one call as the App may take before it fails. Default 30
|
|
85
|
+
* seconds: a mint every caller of a token shares must never wait forever.
|
|
86
|
+
*/
|
|
87
|
+
timeoutMs?: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
interface CachedToken {
|
|
91
|
+
pending: Promise<GithubInstallationToken>;
|
|
92
|
+
expiresAt?: number;
|
|
93
|
+
appFingerprint: string;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
interface RawInstallation {
|
|
97
|
+
id: number;
|
|
98
|
+
account: { login: string; id: number; type: string } | null;
|
|
99
|
+
repository_selection: string;
|
|
100
|
+
permissions?: Record<string, string>;
|
|
101
|
+
events?: string[];
|
|
102
|
+
app_slug: string;
|
|
103
|
+
suspended_at: string | null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
interface RawInstallationToken {
|
|
107
|
+
token: string;
|
|
108
|
+
expires_at: string;
|
|
109
|
+
permissions?: Record<string, string>;
|
|
110
|
+
repository_selection?: string;
|
|
111
|
+
repositories?: Array<{ full_name: string }>;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* GitHub App server-side authentication. Holds no credentials itself: every
|
|
116
|
+
* call names the app, so one instance (and its token cache) can serve every
|
|
117
|
+
* connection a host brokers. Installation tokens are cached per app key,
|
|
118
|
+
* installation, repositories, and permissions, and minted again shortly
|
|
119
|
+
* before they expire; concurrent requests share one mint.
|
|
120
|
+
*/
|
|
121
|
+
export class GithubAppAuth {
|
|
122
|
+
private readonly fetch: FetchLike;
|
|
123
|
+
private readonly apiBaseUrl: string;
|
|
124
|
+
private readonly now: () => number;
|
|
125
|
+
private readonly refreshSkewMs: number;
|
|
126
|
+
private readonly timeoutMs: number;
|
|
127
|
+
private readonly tokens = new Map<string, CachedToken>();
|
|
128
|
+
|
|
129
|
+
constructor(options: GithubAppAuthOptions = {}) {
|
|
130
|
+
this.fetch = options.fetch ?? fetch;
|
|
131
|
+
this.apiBaseUrl = (options.apiBaseUrl ?? API_BASE).replace(/\/+$/, "");
|
|
132
|
+
this.now = options.now ?? Date.now;
|
|
133
|
+
this.refreshSkewMs = options.refreshSkewMs ?? DEFAULT_REFRESH_SKEW_MS;
|
|
134
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
appJwt(args: { app: GithubAppCredentials }): string {
|
|
138
|
+
return createGithubAppJwt({ ...args.app, now: this.now() });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* An installation access token, optionally narrowed to repository names
|
|
143
|
+
* (without the owner) and a subset of the installation's permissions.
|
|
144
|
+
*/
|
|
145
|
+
async installationToken(args: {
|
|
146
|
+
app: GithubAppCredentials;
|
|
147
|
+
installationId: number;
|
|
148
|
+
repositories?: readonly string[];
|
|
149
|
+
permissions?: GithubPermissions;
|
|
150
|
+
}): Promise<GithubInstallationToken> {
|
|
151
|
+
requireInstallationId(args.installationId);
|
|
152
|
+
const repositories = [
|
|
153
|
+
...new Set((args.repositories ?? []).map(repositoryName)),
|
|
154
|
+
].sort();
|
|
155
|
+
const permissions = Object.entries(args.permissions ?? {}).sort(
|
|
156
|
+
([left], [right]) => left.localeCompare(right),
|
|
157
|
+
);
|
|
158
|
+
const appFingerprint = fingerprint(args.app);
|
|
159
|
+
const key = JSON.stringify([
|
|
160
|
+
appFingerprint,
|
|
161
|
+
args.installationId,
|
|
162
|
+
repositories,
|
|
163
|
+
permissions,
|
|
164
|
+
]);
|
|
165
|
+
const now = this.now();
|
|
166
|
+
const cached = this.tokens.get(key);
|
|
167
|
+
if (
|
|
168
|
+
cached &&
|
|
169
|
+
(cached.expiresAt === undefined ||
|
|
170
|
+
cached.expiresAt - this.refreshSkewMs > now)
|
|
171
|
+
) {
|
|
172
|
+
return cached.pending;
|
|
173
|
+
}
|
|
174
|
+
this.sweep(now);
|
|
175
|
+
const entry: CachedToken = {
|
|
176
|
+
appFingerprint,
|
|
177
|
+
pending: this.mint({
|
|
178
|
+
app: args.app,
|
|
179
|
+
installationId: args.installationId,
|
|
180
|
+
repositories,
|
|
181
|
+
permissions: Object.fromEntries(permissions),
|
|
182
|
+
}),
|
|
183
|
+
};
|
|
184
|
+
this.tokens.set(key, entry);
|
|
185
|
+
try {
|
|
186
|
+
const token = await entry.pending;
|
|
187
|
+
entry.expiresAt = token.expiresAt;
|
|
188
|
+
return token;
|
|
189
|
+
} catch (error) {
|
|
190
|
+
if (this.tokens.get(key) === entry) this.tokens.delete(key);
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Every installation of the app. */
|
|
196
|
+
async listInstallations(args: {
|
|
197
|
+
app: GithubAppCredentials;
|
|
198
|
+
}): Promise<GithubInstallation[]> {
|
|
199
|
+
const installations: GithubInstallation[] = [];
|
|
200
|
+
for (let page = 1; ; page++) {
|
|
201
|
+
const batch = await this.appRequest<RawInstallation[]>({
|
|
202
|
+
app: args.app,
|
|
203
|
+
path: `/app/installations?per_page=100&page=${page}`,
|
|
204
|
+
});
|
|
205
|
+
installations.push(...batch.map(mapInstallation));
|
|
206
|
+
if (batch.length < 100) return installations;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async installation(args: {
|
|
211
|
+
app: GithubAppCredentials;
|
|
212
|
+
installationId: number;
|
|
213
|
+
}): Promise<GithubInstallation> {
|
|
214
|
+
requireInstallationId(args.installationId);
|
|
215
|
+
return mapInstallation(
|
|
216
|
+
await this.appRequest<RawInstallation>({
|
|
217
|
+
app: args.app,
|
|
218
|
+
path: `/app/installations/${args.installationId}`,
|
|
219
|
+
}),
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* The installation covering an owner (user or organization), or one
|
|
225
|
+
* repository of it. Null when the app is not installed there.
|
|
226
|
+
*/
|
|
227
|
+
async findInstallation(args: {
|
|
228
|
+
app: GithubAppCredentials;
|
|
229
|
+
owner: string;
|
|
230
|
+
repository?: string;
|
|
231
|
+
}): Promise<GithubInstallation | null> {
|
|
232
|
+
const owner = segment(args.owner, "owner");
|
|
233
|
+
const paths = args.repository
|
|
234
|
+
? [
|
|
235
|
+
`/repos/${owner}/${segment(repositoryName(args.repository), "repository")}/installation`,
|
|
236
|
+
]
|
|
237
|
+
: [`/orgs/${owner}/installation`, `/users/${owner}/installation`];
|
|
238
|
+
for (const path of paths) {
|
|
239
|
+
try {
|
|
240
|
+
return mapInstallation(
|
|
241
|
+
await this.appRequest<RawInstallation>({ app: args.app, path }),
|
|
242
|
+
);
|
|
243
|
+
} catch (error) {
|
|
244
|
+
if (!(error instanceof GithubApiError && error.status === 404)) {
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Revoke and forget every cached installation token of an app, for example
|
|
254
|
+
* when its connection is removed. Revocation is best-effort: tokens expire
|
|
255
|
+
* within the hour regardless.
|
|
256
|
+
*/
|
|
257
|
+
async revokeCachedTokens(args: { app: GithubAppCredentials }): Promise<void> {
|
|
258
|
+
const appFingerprint = fingerprint(args.app);
|
|
259
|
+
const entries = [...this.tokens].filter(
|
|
260
|
+
([, entry]) => entry.appFingerprint === appFingerprint,
|
|
261
|
+
);
|
|
262
|
+
for (const [key] of entries) this.tokens.delete(key);
|
|
263
|
+
await Promise.all(
|
|
264
|
+
entries.map(async ([, entry]) => {
|
|
265
|
+
const token = await entry.pending.catch(() => null);
|
|
266
|
+
if (!token || token.expiresAt <= this.now()) return;
|
|
267
|
+
await this.fetch(`${this.apiBaseUrl}/installation/token`, {
|
|
268
|
+
method: "DELETE",
|
|
269
|
+
headers: headers(token.token),
|
|
270
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
271
|
+
}).catch(() => undefined);
|
|
272
|
+
}),
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
private async mint(args: {
|
|
277
|
+
app: GithubAppCredentials;
|
|
278
|
+
installationId: number;
|
|
279
|
+
repositories: readonly string[];
|
|
280
|
+
permissions: Record<string, string>;
|
|
281
|
+
}): Promise<GithubInstallationToken> {
|
|
282
|
+
const raw = await this.appRequest<RawInstallationToken>({
|
|
283
|
+
app: args.app,
|
|
284
|
+
path: `/app/installations/${args.installationId}/access_tokens`,
|
|
285
|
+
method: "POST",
|
|
286
|
+
body: {
|
|
287
|
+
...(args.repositories.length
|
|
288
|
+
? { repositories: args.repositories }
|
|
289
|
+
: {}),
|
|
290
|
+
...(Object.keys(args.permissions).length
|
|
291
|
+
? { permissions: args.permissions }
|
|
292
|
+
: {}),
|
|
293
|
+
},
|
|
294
|
+
});
|
|
295
|
+
const expiresAt = Date.parse(raw.expires_at);
|
|
296
|
+
if (!raw.token || Number.isNaN(expiresAt)) {
|
|
297
|
+
throw new GithubAuthError(
|
|
298
|
+
"invalid_installation_token",
|
|
299
|
+
"GitHub returned an incomplete installation token",
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
return {
|
|
303
|
+
token: raw.token,
|
|
304
|
+
expiresAt,
|
|
305
|
+
permissions: raw.permissions ?? {},
|
|
306
|
+
repositorySelection:
|
|
307
|
+
raw.repository_selection === "selected" ? "selected" : "all",
|
|
308
|
+
...(raw.repositories
|
|
309
|
+
? { repositories: raw.repositories.map((repo) => repo.full_name) }
|
|
310
|
+
: {}),
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
private async appRequest<T>(args: {
|
|
315
|
+
app: GithubAppCredentials;
|
|
316
|
+
path: string;
|
|
317
|
+
method?: string;
|
|
318
|
+
body?: unknown;
|
|
319
|
+
}): Promise<T> {
|
|
320
|
+
const response = await this.fetch(`${this.apiBaseUrl}${args.path}`, {
|
|
321
|
+
method: args.method ?? "GET",
|
|
322
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
323
|
+
headers: {
|
|
324
|
+
...headers(this.appJwt({ app: args.app })),
|
|
325
|
+
...(args.body !== undefined
|
|
326
|
+
? { "Content-Type": "application/json" }
|
|
327
|
+
: {}),
|
|
328
|
+
},
|
|
329
|
+
...(args.body !== undefined ? { body: JSON.stringify(args.body) } : {}),
|
|
330
|
+
});
|
|
331
|
+
if (!response.ok) {
|
|
332
|
+
const body = (await response.json().catch(() => ({}))) as {
|
|
333
|
+
message?: string;
|
|
334
|
+
};
|
|
335
|
+
throw new GithubApiError(
|
|
336
|
+
response.status,
|
|
337
|
+
body.message ?? `GitHub API returned ${response.status}`,
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
return (await response.json()) as T;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
private sweep(now: number): void {
|
|
344
|
+
for (const [key, entry] of this.tokens) {
|
|
345
|
+
if (entry.expiresAt !== undefined && entry.expiresAt <= now) {
|
|
346
|
+
this.tokens.delete(key);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function headers(bearer: string): Record<string, string> {
|
|
353
|
+
return {
|
|
354
|
+
Accept: "application/vnd.github+json",
|
|
355
|
+
Authorization: `Bearer ${bearer}`,
|
|
356
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Cache identity of an app: the private key is part of it, so material
|
|
362
|
+
* naming someone else's app ID with a different key never reuses its tokens.
|
|
363
|
+
*/
|
|
364
|
+
function fingerprint(app: GithubAppCredentials): string {
|
|
365
|
+
return createHash("sha256")
|
|
366
|
+
.update(app.appId.trim())
|
|
367
|
+
.update("\0")
|
|
368
|
+
.update(app.privateKey.trim())
|
|
369
|
+
.digest("hex");
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function mapInstallation(raw: RawInstallation): GithubInstallation {
|
|
373
|
+
return {
|
|
374
|
+
id: raw.id,
|
|
375
|
+
account: raw.account
|
|
376
|
+
? { login: raw.account.login, id: raw.account.id, type: raw.account.type }
|
|
377
|
+
: null,
|
|
378
|
+
repositorySelection:
|
|
379
|
+
raw.repository_selection === "selected" ? "selected" : "all",
|
|
380
|
+
permissions: raw.permissions ?? {},
|
|
381
|
+
events: raw.events ?? [],
|
|
382
|
+
appSlug: raw.app_slug,
|
|
383
|
+
suspendedAt: raw.suspended_at,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function requireInstallationId(value: number): void {
|
|
388
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
389
|
+
throw new GithubAuthError(
|
|
390
|
+
"invalid_installation",
|
|
391
|
+
"A GitHub App installation ID must be a positive integer",
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** `owner/name` or `name` → `name`, the form installation tokens take. */
|
|
397
|
+
function repositoryName(repository: string): string {
|
|
398
|
+
const name = repository.trim().split("/").pop() ?? "";
|
|
399
|
+
return segment(name.replace(/\.git$/, ""), "repository");
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function segment(value: string, what: string): string {
|
|
403
|
+
const trimmed = value.trim();
|
|
404
|
+
if (!/^[\w.-]+$/.test(trimmed) || trimmed === "." || trimmed === "..") {
|
|
405
|
+
throw new GithubApiError(400, `Invalid ${what}: ${value}`);
|
|
406
|
+
}
|
|
407
|
+
return trimmed;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function base64url(value: string): string {
|
|
411
|
+
return Buffer.from(value).toString("base64url");
|
|
412
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
export {
|
|
2
|
+
GithubApi,
|
|
3
|
+
type GithubApiOptions,
|
|
4
|
+
gitCredentialsFor,
|
|
5
|
+
githubGraphqlUrl,
|
|
6
|
+
isGithubRemoteUrl,
|
|
7
|
+
pullRequestFromUrl,
|
|
8
|
+
repoFullNameFromUrl,
|
|
9
|
+
} from "./api.js";
|
|
10
|
+
export {
|
|
11
|
+
createGithubAppJwt,
|
|
12
|
+
GithubAppAuth,
|
|
13
|
+
type GithubAppAuthOptions,
|
|
14
|
+
parseGithubAppPrivateKey,
|
|
15
|
+
} from "./app-auth.js";
|
|
16
|
+
export {
|
|
17
|
+
buildGithubAppManifest,
|
|
18
|
+
convertGithubAppManifest,
|
|
19
|
+
DEFAULT_GITHUB_APP_EVENTS,
|
|
20
|
+
DEFAULT_GITHUB_APP_PERMISSIONS,
|
|
21
|
+
type GithubAppManifest,
|
|
22
|
+
type GithubAppManifestOptions,
|
|
23
|
+
githubAppManifestForm,
|
|
24
|
+
} from "./manifest.js";
|
|
25
|
+
export {
|
|
26
|
+
buildAuthorizeUrl,
|
|
27
|
+
buildInstallationUrl,
|
|
28
|
+
exchangeCode,
|
|
29
|
+
isTokenStale,
|
|
30
|
+
pollDeviceToken,
|
|
31
|
+
refreshAccessToken,
|
|
32
|
+
requestDeviceCode,
|
|
33
|
+
revokeUserToken,
|
|
34
|
+
} from "./oauth.js";
|
|
35
|
+
export {
|
|
36
|
+
type GithubRestMethod,
|
|
37
|
+
type GithubRestRequest,
|
|
38
|
+
type GithubRestResponse,
|
|
39
|
+
githubRestRequest,
|
|
40
|
+
githubRestUrl,
|
|
41
|
+
repositoryFromRestPath,
|
|
42
|
+
} from "./rest.js";
|
|
43
|
+
export {
|
|
44
|
+
type DeviceCodeGrant,
|
|
45
|
+
type FetchLike,
|
|
46
|
+
type GithubActor,
|
|
47
|
+
GithubApiError,
|
|
48
|
+
type GithubAppConfig,
|
|
49
|
+
type GithubAppCredentials,
|
|
50
|
+
type GithubAppRegistration,
|
|
51
|
+
GithubAuthError,
|
|
52
|
+
type GithubCheckRun,
|
|
53
|
+
type GithubCheckRunAnnotation,
|
|
54
|
+
type GithubCheckRunFields,
|
|
55
|
+
type GithubComment,
|
|
56
|
+
GithubGraphqlError,
|
|
57
|
+
type GithubInstallation,
|
|
58
|
+
type GithubInstallationToken,
|
|
59
|
+
type GithubJson,
|
|
60
|
+
type GithubPermissionLevel,
|
|
61
|
+
type GithubPermissions,
|
|
62
|
+
type GithubPullRequest,
|
|
63
|
+
type GithubPullRequestFile,
|
|
64
|
+
type GithubPullRequestReview,
|
|
65
|
+
type GithubPullRequestStatus,
|
|
66
|
+
type GithubRepo,
|
|
67
|
+
type GithubRepositoryEvent,
|
|
68
|
+
type GithubReviewComment,
|
|
69
|
+
type GithubReviewEvent,
|
|
70
|
+
type GithubReviewThread,
|
|
71
|
+
type GithubReviewThreadComment,
|
|
72
|
+
type GithubTokenSet,
|
|
73
|
+
type GithubUser,
|
|
74
|
+
} from "./types.js";
|
package/src/manifest.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type FetchLike,
|
|
3
|
+
GithubApiError,
|
|
4
|
+
type GithubAppRegistration,
|
|
5
|
+
type GithubPermissions,
|
|
6
|
+
} from "./types.js";
|
|
7
|
+
|
|
8
|
+
const GITHUB_BASE = "https://github.com";
|
|
9
|
+
const API_BASE = "https://api.github.com";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Permissions a self-registered app asks for by default: read repository
|
|
13
|
+
* metadata and contents for sync, write branches, review and comment on pull
|
|
14
|
+
* requests and issues, and report check runs. Hosts pass their own set when
|
|
15
|
+
* they need less (or more).
|
|
16
|
+
*/
|
|
17
|
+
export const DEFAULT_GITHUB_APP_PERMISSIONS: GithubPermissions = {
|
|
18
|
+
metadata: "read",
|
|
19
|
+
contents: "write",
|
|
20
|
+
pull_requests: "write",
|
|
21
|
+
issues: "write",
|
|
22
|
+
checks: "write",
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** Events matching the default permissions, subscribed when a webhook is set. */
|
|
26
|
+
export const DEFAULT_GITHUB_APP_EVENTS: readonly string[] = [
|
|
27
|
+
"push",
|
|
28
|
+
"pull_request",
|
|
29
|
+
"pull_request_review",
|
|
30
|
+
"pull_request_review_comment",
|
|
31
|
+
"issue_comment",
|
|
32
|
+
"check_run",
|
|
33
|
+
"check_suite",
|
|
34
|
+
];
|
|
35
|
+
|
|
36
|
+
export interface GithubAppManifestOptions {
|
|
37
|
+
/** App name shown on GitHub; must be unique across GitHub. */
|
|
38
|
+
name: string;
|
|
39
|
+
/** Homepage of the host that owns the app. */
|
|
40
|
+
url: string;
|
|
41
|
+
description?: string;
|
|
42
|
+
/** Where GitHub returns the browser with `?code=` after creating the app. */
|
|
43
|
+
redirectUrl: string;
|
|
44
|
+
/** User-authorization callback URLs, for member (user-to-server) OAuth. */
|
|
45
|
+
callbackUrls?: readonly string[];
|
|
46
|
+
/** Where GitHub sends people after they install the app. */
|
|
47
|
+
setupUrl?: string;
|
|
48
|
+
/** Webhook delivery URL; events are subscribed only when set. */
|
|
49
|
+
webhookUrl?: string;
|
|
50
|
+
/** Allow installation on other accounts. Default false. */
|
|
51
|
+
public?: boolean;
|
|
52
|
+
permissions?: GithubPermissions;
|
|
53
|
+
events?: readonly string[];
|
|
54
|
+
/** Ask for user authorization during installation. */
|
|
55
|
+
requestOauthOnInstall?: boolean;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The JSON document GitHub's manifest flow takes (field names are GitHub's). */
|
|
59
|
+
export interface GithubAppManifest {
|
|
60
|
+
name: string;
|
|
61
|
+
url: string;
|
|
62
|
+
description?: string;
|
|
63
|
+
redirect_url: string;
|
|
64
|
+
callback_urls?: string[];
|
|
65
|
+
setup_url?: string;
|
|
66
|
+
hook_attributes?: { url: string; active: boolean };
|
|
67
|
+
public: boolean;
|
|
68
|
+
default_permissions: Record<string, string>;
|
|
69
|
+
default_events: string[];
|
|
70
|
+
request_oauth_on_install?: boolean;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Build the manifest for "Register your own app": an administrator submits it
|
|
75
|
+
* to GitHub (see {@link githubAppManifestForm}), confirms the app name, and
|
|
76
|
+
* GitHub redirects back with a code for {@link convertGithubAppManifest}.
|
|
77
|
+
*/
|
|
78
|
+
export function buildGithubAppManifest(
|
|
79
|
+
options: GithubAppManifestOptions,
|
|
80
|
+
): GithubAppManifest {
|
|
81
|
+
const name = options.name.trim();
|
|
82
|
+
if (!name) throw new Error("A GitHub App name is required");
|
|
83
|
+
return {
|
|
84
|
+
name,
|
|
85
|
+
url: options.url,
|
|
86
|
+
...(options.description ? { description: options.description } : {}),
|
|
87
|
+
redirect_url: options.redirectUrl,
|
|
88
|
+
...(options.callbackUrls?.length
|
|
89
|
+
? { callback_urls: [...options.callbackUrls] }
|
|
90
|
+
: {}),
|
|
91
|
+
...(options.setupUrl ? { setup_url: options.setupUrl } : {}),
|
|
92
|
+
...(options.webhookUrl
|
|
93
|
+
? { hook_attributes: { url: options.webhookUrl, active: true } }
|
|
94
|
+
: {}),
|
|
95
|
+
public: options.public ?? false,
|
|
96
|
+
default_permissions: {
|
|
97
|
+
...(options.permissions ?? DEFAULT_GITHUB_APP_PERMISSIONS),
|
|
98
|
+
},
|
|
99
|
+
default_events: options.webhookUrl
|
|
100
|
+
? [...(options.events ?? DEFAULT_GITHUB_APP_EVENTS)]
|
|
101
|
+
: [],
|
|
102
|
+
...(options.requestOauthOnInstall !== undefined
|
|
103
|
+
? { request_oauth_on_install: options.requestOauthOnInstall }
|
|
104
|
+
: {}),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The browser form that starts the manifest flow. GitHub only accepts the
|
|
110
|
+
* manifest as a form POST from the administrator's browser, so hosts render
|
|
111
|
+
* `<form method="post" action={action}>` with one hidden `manifest` field.
|
|
112
|
+
* `state` comes back on the redirect and must be checked by the host.
|
|
113
|
+
*/
|
|
114
|
+
export function githubAppManifestForm(args: {
|
|
115
|
+
manifest: GithubAppManifest;
|
|
116
|
+
state: string;
|
|
117
|
+
/** Register under an organization instead of the signed-in user. */
|
|
118
|
+
organization?: string;
|
|
119
|
+
/** GitHub Enterprise Server web origin. Default `https://github.com`. */
|
|
120
|
+
webBaseUrl?: string;
|
|
121
|
+
}): { action: string; fields: { manifest: string } } {
|
|
122
|
+
const base = (args.webBaseUrl ?? GITHUB_BASE).replace(/\/+$/, "");
|
|
123
|
+
if (args.organization && !/^[\w.-]+$/.test(args.organization)) {
|
|
124
|
+
throw new Error(`Invalid organization: ${args.organization}`);
|
|
125
|
+
}
|
|
126
|
+
const action = new URL(
|
|
127
|
+
args.organization
|
|
128
|
+
? `${base}/organizations/${args.organization}/settings/apps/new`
|
|
129
|
+
: `${base}/settings/apps/new`,
|
|
130
|
+
);
|
|
131
|
+
action.searchParams.set("state", args.state);
|
|
132
|
+
return {
|
|
133
|
+
action: action.toString(),
|
|
134
|
+
fields: { manifest: JSON.stringify(args.manifest) },
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
interface RawConversion {
|
|
139
|
+
id: number;
|
|
140
|
+
slug: string;
|
|
141
|
+
name: string;
|
|
142
|
+
owner: { login: string } | null;
|
|
143
|
+
html_url: string;
|
|
144
|
+
client_id: string;
|
|
145
|
+
client_secret: string;
|
|
146
|
+
webhook_secret: string | null;
|
|
147
|
+
pem: string;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Exchange the manifest flow's one-hour code for the new app's credentials.
|
|
152
|
+
* Unauthenticated by design: the code itself is the proof.
|
|
153
|
+
*/
|
|
154
|
+
export async function convertGithubAppManifest(args: {
|
|
155
|
+
code: string;
|
|
156
|
+
fetch?: FetchLike;
|
|
157
|
+
apiBaseUrl?: string;
|
|
158
|
+
}): Promise<GithubAppRegistration> {
|
|
159
|
+
if (!/^[\w-]+$/.test(args.code)) {
|
|
160
|
+
throw new GithubApiError(400, "Invalid manifest code");
|
|
161
|
+
}
|
|
162
|
+
const base = (args.apiBaseUrl ?? API_BASE).replace(/\/+$/, "");
|
|
163
|
+
const response = await (args.fetch ?? fetch)(
|
|
164
|
+
`${base}/app-manifests/${args.code}/conversions`,
|
|
165
|
+
{
|
|
166
|
+
method: "POST",
|
|
167
|
+
headers: {
|
|
168
|
+
Accept: "application/vnd.github+json",
|
|
169
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
);
|
|
173
|
+
if (!response.ok) {
|
|
174
|
+
const body = (await response.json().catch(() => ({}))) as {
|
|
175
|
+
message?: string;
|
|
176
|
+
};
|
|
177
|
+
throw new GithubApiError(
|
|
178
|
+
response.status,
|
|
179
|
+
body.message ?? `GitHub API returned ${response.status}`,
|
|
180
|
+
);
|
|
181
|
+
}
|
|
182
|
+
const raw = (await response.json()) as RawConversion;
|
|
183
|
+
if (!raw.id || !raw.pem || !raw.client_id || !raw.client_secret) {
|
|
184
|
+
throw new GithubApiError(502, "GitHub returned incomplete app credentials");
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
appId: String(raw.id),
|
|
188
|
+
slug: raw.slug,
|
|
189
|
+
name: raw.name,
|
|
190
|
+
owner: raw.owner?.login ?? null,
|
|
191
|
+
htmlUrl: raw.html_url,
|
|
192
|
+
clientId: raw.client_id,
|
|
193
|
+
clientSecret: raw.client_secret,
|
|
194
|
+
webhookSecret: raw.webhook_secret ?? null,
|
|
195
|
+
privateKey: raw.pem,
|
|
196
|
+
};
|
|
197
|
+
}
|