@notation/factory-github 0.5.5 → 0.6.0

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.
@@ -4,7 +4,7 @@ import {
4
4
  type Connection as ConnectionContract,
5
5
  type Router,
6
6
  } from "@notation/factory";
7
- import { webhookPath } from "@notation/factory/router";
7
+ import { RESTART_CALLBACK_PATH, webhookPath } from "@notation/factory/router";
8
8
  import * as v from "valibot";
9
9
  import { appName } from "../lib/app-name.ts";
10
10
  import { permissionsSchema } from "../lib/permissions.ts";
@@ -47,6 +47,7 @@ export class Connection
47
47
  name: appName(getActiveResourceCollection()?.scope, id),
48
48
  org,
49
49
  hookUrl: text`${router.url}${webhookPath(key)}`,
50
+ restartUrl: text`${router.url}${RESTART_CALLBACK_PATH}`,
50
51
  },
51
52
  }),
52
53
  );
package/lib/app.ts CHANGED
@@ -68,6 +68,7 @@ export const createApp = async (params: {
68
68
  name: string;
69
69
  org?: string;
70
70
  hookUrl: string;
71
+ restartUrl?: string;
71
72
  events?: GithubEvent[];
72
73
  permissions?: Permissions;
73
74
  }): Promise<{ id: string; clientId: string; privateKey: string; clientSecret: string }> => {
@@ -93,7 +94,7 @@ export const createApp = async (params: {
93
94
  url: HOMEPAGE,
94
95
  hook_attributes: { url: params.hookUrl, active: true },
95
96
  redirect_url: `http://localhost:${port}/callback`,
96
- callback_urls: [OPERATOR_CALLBACK_URL],
97
+ callback_urls: [OPERATOR_CALLBACK_URL, ...(params.restartUrl ? [params.restartUrl] : [])],
97
98
  // An App on a personal account is public, so that orgs can install it.
98
99
  public: !params.org,
99
100
  default_events: params.events ?? [],
@@ -201,6 +202,19 @@ export const requestAppDeletion = async (key: { id: string; org?: string }): Pro
201
202
  openBrowser(url);
202
203
  };
203
204
 
205
+ /**
206
+ * GitHub has no API for an App's callback URLs, so this opens the App's
207
+ * settings page and prints the URL to add there. It doesn't wait, since
208
+ * GitHub's API doesn't show the callback URLs either.
209
+ */
210
+ export const requestCallbackUrl = async (key: { id: string; org?: string }, url: string): Promise<void> => {
211
+ const slug = await appSlug(key.id);
212
+ const owner = key.org ? `/organizations/${key.org}` : "";
213
+ const settings = `${GITHUB_WEB}${owner}/settings/apps/${slug}`;
214
+ console.error(`Add ${url} as a callback URL of the GitHub App ${slug} on ${settings}, and save. Restart links of lost runs sign people in through it.`);
215
+ openBrowser(settings);
216
+ };
217
+
204
218
  /** How long a deploy waits for you to save an App's new permissions and events. */
205
219
  const APP_CHANGE_TIMEOUT_MS = 15 * 60 * 1000;
206
220
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notation/factory-github",
3
- "version": "0.5.5",
3
+ "version": "0.6.0",
4
4
  "author": "Daniel Grant",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -32,9 +32,9 @@
32
32
  "valibot": "^1.1.0"
33
33
  },
34
34
  "peerDependencies": {
35
- "@notation/factory": "^0.5.5"
35
+ "@notation/factory": "^0.6.0"
36
36
  },
37
37
  "devDependencies": {
38
- "@notation/factory": "0.5.5"
38
+ "@notation/factory": "0.6.0"
39
39
  }
40
40
  }
package/resources/app.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  createApp,
5
5
  readApp,
6
6
  requestAppChange,
7
+ requestCallbackUrl,
7
8
  requestAppDeletion,
