-
Notifications
You must be signed in to change notification settings - Fork 141
/
fetch-installation-token.ts
62 lines (58 loc) · 1.51 KB
/
fetch-installation-token.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { getOctokit } from "@actions/github";
import { createAppAuth } from "@octokit/auth-app";
import { request } from "@octokit/request";
import ensureError from "ensure-error";
export const fetchInstallationToken = async ({
appId,
githubApiUrl,
installationId,
owner,
permissions,
privateKey,
repo,
}: Readonly<{
appId: string;
githubApiUrl: URL;
installationId?: number;
owner: string;
permissions?: Record<string, string>;
privateKey: string;
repo: string;
}>): Promise<string> => {
const app = createAppAuth({
appId,
privateKey,
request: request.defaults({
baseUrl: githubApiUrl
.toString()
// Remove optional trailing `/`.
.replace(/\/$/, ""),
}),
});
const authApp = await app({ type: "app" });
const octokit = getOctokit(authApp.token);
if (installationId === undefined) {
try {
({
data: { id: installationId },
} = await octokit.rest.apps.getRepoInstallation({ owner, repo }));
} catch (error: unknown) {
throw new Error(
"Could not get repo installation. Is the app installed on this repo?",
{ cause: ensureError(error) },
);
}
}
try {
const { data: installation } =
await octokit.rest.apps.createInstallationAccessToken({
installation_id: installationId,
permissions,
});
return installation.token;
} catch (error: unknown) {
throw new Error("Could not create installation access token.", {
cause: ensureError(error),
});
}
};