@opengeni/github 0.3.12 → 0.3.18
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/dist/index.d.ts +26 -4
- package/dist/index.js +165 -4
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +234 -6
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Settings } from '@opengeni/config';
|
|
2
|
-
import { GitHubUserInstallationAccess, GitHubRepository } from '@opengeni/contracts';
|
|
2
|
+
import { GitHubUserInstallationAccess, GitHubInstallationBindingProof, GitHubRepository } from '@opengeni/contracts';
|
|
3
3
|
|
|
4
4
|
declare const stateMaxAgeSeconds: number;
|
|
5
5
|
declare class GitHubAppConfigurationError extends Error {
|
|
@@ -7,9 +7,17 @@ declare class GitHubAppConfigurationError extends Error {
|
|
|
7
7
|
constructor(missing: string[]);
|
|
8
8
|
}
|
|
9
9
|
declare class GitHubAppApiError extends Error {
|
|
10
|
+
readonly status: number | null;
|
|
11
|
+
constructor(message: string, status?: number | null);
|
|
12
|
+
}
|
|
13
|
+
type GitHubInstallationAuthorityFailure = "authority_denied" | "authority_unavailable" | "installation_missing" | "installation_suspended" | "repository_access_empty";
|
|
14
|
+
declare class GitHubInstallationAuthorityError extends GitHubAppApiError {
|
|
15
|
+
readonly reason: GitHubInstallationAuthorityFailure;
|
|
16
|
+
constructor(reason: GitHubInstallationAuthorityFailure, message: string, status?: number | null);
|
|
10
17
|
}
|
|
11
18
|
type GitHubAppInstallationSummary = {
|
|
12
19
|
installationId: number;
|
|
20
|
+
accountId: number;
|
|
13
21
|
accountLogin: string | null;
|
|
14
22
|
accountType: string | null;
|
|
15
23
|
suspended: boolean;
|
|
@@ -57,12 +65,26 @@ declare function verifyGitHubInstallationAccessForUser(settings: Settings, input
|
|
|
57
65
|
declare function authorizeGitHubAppUser(settings: Settings, input: {
|
|
58
66
|
code: string;
|
|
59
67
|
}): Promise<GitHubUserInstallationAccess[]>;
|
|
68
|
+
/**
|
|
69
|
+
* Prove current GitHub installation authority without treating repository
|
|
70
|
+
* administration or installation visibility as delegation authority.
|
|
71
|
+
*
|
|
72
|
+
* GitHub exposes an exact personal-account owner through the authenticated
|
|
73
|
+
* user's immutable id. For organizations, GitHub's authenticated membership
|
|
74
|
+
* endpoint exposes active owners as role=admin. GitHub does not expose an
|
|
75
|
+
* equivalent current-authority receipt for App Managers, so that case remains
|
|
76
|
+
* unsupported and fails closed.
|
|
77
|
+
*/
|
|
78
|
+
declare function authorizeGitHubInstallationBinding(settings: Settings, input: {
|
|
79
|
+
code: string;
|
|
80
|
+
installationId: number;
|
|
81
|
+
}): Promise<GitHubInstallationBindingProof>;
|
|
60
82
|
declare function listGitHubAppRepositories(settings: Settings, input?: {
|
|
61
83
|
installationIds?: number[];
|
|
62
84
|
}): Promise<GitHubRepository[]>;
|
|
63
85
|
declare function createGitHubAppInstallationToken(settings: Settings, input: {
|
|
64
86
|
installationId: number;
|
|
65
|
-
repositoryIds
|
|
87
|
+
repositoryIds: number[];
|
|
66
88
|
}): Promise<string>;
|
|
67
89
|
type GitHubAppInstallationToken = {
|
|
68
90
|
token: string;
|
|
@@ -70,7 +92,7 @@ type GitHubAppInstallationToken = {
|
|
|
70
92
|
};
|
|
71
93
|
declare function createGitHubAppInstallationTokenWithExpiry(settings: Settings, input: {
|
|
72
94
|
installationId: number;
|
|
73
|
-
repositoryIds
|
|
95
|
+
repositoryIds: number[];
|
|
74
96
|
}): Promise<GitHubAppInstallationToken>;
|
|
75
97
|
declare function githubAppBotIdentity(settings: Settings): {
|
|
76
98
|
name: string;
|
|
@@ -78,4 +100,4 @@ declare function githubAppBotIdentity(settings: Settings): {
|
|
|
78
100
|
} | null;
|
|
79
101
|
declare function normalizeGitHubAppPrivateKey(value: string): string;
|
|
80
102
|
|
|
81
|
-
export { GitHubAppApiError, GitHubAppConfigurationError, type GitHubAppInstallationSummary, type GitHubAppInstallationToken, type GitHubSignedStatePayload, authorizeGitHubAppUser, buildGitHubAppManifest, convertGitHubAppManifest, createGitHubAppInstallationToken, createGitHubAppInstallationTokenWithExpiry, createSignedState, envLinesFromGitHubManifestConversion, getGitHubAppInstallationSummary, githubAppBotIdentity, githubAppMissingSettings, githubOAuthAuthorizeUrl, listGitHubAppInstallationSummaries, listGitHubAppRepositories, normalizeGitHubAppPrivateKey, organizationAppManifestUrl, personalAppManifestUrl, readSignedState, stateMaxAgeSeconds, verifyGitHubInstallationAccessForUser, verifySignedState };
|
|
103
|
+
export { GitHubAppApiError, GitHubAppConfigurationError, type GitHubAppInstallationSummary, type GitHubAppInstallationToken, GitHubInstallationAuthorityError, type GitHubInstallationAuthorityFailure, type GitHubSignedStatePayload, authorizeGitHubAppUser, authorizeGitHubInstallationBinding, buildGitHubAppManifest, convertGitHubAppManifest, createGitHubAppInstallationToken, createGitHubAppInstallationTokenWithExpiry, createSignedState, envLinesFromGitHubManifestConversion, getGitHubAppInstallationSummary, githubAppBotIdentity, githubAppMissingSettings, githubOAuthAuthorizeUrl, listGitHubAppInstallationSummaries, listGitHubAppRepositories, normalizeGitHubAppPrivateKey, organizationAppManifestUrl, personalAppManifestUrl, readSignedState, stateMaxAgeSeconds, verifyGitHubInstallationAccessForUser, verifySignedState };
|
package/dist/index.js
CHANGED
|
@@ -14,6 +14,16 @@ var GitHubAppConfigurationError = class extends Error {
|
|
|
14
14
|
}
|
|
15
15
|
};
|
|
16
16
|
var GitHubAppApiError = class extends Error {
|
|
17
|
+
constructor(message, status = null) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.status = status;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
var GitHubInstallationAuthorityError = class extends GitHubAppApiError {
|
|
23
|
+
constructor(reason, message, status = null) {
|
|
24
|
+
super(message, status);
|
|
25
|
+
this.reason = reason;
|
|
26
|
+
}
|
|
17
27
|
};
|
|
18
28
|
function githubAppMissingSettings(settings) {
|
|
19
29
|
const required = {
|
|
@@ -30,7 +40,11 @@ function buildGitHubAppManifest(input) {
|
|
|
30
40
|
const permissions = {
|
|
31
41
|
metadata: "read",
|
|
32
42
|
contents: "write",
|
|
33
|
-
pull_requests: "write"
|
|
43
|
+
pull_requests: "write",
|
|
44
|
+
// Required for the authenticated-user membership endpoint that proves an
|
|
45
|
+
// active organization owner. Existing installations must approve this
|
|
46
|
+
// permission before organization-owner self-service can succeed.
|
|
47
|
+
members: "read"
|
|
34
48
|
};
|
|
35
49
|
if (input.includeCiPermissions) {
|
|
36
50
|
permissions.actions = "read";
|
|
@@ -161,6 +175,87 @@ async function authorizeGitHubAppUser(settings, input) {
|
|
|
161
175
|
}))
|
|
162
176
|
);
|
|
163
177
|
}
|
|
178
|
+
async function authorizeGitHubInstallationBinding(settings, input) {
|
|
179
|
+
const userToken = await exchangeGitHubOAuthCodeForUserToken(settings, input.code);
|
|
180
|
+
const actor = await getAuthenticatedGitHubUser(userToken);
|
|
181
|
+
const visibleInstallations = await listUserAccessibleInstallations(userToken);
|
|
182
|
+
const visible = visibleInstallations.find(
|
|
183
|
+
(installation2) => installation2.installationId === input.installationId
|
|
184
|
+
);
|
|
185
|
+
if (!visible) {
|
|
186
|
+
throw new GitHubInstallationAuthorityError(
|
|
187
|
+
"authority_denied",
|
|
188
|
+
"GitHub did not associate this installation with the authorized user"
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
const jwt = await createGitHubAppJwt(settings);
|
|
192
|
+
const livePayload = (await listInstallations(jwt)).find(
|
|
193
|
+
(installation2) => asInt(installation2.id) === input.installationId
|
|
194
|
+
);
|
|
195
|
+
if (!livePayload) {
|
|
196
|
+
throw new GitHubInstallationAuthorityError(
|
|
197
|
+
"installation_missing",
|
|
198
|
+
"GitHub App installation was deleted or is not owned by this App"
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
const installation = installationSummaryFromPayload(livePayload);
|
|
202
|
+
if (installation.accountId !== visible.accountId || installation.accountLogin !== visible.accountLogin || installation.accountType !== visible.accountType) {
|
|
203
|
+
throw new GitHubInstallationAuthorityError(
|
|
204
|
+
"authority_denied",
|
|
205
|
+
"GitHub installation identity changed during authorization"
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
if (installation.suspended) {
|
|
209
|
+
throw new GitHubInstallationAuthorityError(
|
|
210
|
+
"installation_suspended",
|
|
211
|
+
"GitHub App installation is suspended"
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
let authorityKind;
|
|
215
|
+
if (installation.accountType === "User" && actor.id === installation.accountId) {
|
|
216
|
+
authorityKind = "personal_owner";
|
|
217
|
+
} else if (installation.accountType === "Organization" && installation.accountLogin) {
|
|
218
|
+
await assertActiveOrganizationOwner(
|
|
219
|
+
userToken,
|
|
220
|
+
installation.accountId,
|
|
221
|
+
installation.accountLogin
|
|
222
|
+
);
|
|
223
|
+
authorityKind = "organization_owner";
|
|
224
|
+
} else {
|
|
225
|
+
throw new GitHubInstallationAuthorityError(
|
|
226
|
+
"authority_denied",
|
|
227
|
+
"Only a GitHub personal-account owner or organization owner may bind an installation"
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
const installationToken = await createInstallationToken(jwt, {
|
|
231
|
+
installationId: installation.installationId
|
|
232
|
+
});
|
|
233
|
+
const repositories = await listInstallationRepositories(
|
|
234
|
+
installationToken.token,
|
|
235
|
+
installation.installationId,
|
|
236
|
+
{ login: installation.accountLogin, type: installation.accountType }
|
|
237
|
+
);
|
|
238
|
+
if (repositories.length === 0) {
|
|
239
|
+
throw new GitHubInstallationAuthorityError(
|
|
240
|
+
"repository_access_empty",
|
|
241
|
+
"GitHub App installation does not currently grant access to any repositories"
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
if (authorityKind === "organization_owner") {
|
|
245
|
+
await assertActiveOrganizationOwner(
|
|
246
|
+
userToken,
|
|
247
|
+
installation.accountId,
|
|
248
|
+
installation.accountLogin
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
actorId: actor.id,
|
|
253
|
+
actorLogin: actor.login,
|
|
254
|
+
authorityKind,
|
|
255
|
+
installation,
|
|
256
|
+
repositories
|
|
257
|
+
};
|
|
258
|
+
}
|
|
164
259
|
async function listGitHubAppRepositories(settings, input = {}) {
|
|
165
260
|
const missing = githubAppMissingSettings(settings);
|
|
166
261
|
if (missing.length > 0) {
|
|
@@ -201,8 +296,22 @@ async function createGitHubAppInstallationTokenWithExpiry(settings, input) {
|
|
|
201
296
|
if (missing.length > 0) {
|
|
202
297
|
throw new GitHubAppConfigurationError(missing);
|
|
203
298
|
}
|
|
299
|
+
if (!Array.isArray(input.repositoryIds)) {
|
|
300
|
+
throw new GitHubAppApiError(
|
|
301
|
+
"GitHub installation token mint requires an explicit, unique repository allowlist"
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
const repositoryIds = [...new Set(input.repositoryIds)];
|
|
305
|
+
if (!Number.isSafeInteger(input.installationId) || input.installationId <= 0 || repositoryIds.length === 0 || repositoryIds.length !== input.repositoryIds.length || repositoryIds.some((id) => !Number.isSafeInteger(id) || id <= 0)) {
|
|
306
|
+
throw new GitHubAppApiError(
|
|
307
|
+
"GitHub installation token mint requires an explicit, unique repository allowlist"
|
|
308
|
+
);
|
|
309
|
+
}
|
|
204
310
|
const jwt = await createGitHubAppJwt(settings);
|
|
205
|
-
return await createInstallationToken(jwt,
|
|
311
|
+
return await createInstallationToken(jwt, {
|
|
312
|
+
installationId: input.installationId,
|
|
313
|
+
repositoryIds
|
|
314
|
+
});
|
|
206
315
|
}
|
|
207
316
|
function githubAppBotIdentity(settings) {
|
|
208
317
|
const appId = settings.githubAppId?.trim();
|
|
@@ -271,6 +380,51 @@ async function exchangeGitHubOAuthCodeForUserToken(settings, code) {
|
|
|
271
380
|
}
|
|
272
381
|
return payload.access_token;
|
|
273
382
|
}
|
|
383
|
+
async function getAuthenticatedGitHubUser(token) {
|
|
384
|
+
const payload = await githubGet("/user", token);
|
|
385
|
+
const id = payload && typeof payload === "object" ? asInt(payload.id) : null;
|
|
386
|
+
const login = payload && typeof payload === "object" && typeof payload.login === "string" ? payload.login : null;
|
|
387
|
+
if (id === null || !login) {
|
|
388
|
+
throw new GitHubAppApiError("GitHub returned an invalid authenticated user payload");
|
|
389
|
+
}
|
|
390
|
+
return { id, login };
|
|
391
|
+
}
|
|
392
|
+
async function getAuthenticatedOrganizationMembership(token, organizationLogin) {
|
|
393
|
+
let payload;
|
|
394
|
+
try {
|
|
395
|
+
payload = await githubGet(
|
|
396
|
+
`/user/memberships/orgs/${encodeURIComponent(organizationLogin)}`,
|
|
397
|
+
token
|
|
398
|
+
);
|
|
399
|
+
} catch (error) {
|
|
400
|
+
if (error instanceof GitHubAppApiError) {
|
|
401
|
+
throw new GitHubInstallationAuthorityError(
|
|
402
|
+
"authority_unavailable",
|
|
403
|
+
"GitHub could not prove current organization-owner membership",
|
|
404
|
+
error.status
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
throw error;
|
|
408
|
+
}
|
|
409
|
+
const organization = payload && typeof payload === "object" && payload.organization ? payload.organization : null;
|
|
410
|
+
const organizationId = organization && typeof organization === "object" ? asInt(organization.id) : null;
|
|
411
|
+
if (organizationId === null || typeof payload?.role !== "string" || typeof payload?.state !== "string") {
|
|
412
|
+
throw new GitHubInstallationAuthorityError(
|
|
413
|
+
"authority_unavailable",
|
|
414
|
+
"GitHub returned an invalid organization membership proof"
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
return { organizationId, role: payload.role, state: payload.state };
|
|
418
|
+
}
|
|
419
|
+
async function assertActiveOrganizationOwner(token, organizationId, organizationLogin) {
|
|
420
|
+
const membership = await getAuthenticatedOrganizationMembership(token, organizationLogin);
|
|
421
|
+
if (membership.organizationId !== organizationId || membership.state !== "active" || membership.role !== "admin") {
|
|
422
|
+
throw new GitHubInstallationAuthorityError(
|
|
423
|
+
"authority_denied",
|
|
424
|
+
"Only an active GitHub organization owner may bind this installation"
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
274
428
|
async function listUserAccessibleInstallations(token) {
|
|
275
429
|
const out = [];
|
|
276
430
|
for (let page = 1; ; page += 1) {
|
|
@@ -376,21 +530,26 @@ function installationSummaryFromPayload(payload) {
|
|
|
376
530
|
throw new GitHubAppApiError("GitHub returned an installation without id");
|
|
377
531
|
}
|
|
378
532
|
const account = typeof payload.account === "object" && payload.account ? payload.account : {};
|
|
533
|
+
const accountId = asInt(account.id);
|
|
534
|
+
if (accountId === null) {
|
|
535
|
+
throw new GitHubAppApiError("GitHub returned an installation without an account id");
|
|
536
|
+
}
|
|
379
537
|
return {
|
|
380
538
|
installationId,
|
|
539
|
+
accountId,
|
|
381
540
|
accountLogin: typeof account.login === "string" ? account.login : null,
|
|
382
541
|
accountType: typeof account.type === "string" ? account.type : null,
|
|
383
542
|
suspended: Boolean(payload.suspended_at)
|
|
384
543
|
};
|
|
385
544
|
}
|
|
386
|
-
async function githubGet(path, token, params) {
|
|
545
|
+
async function githubGet(path, token, params = {}) {
|
|
387
546
|
const url = new URL(`${githubApiBase}${path}`);
|
|
388
547
|
for (const [key, value] of Object.entries(params)) {
|
|
389
548
|
url.searchParams.set(key, value);
|
|
390
549
|
}
|
|
391
550
|
const response = await fetch(url, { headers: githubHeaders(token) });
|
|
392
551
|
if (!response.ok) {
|
|
393
|
-
throw new GitHubAppApiError(await githubErrorMessage(response));
|
|
552
|
+
throw new GitHubAppApiError(await githubErrorMessage(response), response.status);
|
|
394
553
|
}
|
|
395
554
|
return await response.json();
|
|
396
555
|
}
|
|
@@ -470,7 +629,9 @@ function asInt(value) {
|
|
|
470
629
|
export {
|
|
471
630
|
GitHubAppApiError,
|
|
472
631
|
GitHubAppConfigurationError,
|
|
632
|
+
GitHubInstallationAuthorityError,
|
|
473
633
|
authorizeGitHubAppUser,
|
|
634
|
+
authorizeGitHubInstallationBinding,
|
|
474
635
|
buildGitHubAppManifest,
|
|
475
636
|
convertGitHubAppManifest,
|
|
476
637
|
createGitHubAppInstallationToken,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Settings } from \"@opengeni/config\";\nimport type {\n GitHubRepository,\n GitHubRepositoryPermissions,\n GitHubUserInstallationAccess,\n GitHubUserRepositoryAccess,\n} from \"@opengeni/contracts\";\nimport { createHmac, createPrivateKey, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { SignJWT, importPKCS8 } from \"jose\";\n\nconst githubApiBase = \"https://api.github.com\";\nconst githubApiVersion = \"2022-11-28\";\nconst githubTokenMintTimeoutMs = 60_000;\nexport const stateMaxAgeSeconds = 60 * 60;\nconst pkcs8PrivateKeyHeader = `-----BEGIN ${\"PRIVATE KEY\"}-----`;\nconst rsaPrivateKeyHeader = `-----BEGIN ${\"RSA PRIVATE KEY\"}-----`;\n\nexport class GitHubAppConfigurationError extends Error {\n constructor(readonly missing: string[]) {\n super(\"GitHub App is not configured\");\n }\n}\n\nexport class GitHubAppApiError extends Error {}\n\nexport type GitHubAppInstallationSummary = {\n installationId: number;\n accountLogin: string | null;\n accountType: string | null;\n suspended: boolean;\n};\n\nexport type GitHubSignedStatePayload = {\n nonce: string;\n iat: number;\n accountId?: string;\n workspaceId?: string;\n [key: string]: unknown;\n};\n\nexport function githubAppMissingSettings(settings: Settings): string[] {\n const required: Record<string, string | undefined> = {\n OPENGENI_GITHUB_APP_ID: settings.githubAppId,\n OPENGENI_GITHUB_CLIENT_ID: settings.githubClientId,\n OPENGENI_GITHUB_CLIENT_SECRET: settings.githubClientSecret,\n OPENGENI_GITHUB_APP_SLUG: settings.githubAppSlug,\n OPENGENI_GITHUB_APP_PRIVATE_KEY: settings.githubAppPrivateKey,\n };\n return Object.entries(required).flatMap(([name, value]) => (value && value.trim() ? [] : [name]));\n}\n\nexport function buildGitHubAppManifest(input: {\n appName: string;\n baseUrl: string;\n public: boolean;\n includeCiPermissions: boolean;\n setupUrl?: string;\n}): Record<string, unknown> {\n const base = input.baseUrl.replace(/\\/+$/, \"\");\n const permissions: Record<string, string> = {\n metadata: \"read\",\n contents: \"write\",\n pull_requests: \"write\",\n };\n if (input.includeCiPermissions) {\n permissions.actions = \"read\";\n permissions.checks = \"read\";\n permissions.statuses = \"write\";\n }\n const manifest: Record<string, unknown> = {\n name: input.appName,\n url: base,\n redirect_url: `${base}/v1/github/app-manifest/callback`,\n callback_urls: [`${base}/v1/github/oauth/callback`],\n public: input.public,\n request_oauth_on_install: true,\n default_permissions: permissions,\n };\n if (input.setupUrl) {\n manifest.setup_url = input.setupUrl;\n manifest.setup_on_update = true;\n }\n return manifest;\n}\n\nexport function personalAppManifestUrl(state: string): string {\n return `https://github.com/settings/apps/new?state=${state}`;\n}\n\nexport function organizationAppManifestUrl(organization: string, state: string): string {\n return `https://github.com/organizations/${encodeURIComponent(organization)}/settings/apps/new?state=${state}`;\n}\n\nexport function githubOAuthAuthorizeUrl(input: {\n clientId: string;\n state: string;\n redirectUri?: string;\n}): string {\n const url = new URL(\"https://github.com/login/oauth/authorize\");\n url.searchParams.set(\"client_id\", input.clientId);\n url.searchParams.set(\"state\", input.state);\n if (input.redirectUri) {\n url.searchParams.set(\"redirect_uri\", input.redirectUri);\n }\n return url.toString();\n}\n\nexport function createSignedState(\n secret: string,\n payloadOrNow: Record<string, unknown> | number = {},\n nowArg = Math.floor(Date.now() / 1000),\n): string {\n const payloadInput = typeof payloadOrNow === \"number\" ? {} : payloadOrNow;\n const now = typeof payloadOrNow === \"number\" ? payloadOrNow : nowArg;\n const payload = {\n ...payloadInput,\n nonce: randomBytes(16).toString(\"base64url\"),\n iat: now,\n };\n const encoded = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n return `${encoded}.${signStatePayload(encoded, secret)}`;\n}\n\nexport function readSignedState(\n state: string,\n secret: string,\n now = Math.floor(Date.now() / 1000),\n): GitHubSignedStatePayload | null {\n const [encoded, signature] = state.split(\".\", 2);\n if (!encoded || !signature) {\n return null;\n }\n const expected = signStatePayload(encoded, secret);\n if (!safeEqual(signature, expected)) {\n return null;\n }\n let payload: unknown;\n try {\n payload = JSON.parse(Buffer.from(encoded, \"base64url\").toString(\"utf8\"));\n } catch {\n return null;\n }\n if (\n !payload ||\n typeof payload !== \"object\" ||\n typeof (payload as { iat?: unknown }).iat !== \"number\" ||\n typeof (payload as { nonce?: unknown }).nonce !== \"string\"\n ) {\n return null;\n }\n const age = now - (payload as { iat: number }).iat;\n return age >= 0 && age <= stateMaxAgeSeconds ? (payload as GitHubSignedStatePayload) : null;\n}\n\nexport function verifySignedState(\n state: string,\n secret: string,\n now = Math.floor(Date.now() / 1000),\n): boolean {\n return readSignedState(state, secret, now) !== null;\n}\n\nexport function envLinesFromGitHubManifestConversion(payload: Record<string, unknown>): string[] {\n const privateKey = String(payload.pem ?? \"\").replace(/\\n/g, \"\\\\n\");\n return [\n `OPENGENI_GITHUB_APP_ID=${payload.id ?? \"\"}`,\n `OPENGENI_GITHUB_CLIENT_ID=${payload.client_id ?? \"\"}`,\n `OPENGENI_GITHUB_CLIENT_SECRET=${payload.client_secret ?? \"\"}`,\n `OPENGENI_GITHUB_APP_SLUG=${payload.slug ?? \"\"}`,\n `OPENGENI_GITHUB_WEBHOOK_SECRET=${payload.webhook_secret ?? \"\"}`,\n `OPENGENI_GITHUB_APP_PRIVATE_KEY=\"${privateKey}\"`,\n ];\n}\n\nexport async function convertGitHubAppManifest(code: string): Promise<Record<string, unknown>> {\n const response = await fetch(`${githubApiBase}/app-manifests/${code}/conversions`, {\n method: \"POST\",\n headers: githubHeaders(undefined),\n });\n if (!response.ok) {\n throw new GitHubAppApiError(await githubErrorMessage(response));\n }\n const payload = await response.json();\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new GitHubAppApiError(\"GitHub returned an invalid manifest conversion payload\");\n }\n return payload as Record<string, unknown>;\n}\n\nexport async function listGitHubAppInstallationSummaries(\n settings: Settings,\n): Promise<GitHubAppInstallationSummary[]> {\n const missing = githubAppMissingSettings(settings);\n if (missing.length > 0) {\n throw new GitHubAppConfigurationError(missing);\n }\n const jwt = await createGitHubAppJwt(settings);\n const installations = await listInstallations(jwt);\n return installations.map(installationSummaryFromPayload);\n}\n\nexport async function getGitHubAppInstallationSummary(\n settings: Settings,\n installationId: number,\n): Promise<GitHubAppInstallationSummary | null> {\n const installations = await listGitHubAppInstallationSummaries(settings);\n return (\n installations.find((installation) => installation.installationId === installationId) ?? null\n );\n}\n\nexport async function verifyGitHubInstallationAccessForUser(\n settings: Settings,\n input: {\n code: string;\n installationId: number;\n },\n): Promise<GitHubAppInstallationSummary> {\n const token = await exchangeGitHubOAuthCodeForUserToken(settings, input.code);\n const installations = await listUserAccessibleInstallations(token);\n const installation = installations.find(\n (candidate) => candidate.installationId === input.installationId,\n );\n if (!installation) {\n throw new GitHubAppApiError(\"GitHub installation is not accessible to the installing user\");\n }\n return installation;\n}\n\n/**\n * Exchange a GitHub App user-authorization code and discover the installations\n * and repositories the user can explicitly access. This is compatibility\n * discovery metadata only: visibility and repository permission bits do not\n * prove that the human may install, configure, or bind the App installation.\n * No production binding path may treat this result as authority.\n */\nexport async function authorizeGitHubAppUser(\n settings: Settings,\n input: { code: string },\n): Promise<GitHubUserInstallationAccess[]> {\n const token = await exchangeGitHubOAuthCodeForUserToken(settings, input.code);\n const installations = await listUserAccessibleInstallations(token);\n return await Promise.all(\n installations.map(async (installation) => ({\n ...installation,\n repositories: installation.suspended\n ? []\n : await listUserInstallationRepositories(token, installation),\n })),\n );\n}\n\nexport async function listGitHubAppRepositories(\n settings: Settings,\n input: {\n installationIds?: number[];\n } = {},\n): Promise<GitHubRepository[]> {\n const missing = githubAppMissingSettings(settings);\n if (missing.length > 0) {\n throw new GitHubAppConfigurationError(missing);\n }\n const allowedInstallations = input.installationIds ? new Set(input.installationIds) : null;\n if (allowedInstallations && allowedInstallations.size === 0) {\n return [];\n }\n const jwt = await createGitHubAppJwt(settings);\n const installations = await listInstallations(jwt);\n const repositories: GitHubRepository[] = [];\n for (const installation of installations) {\n if (installation.suspended_at) {\n continue;\n }\n const installationId = asInt(installation.id);\n if (installationId === null) {\n continue;\n }\n if (allowedInstallations && !allowedInstallations.has(installationId)) {\n continue;\n }\n const account =\n typeof installation.account === \"object\" && installation.account\n ? (installation.account as Record<string, unknown>)\n : {};\n const token = await createInstallationToken(jwt, { installationId });\n repositories.push(\n ...(await listInstallationRepositories(token.token, installationId, account)),\n );\n }\n repositories.sort((left, right) => left.fullName.localeCompare(right.fullName));\n return repositories;\n}\n\nexport async function createGitHubAppInstallationToken(\n settings: Settings,\n input: {\n installationId: number;\n repositoryIds?: number[];\n },\n): Promise<string> {\n return (await createGitHubAppInstallationTokenWithExpiry(settings, input)).token;\n}\n\nexport type GitHubAppInstallationToken = {\n token: string;\n expiresAt: string | null;\n};\n\nexport async function createGitHubAppInstallationTokenWithExpiry(\n settings: Settings,\n input: {\n installationId: number;\n repositoryIds?: number[];\n },\n): Promise<GitHubAppInstallationToken> {\n const missing = githubAppMissingSettings(settings);\n if (missing.length > 0) {\n throw new GitHubAppConfigurationError(missing);\n }\n const jwt = await createGitHubAppJwt(settings);\n return await createInstallationToken(jwt, input);\n}\n\nexport function githubAppBotIdentity(settings: Settings): { name: string; email: string } | null {\n const appId = settings.githubAppId?.trim();\n const slug = settings.githubAppSlug?.trim();\n if (!appId || !slug) {\n return null;\n }\n const login = `${slug}[bot]`;\n return {\n name: login,\n email: `${appId}+${login}@users.noreply.github.com`,\n };\n}\n\nasync function createGitHubAppJwt(settings: Settings): Promise<string> {\n const privateKey = normalizeGitHubAppPrivateKey(settings.githubAppPrivateKey ?? \"\");\n const appId = settings.githubAppId?.trim();\n if (!appId || !privateKey) {\n throw new GitHubAppConfigurationError(githubAppMissingSettings(settings));\n }\n const key = await importPKCS8(privateKey, \"RS256\");\n const now = Math.floor(Date.now() / 1000);\n return await new SignJWT({})\n .setProtectedHeader({ alg: \"RS256\" })\n .setIssuedAt(now - 60)\n .setExpirationTime(now + 9 * 60)\n .setIssuer(appId)\n .sign(key);\n}\n\nasync function listInstallations(token: string): Promise<Array<Record<string, unknown>>> {\n const out: Array<Record<string, unknown>> = [];\n for (let page = 1; ; page += 1) {\n const payload = await githubGet(\"/app/installations\", token, {\n per_page: \"100\",\n page: String(page),\n });\n if (!Array.isArray(payload)) {\n throw new GitHubAppApiError(\"GitHub returned an invalid installations payload\");\n }\n out.push(\n ...payload.filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === \"object\" && !Array.isArray(item)),\n ),\n );\n if (payload.length < 100) {\n return out;\n }\n }\n}\n\nasync function exchangeGitHubOAuthCodeForUserToken(\n settings: Settings,\n code: string,\n): Promise<string> {\n if (!settings.githubClientId || !settings.githubClientSecret) {\n throw new GitHubAppConfigurationError(githubAppMissingSettings(settings));\n }\n const response = await fetch(\"https://github.com/login/oauth/access_token\", {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n client_id: settings.githubClientId,\n client_secret: settings.githubClientSecret,\n code,\n }),\n });\n if (!response.ok) {\n throw new GitHubAppApiError(await githubErrorMessage(response));\n }\n const payload = await response.json();\n if (!payload || typeof payload !== \"object\" || typeof payload.access_token !== \"string\") {\n throw new GitHubAppApiError(\"GitHub returned an invalid OAuth token payload\");\n }\n return payload.access_token;\n}\n\nasync function listUserAccessibleInstallations(\n token: string,\n): Promise<GitHubAppInstallationSummary[]> {\n const out: GitHubAppInstallationSummary[] = [];\n for (let page = 1; ; page += 1) {\n const payload = await githubGet(\"/user/installations\", token, {\n per_page: \"100\",\n page: String(page),\n });\n const installations: unknown[] | null =\n payload && typeof payload === \"object\" && Array.isArray(payload.installations)\n ? (payload.installations as unknown[])\n : null;\n if (!installations) {\n throw new GitHubAppApiError(\"GitHub returned an invalid user installations payload\");\n }\n out.push(\n ...installations\n .filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === \"object\" && !Array.isArray(item)),\n )\n .map(installationSummaryFromPayload),\n );\n if (installations.length < 100) {\n return out;\n }\n }\n}\n\nasync function listUserInstallationRepositories(\n token: string,\n installation: GitHubAppInstallationSummary,\n): Promise<GitHubUserRepositoryAccess[]> {\n const out: GitHubUserRepositoryAccess[] = [];\n const account = {\n ...(installation.accountLogin ? { login: installation.accountLogin } : {}),\n ...(installation.accountType ? { type: installation.accountType } : {}),\n };\n for (let page = 1; ; page += 1) {\n const payload = await githubGet(\n `/user/installations/${installation.installationId}/repositories`,\n token,\n { per_page: \"100\", page: String(page) },\n );\n if (\n !payload ||\n typeof payload !== \"object\" ||\n Array.isArray(payload) ||\n !Array.isArray(payload.repositories)\n ) {\n throw new GitHubAppApiError(\n \"GitHub returned an invalid user installation repositories payload\",\n );\n }\n for (const repository of payload.repositories) {\n if (!repository || typeof repository !== \"object\" || Array.isArray(repository)) {\n continue;\n }\n const record = repository as Record<string, unknown>;\n out.push({\n ...repositoryFromPayload(record, installation.installationId, account),\n permissions: repositoryPermissionsFromPayload(record.permissions),\n });\n }\n if (payload.repositories.length < 100) {\n return out;\n }\n }\n}\n\nasync function createInstallationToken(\n appJwt: string,\n input: {\n installationId: number;\n repositoryIds?: number[];\n },\n): Promise<GitHubAppInstallationToken> {\n const scoped = input.repositoryIds && input.repositoryIds.length > 0;\n const response = await fetch(\n `${githubApiBase}/app/installations/${input.installationId}/access_tokens`,\n {\n method: \"POST\",\n headers: {\n ...githubHeaders(appJwt),\n ...(scoped ? { \"Content-Type\": \"application/json\" } : {}),\n },\n signal: AbortSignal.timeout(githubTokenMintTimeoutMs),\n ...(scoped ? { body: JSON.stringify({ repository_ids: input.repositoryIds }) } : {}),\n },\n );\n if (!response.ok) {\n throw new GitHubAppApiError(await githubErrorMessage(response));\n }\n const payload = await response.json();\n if (!payload || typeof payload !== \"object\" || typeof payload.token !== \"string\") {\n throw new GitHubAppApiError(\"GitHub returned an invalid installation token payload\");\n }\n return {\n token: payload.token,\n expiresAt: typeof payload.expires_at === \"string\" ? payload.expires_at : null,\n };\n}\n\nasync function listInstallationRepositories(\n token: string,\n installationId: number,\n account: Record<string, unknown>,\n): Promise<GitHubRepository[]> {\n const out: GitHubRepository[] = [];\n for (let page = 1; ; page += 1) {\n const payload = await githubGet(\"/installation/repositories\", token, {\n per_page: \"100\",\n page: String(page),\n });\n if (\n !payload ||\n typeof payload !== \"object\" ||\n Array.isArray(payload) ||\n !Array.isArray(payload.repositories)\n ) {\n throw new GitHubAppApiError(\"GitHub returned an invalid repositories payload\");\n }\n for (const repo of payload.repositories) {\n if (repo && typeof repo === \"object\" && !Array.isArray(repo)) {\n out.push(repositoryFromPayload(repo as Record<string, unknown>, installationId, account));\n }\n }\n if (payload.repositories.length < 100) {\n return out;\n }\n }\n}\n\nfunction installationSummaryFromPayload(\n payload: Record<string, unknown>,\n): GitHubAppInstallationSummary {\n const installationId = asInt(payload.id);\n if (installationId === null) {\n throw new GitHubAppApiError(\"GitHub returned an installation without id\");\n }\n const account =\n typeof payload.account === \"object\" && payload.account\n ? (payload.account as Record<string, unknown>)\n : {};\n return {\n installationId,\n accountLogin: typeof account.login === \"string\" ? account.login : null,\n accountType: typeof account.type === \"string\" ? account.type : null,\n suspended: Boolean(payload.suspended_at),\n };\n}\n\nasync function githubGet(\n path: string,\n token: string,\n params: Record<string, string>,\n): Promise<any> {\n const url = new URL(`${githubApiBase}${path}`);\n for (const [key, value] of Object.entries(params)) {\n url.searchParams.set(key, value);\n }\n const response = await fetch(url, { headers: githubHeaders(token) });\n if (!response.ok) {\n throw new GitHubAppApiError(await githubErrorMessage(response));\n }\n return await response.json();\n}\n\nfunction repositoryFromPayload(\n payload: Record<string, unknown>,\n installationId: number,\n account: Record<string, unknown>,\n): GitHubRepository {\n const id = asInt(payload.id);\n const fullName = String(payload.full_name ?? \"\");\n if (id === null || !fullName) {\n throw new GitHubAppApiError(\"GitHub returned a repository without id/full_name\");\n }\n return {\n id,\n installationId,\n fullName,\n name: String(payload.name ?? fullName.split(\"/\").at(-1) ?? fullName),\n private: Boolean(payload.private),\n htmlUrl: String(payload.html_url ?? `https://github.com/${fullName}`),\n cloneUrl: String(payload.clone_url ?? `https://github.com/${fullName}.git`),\n defaultBranch: String(payload.default_branch ?? \"main\"),\n accountLogin: String(account.login ?? fullName.split(\"/\", 1)[0]),\n accountType: typeof account.type === \"string\" ? account.type : null,\n };\n}\n\nfunction repositoryPermissionsFromPayload(payload: unknown): GitHubRepositoryPermissions {\n const permissions =\n payload && typeof payload === \"object\" && !Array.isArray(payload)\n ? (payload as Record<string, unknown>)\n : {};\n return {\n admin: permissions.admin === true,\n maintain: permissions.maintain === true,\n push: permissions.push === true,\n triage: permissions.triage === true,\n pull: permissions.pull === true,\n };\n}\n\nfunction githubHeaders(token?: string): HeadersInit {\n return {\n Accept: \"application/vnd.github+json\",\n ...(token ? { Authorization: `Bearer ${token}` } : {}),\n \"X-GitHub-Api-Version\": githubApiVersion,\n };\n}\n\nasync function githubErrorMessage(response: Response): Promise<string> {\n try {\n const payload = await response.json();\n if (payload && typeof payload === \"object\" && \"message\" in payload) {\n return `GitHub API ${response.status}: ${String(payload.message)}`;\n }\n } catch {\n // fall through\n }\n return `GitHub API ${response.status}: ${await response.text()}`;\n}\n\nexport function normalizeGitHubAppPrivateKey(value: string): string {\n const privateKey = value.trim().replace(/\\\\n/g, \"\\n\");\n if (!privateKey || privateKey.startsWith(pkcs8PrivateKeyHeader)) {\n return privateKey;\n }\n if (privateKey.startsWith(rsaPrivateKeyHeader)) {\n return createPrivateKey(privateKey).export({ type: \"pkcs8\", format: \"pem\" }).toString();\n }\n return privateKey;\n}\n\nfunction signStatePayload(encoded: string, secret: string): string {\n return createHmac(\"sha256\", secret).update(encoded).digest(\"base64url\");\n}\n\nfunction safeEqual(left: string, right: string): boolean {\n const a = Buffer.from(left);\n const b = Buffer.from(right);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\nfunction asInt(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isInteger(value)) {\n return value;\n }\n if (typeof value === \"string\" && /^\\d+$/.test(value)) {\n return Number(value);\n }\n return null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AAW,EAAE,UAAU,gBAAgB,GAAG,CAAC;AACtD;AAEA,SAAS,MAAM,OAA+B;AAC5C,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,GAAG;AACxD,WAAO;AAAA,EACT;AACA,MAAI,OAAO,UAAU,YAAY,QAAQ,KAAK,KAAK,GAAG;AACpD,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Settings } from \"@opengeni/config\";\nimport type {\n GitHubInstallationBindingProof,\n GitHubRepository,\n GitHubRepositoryPermissions,\n GitHubUserInstallationAccess,\n GitHubUserRepositoryAccess,\n} from \"@opengeni/contracts\";\nimport { createHmac, createPrivateKey, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { SignJWT, importPKCS8 } from \"jose\";\n\nconst githubApiBase = \"https://api.github.com\";\nconst githubApiVersion = \"2022-11-28\";\nconst githubTokenMintTimeoutMs = 60_000;\nexport const stateMaxAgeSeconds = 60 * 60;\nconst pkcs8PrivateKeyHeader = `-----BEGIN ${\"PRIVATE KEY\"}-----`;\nconst rsaPrivateKeyHeader = `-----BEGIN ${\"RSA PRIVATE KEY\"}-----`;\n\nexport class GitHubAppConfigurationError extends Error {\n constructor(readonly missing: string[]) {\n super(\"GitHub App is not configured\");\n }\n}\n\nexport class GitHubAppApiError extends Error {\n constructor(\n message: string,\n readonly status: number | null = null,\n ) {\n super(message);\n }\n}\n\nexport type GitHubInstallationAuthorityFailure =\n | \"authority_denied\"\n | \"authority_unavailable\"\n | \"installation_missing\"\n | \"installation_suspended\"\n | \"repository_access_empty\";\n\nexport class GitHubInstallationAuthorityError extends GitHubAppApiError {\n constructor(\n readonly reason: GitHubInstallationAuthorityFailure,\n message: string,\n status: number | null = null,\n ) {\n super(message, status);\n }\n}\n\nexport type GitHubAppInstallationSummary = {\n installationId: number;\n accountId: number;\n accountLogin: string | null;\n accountType: string | null;\n suspended: boolean;\n};\n\nexport type GitHubSignedStatePayload = {\n nonce: string;\n iat: number;\n accountId?: string;\n workspaceId?: string;\n [key: string]: unknown;\n};\n\nexport function githubAppMissingSettings(settings: Settings): string[] {\n const required: Record<string, string | undefined> = {\n OPENGENI_GITHUB_APP_ID: settings.githubAppId,\n OPENGENI_GITHUB_CLIENT_ID: settings.githubClientId,\n OPENGENI_GITHUB_CLIENT_SECRET: settings.githubClientSecret,\n OPENGENI_GITHUB_APP_SLUG: settings.githubAppSlug,\n OPENGENI_GITHUB_APP_PRIVATE_KEY: settings.githubAppPrivateKey,\n };\n return Object.entries(required).flatMap(([name, value]) => (value && value.trim() ? [] : [name]));\n}\n\nexport function buildGitHubAppManifest(input: {\n appName: string;\n baseUrl: string;\n public: boolean;\n includeCiPermissions: boolean;\n setupUrl?: string;\n}): Record<string, unknown> {\n const base = input.baseUrl.replace(/\\/+$/, \"\");\n const permissions: Record<string, string> = {\n metadata: \"read\",\n contents: \"write\",\n pull_requests: \"write\",\n // Required for the authenticated-user membership endpoint that proves an\n // active organization owner. Existing installations must approve this\n // permission before organization-owner self-service can succeed.\n members: \"read\",\n };\n if (input.includeCiPermissions) {\n permissions.actions = \"read\";\n permissions.checks = \"read\";\n permissions.statuses = \"write\";\n }\n const manifest: Record<string, unknown> = {\n name: input.appName,\n url: base,\n redirect_url: `${base}/v1/github/app-manifest/callback`,\n callback_urls: [`${base}/v1/github/oauth/callback`],\n public: input.public,\n request_oauth_on_install: true,\n default_permissions: permissions,\n };\n if (input.setupUrl) {\n manifest.setup_url = input.setupUrl;\n manifest.setup_on_update = true;\n }\n return manifest;\n}\n\nexport function personalAppManifestUrl(state: string): string {\n return `https://github.com/settings/apps/new?state=${state}`;\n}\n\nexport function organizationAppManifestUrl(organization: string, state: string): string {\n return `https://github.com/organizations/${encodeURIComponent(organization)}/settings/apps/new?state=${state}`;\n}\n\nexport function githubOAuthAuthorizeUrl(input: {\n clientId: string;\n state: string;\n redirectUri?: string;\n}): string {\n const url = new URL(\"https://github.com/login/oauth/authorize\");\n url.searchParams.set(\"client_id\", input.clientId);\n url.searchParams.set(\"state\", input.state);\n if (input.redirectUri) {\n url.searchParams.set(\"redirect_uri\", input.redirectUri);\n }\n return url.toString();\n}\n\nexport function createSignedState(\n secret: string,\n payloadOrNow: Record<string, unknown> | number = {},\n nowArg = Math.floor(Date.now() / 1000),\n): string {\n const payloadInput = typeof payloadOrNow === \"number\" ? {} : payloadOrNow;\n const now = typeof payloadOrNow === \"number\" ? payloadOrNow : nowArg;\n const payload = {\n ...payloadInput,\n nonce: randomBytes(16).toString(\"base64url\"),\n iat: now,\n };\n const encoded = Buffer.from(JSON.stringify(payload)).toString(\"base64url\");\n return `${encoded}.${signStatePayload(encoded, secret)}`;\n}\n\nexport function readSignedState(\n state: string,\n secret: string,\n now = Math.floor(Date.now() / 1000),\n): GitHubSignedStatePayload | null {\n const [encoded, signature] = state.split(\".\", 2);\n if (!encoded || !signature) {\n return null;\n }\n const expected = signStatePayload(encoded, secret);\n if (!safeEqual(signature, expected)) {\n return null;\n }\n let payload: unknown;\n try {\n payload = JSON.parse(Buffer.from(encoded, \"base64url\").toString(\"utf8\"));\n } catch {\n return null;\n }\n if (\n !payload ||\n typeof payload !== \"object\" ||\n typeof (payload as { iat?: unknown }).iat !== \"number\" ||\n typeof (payload as { nonce?: unknown }).nonce !== \"string\"\n ) {\n return null;\n }\n const age = now - (payload as { iat: number }).iat;\n return age >= 0 && age <= stateMaxAgeSeconds ? (payload as GitHubSignedStatePayload) : null;\n}\n\nexport function verifySignedState(\n state: string,\n secret: string,\n now = Math.floor(Date.now() / 1000),\n): boolean {\n return readSignedState(state, secret, now) !== null;\n}\n\nexport function envLinesFromGitHubManifestConversion(payload: Record<string, unknown>): string[] {\n const privateKey = String(payload.pem ?? \"\").replace(/\\n/g, \"\\\\n\");\n return [\n `OPENGENI_GITHUB_APP_ID=${payload.id ?? \"\"}`,\n `OPENGENI_GITHUB_CLIENT_ID=${payload.client_id ?? \"\"}`,\n `OPENGENI_GITHUB_CLIENT_SECRET=${payload.client_secret ?? \"\"}`,\n `OPENGENI_GITHUB_APP_SLUG=${payload.slug ?? \"\"}`,\n `OPENGENI_GITHUB_WEBHOOK_SECRET=${payload.webhook_secret ?? \"\"}`,\n `OPENGENI_GITHUB_APP_PRIVATE_KEY=\"${privateKey}\"`,\n ];\n}\n\nexport async function convertGitHubAppManifest(code: string): Promise<Record<string, unknown>> {\n const response = await fetch(`${githubApiBase}/app-manifests/${code}/conversions`, {\n method: \"POST\",\n headers: githubHeaders(undefined),\n });\n if (!response.ok) {\n throw new GitHubAppApiError(await githubErrorMessage(response));\n }\n const payload = await response.json();\n if (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n throw new GitHubAppApiError(\"GitHub returned an invalid manifest conversion payload\");\n }\n return payload as Record<string, unknown>;\n}\n\nexport async function listGitHubAppInstallationSummaries(\n settings: Settings,\n): Promise<GitHubAppInstallationSummary[]> {\n const missing = githubAppMissingSettings(settings);\n if (missing.length > 0) {\n throw new GitHubAppConfigurationError(missing);\n }\n const jwt = await createGitHubAppJwt(settings);\n const installations = await listInstallations(jwt);\n return installations.map(installationSummaryFromPayload);\n}\n\nexport async function getGitHubAppInstallationSummary(\n settings: Settings,\n installationId: number,\n): Promise<GitHubAppInstallationSummary | null> {\n const installations = await listGitHubAppInstallationSummaries(settings);\n return (\n installations.find((installation) => installation.installationId === installationId) ?? null\n );\n}\n\nexport async function verifyGitHubInstallationAccessForUser(\n settings: Settings,\n input: {\n code: string;\n installationId: number;\n },\n): Promise<GitHubAppInstallationSummary> {\n const token = await exchangeGitHubOAuthCodeForUserToken(settings, input.code);\n const installations = await listUserAccessibleInstallations(token);\n const installation = installations.find(\n (candidate) => candidate.installationId === input.installationId,\n );\n if (!installation) {\n throw new GitHubAppApiError(\"GitHub installation is not accessible to the installing user\");\n }\n return installation;\n}\n\n/**\n * Exchange a GitHub App user-authorization code and discover the installations\n * and repositories the user can explicitly access. This is compatibility\n * discovery metadata only: visibility and repository permission bits do not\n * prove that the human may install, configure, or bind the App installation.\n * No production binding path may treat this result as authority.\n */\nexport async function authorizeGitHubAppUser(\n settings: Settings,\n input: { code: string },\n): Promise<GitHubUserInstallationAccess[]> {\n const token = await exchangeGitHubOAuthCodeForUserToken(settings, input.code);\n const installations = await listUserAccessibleInstallations(token);\n return await Promise.all(\n installations.map(async (installation) => ({\n ...installation,\n repositories: installation.suspended\n ? []\n : await listUserInstallationRepositories(token, installation),\n })),\n );\n}\n\n/**\n * Prove current GitHub installation authority without treating repository\n * administration or installation visibility as delegation authority.\n *\n * GitHub exposes an exact personal-account owner through the authenticated\n * user's immutable id. For organizations, GitHub's authenticated membership\n * endpoint exposes active owners as role=admin. GitHub does not expose an\n * equivalent current-authority receipt for App Managers, so that case remains\n * unsupported and fails closed.\n */\nexport async function authorizeGitHubInstallationBinding(\n settings: Settings,\n input: { code: string; installationId: number },\n): Promise<GitHubInstallationBindingProof> {\n const userToken = await exchangeGitHubOAuthCodeForUserToken(settings, input.code);\n const actor = await getAuthenticatedGitHubUser(userToken);\n const visibleInstallations = await listUserAccessibleInstallations(userToken);\n const visible = visibleInstallations.find(\n (installation) => installation.installationId === input.installationId,\n );\n if (!visible) {\n throw new GitHubInstallationAuthorityError(\n \"authority_denied\",\n \"GitHub did not associate this installation with the authorized user\",\n );\n }\n\n const jwt = await createGitHubAppJwt(settings);\n const livePayload = (await listInstallations(jwt)).find(\n (installation) => asInt(installation.id) === input.installationId,\n );\n if (!livePayload) {\n throw new GitHubInstallationAuthorityError(\n \"installation_missing\",\n \"GitHub App installation was deleted or is not owned by this App\",\n );\n }\n const installation = installationSummaryFromPayload(livePayload);\n if (\n installation.accountId !== visible.accountId ||\n installation.accountLogin !== visible.accountLogin ||\n installation.accountType !== visible.accountType\n ) {\n throw new GitHubInstallationAuthorityError(\n \"authority_denied\",\n \"GitHub installation identity changed during authorization\",\n );\n }\n if (installation.suspended) {\n throw new GitHubInstallationAuthorityError(\n \"installation_suspended\",\n \"GitHub App installation is suspended\",\n );\n }\n\n let authorityKind: GitHubInstallationBindingProof[\"authorityKind\"];\n if (installation.accountType === \"User\" && actor.id === installation.accountId) {\n authorityKind = \"personal_owner\";\n } else if (installation.accountType === \"Organization\" && installation.accountLogin) {\n await assertActiveOrganizationOwner(\n userToken,\n installation.accountId,\n installation.accountLogin,\n );\n authorityKind = \"organization_owner\";\n } else {\n throw new GitHubInstallationAuthorityError(\n \"authority_denied\",\n \"Only a GitHub personal-account owner or organization owner may bind an installation\",\n );\n }\n\n const installationToken = await createInstallationToken(jwt, {\n installationId: installation.installationId,\n });\n const repositories = await listInstallationRepositories(\n installationToken.token,\n installation.installationId,\n { login: installation.accountLogin, type: installation.accountType },\n );\n if (repositories.length === 0) {\n throw new GitHubInstallationAuthorityError(\n \"repository_access_empty\",\n \"GitHub App installation does not currently grant access to any repositories\",\n );\n }\n if (authorityKind === \"organization_owner\") {\n // Repository enumeration is an async provider boundary. Re-read the live\n // owner tuple after it so a role revoked after the chooser proof cannot be\n // durably bound with a later, misleading authority timestamp.\n await assertActiveOrganizationOwner(\n userToken,\n installation.accountId,\n installation.accountLogin!,\n );\n }\n return {\n actorId: actor.id,\n actorLogin: actor.login,\n authorityKind,\n installation,\n repositories,\n };\n}\n\nexport async function listGitHubAppRepositories(\n settings: Settings,\n input: {\n installationIds?: number[];\n } = {},\n): Promise<GitHubRepository[]> {\n const missing = githubAppMissingSettings(settings);\n if (missing.length > 0) {\n throw new GitHubAppConfigurationError(missing);\n }\n const allowedInstallations = input.installationIds ? new Set(input.installationIds) : null;\n if (allowedInstallations && allowedInstallations.size === 0) {\n return [];\n }\n const jwt = await createGitHubAppJwt(settings);\n const installations = await listInstallations(jwt);\n const repositories: GitHubRepository[] = [];\n for (const installation of installations) {\n if (installation.suspended_at) {\n continue;\n }\n const installationId = asInt(installation.id);\n if (installationId === null) {\n continue;\n }\n if (allowedInstallations && !allowedInstallations.has(installationId)) {\n continue;\n }\n const account =\n typeof installation.account === \"object\" && installation.account\n ? (installation.account as Record<string, unknown>)\n : {};\n const token = await createInstallationToken(jwt, { installationId });\n repositories.push(\n ...(await listInstallationRepositories(token.token, installationId, account)),\n );\n }\n repositories.sort((left, right) => left.fullName.localeCompare(right.fullName));\n return repositories;\n}\n\nexport async function createGitHubAppInstallationToken(\n settings: Settings,\n input: {\n installationId: number;\n repositoryIds: number[];\n },\n): Promise<string> {\n return (await createGitHubAppInstallationTokenWithExpiry(settings, input)).token;\n}\n\nexport type GitHubAppInstallationToken = {\n token: string;\n expiresAt: string | null;\n};\n\nexport async function createGitHubAppInstallationTokenWithExpiry(\n settings: Settings,\n input: {\n installationId: number;\n repositoryIds: number[];\n },\n): Promise<GitHubAppInstallationToken> {\n const missing = githubAppMissingSettings(settings);\n if (missing.length > 0) {\n throw new GitHubAppConfigurationError(missing);\n }\n if (!Array.isArray(input.repositoryIds)) {\n throw new GitHubAppApiError(\n \"GitHub installation token mint requires an explicit, unique repository allowlist\",\n );\n }\n const repositoryIds = [...new Set(input.repositoryIds)];\n if (\n !Number.isSafeInteger(input.installationId) ||\n input.installationId <= 0 ||\n repositoryIds.length === 0 ||\n repositoryIds.length !== input.repositoryIds.length ||\n repositoryIds.some((id) => !Number.isSafeInteger(id) || id <= 0)\n ) {\n throw new GitHubAppApiError(\n \"GitHub installation token mint requires an explicit, unique repository allowlist\",\n );\n }\n const jwt = await createGitHubAppJwt(settings);\n return await createInstallationToken(jwt, {\n installationId: input.installationId,\n repositoryIds,\n });\n}\n\nexport function githubAppBotIdentity(settings: Settings): { name: string; email: string } | null {\n const appId = settings.githubAppId?.trim();\n const slug = settings.githubAppSlug?.trim();\n if (!appId || !slug) {\n return null;\n }\n const login = `${slug}[bot]`;\n return {\n name: login,\n email: `${appId}+${login}@users.noreply.github.com`,\n };\n}\n\nasync function createGitHubAppJwt(settings: Settings): Promise<string> {\n const privateKey = normalizeGitHubAppPrivateKey(settings.githubAppPrivateKey ?? \"\");\n const appId = settings.githubAppId?.trim();\n if (!appId || !privateKey) {\n throw new GitHubAppConfigurationError(githubAppMissingSettings(settings));\n }\n const key = await importPKCS8(privateKey, \"RS256\");\n const now = Math.floor(Date.now() / 1000);\n return await new SignJWT({})\n .setProtectedHeader({ alg: \"RS256\" })\n .setIssuedAt(now - 60)\n .setExpirationTime(now + 9 * 60)\n .setIssuer(appId)\n .sign(key);\n}\n\nasync function listInstallations(token: string): Promise<Array<Record<string, unknown>>> {\n const out: Array<Record<string, unknown>> = [];\n for (let page = 1; ; page += 1) {\n const payload = await githubGet(\"/app/installations\", token, {\n per_page: \"100\",\n page: String(page),\n });\n if (!Array.isArray(payload)) {\n throw new GitHubAppApiError(\"GitHub returned an invalid installations payload\");\n }\n out.push(\n ...payload.filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === \"object\" && !Array.isArray(item)),\n ),\n );\n if (payload.length < 100) {\n return out;\n }\n }\n}\n\nasync function exchangeGitHubOAuthCodeForUserToken(\n settings: Settings,\n code: string,\n): Promise<string> {\n if (!settings.githubClientId || !settings.githubClientSecret) {\n throw new GitHubAppConfigurationError(githubAppMissingSettings(settings));\n }\n const response = await fetch(\"https://github.com/login/oauth/access_token\", {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n client_id: settings.githubClientId,\n client_secret: settings.githubClientSecret,\n code,\n }),\n });\n if (!response.ok) {\n throw new GitHubAppApiError(await githubErrorMessage(response));\n }\n const payload = await response.json();\n if (!payload || typeof payload !== \"object\" || typeof payload.access_token !== \"string\") {\n throw new GitHubAppApiError(\"GitHub returned an invalid OAuth token payload\");\n }\n return payload.access_token;\n}\n\nasync function getAuthenticatedGitHubUser(token: string): Promise<{ id: number; login: string }> {\n const payload = await githubGet(\"/user\", token);\n const id = payload && typeof payload === \"object\" ? asInt(payload.id) : null;\n const login =\n payload && typeof payload === \"object\" && typeof payload.login === \"string\"\n ? payload.login\n : null;\n if (id === null || !login) {\n throw new GitHubAppApiError(\"GitHub returned an invalid authenticated user payload\");\n }\n return { id, login };\n}\n\nasync function getAuthenticatedOrganizationMembership(\n token: string,\n organizationLogin: string,\n): Promise<{ organizationId: number; role: string; state: string }> {\n let payload: any;\n try {\n payload = await githubGet(\n `/user/memberships/orgs/${encodeURIComponent(organizationLogin)}`,\n token,\n );\n } catch (error) {\n if (error instanceof GitHubAppApiError) {\n throw new GitHubInstallationAuthorityError(\n \"authority_unavailable\",\n \"GitHub could not prove current organization-owner membership\",\n error.status,\n );\n }\n throw error;\n }\n const organization =\n payload && typeof payload === \"object\" && payload.organization ? payload.organization : null;\n const organizationId =\n organization && typeof organization === \"object\" ? asInt(organization.id) : null;\n if (\n organizationId === null ||\n typeof payload?.role !== \"string\" ||\n typeof payload?.state !== \"string\"\n ) {\n throw new GitHubInstallationAuthorityError(\n \"authority_unavailable\",\n \"GitHub returned an invalid organization membership proof\",\n );\n }\n return { organizationId, role: payload.role, state: payload.state };\n}\n\nasync function assertActiveOrganizationOwner(\n token: string,\n organizationId: number,\n organizationLogin: string,\n): Promise<void> {\n const membership = await getAuthenticatedOrganizationMembership(token, organizationLogin);\n if (\n membership.organizationId !== organizationId ||\n membership.state !== \"active\" ||\n membership.role !== \"admin\"\n ) {\n throw new GitHubInstallationAuthorityError(\n \"authority_denied\",\n \"Only an active GitHub organization owner may bind this installation\",\n );\n }\n}\n\nasync function listUserAccessibleInstallations(\n token: string,\n): Promise<GitHubAppInstallationSummary[]> {\n const out: GitHubAppInstallationSummary[] = [];\n for (let page = 1; ; page += 1) {\n const payload = await githubGet(\"/user/installations\", token, {\n per_page: \"100\",\n page: String(page),\n });\n const installations: unknown[] | null =\n payload && typeof payload === \"object\" && Array.isArray(payload.installations)\n ? (payload.installations as unknown[])\n : null;\n if (!installations) {\n throw new GitHubAppApiError(\"GitHub returned an invalid user installations payload\");\n }\n out.push(\n ...installations\n .filter((item): item is Record<string, unknown> =>\n Boolean(item && typeof item === \"object\" && !Array.isArray(item)),\n )\n .map(installationSummaryFromPayload),\n );\n if (installations.length < 100) {\n return out;\n }\n }\n}\n\nasync function listUserInstallationRepositories(\n token: string,\n installation: GitHubAppInstallationSummary,\n): Promise<GitHubUserRepositoryAccess[]> {\n const out: GitHubUserRepositoryAccess[] = [];\n const account = {\n ...(installation.accountLogin ? { login: installation.accountLogin } : {}),\n ...(installation.accountType ? { type: installation.accountType } : {}),\n };\n for (let page = 1; ; page += 1) {\n const payload = await githubGet(\n `/user/installations/${installation.installationId}/repositories`,\n token,\n { per_page: \"100\", page: String(page) },\n );\n if (\n !payload ||\n typeof payload !== \"object\" ||\n Array.isArray(payload) ||\n !Array.isArray(payload.repositories)\n ) {\n throw new GitHubAppApiError(\n \"GitHub returned an invalid user installation repositories payload\",\n );\n }\n for (const repository of payload.repositories) {\n if (!repository || typeof repository !== \"object\" || Array.isArray(repository)) {\n continue;\n }\n const record = repository as Record<string, unknown>;\n out.push({\n ...repositoryFromPayload(record, installation.installationId, account),\n permissions: repositoryPermissionsFromPayload(record.permissions),\n });\n }\n if (payload.repositories.length < 100) {\n return out;\n }\n }\n}\n\nasync function createInstallationToken(\n appJwt: string,\n input: {\n installationId: number;\n repositoryIds?: number[];\n },\n): Promise<GitHubAppInstallationToken> {\n const scoped = input.repositoryIds && input.repositoryIds.length > 0;\n const response = await fetch(\n `${githubApiBase}/app/installations/${input.installationId}/access_tokens`,\n {\n method: \"POST\",\n headers: {\n ...githubHeaders(appJwt),\n ...(scoped ? { \"Content-Type\": \"application/json\" } : {}),\n },\n signal: AbortSignal.timeout(githubTokenMintTimeoutMs),\n ...(scoped ? { body: JSON.stringify({ repository_ids: input.repositoryIds }) } : {}),\n },\n );\n if (!response.ok) {\n throw new GitHubAppApiError(await githubErrorMessage(response));\n }\n const payload = await response.json();\n if (!payload || typeof payload !== \"object\" || typeof payload.token !== \"string\") {\n throw new GitHubAppApiError(\"GitHub returned an invalid installation token payload\");\n }\n return {\n token: payload.token,\n expiresAt: typeof payload.expires_at === \"string\" ? payload.expires_at : null,\n };\n}\n\nasync function listInstallationRepositories(\n token: string,\n installationId: number,\n account: Record<string, unknown>,\n): Promise<GitHubRepository[]> {\n const out: GitHubRepository[] = [];\n for (let page = 1; ; page += 1) {\n const payload = await githubGet(\"/installation/repositories\", token, {\n per_page: \"100\",\n page: String(page),\n });\n if (\n !payload ||\n typeof payload !== \"object\" ||\n Array.isArray(payload) ||\n !Array.isArray(payload.repositories)\n ) {\n throw new GitHubAppApiError(\"GitHub returned an invalid repositories payload\");\n }\n for (const repo of payload.repositories) {\n if (repo && typeof repo === \"object\" && !Array.isArray(repo)) {\n out.push(repositoryFromPayload(repo as Record<string, unknown>, installationId, account));\n }\n }\n if (payload.repositories.length < 100) {\n return out;\n }\n }\n}\n\nfunction installationSummaryFromPayload(\n payload: Record<string, unknown>,\n): GitHubAppInstallationSummary {\n const installationId = asInt(payload.id);\n if (installationId === null) {\n throw new GitHubAppApiError(\"GitHub returned an installation without id\");\n }\n const account =\n typeof payload.account === \"object\" && payload.account\n ? (payload.account as Record<string, unknown>)\n : {};\n const accountId = asInt(account.id);\n if (accountId === null) {\n throw new GitHubAppApiError(\"GitHub returned an installation without an account id\");\n }\n return {\n installationId,\n accountId,\n accountLogin: typeof account.login === \"string\" ? account.login : null,\n accountType: typeof account.type === \"string\" ? account.type : null,\n suspended: Boolean(payload.suspended_at),\n };\n}\n\nasync function githubGet(\n path: string,\n token: string,\n params: Record<string, string> = {},\n): Promise<any> {\n const url = new URL(`${githubApiBase}${path}`);\n for (const [key, value] of Object.entries(params)) {\n url.searchParams.set(key, value);\n }\n const response = await fetch(url, { headers: githubHeaders(token) });\n if (!response.ok) {\n throw new GitHubAppApiError(await githubErrorMessage(response), response.status);\n }\n return await response.json();\n}\n\nfunction repositoryFromPayload(\n payload: Record<string, unknown>,\n installationId: number,\n account: Record<string, unknown>,\n): GitHubRepository {\n const id = asInt(payload.id);\n const fullName = String(payload.full_name ?? \"\");\n if (id === null || !fullName) {\n throw new GitHubAppApiError(\"GitHub returned a repository without id/full_name\");\n }\n return {\n id,\n installationId,\n fullName,\n name: String(payload.name ?? fullName.split(\"/\").at(-1) ?? fullName),\n private: Boolean(payload.private),\n htmlUrl: String(payload.html_url ?? `https://github.com/${fullName}`),\n cloneUrl: String(payload.clone_url ?? `https://github.com/${fullName}.git`),\n defaultBranch: String(payload.default_branch ?? \"main\"),\n accountLogin: String(account.login ?? fullName.split(\"/\", 1)[0]),\n accountType: typeof account.type === \"string\" ? account.type : null,\n };\n}\n\nfunction repositoryPermissionsFromPayload(payload: unknown): GitHubRepositoryPermissions {\n const permissions =\n payload && typeof payload === \"object\" && !Array.isArray(payload)\n ? (payload as Record<string, unknown>)\n : {};\n return {\n admin: permissions.admin === true,\n maintain: permissions.maintain === true,\n push: permissions.push === true,\n triage: permissions.triage === true,\n pull: permissions.pull === true,\n };\n}\n\nfunction githubHeaders(token?: string): HeadersInit {\n return {\n Accept: \"application/vnd.github+json\",\n ...(token ? { Authorization: `Bearer ${token}` } : {}),\n \"X-GitHub-Api-Version\": githubApiVersion,\n };\n}\n\nasync function githubErrorMessage(response: Response): Promise<string> {\n try {\n const payload = await response.json();\n if (payload && typeof payload === \"object\" && \"message\" in payload) {\n return `GitHub API ${response.status}: ${String(payload.message)}`;\n }\n } catch {\n // fall through\n }\n return `GitHub API ${response.status}: ${await response.text()}`;\n}\n\nexport function normalizeGitHubAppPrivateKey(value: string): string {\n const privateKey = value.trim().replace(/\\\\n/g, \"\\n\");\n if (!privateKey || privateKey.startsWith(pkcs8PrivateKeyHeader)) {\n return privateKey;\n }\n if (privateKey.startsWith(rsaPrivateKeyHeader)) {\n return createPrivateKey(privateKey).export({ type: \"pkcs8\", format: \"pem\" }).toString();\n }\n return privateKey;\n}\n\nfunction signStatePayload(encoded: string, secret: string): string {\n return createHmac(\"sha256\", secret).update(encoded).digest(\"base64url\");\n}\n\nfunction safeEqual(left: string, right: string): boolean {\n const a = Buffer.from(left);\n const b = Buffer.from(right);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\nfunction asInt(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isInteger(value)) {\n return value;\n }\n if (typeof value === \"string\" && /^\\d+$/.test(value)) {\n return Number(value);\n }\n return null;\n}\n"],"mappings":";AAQA,SAAS,YAAY,kBAAkB,aAAa,uBAAuB;AAC3E,SAAS,SAAS,mBAAmB;AAErC,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AACzB,IAAM,2BAA2B;AAC1B,IAAM,qBAAqB,KAAK;AACvC,IAAM,wBAAwB,cAAc,aAAa;AACzD,IAAM,sBAAsB,cAAc,iBAAiB;AAEpD,IAAM,8BAAN,cAA0C,MAAM;AAAA,EACrD,YAAqB,SAAmB;AACtC,UAAM,8BAA8B;AADjB;AAAA,EAErB;AACF;AAEO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,YACE,SACS,SAAwB,MACjC;AACA,UAAM,OAAO;AAFJ;AAAA,EAGX;AACF;AASO,IAAM,mCAAN,cAA+C,kBAAkB;AAAA,EACtE,YACW,QACT,SACA,SAAwB,MACxB;AACA,UAAM,SAAS,MAAM;AAJZ;AAAA,EAKX;AACF;AAkBO,SAAS,yBAAyB,UAA8B;AACrE,QAAM,WAA+C;AAAA,IACnD,wBAAwB,SAAS;AAAA,IACjC,2BAA2B,SAAS;AAAA,IACpC,+BAA+B,SAAS;AAAA,IACxC,0BAA0B,SAAS;AAAA,IACnC,iCAAiC,SAAS;AAAA,EAC5C;AACA,SAAO,OAAO,QAAQ,QAAQ,EAAE,QAAQ,CAAC,CAAC,MAAM,KAAK,MAAO,SAAS,MAAM,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI,CAAE;AAClG;AAEO,SAAS,uBAAuB,OAMX;AAC1B,QAAM,OAAO,MAAM,QAAQ,QAAQ,QAAQ,EAAE;AAC7C,QAAM,cAAsC;AAAA,IAC1C,UAAU;AAAA,IACV,UAAU;AAAA,IACV,eAAe;AAAA;AAAA;AAAA;AAAA,IAIf,SAAS;AAAA,EACX;AACA,MAAI,MAAM,sBAAsB;AAC9B,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AAK,IAAI;AAC1B,QAAM,IAAI,OAAO,KAAK,KAAK;AAC3B,SAAO,EAAE,WAAW,EAAE,UAAU,gBAAgB,GAAG,CAAC;AACtD;AAEA,SAAS,MAAM,OAA+B;AAC5C,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,GAAG;AACxD,WAAO;AAAA,EACT;AACA,MAAI,OAAO,UAAU,YAAY,QAAQ,KAAK,KAAK,GAAG;AACpD,WAAO,OAAO,KAAK;AAAA,EACrB;AACA,SAAO;AACT;","names":["installation"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opengeni/github",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.18",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -31,8 +31,8 @@
|
|
|
31
31
|
"prepublishOnly": "bash ../../scripts/prepublish-guard"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@opengeni/config": "^0.7.
|
|
35
|
-
"@opengeni/contracts": "^0.19.
|
|
34
|
+
"@opengeni/config": "^0.7.6",
|
|
35
|
+
"@opengeni/contracts": "^0.19.4",
|
|
36
36
|
"jose": "^6.1.3"
|
|
37
37
|
}
|
|
38
38
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Settings } from "@opengeni/config";
|
|
2
2
|
import type {
|
|
3
|
+
GitHubInstallationBindingProof,
|
|
3
4
|
GitHubRepository,
|
|
4
5
|
GitHubRepositoryPermissions,
|
|
5
6
|
GitHubUserInstallationAccess,
|
|
@@ -21,10 +22,35 @@ export class GitHubAppConfigurationError extends Error {
|
|
|
21
22
|
}
|
|
22
23
|
}
|
|
23
24
|
|
|
24
|
-
export class GitHubAppApiError extends Error {
|
|
25
|
+
export class GitHubAppApiError extends Error {
|
|
26
|
+
constructor(
|
|
27
|
+
message: string,
|
|
28
|
+
readonly status: number | null = null,
|
|
29
|
+
) {
|
|
30
|
+
super(message);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type GitHubInstallationAuthorityFailure =
|
|
35
|
+
| "authority_denied"
|
|
36
|
+
| "authority_unavailable"
|
|
37
|
+
| "installation_missing"
|
|
38
|
+
| "installation_suspended"
|
|
39
|
+
| "repository_access_empty";
|
|
40
|
+
|
|
41
|
+
export class GitHubInstallationAuthorityError extends GitHubAppApiError {
|
|
42
|
+
constructor(
|
|
43
|
+
readonly reason: GitHubInstallationAuthorityFailure,
|
|
44
|
+
message: string,
|
|
45
|
+
status: number | null = null,
|
|
46
|
+
) {
|
|
47
|
+
super(message, status);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
25
50
|
|
|
26
51
|
export type GitHubAppInstallationSummary = {
|
|
27
52
|
installationId: number;
|
|
53
|
+
accountId: number;
|
|
28
54
|
accountLogin: string | null;
|
|
29
55
|
accountType: string | null;
|
|
30
56
|
suspended: boolean;
|
|
@@ -61,6 +87,10 @@ export function buildGitHubAppManifest(input: {
|
|
|
61
87
|
metadata: "read",
|
|
62
88
|
contents: "write",
|
|
63
89
|
pull_requests: "write",
|
|
90
|
+
// Required for the authenticated-user membership endpoint that proves an
|
|
91
|
+
// active organization owner. Existing installations must approve this
|
|
92
|
+
// permission before organization-owner self-service can succeed.
|
|
93
|
+
members: "read",
|
|
64
94
|
};
|
|
65
95
|
if (input.includeCiPermissions) {
|
|
66
96
|
permissions.actions = "read";
|
|
@@ -250,6 +280,111 @@ export async function authorizeGitHubAppUser(
|
|
|
250
280
|
);
|
|
251
281
|
}
|
|
252
282
|
|
|
283
|
+
/**
|
|
284
|
+
* Prove current GitHub installation authority without treating repository
|
|
285
|
+
* administration or installation visibility as delegation authority.
|
|
286
|
+
*
|
|
287
|
+
* GitHub exposes an exact personal-account owner through the authenticated
|
|
288
|
+
* user's immutable id. For organizations, GitHub's authenticated membership
|
|
289
|
+
* endpoint exposes active owners as role=admin. GitHub does not expose an
|
|
290
|
+
* equivalent current-authority receipt for App Managers, so that case remains
|
|
291
|
+
* unsupported and fails closed.
|
|
292
|
+
*/
|
|
293
|
+
export async function authorizeGitHubInstallationBinding(
|
|
294
|
+
settings: Settings,
|
|
295
|
+
input: { code: string; installationId: number },
|
|
296
|
+
): Promise<GitHubInstallationBindingProof> {
|
|
297
|
+
const userToken = await exchangeGitHubOAuthCodeForUserToken(settings, input.code);
|
|
298
|
+
const actor = await getAuthenticatedGitHubUser(userToken);
|
|
299
|
+
const visibleInstallations = await listUserAccessibleInstallations(userToken);
|
|
300
|
+
const visible = visibleInstallations.find(
|
|
301
|
+
(installation) => installation.installationId === input.installationId,
|
|
302
|
+
);
|
|
303
|
+
if (!visible) {
|
|
304
|
+
throw new GitHubInstallationAuthorityError(
|
|
305
|
+
"authority_denied",
|
|
306
|
+
"GitHub did not associate this installation with the authorized user",
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const jwt = await createGitHubAppJwt(settings);
|
|
311
|
+
const livePayload = (await listInstallations(jwt)).find(
|
|
312
|
+
(installation) => asInt(installation.id) === input.installationId,
|
|
313
|
+
);
|
|
314
|
+
if (!livePayload) {
|
|
315
|
+
throw new GitHubInstallationAuthorityError(
|
|
316
|
+
"installation_missing",
|
|
317
|
+
"GitHub App installation was deleted or is not owned by this App",
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
const installation = installationSummaryFromPayload(livePayload);
|
|
321
|
+
if (
|
|
322
|
+
installation.accountId !== visible.accountId ||
|
|
323
|
+
installation.accountLogin !== visible.accountLogin ||
|
|
324
|
+
installation.accountType !== visible.accountType
|
|
325
|
+
) {
|
|
326
|
+
throw new GitHubInstallationAuthorityError(
|
|
327
|
+
"authority_denied",
|
|
328
|
+
"GitHub installation identity changed during authorization",
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
if (installation.suspended) {
|
|
332
|
+
throw new GitHubInstallationAuthorityError(
|
|
333
|
+
"installation_suspended",
|
|
334
|
+
"GitHub App installation is suspended",
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
let authorityKind: GitHubInstallationBindingProof["authorityKind"];
|
|
339
|
+
if (installation.accountType === "User" && actor.id === installation.accountId) {
|
|
340
|
+
authorityKind = "personal_owner";
|
|
341
|
+
} else if (installation.accountType === "Organization" && installation.accountLogin) {
|
|
342
|
+
await assertActiveOrganizationOwner(
|
|
343
|
+
userToken,
|
|
344
|
+
installation.accountId,
|
|
345
|
+
installation.accountLogin,
|
|
346
|
+
);
|
|
347
|
+
authorityKind = "organization_owner";
|
|
348
|
+
} else {
|
|
349
|
+
throw new GitHubInstallationAuthorityError(
|
|
350
|
+
"authority_denied",
|
|
351
|
+
"Only a GitHub personal-account owner or organization owner may bind an installation",
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const installationToken = await createInstallationToken(jwt, {
|
|
356
|
+
installationId: installation.installationId,
|
|
357
|
+
});
|
|
358
|
+
const repositories = await listInstallationRepositories(
|
|
359
|
+
installationToken.token,
|
|
360
|
+
installation.installationId,
|
|
361
|
+
{ login: installation.accountLogin, type: installation.accountType },
|
|
362
|
+
);
|
|
363
|
+
if (repositories.length === 0) {
|
|
364
|
+
throw new GitHubInstallationAuthorityError(
|
|
365
|
+
"repository_access_empty",
|
|
366
|
+
"GitHub App installation does not currently grant access to any repositories",
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
if (authorityKind === "organization_owner") {
|
|
370
|
+
// Repository enumeration is an async provider boundary. Re-read the live
|
|
371
|
+
// owner tuple after it so a role revoked after the chooser proof cannot be
|
|
372
|
+
// durably bound with a later, misleading authority timestamp.
|
|
373
|
+
await assertActiveOrganizationOwner(
|
|
374
|
+
userToken,
|
|
375
|
+
installation.accountId,
|
|
376
|
+
installation.accountLogin!,
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
return {
|
|
380
|
+
actorId: actor.id,
|
|
381
|
+
actorLogin: actor.login,
|
|
382
|
+
authorityKind,
|
|
383
|
+
installation,
|
|
384
|
+
repositories,
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
253
388
|
export async function listGitHubAppRepositories(
|
|
254
389
|
settings: Settings,
|
|
255
390
|
input: {
|
|
@@ -295,7 +430,7 @@ export async function createGitHubAppInstallationToken(
|
|
|
295
430
|
settings: Settings,
|
|
296
431
|
input: {
|
|
297
432
|
installationId: number;
|
|
298
|
-
repositoryIds
|
|
433
|
+
repositoryIds: number[];
|
|
299
434
|
},
|
|
300
435
|
): Promise<string> {
|
|
301
436
|
return (await createGitHubAppInstallationTokenWithExpiry(settings, input)).token;
|
|
@@ -310,15 +445,35 @@ export async function createGitHubAppInstallationTokenWithExpiry(
|
|
|
310
445
|
settings: Settings,
|
|
311
446
|
input: {
|
|
312
447
|
installationId: number;
|
|
313
|
-
repositoryIds
|
|
448
|
+
repositoryIds: number[];
|
|
314
449
|
},
|
|
315
450
|
): Promise<GitHubAppInstallationToken> {
|
|
316
451
|
const missing = githubAppMissingSettings(settings);
|
|
317
452
|
if (missing.length > 0) {
|
|
318
453
|
throw new GitHubAppConfigurationError(missing);
|
|
319
454
|
}
|
|
455
|
+
if (!Array.isArray(input.repositoryIds)) {
|
|
456
|
+
throw new GitHubAppApiError(
|
|
457
|
+
"GitHub installation token mint requires an explicit, unique repository allowlist",
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
const repositoryIds = [...new Set(input.repositoryIds)];
|
|
461
|
+
if (
|
|
462
|
+
!Number.isSafeInteger(input.installationId) ||
|
|
463
|
+
input.installationId <= 0 ||
|
|
464
|
+
repositoryIds.length === 0 ||
|
|
465
|
+
repositoryIds.length !== input.repositoryIds.length ||
|
|
466
|
+
repositoryIds.some((id) => !Number.isSafeInteger(id) || id <= 0)
|
|
467
|
+
) {
|
|
468
|
+
throw new GitHubAppApiError(
|
|
469
|
+
"GitHub installation token mint requires an explicit, unique repository allowlist",
|
|
470
|
+
);
|
|
471
|
+
}
|
|
320
472
|
const jwt = await createGitHubAppJwt(settings);
|
|
321
|
-
return await createInstallationToken(jwt,
|
|
473
|
+
return await createInstallationToken(jwt, {
|
|
474
|
+
installationId: input.installationId,
|
|
475
|
+
repositoryIds,
|
|
476
|
+
});
|
|
322
477
|
}
|
|
323
478
|
|
|
324
479
|
export function githubAppBotIdentity(settings: Settings): { name: string; email: string } | null {
|
|
@@ -400,6 +555,74 @@ async function exchangeGitHubOAuthCodeForUserToken(
|
|
|
400
555
|
return payload.access_token;
|
|
401
556
|
}
|
|
402
557
|
|
|
558
|
+
async function getAuthenticatedGitHubUser(token: string): Promise<{ id: number; login: string }> {
|
|
559
|
+
const payload = await githubGet("/user", token);
|
|
560
|
+
const id = payload && typeof payload === "object" ? asInt(payload.id) : null;
|
|
561
|
+
const login =
|
|
562
|
+
payload && typeof payload === "object" && typeof payload.login === "string"
|
|
563
|
+
? payload.login
|
|
564
|
+
: null;
|
|
565
|
+
if (id === null || !login) {
|
|
566
|
+
throw new GitHubAppApiError("GitHub returned an invalid authenticated user payload");
|
|
567
|
+
}
|
|
568
|
+
return { id, login };
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async function getAuthenticatedOrganizationMembership(
|
|
572
|
+
token: string,
|
|
573
|
+
organizationLogin: string,
|
|
574
|
+
): Promise<{ organizationId: number; role: string; state: string }> {
|
|
575
|
+
let payload: any;
|
|
576
|
+
try {
|
|
577
|
+
payload = await githubGet(
|
|
578
|
+
`/user/memberships/orgs/${encodeURIComponent(organizationLogin)}`,
|
|
579
|
+
token,
|
|
580
|
+
);
|
|
581
|
+
} catch (error) {
|
|
582
|
+
if (error instanceof GitHubAppApiError) {
|
|
583
|
+
throw new GitHubInstallationAuthorityError(
|
|
584
|
+
"authority_unavailable",
|
|
585
|
+
"GitHub could not prove current organization-owner membership",
|
|
586
|
+
error.status,
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
throw error;
|
|
590
|
+
}
|
|
591
|
+
const organization =
|
|
592
|
+
payload && typeof payload === "object" && payload.organization ? payload.organization : null;
|
|
593
|
+
const organizationId =
|
|
594
|
+
organization && typeof organization === "object" ? asInt(organization.id) : null;
|
|
595
|
+
if (
|
|
596
|
+
organizationId === null ||
|
|
597
|
+
typeof payload?.role !== "string" ||
|
|
598
|
+
typeof payload?.state !== "string"
|
|
599
|
+
) {
|
|
600
|
+
throw new GitHubInstallationAuthorityError(
|
|
601
|
+
"authority_unavailable",
|
|
602
|
+
"GitHub returned an invalid organization membership proof",
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
return { organizationId, role: payload.role, state: payload.state };
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
async function assertActiveOrganizationOwner(
|
|
609
|
+
token: string,
|
|
610
|
+
organizationId: number,
|
|
611
|
+
organizationLogin: string,
|
|
612
|
+
): Promise<void> {
|
|
613
|
+
const membership = await getAuthenticatedOrganizationMembership(token, organizationLogin);
|
|
614
|
+
if (
|
|
615
|
+
membership.organizationId !== organizationId ||
|
|
616
|
+
membership.state !== "active" ||
|
|
617
|
+
membership.role !== "admin"
|
|
618
|
+
) {
|
|
619
|
+
throw new GitHubInstallationAuthorityError(
|
|
620
|
+
"authority_denied",
|
|
621
|
+
"Only an active GitHub organization owner may bind this installation",
|
|
622
|
+
);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
403
626
|
async function listUserAccessibleInstallations(
|
|
404
627
|
token: string,
|
|
405
628
|
): Promise<GitHubAppInstallationSummary[]> {
|
|
@@ -544,8 +767,13 @@ function installationSummaryFromPayload(
|
|
|
544
767
|
typeof payload.account === "object" && payload.account
|
|
545
768
|
? (payload.account as Record<string, unknown>)
|
|
546
769
|
: {};
|
|
770
|
+
const accountId = asInt(account.id);
|
|
771
|
+
if (accountId === null) {
|
|
772
|
+
throw new GitHubAppApiError("GitHub returned an installation without an account id");
|
|
773
|
+
}
|
|
547
774
|
return {
|
|
548
775
|
installationId,
|
|
776
|
+
accountId,
|
|
549
777
|
accountLogin: typeof account.login === "string" ? account.login : null,
|
|
550
778
|
accountType: typeof account.type === "string" ? account.type : null,
|
|
551
779
|
suspended: Boolean(payload.suspended_at),
|
|
@@ -555,7 +783,7 @@ function installationSummaryFromPayload(
|
|
|
555
783
|
async function githubGet(
|
|
556
784
|
path: string,
|
|
557
785
|
token: string,
|
|
558
|
-
params: Record<string, string
|
|
786
|
+
params: Record<string, string> = {},
|
|
559
787
|
): Promise<any> {
|
|
560
788
|
const url = new URL(`${githubApiBase}${path}`);
|
|
561
789
|
for (const [key, value] of Object.entries(params)) {
|
|
@@ -563,7 +791,7 @@ async function githubGet(
|
|
|
563
791
|
}
|
|
564
792
|
const response = await fetch(url, { headers: githubHeaders(token) });
|
|
565
793
|
if (!response.ok) {
|
|
566
|
-
throw new GitHubAppApiError(await githubErrorMessage(response));
|
|
794
|
+
throw new GitHubAppApiError(await githubErrorMessage(response), response.status);
|
|
567
795
|
}
|
|
568
796
|
return await response.json();
|
|
569
797
|
}
|