8
9
  } from "../lib/app.ts";
9
10
  import {
@@ -21,11 +22,13 @@ type AppApi = {
21
22
  name: string;
22
23
  org?: string;
23
24
  hookUrl: string;
25
+ restartUrl?: string;
24
26
  events?: GithubEvent[];
25
27
  permissions?: Permissions;
26
28
  };
27
29
  UpdateParams: {
28
30
  hookUrl: string;
31
+ restartUrl?: string;
29
32
  events?: GithubEvent[];
30
33
  permissions?: Permissions;
31
34
  };
@@ -63,6 +66,8 @@ export const App = defineResource<AppApi>({
63
66
  value: v.string(),
64
67
  },
65
68
  hookUrl: { propertyType: "param", presence: "required", value: v.string() },
69
+ /** The router's page that the sign-in of a lost run's restart link returns to, which the App allows as a callback URL. */
70
+ restartUrl: { propertyType: "param", presence: "optional", value: v.string() },
66
71
  events: {
67
72
  propertyType: "param",
68
73
  presence: "optional",
@@ -110,6 +115,7 @@ export const App = defineResource<AppApi>({
110
115
  permissions: params.permissions,
111
116
  });
112
117
  }
118
+ if (patch.restartUrl !== undefined) await requestCallbackUrl({ ...key, org: params.org }, patch.restartUrl);
113
119
  // A new hookUrl reaches GitHub through the router's sync, which signs
114
120
  // in as the App with its private key.
115
121
  },
@@ -416,3 +416,14 @@ test("acknowledge adds no label that the issue has", async () => {
416
416
  assert.equal(writes.filter(([, path]) => path.endsWith("/labels")).length, 0);
417
417
  });
418
418
  });
419
+
420
+ test("canTrigger checks a signed-in person against the trigger's from, with their role on the repo", async () => {
421
+ await withGithub({ roles: { carol: "write", dave: "triage" } }, async () => {
422
+ const d = await accepted("issue_comment", commentPayload);
423
+ const both = selector({ from: [{ kind: "user", login: "Alice" }, collaborators] });
424
+ assert.equal(await keyed.canTrigger!(both, d, { login: "alice", id: "1" }), true);
425
+ assert.equal(await keyed.canTrigger!(both, d, { login: "carol", id: "2" }), true);
426
+ assert.equal(await keyed.canTrigger!(both, d, { login: "dave", id: "3" }), false);
427
+ assert.equal(await keyed.canTrigger!(selector({ from: { kind: "team", slug: "acme/devs" } }), d, { login: "alice", id: "1" }), false);
428
+ });
429
+ });
package/router/index.ts CHANGED
@@ -411,12 +411,19 @@ export const channel = (ctx: ChannelContext): Channel<GithubEvent> => {
411
411
  return installedRepos(await auth());
412
412
  },
413
413
 
414
- async signInUrl(state) {
415
- return signInUrl(ctx.value(CHANNEL_VALUES.clientId), state);
414
+ async signInUrl(state, redirect) {
415
+ return signInUrl(ctx.value(CHANNEL_VALUES.clientId), state, redirect);
416
416
  },
417
417
 
418
- async signIn(code) {
419
- return signIn({ clientId: ctx.value(CHANNEL_VALUES.clientId), clientSecret: await ctx.secret(CHANNEL_SECRETS.clientSecret) }, code);
418
+ async signIn(code, redirect) {
419
+ return signIn({ clientId: ctx.value(CHANNEL_VALUES.clientId), clientSecret: await ctx.secret(CHANNEL_SECRETS.clientSecret) }, code, redirect);
420
+ },
421
+
422
+ // A team in `from` needs a call that the router doesn't make yet, so it doesn't let the person in.
423
+ async canTrigger(selector, delivery, { login }) {
424
+ const person: Author = { login, bot: false, write: false };
425
+ await resolveRoles(await auth(), delivery.repo, [person]);
426
+ return checkAuthor((selector as Selector).from, person).result === "allowed";
420
427
  },
421
428
  };
422
429
  };
