@notation/factory-github 0.1.1 → 0.1.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notation/factory-github",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "author": "Daniel Grant",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -27,13 +27,13 @@
27
27
  "access": "public"
28
28
  },
29
29
  "dependencies": {
30
- "@notation/resource": "0.28.0",
30
+ "@notation/resource": "0.28.1",
31
31
  "valibot": "^1.1.0"
32
32
  },
33
33
  "peerDependencies": {
34
- "@notation/factory": "^0.1.1"
34
+ "@notation/factory": "^0.1.3"
35
35
  },
36
36
  "devDependencies": {
37
- "@notation/factory": "0.1.1"
37
+ "@notation/factory": "0.1.3"
38
38
  }
39
39
  }
@@ -1,5 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
- import { createHmac } from "node:crypto";
2
+ import { createHmac, generateKeyPairSync } from "node:crypto";
3
3
  import { test } from "node:test";
4
4
  import type { Delivery } from "@notation/factory/router";
5
5
  import { channel as github, type GithubEvent, mentions, verifySignature, webhookSecret } from "./index.ts";
@@ -57,8 +57,8 @@ test("receive parses a signed comment to its App", async () => {
57
57
  event: "issue_comment",
58
58
  data: {
59
59
  action: "created",
60
- author: { login: "alice", association: "NONE", bot: false },
61
- opener: { login: "bob", association: "", bot: false },
60
+ author: { login: "alice", association: "NONE", bot: false, write: false },
61
+ opener: { login: "bob", association: "", bot: false, write: false },
62
62
  body: "@claude fix",
63
63
  before: "@claude fix",
64
64
  labels: ["bug"],
@@ -107,7 +107,7 @@ const delivery = (data: Partial<GithubEvent>): Delivery<GithubEvent> => ({
107
107
  event: "issue_comment",
108
108
  data: {
109
109
  action: "created",
110
- author: { login: "alice", association: "NONE", bot: false },
110
+ author: { login: "alice", association: "NONE", bot: false, write: false },
111
111
  body: "@claude fix",
112
112
  before: "@claude fix",
113
113
  labels: [],
@@ -126,34 +126,34 @@ const selector = (over: object = {}) => ({
126
126
  test("from allows a listed user, and a collaborator by author association", () => {
127
127
  assert.deepEqual(channel.match(selector(), delivery({})), { result: "allowed" });
128
128
  assert.deepEqual(
129
- channel.match(selector(), delivery({ author: { login: "bob", association: "NONE", bot: false } })),
129
+ channel.match(selector(), delivery({ author: { login: "bob", association: "NONE", bot: false, write: false } })),
130
130
  { result: "denied" },
131
131
  );
132
132
  const collaborators = selector({ from: { kind: "collaborators" } });
133
133
  assert.deepEqual(
134
- channel.match(collaborators, delivery({ author: { login: "bob", association: "COLLABORATOR", bot: false } })),
134
+ channel.match(collaborators, delivery({ author: { login: "bob", association: "COLLABORATOR", bot: false, write: true } })),
135
135
  { result: "allowed" },
136
136
  );
137
137
  });
138
138
 
139
139
  test("a comment matches only if the issue's author matches from too", () => {
140
140
  const collaborators = selector({ from: { kind: "collaborators" } });
141
- const member = { login: "alice", association: "MEMBER", bot: false };
141
+ const member = { login: "alice", association: "MEMBER", bot: false, write: true };
142
142
  assert.deepEqual(
143
- channel.match(collaborators, delivery({ author: member, opener: { login: "eve", association: "NONE", bot: false } })),
143
+ channel.match(collaborators, delivery({ author: member, opener: { login: "eve", association: "NONE", bot: false, write: false } })),
144
144
  { result: "denied" },
145
145
  );
146
146
  assert.deepEqual(
147
- channel.match(collaborators, delivery({ author: member, opener: { login: "bob", association: "OWNER", bot: false } })),
147
+ channel.match(collaborators, delivery({ author: member, opener: { login: "bob", association: "OWNER", bot: false, write: true } })),
148
148
  { result: "allowed" },
149
149
  );
150
150
  });
151
151
 
152
152
  test("bots never match, even with write access", () => {
153
153
  const collaborators = selector({ from: { kind: "collaborators" } });
154
- const bot = { login: "renovate[bot]", association: "MEMBER", bot: true };
154
+ const bot = { login: "renovate[bot]", association: "MEMBER", bot: true, write: true };
155
155
  assert.deepEqual(channel.match(collaborators, delivery({ author: bot })), { result: "denied" });
156
- const human = { login: "alice", association: "MEMBER", bot: false };
156
+ const human = { login: "alice", association: "MEMBER", bot: false, write: true };
157
157
  assert.deepEqual(channel.match(collaborators, delivery({ author: human, opener: bot })), { result: "denied" });
158
158
  });
159
159
 
@@ -165,13 +165,13 @@ test("receive marks bot authors", async () => {
165
165
  const received = await channel.receive(await request("issue_comment", fromBot));
166
166
  assert.equal(received.status, "accepted");
167
167
  const { data } = (received as { delivery: Delivery<GithubEvent> }).delivery;
168
- assert.deepEqual(data.opener, { login: "dependabot[bot]", association: "NONE", bot: true });
168
+ assert.deepEqual(data.opener, { login: "dependabot[bot]", association: "NONE", bot: true, write: false });
169
169
  });
170
170
 
171
171
  test("a team in from leaves a check for the router to make", () => {
172
172
  const team = selector({ from: [{ kind: "team", slug: "acme/core" }] });
173
173
  assert.deepEqual(
174
- channel.match(team, delivery({ author: { login: "bob", association: "NONE", bot: false } })),
174
+ channel.match(team, delivery({ author: { login: "bob", association: "NONE", bot: false, write: false } })),
175
175
  { result: "check", sets: [{ kind: "team", slug: "acme/core" }] },
176
176
  );
177
177
  });
@@ -196,3 +196,37 @@ test("mentions match as GitHub does", () => {
196
196
  assert.equal(mentions("me@claude.ai", "@claude"), false);
197
197
  assert.equal(mentions("@claude-bot", "@claude"), false);
198
198
  });
199
+
200
+ test("receive asks GitHub whether authors whose association hides it can push", async () => {
201
+ const { privateKey } = generateKeyPairSync("rsa", {
202
+ modulusLength: 2048,
203
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
204
+ publicKeyEncoding: { type: "spki", format: "pem" },
205
+ });
206
+ const keyed = github({
207
+ secret: async (name) => (name === "ROOT_KEY" ? ROOT_KEY : privateKey),
208
+ value: (name) => (name === "APP_ID" ? "123" : ""),
209
+ });
210
+ const asked: string[] = [];
211
+ const realFetch = globalThis.fetch;
212
+ globalThis.fetch = (async (input: string | URL | Request) => {
213
+ const url = String(input instanceof Request ? input.url : input);
214
+ asked.push(new URL(url).pathname);
215
+ if (url.endsWith("/installation")) return Response.json({ id: 1 });
216
+ if (url.endsWith("/access_tokens")) return Response.json({ token: "t" });
217
+ // A private member of the org, and an outsider.
218
+ if (url.endsWith("/collaborators/alice/permission")) return Response.json({ permission: "write", role_name: "write" });
219
+ return new Response("Not Found", { status: 404 });
220
+ }) as typeof fetch;
221
+ try {
222
+ const received = await keyed.receive(await request("issue_comment", commentPayload));
223
+ assert.equal(received.status, "accepted");
224
+ const { data } = (received as { delivery: Delivery<GithubEvent> }).delivery;
225
+ assert.equal(data.author.write, true);
226
+ assert.equal(data.opener?.write, false);
227
+ assert.ok(asked.includes("/repos/acme/api/collaborators/alice/permission"));
228
+ assert.ok(asked.includes("/repos/acme/api/collaborators/bob/permission"));
229
+ } finally {
230
+ globalThis.fetch = realFetch;
231
+ }
232
+ });
package/router/index.ts CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  } from "@notation/factory/router";
9
9
  import type { AuthorSet } from "../implementations/selectors.ts";
10
10
  import { appJwt } from "./app-jwt.ts";
11
- import { comment, readDir, repoToken, sourceChanges, writeCheck as writeRepoCheck, writeStatus as writeRepoStatus } from "./repos.ts";
11
+ import { comment, readDir, repoToken, sourceChanges, writeCheck as writeRepoCheck, writers, writeStatus as writeRepoStatus } from "./repos.ts";
12
12
 
13
13
  /** The webhook secret of the App with id `appId`, which the router derives from the root key. */
14
14
  export const webhookSecret = (rootKey: string, appId: string) =>
@@ -28,8 +28,11 @@ export const verifySignature = async (
28
28
  export const CHANNEL_SECRETS = { rootKey: "ROOT_KEY", privateKey: "PRIVATE_KEY" } as const;
29
29
  export const CHANNEL_VALUES = { appId: "APP_ID" } as const;
30
30
 
31
- /** Someone who posted to a thread. `bot` is set for an App or another bot account. */
32
- export type Author = { login: string; association: string; bot: boolean };
31
+ /**
32
+ * Someone who posted to a thread. `bot` is set for an App or another bot
33
+ * account. `write` is whether they can push to the repo.
34
+ */
35
+ export type Author = { login: string; association: string; bot: boolean; write: boolean };
33
36
 
34
37
  /** The parts of an issue or comment event that selectors read. */
35
38
  export type GithubEvent = {
@@ -54,6 +57,7 @@ const authorOf = (post: Post): Author => ({
54
57
  login: post.user?.login ?? "",
55
58
  association: post.author_association ?? "",
56
59
  bot: post.user?.type === "Bot",
60
+ write: WRITE_ACCESS.has(post.author_association ?? ""),
57
61
  });
58
62
 
59
63
  const parse = (event: string, payload: any): GithubEvent | undefined => {
@@ -162,7 +166,7 @@ const checkOne = (sets: AuthorSet[], author: Author): AuthorCheck => {
162
166
  const allowed = sets.some((s) =>
163
167
  s.kind === "user"
164
168
  ? s.login.toLowerCase() === author.login.toLowerCase()
165
- : s.kind === "collaborators" && WRITE_ACCESS.has(author.association),
169
+ : s.kind === "collaborators" && author.write,
166
170
  );
167
171
  if (allowed) return { result: "allowed" };
168
172
  const teams = sets.filter((s) => s.kind === "team");
@@ -182,6 +186,21 @@ const checkAuthor = (from: Selector["from"], { author, opener }: GithubEvent): A
182
186
  return pending ?? { result: "allowed" };
183
187
  };
184
188
 
189
+ /**
190
+ * Sets `write` on the event's humans whose association doesn't show it, by
191
+ * asking GitHub. If GitHub can't answer, they stay without write access.
192
+ */
193
+ const resolveWriters = async (auth: { appId: string; privateKey: string }, repo: string, data: GithubEvent) => {
194
+ const unknown = [data.author, ...(data.opener ? [data.opener] : [])].filter((a) => !a.bot && !a.write && a.login);
195
+ if (unknown.length === 0) return;
196
+ try {
197
+ const found = await writers(auth, repo, [...new Set(unknown.map((a) => a.login))]);
198
+ for (const a of unknown) a.write = found.has(a.login);
199
+ } catch (error) {
200
+ console.log(JSON.stringify({ state: "permission check failed", repo, error: error instanceof Error ? error.message : String(error) }));
201
+ }
202
+ };
203
+
185
204
  /** One GitHub App's webhook. A delivery's scope is its repo. */
186
205
  export const channel = (ctx: ChannelContext): Channel<GithubEvent> => {
187
206
  const appId = ctx.value(CHANNEL_VALUES.appId);
@@ -208,6 +227,7 @@ export const channel = (ctx: ChannelContext): Channel<GithubEvent> => {
208
227
  const repo: string | undefined = payload.repository?.full_name;
209
228
  const data = parse(event, payload);
210
229
  if (!repo || !data) return { status: "ignored", reason: event };
230
+ await resolveWriters(await auth(), repo, data);
211
231
  // The App's own replies would otherwise start runs.
212
232
  const post = event === "issue_comment" ? payload.comment : payload.issue;
213
233
  if (String(post?.performed_via_github_app?.id ?? "") === appId) {
package/router/repos.ts CHANGED
@@ -60,6 +60,29 @@ export const repoToken = async (
60
60
  return token;
61
61
  };
62
62
 
63
+ /** Permissions that let a user push to a repo. */
64
+ const WRITE_PERMISSIONS = new Set(["admin", "maintain", "write"]);
65
+
66
+ /**
67
+ * The logins among `logins` that can push to `repo`, asked of GitHub. A
68
+ * webhook's author association doesn't show private org membership, so the
69
+ * channel asks when the association doesn't show write access.
70
+ */
71
+ export const writers = async (auth: AppAuth, repo: string, logins: string[]) => {
72
+ const token = await repoToken(auth, repo, { metadata: "read" });
73
+ const found = new Set<string>();
74
+ for (const login of logins) {
75
+ const response = await github("GET", `/repos/${repo}/collaborators/${encodeURIComponent(login)}/permission`, token);
76
+ if (response.status === 404) continue;
77
+ const { permission, role_name } = (await (await ok(response, `GET /repos/${repo}/collaborators/${login}/permission`)).json()) as {
78
+ permission: string;
79
+ role_name?: string;
80
+ };
81
+ if (WRITE_PERMISSIONS.has(permission) || WRITE_PERMISSIONS.has(role_name ?? "")) found.add(login);
82
+ }
83
+ return found;
84
+ };
85
+
63
86
  /**
64
87
  * The files under `dir` in `repo` at `ref`, or at the default branch's head:
65
88
  * 1. Resolves the ref to a commit and its tree.