@notation/factory-github 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Notation Labs Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,69 @@
1
+ import {
2
+ type Channel as ChannelContract,
3
+ type ChannelConfig,
4
+ channelConfig,
5
+ OutpostGroup,
6
+ type Selector,
7
+ } from "@notation/factory";
8
+ import * as v from "valibot";
9
+ import type { ConnectionRef } from "./connection-ref.ts";
10
+ import {
11
+ type IssueCommentEvent,
12
+ type IssueCommentSelector,
13
+ issueCommentSelector,
14
+ type IssueEvent,
15
+ type IssueSelector,
16
+ issueSelector,
17
+ } from "./selectors.ts";
18
+
19
+ /**
20
+ * A repo's issues on a GitHub connection, made by `connection.channel(...)`.
21
+ * Its grant is the App's installation on the repo. Its selectors are data the
22
+ * router matches; a conversation is an issue.
23
+ */
24
+ export class Channel
25
+ extends OutpostGroup<ChannelConfig>
26
+ implements ChannelContract
27
+ {
28
+ /** Unset means the outpost's repo. */
29
+ readonly scope: string | undefined;
30
+ readonly connection: ConnectionRef;
31
+
32
+ constructor(
33
+ id: string,
34
+ { connection, ...config }: ChannelConfig & { connection: ConnectionRef },
35
+ ) {
36
+ super("github/Channel", id, config);
37
+ const { outpost } = this;
38
+ const { scope } = v.parse(channelConfig, config);
39
+ this.scope = scope;
40
+ this.connection = connection;
41
+ outpost.store.contribute({
42
+ channels: {
43
+ [id]: {
44
+ provider: "github",
45
+ connection: this.connection.name,
46
+ ...(scope ? { scope } : {}),
47
+ },
48
+ },
49
+ });
50
+ }
51
+
52
+ /** Issue events. `actions` defaults to `["opened"]`. */
53
+ issue(opts: IssueSelector): Selector<IssueEvent> {
54
+ return {
55
+ channel: this,
56
+ event: "issues",
57
+ match: v.parse(issueSelector, opts),
58
+ };
59
+ }
60
+
61
+ /** Comments on issues and pull requests. `actions` defaults to `["created"]`; with `"edited"`, only edits that newly add `mention` match. */
62
+ issueComment(opts: IssueCommentSelector): Selector<IssueCommentEvent> {
63
+ return {
64
+ channel: this,
65
+ event: "issue_comment",
66
+ match: v.parse(issueCommentSelector, opts),
67
+ };
68
+ }
69
+ }
@@ -0,0 +1,40 @@
1
+ import { ResourceGroup } from "@notation/resource";
2
+ import type { CodeHost as CodeHostContract, RepoPattern } from "@notation/factory";
3
+ import * as v from "valibot";
4
+ import type { Connection } from "./connection.ts";
5
+
6
+ const codeHostConfig = v.object({
7
+ allow: v.array(v.object({ owner: v.string(), repo: v.optional(v.string()) })),
8
+ });
9
+ export type CodeHostConfig = v.InferInput<typeof codeHostConfig>;
10
+
11
+ export type CodeHostOptions = CodeHostConfig & { connection: Connection };
12
+
13
+ /**
14
+ * `new github.CodeHost(...)`: the infra's repos are on GitHub. Installed repos
15
+ * that match `allow` get outposts, and the router mints their containers'
16
+ * installation tokens through the connection's App. Those last an hour and can
17
+ * be limited to one repo and a set of permissions, so every `github.Policy`
18
+ * passes.
19
+ */
20
+ export class CodeHost
21
+ extends ResourceGroup<CodeHostConfig>
22
+ implements CodeHostContract
23
+ {
24
+ readonly connection: Connection;
25
+ readonly allow: RepoPattern[];
26
+
27
+ constructor(id: string, { connection, ...config }: CodeHostOptions) {
28
+ const { allow } = v.parse(codeHostConfig, config);
29
+ super("github/CodeHost", id, config);
30
+ this.connection = connection;
31
+ this.allow = allow;
32
+ this.connection.router.store.contribute({
33
+ codeHost: {
34
+ provider: "github",
35
+ connection: this.connection.name,
36
+ allow,
37
+ },
38
+ });
39
+ }
40
+ }
@@ -0,0 +1,26 @@
1
+ import { ResourceGroup } from "@notation/resource";
2
+ import type {
3
+ ChannelOptions,
4
+ ConnectionRef as ConnectionRefContract,
5
+ } from "@notation/factory";
6
+ import { Channel } from "./channel.ts";
7
+
8
+ type ConnectionRefConfig = { name: string };
9
+
10
+ /** In an outpost: a GitHub connection the infra declares, from `github.Connection.get(name)`. */
11
+ export class ConnectionRef
12
+ extends ResourceGroup<ConnectionRefConfig>
13
+ implements ConnectionRefContract
14
+ {
15
+ readonly name: string;
16
+
17
+ constructor(id: string, config: ConnectionRefConfig) {
18
+ super("github/ConnectionRef", id, config);
19
+ this.name = config.name;
20
+ }
21
+
22
+ /** A repo's issues. `scope` defaults to the outpost's repo. */
23
+ channel({ id, ...config }: ChannelOptions): Channel {
24
+ return new Channel(id, { ...config, connection: this });
25
+ }
26
+ }
@@ -0,0 +1,88 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { getActiveResourceCollection, ResourceGroup, text } from "@notation/resource";
3
+ import {
4
+ type Connection as ConnectionContract,
5
+ type Router,
6
+ } from "@notation/factory";
7
+ import { webhookPath } from "@notation/factory/router";
8
+ import * as v from "valibot";
9
+ import { appName } from "../lib/app-name.ts";
10
+ import { App, type AppInstance } from "../resources/app.ts";
11
+ import { CHANNEL_SECRETS, CHANNEL_VALUES } from "../router/index.ts";
12
+ import { ConnectionRef } from "./connection-ref.ts";
13
+
14
+ const connectionConfig = v.object({
15
+ org: v.optional(v.string()),
16
+ });
17
+ export type ConnectionConfig = v.InferInput<typeof connectionConfig>;
18
+
19
+ export type ConnectionOptions = ConnectionConfig & { router: Router };
20
+
21
+ /**
22
+ * `new github.Connection(...)`: Notation Factory on GitHub, as one App whose
23
+ * webhook is the connection's path on the router. The router runs the
24
+ * connection's channel, which reads the App's private key. The key goes from
25
+ * the App to the router's vault in memory.
26
+ */
27
+ export class Connection
28
+ extends ResourceGroup<ConnectionConfig>
29
+ implements ConnectionContract
30
+ {
31
+ readonly name: string;
32
+ readonly router: Router;
33
+ readonly app: AppInstance;
34
+
35
+ constructor(id: string, { router, ...config }: ConnectionOptions) {
36
+ const { org } = v.parse(connectionConfig, config);
37
+ super("github/Connection", id, config);
38
+ this.name = id;
39
+ this.router = router;
40
+ const key = `github/${id}`;
41
+ this.app = this.add(
42
+ new App(`${id}-app`, {
43
+ config: {
44
+ name: appName(getActiveResourceCollection()?.scope, id),
45
+ org,
46
+ hookUrl: text`${router.url}${webhookPath(key)}`,
47
+ },
48
+ }),
49
+ );
50
+ this.app.contribute({
51
+ events: ["issues", "issue_comment", "push"],
52
+ permissions: {
53
+ contents: "write",
54
+ issues: "write",
55
+ pull_requests: "write",
56
+ actions_variables: "write",
57
+ checks: "write",
58
+ metadata: "read",
59
+ },
60
+ });
61
+ router.channel({
62
+ connection: key,
63
+ module: fileURLToPath(new URL("../router/index.ts", import.meta.url)),
64
+ secrets: {
65
+ [CHANNEL_SECRETS.rootKey]: router.rootKey,
66
+ [CHANNEL_SECRETS.privateKey]: router.vault.secret({
67
+ id: `${id}-private-key`,
68
+ value: this.app.credentials.privateKey,
69
+ }),
70
+ },
71
+ values: { [CHANNEL_VALUES.appId]: this.app.outputRef("id") },
72
+ });
73
+ router.store.contribute({
74
+ connections: {
75
+ [key]: {
76
+ provider: "github",
77
+ source: this.app.outputRef("id"),
78
+ credentials: {},
79
+ },
80
+ },
81
+ });
82
+ }
83
+
84
+ /** In an outpost: the connection the infra declares as `name`. */
85
+ static get(name: string): ConnectionRef {
86
+ return new ConnectionRef(name, { name });
87
+ }
88
+ }
@@ -0,0 +1,16 @@
1
+ export type { Channel } from "./channel.ts";
2
+ export { CodeHost, type CodeHostOptions } from "./code-host.ts";
3
+ export { Connection, type ConnectionOptions } from "./connection.ts";
4
+ export type { ConnectionRef } from "./connection-ref.ts";
5
+ export { OperatorAuth, type OperatorAuthOptions } from "./operator-auth.ts";
6
+ export { Policy, type PolicyOptions } from "./policy.ts";
7
+ export {
8
+ type AuthorSet,
9
+ collaborators,
10
+ type IssueCommentEvent,
11
+ type IssueCommentSelector,
12
+ type IssueEvent,
13
+ type IssueSelector,
14
+ team,
15
+ user,
16
+ } from "./selectors.ts";
@@ -0,0 +1,33 @@
1
+ import { ResourceGroup } from "@notation/resource";
2
+ import type { OperatorAuth as OperatorAuthContract } from "@notation/factory";
3
+ import * as v from "valibot";
4
+ import type { Connection } from "./connection.ts";
5
+
6
+ const operatorAuthConfig = v.object({ logins: v.array(v.string()) });
7
+ export type OperatorAuthConfig = v.InferInput<typeof operatorAuthConfig>;
8
+
9
+ export type OperatorAuthOptions = OperatorAuthConfig & {
10
+ connection: Connection;
11
+ };
12
+
13
+ /** Operators sign in with GitHub, through the connection's App, and the router checks their login against `logins`. */
14
+ export class OperatorAuth
15
+ extends ResourceGroup<OperatorAuthConfig>
16
+ implements OperatorAuthContract
17
+ {
18
+ readonly provider = "github";
19
+ readonly connection: Connection;
20
+
21
+ constructor(id: string, { connection, ...config }: OperatorAuthOptions) {
22
+ const { logins } = v.parse(operatorAuthConfig, config);
23
+ super("github/OperatorAuth", id, config);
24
+ this.connection = connection;
25
+ connection.router.store.contribute({
26
+ operators: {
27
+ provider: "github",
28
+ connection: connection.name,
29
+ logins,
30
+ },
31
+ });
32
+ }
33
+ }
@@ -0,0 +1,21 @@
1
+ import { ConnectionRef } from "./connection-ref.ts";
2
+
3
+ export type { Channel } from "./channel.ts";
4
+ export type { ConnectionRef } from "./connection-ref.ts";
5
+ export { Policy, type PolicyOptions } from "./policy.ts";
6
+ export {
7
+ type AuthorSet,
8
+ collaborators,
9
+ type IssueCommentEvent,
10
+ type IssueCommentSelector,
11
+ type IssueEvent,
12
+ type IssueSelector,
13
+ team,
14
+ user,
15
+ } from "./selectors.ts";
16
+
17
+ /** In an outpost, `Connection` only has `get`: the connection itself is the hub's. */
18
+ export const Connection = {
19
+ /** The connection the infra declares as `name`. */
20
+ get: (name: string): ConnectionRef => new ConnectionRef(name, { name }),
21
+ };
@@ -0,0 +1,41 @@
1
+ import { OutpostGroup, type PolicyContract } from "@notation/factory";
2
+ import * as v from "valibot";
3
+
4
+ const level = v.optional(v.picklist(["read", "write"]));
5
+
6
+ const policyConfig = v.object({
7
+ repo: v.optional(v.string()),
8
+ permissions: v.object({
9
+ actions: level,
10
+ actions_variables: level,
11
+ checks: level,
12
+ contents: level,
13
+ issues: level,
14
+ metadata: level,
15
+ pull_requests: level,
16
+ statuses: level,
17
+ workflows: level,
18
+ }),
19
+ });
20
+ export type PolicyConfig = v.InferInput<typeof policyConfig>;
21
+
22
+ export type PolicyOptions = PolicyConfig;
23
+
24
+ /** A 1-hour installation token for `repo` (default: the outpost's repo), with `permissions`, minted by the code host before each run. */
25
+ export class Policy
26
+ extends OutpostGroup<PolicyConfig>
27
+ implements PolicyContract
28
+ {
29
+ readonly provider = "github";
30
+
31
+ constructor(id: string, config: PolicyOptions) {
32
+ super("github/Policy", id, config);
33
+ const { outpost } = this;
34
+ const { repo, permissions } = v.parse(policyConfig, config);
35
+ outpost.store.contribute({
36
+ policies: {
37
+ [id]: { provider: "github", ...(repo ? { repo } : {}), permissions },
38
+ },
39
+ });
40
+ }
41
+ }
@@ -0,0 +1,66 @@
1
+ import * as v from "valibot";
2
+
3
+ /** Who may start a run. Data, so the router can check it when a delivery arrives. */
4
+ const authorSet = v.variant("kind", [
5
+ v.object({ kind: v.literal("collaborators") }),
6
+ v.object({ kind: v.literal("team"), slug: v.string() }),
7
+ v.object({ kind: v.literal("user"), login: v.string() }),
8
+ ]);
9
+ export type AuthorSet = v.InferOutput<typeof authorSet>;
10
+
11
+ /** Users with write access to the repo. */
12
+ export const collaborators = (): AuthorSet => ({ kind: "collaborators" });
13
+ /** Members of a team, e.g. `"acme/core"`. */
14
+ export const team = (slug: string): AuthorSet => ({ kind: "team", slug });
15
+ /** One user, by login. */
16
+ export const user = (login: string): AuthorSet => ({ kind: "user", login });
17
+
18
+ /** Required: nothing is trusted by default. */
19
+ const from = v.union([authorSet, v.array(authorSet)]);
20
+
21
+ export const issueSelector = v.object({
22
+ actions: v.optional(
23
+ v.array(v.picklist(["opened", "edited", "reopened", "labeled"])),
24
+ ["opened"],
25
+ ),
26
+ mention: v.optional(v.string()),
27
+ labels: v.optional(v.array(v.string())),
28
+ from,
29
+ });
30
+ export type IssueSelector = v.InferInput<typeof issueSelector>;
31
+
32
+ export const issueCommentSelector = v.object({
33
+ actions: v.optional(v.array(v.picklist(["created", "edited"])), ["created"]),
34
+ mention: v.optional(v.string()),
35
+ labels: v.optional(v.array(v.string())),
36
+ from,
37
+ });
38
+ export type IssueCommentSelector = v.InferInput<typeof issueCommentSelector>;
39
+
40
+ /** The parts of GitHub's webhook payloads worktree functions read. */
41
+ type User = { login: string };
42
+ type Issue = {
43
+ number: number;
44
+ title: string;
45
+ body: string | null;
46
+ labels: { name: string }[];
47
+ user: User;
48
+ /** Set when the issue is a pull request. */
49
+ pull_request?: { url: string };
50
+ };
51
+ type Repository = { full_name: string; default_branch: string };
52
+
53
+ export type IssueEvent = {
54
+ action: "opened" | "edited" | "reopened" | "labeled";
55
+ issue: Issue;
56
+ repository: Repository;
57
+ sender: User;
58
+ };
59
+
60
+ export type IssueCommentEvent = {
61
+ action: "created" | "edited";
62
+ issue: Issue;
63
+ comment: { id: number; body: string; user: User };
64
+ repository: Repository;
65
+ sender: User;
66
+ };
@@ -0,0 +1,11 @@
1
+ import { physicalName } from "@notation/resource";
2
+
3
+ /** GitHub App names are at most 34 characters. */
4
+ const GITHUB_APP_NAME_MAX_LENGTH = 34;
5
+
6
+ /** The hub a connection's App belongs to: its Notation app and stage. */
7
+ export type HubScope = { app: string; stage: string };
8
+
9
+ /** The name of a connection's GitHub App: `<app>--<stage>--<id>`, shortened with a hash past GitHub's limit. */
10
+ export const appName = (scope: HubScope | undefined, connectionId: string) =>
11
+ physicalName(scope, connectionId, { maxLength: GITHUB_APP_NAME_MAX_LENGTH });
package/lib/app.ts ADDED
@@ -0,0 +1,222 @@
1
+ import { execFile } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { createServer } from "node:http";
4
+ import type { AddressInfo } from "node:net";
5
+ import type { GithubEvent, Permissions } from "./permissions.ts";
6
+
7
+ const GITHUB_WEB = "https://github.com";
8
+ const GITHUB_API = "https://api.github.com";
9
+ const HOMEPAGE = "https://github.com/notationlabs/factory";
10
+
11
+ const github = async <T>(
12
+ method: string,
13
+ path: string,
14
+ token?: string,
15
+ ): Promise<T> => {
16
+ const response = await fetch(`${GITHUB_API}${path}`, {
17
+ method,
18
+ headers: {
19
+ accept: "application/vnd.github+json",
20
+ "user-agent": "notation-factory",
21
+ "x-github-api-version": "2022-11-28",
22
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
23
+ },
24
+ });
25
+ if (!response.ok) {
26
+ throw new Error(
27
+ `GitHub ${method} ${path}: ${response.status} ${await response.text()}`,
28
+ );
29
+ }
30
+ return (await response.json()) as T;
31
+ };
32
+
33
+ /** The token of your gh login, if there is one: `GH_TOKEN` wins, as it does for gh itself. */
34
+ const ghToken = () =>
35
+ new Promise<string | undefined>((resolve) => {
36
+ if (process.env.GH_TOKEN) return resolve(process.env.GH_TOKEN);
37
+ execFile("gh", ["auth", "token"], (error, stdout) =>
38
+ resolve(error ? undefined : stdout.trim() || undefined),
39
+ );
40
+ });
41
+
42
+ const openBrowser = (url: string) => {
43
+ const cmd =
44
+ process.platform === "darwin"
45
+ ? "open"
46
+ : process.platform === "win32"
47
+ ? "explorer"
48
+ : "xdg-open";
49
+ execFile(cmd, [url], () => {});
50
+ };
51
+
52
+ /**
53
+ * Creates the App with GitHub's manifest flow:
54
+ *
55
+ * 1. A local server serves a page that posts the manifest to GitHub's new
56
+ * App form, under `org` if there is one, otherwise under your account.
57
+ * 2. You confirm the App in the browser, and GitHub redirects to the local
58
+ * server with a one-time code.
59
+ * 3. The code is exchanged for the App, which includes its private key.
60
+ */
61
+ export const createApp = async (params: {
62
+ name: string;
63
+ org?: string;
64
+ hookUrl: string;
65
+ events?: GithubEvent[];
66
+ permissions?: Permissions;
67
+ }): Promise<{ slug: string; id: string; privateKey: string }> => {
68
+ const state = randomBytes(16).toString("hex");
69
+ type Created = { slug: string; id: string; privateKey: string };
70
+ let resolve!: (app: Created) => void;
71
+ let reject!: (error: unknown) => void;
72
+ const promise = new Promise<Created>((res, rej) => {
73
+ resolve = res;
74
+ reject = rej;
75
+ });
76
+
77
+ const server = createServer(async (req, res) => {
78
+ const url = new URL(req.url ?? "/", "http://localhost");
79
+ const send = (status: number, body: string, type = "text/plain") => {
80
+ res.writeHead(status, { "content-type": type });
81
+ res.end(body);
82
+ };
83
+ if (url.pathname === "/") {
84
+ const { port } = server.address() as AddressInfo;
85
+ const manifest = {
86
+ name: params.name,
87
+ url: HOMEPAGE,
88
+ hook_attributes: { url: params.hookUrl, active: true },
89
+ redirect_url: `http://localhost:${port}/callback`,
90
+ // An App on a personal account is public, so that orgs can install it.
91
+ public: !params.org,
92
+ default_events: params.events ?? [],
93
+ default_permissions: params.permissions ?? {},
94
+ };
95
+ const owner = params.org ? `/organizations/${params.org}` : "";
96
+ const action = `${GITHUB_WEB}${owner}/settings/apps/new?state=${state}`;
97
+ const value = JSON.stringify(manifest)
98
+ .replace(/&/g, "&amp;")
99
+ .replace(/'/g, "&#39;");
100
+ return send(
101
+ 200,
102
+ `<form id="f" method="post" action="${action}"><input type="hidden" name="manifest" value='${value}'></form><script>f.submit()</script>`,
103
+ "text/html",
104
+ );
105
+ }
106
+ const code = url.searchParams.get("code");
107
+ if (
108
+ url.pathname !== "/callback" ||
109
+ !code ||
110
+ url.searchParams.get("state") !== state
111
+ ) {
112
+ return send(404, "not found");
113
+ }
114
+ try {
115
+ const app = await github<{ id: number; slug: string; pem: string }>(
116
+ "POST",
117
+ `/app-manifests/${encodeURIComponent(code)}/conversions`,
118
+ );
119
+ resolve({ slug: app.slug, id: String(app.id), privateKey: app.pem });
120
+ send(200, "App created. You can close this tab.");
121
+ } catch (error) {
122
+ reject(error);
123
+ send(500, "Creating the App failed. See the terminal.");
124
+ }
125
+ });
126
+
127
+ await new Promise<void>((listening) =>
128
+ server.listen(0, "localhost", listening),
129
+ );
130
+ const { port } = server.address() as AddressInfo;
131
+ const start = `http://localhost:${port}/`;
132
+ console.error(`Create the GitHub App ${params.name} in your browser: ${start}`);
133
+ openBrowser(start);
134
+ try {
135
+ return await promise;
136
+ } finally {
137
+ server.close();
138
+ }
139
+ };
140
+
141
+ /** Reads the App by its slug. GitHub only shows a private App to its owner, so this uses your gh login when there is one. */
142
+ export const readApp = async (key: {
143
+ slug: string;
144
+ }): Promise<{ slug: string; id: string }> => {
145
+ const app = await github<{ id: number; slug: string }>(
146
+ "GET",
147
+ `/apps/${encodeURIComponent(key.slug)}`,
148
+ await ghToken(),
149
+ );
150
+ return { slug: app.slug, id: String(app.id) };
151
+ };
152
+
153
+ /** Opens the App's advanced settings, where its owner must delete it. */
154
+ export const requestAppDeletion = async (key: { slug: string }): Promise<void> => {
155
+ const app = await github<{ owner: { login: string; type: string } }>(
156
+ "GET",
157
+ `/apps/${encodeURIComponent(key.slug)}`,
158
+ await ghToken(),
159
+ );
160
+ const owner = app.owner.type === "Organization" ? `/organizations/${app.owner.login}` : "";
161
+ const url = `${GITHUB_WEB}${owner}/settings/apps/${key.slug}/advanced`;
162
+ console.error(`Delete the GitHub App ${key.slug} on its settings page: ${url}`);
163
+ openBrowser(url);
164
+ };
165
+
166
+ /** How long a deploy waits for you to save an App's new permissions and events. */
167
+ const APP_CHANGE_TIMEOUT_MS = 15 * 60 * 1000;
168
+
169
+ const APP_CHANGE_POLL_MS = 5000;
170
+
171
+ /** The requested permissions and events that the App doesn't have yet. */
172
+ const missingFromApp = async (slug: string, change: { events?: GithubEvent[]; permissions?: Permissions }) => {
173
+ const app = await github<{ permissions: Record<string, string>; events: string[] }>(
174
+ "GET",
175
+ `/apps/${encodeURIComponent(slug)}`,
176
+ await ghToken(),
177
+ );
178
+ const permissions = Object.entries(change.permissions ?? {}).filter(
179
+ ([name, level]) => app.permissions[name] !== "write" && app.permissions[name] !== level,
180
+ );
181
+ const events = (change.events ?? []).filter((event) => !app.events.includes(event));
182
+ return { permissions, events };
183
+ };
184
+
185
+ /**
186
+ * GitHub has no API for an App's events and permissions, so you change them
187
+ * in the browser:
188
+ * 1. Opens the App's permissions page, and prints what to set there.
189
+ * 2. Waits until the App has them. Fails the deploy after 15 minutes.
190
+ * 3. Opens the App's installations, where each installation accepts the new
191
+ * permissions. Deploy doesn't wait for that, since checking it needs the
192
+ * App's private key.
193
+ */
194
+ export const requestAppChange = async (
195
+ key: { slug: string; org?: string },
196
+ change: { events?: GithubEvent[]; permissions?: Permissions },
197
+ ): Promise<void> => {
198
+ let missing = await missingFromApp(key.slug, change);
199
+ if (missing.permissions.length || missing.events.length) {
200
+ const owner = key.org ? `/organizations/${key.org}` : "";
201
+ const url = `${GITHUB_WEB}${owner}/settings/apps/${key.slug}/permissions`;
202
+ console.error(
203
+ [
204
+ `Set the GitHub App ${key.slug}'s permissions and events on ${url}, and save:`,
205
+ ` permissions: ${missing.permissions.map(([name, level]) => `${name}: ${level}`).join(", ") || "no change"}`,
206
+ ` events: ${missing.events.join(", ") || "no change"}`,
207
+ ].join("\n"),
208
+ );
209
+ openBrowser(url);
210
+ const deadline = Date.now() + APP_CHANGE_TIMEOUT_MS;
211
+ while (missing.permissions.length || missing.events.length) {
212
+ if (Date.now() > deadline) {
213
+ throw new Error(`The GitHub App ${key.slug} didn't get its new permissions and events within 15 minutes.`);
214
+ }
215
+ await new Promise((done) => setTimeout(done, APP_CHANGE_POLL_MS));
216
+ missing = await missingFromApp(key.slug, change);
217
+ }
218
+ }
219
+ const installations = `${GITHUB_WEB}/apps/${key.slug}/installations/new`;
220
+ console.error(`Accept the GitHub App ${key.slug}'s new permissions on each installation: ${installations}`);
221
+ openBrowser(installations);
222
+ };