@@ -26,6 +26,24 @@ test("signInUrl names the App's client, the CLI's callback and the state", () =>
26
26
  );
27
27
  });
28
28
 
29
+ test("signInUrl and signIn take another callback, such as the router's restart page", async () => {
30
+ const redirect = "https://router.test/restart/callback";
31
+ assert.equal(new URL(signInUrl("Iv1.abc", "s1", redirect)).searchParams.get("redirect_uri"), redirect);
32
+ await withFetch(
33
+ (url, init) => {
34
+ if (url.endsWith("/login/oauth/access_token")) {
35
+ assert.equal(JSON.parse(String(init?.body)).redirect_uri, redirect);
36
+ return Response.json({ access_token: "ghu_1" });
37
+ }
38
+ if (url.endsWith("/user")) return Response.json({ login: "alice", id: 42 });
39
+ return new Response(null, { status: 204 });
40
+ },
41
+ async () => {
42
+ assert.deepEqual(await signIn(app, "c1", redirect), { login: "alice", id: "42" });
43
+ },
44
+ );
45
+ });
46
+
29
47
  test("signIn exchanges the code, reads the user's login and id, and revokes the token", async () => {
30
48
  await withFetch(
31
49
  (url, init) => {
@@ -15,26 +15,30 @@ const headers = (token: string) => ({
15
15
  */
16
16
  export const OPERATOR_CALLBACK_URL = "http://127.0.0.1:47219/callback";
17
17
 
18
- /** GitHub's page that signs a user in to the App, and sends their browser to `OPERATOR_CALLBACK_URL`. */
19
- export const signInUrl = (client: string, state: string) => {
18
+ /**
19
+ * GitHub's page that signs a user in to the App, and sends their browser to
20
+ * `redirect`, which must be one of the App's callback URLs.
21
+ */
22
+ export const signInUrl = (client: string, state: string, redirect = OPERATOR_CALLBACK_URL) => {
20
23
  const url = new URL("/login/oauth/authorize", GITHUB_WEB);
21
24
  url.searchParams.set("client_id", client);
22
- url.searchParams.set("redirect_uri", OPERATOR_CALLBACK_URL);
25
+ url.searchParams.set("redirect_uri", redirect);
23
26
  url.searchParams.set("state", state);
24
27
  return url.toString();
25
28
  };
26
29
 
27
30
  /**
28
- * The login and account id of the user who signed in:
31
+ * The login and account id of the user who signed in, whose browser GitHub
32
+ * sent to `redirect` with `code`:
29
33
  * 1. Exchanges the code for a user access token, with the App's client secret.
30
34
  * 2. Asks GitHub whose token it is.
31
35
  * 3. Revokes the token, which the router has no other use for.
32
36
  */
33
- export const signIn = async (app: { clientId: string; clientSecret: string }, code: string) => {
37
+ export const signIn = async (app: { clientId: string; clientSecret: string }, code: string, redirect = OPERATOR_CALLBACK_URL) => {
34
38
  const exchanged = await fetch(`${GITHUB_WEB}/login/oauth/access_token`, {
35
39
  method: "POST",
36
40
  headers: { Accept: "application/json", "Content-Type": "application/json", "User-Agent": "notation-factory-router" },
37
- body: JSON.stringify({ client_id: app.clientId, client_secret: app.clientSecret, code, redirect_uri: OPERATOR_CALLBACK_URL }),
41
+ body: JSON.stringify({ client_id: app.clientId, client_secret: app.clientSecret, code, redirect_uri: redirect }),
38
42
  });
39
43
  // GitHub answers a bad code with a 200 and an `error`.
40
44
  const result = (await exchanged.json().catch(() => ({}))) as { access_token?: string; error?: string; error_description?: string };