@notation/factory-github 0.5.4 → 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.
- package/implementations/connection.ts +2 -1
- package/implementations/selectors.ts +10 -0
- package/lib/app.ts +15 -1
- package/package.json +3 -3
- package/resources/app.ts +6 -0
- package/router/index.test.ts +64 -5
- package/router/index.ts +55 -13
- package/router/operators.test.ts +18 -0
- package/router/operators.ts +10 -6
- package/router/repos.ts +7 -0
|
@@ -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
|
);
|
|
@@ -18,12 +18,21 @@ export const user = (login: string): AuthorSet => ({ kind: "user", login });
|
|
|
18
18
|
/** Required: nothing is trusted by default. */
|
|
19
19
|
const from = v.union([authorSet, v.array(authorSet)]);
|
|
20
20
|
|
|
21
|
+
/**
|
|
22
|
+
* With `mention`: the label that a run started by a mention adds to the
|
|
23
|
+
* issue. While the issue has the label, a new comment matches without the
|
|
24
|
+
* mention. Defaults to `listen:<mention without @>`. `false` adds no label.
|
|
25
|
+
* GitHub limits label names to 50 characters.
|
|
26
|
+
*/
|
|
27
|
+
const listen = v.optional(v.union([v.pipe(v.string(), v.minLength(1), v.maxLength(50)), v.literal(false)]));
|
|
28
|
+
|
|
21
29
|
export const issueSelector = v.object({
|
|
22
30
|
actions: v.optional(
|
|
23
31
|
v.array(v.picklist(["opened", "edited", "reopened", "labeled"])),
|
|
24
32
|
["opened"],
|
|
25
33
|
),
|
|
26
34
|
mention: v.optional(v.string()),
|
|
35
|
+
listen,
|
|
27
36
|
labels: v.optional(v.array(v.string())),
|
|
28
37
|
from,
|
|
29
38
|
});
|
|
@@ -32,6 +41,7 @@ export type IssueSelector = v.InferInput<typeof issueSelector>;
|
|
|
32
41
|
export const issueCommentSelector = v.object({
|
|
33
42
|
actions: v.optional(v.array(v.picklist(["created", "edited"])), ["created"]),
|
|
34
43
|
mention: v.optional(v.string()),
|
|
44
|
+
listen,
|
|
35
45
|
labels: v.optional(v.array(v.string())),
|
|
36
46
|
from,
|
|
37
47
|
});
|
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.
|
|
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.
|
|
35
|
+
"@notation/factory": "^0.6.0"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
|
-
"@notation/factory": "0.
|
|
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
|
},
|
package/router/index.test.ts
CHANGED
|
@@ -146,10 +146,10 @@ test("a team in from leaves a check for the router to make", () => {
|
|
|
146
146
|
);
|
|
147
147
|
});
|
|
148
148
|
|
|
149
|
-
test("labels must all be on the issue", () => {
|
|
149
|
+
test("labels must all be on the issue, in any case", () => {
|
|
150
150
|
const labelled = selector({ labels: ["bug", "p1"] });
|
|
151
151
|
assert.equal(channel.match(labelled, delivery({ labels: ["bug"] })), undefined);
|
|
152
|
-
assert.ok(channel.match(labelled, delivery({ labels: ["bug", "
|
|
152
|
+
assert.ok(channel.match(labelled, delivery({ labels: ["bug", "P1"] })));
|
|
153
153
|
});
|
|
154
154
|
|
|
155
155
|
test("an edit matches only if it newly adds the mention", () => {
|
|
@@ -158,6 +158,37 @@ test("an edit matches only if it newly adds the mention", () => {
|
|
|
158
158
|
assert.equal(channel.match(selector(), edit("@claude fix")), undefined);
|
|
159
159
|
});
|
|
160
160
|
|
|
161
|
+
test("on an issue with the listen label, a new comment matches without the mention", () => {
|
|
162
|
+
const comment = (labels: string[]) => delivery({ body: "and the tests", before: "and the tests", labels });
|
|
163
|
+
assert.equal(channel.match(selector(), comment([])), undefined);
|
|
164
|
+
assert.ok(channel.match(selector(), comment(["listen:claude"])));
|
|
165
|
+
assert.ok(channel.match(selector({ listen: "agent" }), comment(["Agent"])));
|
|
166
|
+
assert.equal(channel.match(selector({ listen: false }), comment(["listen:claude"])), undefined);
|
|
167
|
+
assert.equal(channel.match(selector(), delivery({ action: "edited", body: "fix", before: "fixx", labels: ["listen:claude"] })), undefined);
|
|
168
|
+
assert.ok(channel.match(selector(), delivery({ labels: ["listen:claude"] })));
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
test("on an issue with the listen label, a comment addressed to someone else doesn't match", () => {
|
|
172
|
+
const comment = (body: string) => delivery({ body, before: body, labels: ["listen:claude"] });
|
|
173
|
+
assert.equal(channel.match(selector(), comment("@droid do it")), undefined);
|
|
174
|
+
assert.equal(channel.match(selector(), comment("what do you think, @bob?")), undefined);
|
|
175
|
+
assert.equal(channel.match(selector(), comment("ping @acme/core")), undefined);
|
|
176
|
+
assert.ok(channel.match(selector(), comment("mail me@example.com")));
|
|
177
|
+
assert.ok(channel.match(selector(), comment("@Claude and @claude again")));
|
|
178
|
+
assert.ok(channel.match(selector(), comment("fix the `@types/node` import")));
|
|
179
|
+
assert.ok(channel.match(selector(), comment("```ts\n@Injectable()\n```\nlike this")));
|
|
180
|
+
assert.ok(channel.match(selector(), comment("> @bob said x\n\nplease do it")));
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
test("the default listen label is cut to GitHub's 50 characters", async () => {
|
|
184
|
+
await withGithub({}, async (_, writes) => {
|
|
185
|
+
const d = await accepted("issue_comment", commentPayload);
|
|
186
|
+
await keyed.acknowledge!(d, [selector({ mention: "@some-org/a-very-long-team-name-that-goes-on-and-on" })]);
|
|
187
|
+
const [, , body] = writes.find(([, path]) => path.endsWith("/labels"))!;
|
|
188
|
+
assert.equal((body as { labels: string[] }).labels[0]!.length, 50);
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
|
|
161
192
|
test("mentions match as GitHub does", () => {
|
|
162
193
|
assert.equal(mentions("@Claude please", "@claude"), true);
|
|
163
194
|
assert.equal(mentions("hi (@claude)", "@claude"), true);
|
|
@@ -205,7 +236,7 @@ const withGithub = async (
|
|
|
205
236
|
const name = roles[decodeURIComponent(role[1]!)];
|
|
206
237
|
return name ? Response.json({ permission: name, role_name: name }) : new Response("Not Found", { status: 404 });
|
|
207
238
|
}
|
|
208
|
-
if (init?.method === "PATCH" || url.pathname.endsWith("/reactions")) {
|
|
239
|
+
if (init?.method === "PATCH" || url.pathname.endsWith("/reactions") || url.pathname.endsWith("/labels")) {
|
|
209
240
|
writes.push([init!.method!, url.pathname, JSON.parse(String(init!.body))]);
|
|
210
241
|
if (deleted.some((id) => url.pathname.endsWith(`/comments/${id}`))) return new Response("Not Found", { status: 404 });
|
|
211
242
|
return Response.json({});
|
|
@@ -359,12 +390,40 @@ test("a reply to a comment that's gone posts a new comment", async () => {
|
|
|
359
390
|
|
|
360
391
|
test("acknowledge reacts with 👀 to the comment that matched, or to the issue for an issue event", async () => {
|
|
361
392
|
await withGithub({}, async (_, writes) => {
|
|
362
|
-
await keyed.acknowledge!(await accepted("issue_comment", commentPayload));
|
|
393
|
+
await keyed.acknowledge!(await accepted("issue_comment", commentPayload), []);
|
|
363
394
|
const opened = { action: "opened", repository: commentPayload.repository, issue: commentPayload.issue };
|
|
364
|
-
await keyed.acknowledge!(await accepted("issues", opened));
|
|
395
|
+
await keyed.acknowledge!(await accepted("issues", opened), []);
|
|
365
396
|
assert.deepEqual(writes, [
|
|
366
397
|
["POST", "/repos/acme/api/issues/comments/99/reactions", { content: "eyes" }],
|
|
367
398
|
["POST", "/repos/acme/api/issues/7/reactions", { content: "eyes" }],
|
|
368
399
|
]);
|
|
369
400
|
});
|
|
370
401
|
});
|
|
402
|
+
|
|
403
|
+
test("acknowledge adds the listen label of each selector that listens", async () => {
|
|
404
|
+
await withGithub({}, async (_, writes) => {
|
|
405
|
+
const d = await accepted("issue_comment", commentPayload);
|
|
406
|
+
await keyed.acknowledge!(d, [selector(), selector({ mention: "@cursor", listen: false })]);
|
|
407
|
+
const labelled = writes.filter(([, path]) => path.endsWith("/labels"));
|
|
408
|
+
assert.deepEqual(labelled, [["POST", "/repos/acme/api/issues/7/labels", { labels: ["listen:claude"] }]]);
|
|
409
|
+
});
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
test("acknowledge adds no label that the issue has", async () => {
|
|
413
|
+
await withGithub({}, async (_, writes) => {
|
|
414
|
+
const d = await accepted("issue_comment", commentPayload);
|
|
415
|
+
await keyed.acknowledge!({ ...d, data: { ...d.data, labels: ["Listen:Claude"] } }, [selector()]);
|
|
416
|
+
assert.equal(writes.filter(([, path]) => path.endsWith("/labels")).length, 0);
|
|
417
|
+
});
|
|
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
|
@@ -12,6 +12,7 @@ import type { AuthorSet } from "../implementations/selectors.ts";
|
|
|
12
12
|
import { appJwt } from "./app-jwt.ts";
|
|
13
13
|
import { signIn, signInUrl } from "./operators.ts";
|
|
14
14
|
import {
|
|
15
|
+
addLabels,
|
|
15
16
|
comment,
|
|
16
17
|
installedRepos,
|
|
17
18
|
type IssueComment,
|
|
@@ -205,19 +206,44 @@ export const mentions = (body: string, mention: string) =>
|
|
|
205
206
|
type Selector = {
|
|
206
207
|
actions: string[];
|
|
207
208
|
mention?: string;
|
|
209
|
+
listen?: string | false;
|
|
208
210
|
labels?: string[];
|
|
209
211
|
from: AuthorSet | AuthorSet[];
|
|
210
212
|
};
|
|
211
213
|
|
|
214
|
+
/** The label that keeps a mention selector listening, if it has one. Outposts deployed before `listen` existed get the default too. */
|
|
215
|
+
const listenLabel = (selector: Pick<Selector, "mention" | "listen">) => {
|
|
216
|
+
if (!selector.mention || selector.listen === false) return undefined;
|
|
217
|
+
// GitHub limits label names to 50 characters, which a team's mention can pass.
|
|
218
|
+
return selector.listen ?? `listen:${selector.mention.replace(/^@/, "")}`.slice(0, 50);
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const hasLabel = (labels: string[], label: string) => labels.some((l) => l.toLowerCase() === label.toLowerCase());
|
|
222
|
+
|
|
223
|
+
const HANDLE = /(?<![\w@.-])@[\w-]+(?:\/[\w-]+)?/g;
|
|
224
|
+
|
|
225
|
+
/** Code and quoted lines, where an `@` isn't a mention. */
|
|
226
|
+
const NOT_MENTIONS = /```[\s\S]*?(?:```|(?![\s\S]))|`[^`\n]*`|^>.*$/gm;
|
|
227
|
+
|
|
228
|
+
/** Whether `body` mentions a user or team other than `mention`, outside code and quotes. */
|
|
229
|
+
const mentionsOther = (body: string, mention: string) => {
|
|
230
|
+
const own = mention.replace(/^@/, "").toLowerCase();
|
|
231
|
+
return (body.replace(NOT_MENTIONS, "").match(HANDLE) ?? []).some((h) => h.slice(1).toLowerCase() !== own);
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
/** Whether the event's body mentions `mention`. An edit counts only if it newly adds the mention. */
|
|
235
|
+
const newlyMentions = (event: GithubEvent, mention: string) =>
|
|
236
|
+
mentions(event.body, mention) && !(event.action === "edited" && mentions(event.before, mention));
|
|
237
|
+
|
|
212
238
|
const selects = (selector: Selector, event: GithubEvent) => {
|
|
213
239
|
if (!selector.actions.includes(event.action)) return false;
|
|
214
|
-
if (selector.labels?.some((l) => !event.labels
|
|
215
|
-
if (selector.mention) {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
240
|
+
if (selector.labels?.some((l) => !hasLabel(event.labels, l))) return false;
|
|
241
|
+
if (selector.mention && !newlyMentions(event, selector.mention)) {
|
|
242
|
+
// On an issue with the listen label, a new comment matches without the mention, unless it's addressed to someone else. Edits don't.
|
|
243
|
+
const label = listenLabel(selector);
|
|
244
|
+
const listening =
|
|
245
|
+
event.action === "created" && label !== undefined && hasLabel(event.labels, label) && !mentionsOther(event.body, selector.mention);
|
|
246
|
+
if (!listening) return false;
|
|
221
247
|
}
|
|
222
248
|
return true;
|
|
223
249
|
};
|
|
@@ -356,9 +382,18 @@ export const channel = (ctx: ChannelContext): Channel<GithubEvent> => {
|
|
|
356
382
|
return threadMessages(await auth(), thread as Thread);
|
|
357
383
|
},
|
|
358
384
|
|
|
359
|
-
async acknowledge(delivery) {
|
|
385
|
+
async acknowledge(delivery, selectors) {
|
|
360
386
|
const payload = delivery.payload as Payload;
|
|
361
|
-
|
|
387
|
+
const a = await auth();
|
|
388
|
+
const labels = new Set<string>();
|
|
389
|
+
for (const s of selectors as Selector[]) {
|
|
390
|
+
const label = listenLabel(s);
|
|
391
|
+
if (label && !hasLabel(delivery.data.labels, label)) labels.add(label);
|
|
392
|
+
}
|
|
393
|
+
await Promise.all([
|
|
394
|
+
reactEyes(a, delivery.repo, { issue: payload.issue.number, comment: payload.comment?.id }),
|
|
395
|
+
labels.size ? addLabels(a, delivery.repo, payload.issue.number, [...labels]) : undefined,
|
|
396
|
+
]);
|
|
362
397
|
},
|
|
363
398
|
|
|
364
399
|
async reply(thread, text, message) {
|
|
@@ -376,12 +411,19 @@ export const channel = (ctx: ChannelContext): Channel<GithubEvent> => {
|
|
|
376
411
|
return installedRepos(await auth());
|
|
377
412
|
},
|
|
378
413
|
|
|
379
|
-
async signInUrl(state) {
|
|
380
|
-
return signInUrl(ctx.value(CHANNEL_VALUES.clientId), state);
|
|
414
|
+
async signInUrl(state, redirect) {
|
|
415
|
+
return signInUrl(ctx.value(CHANNEL_VALUES.clientId), state, redirect);
|
|
416
|
+
},
|
|
417
|
+
|
|
418
|
+
async signIn(code, redirect) {
|
|
419
|
+
return signIn({ clientId: ctx.value(CHANNEL_VALUES.clientId), clientSecret: await ctx.secret(CHANNEL_SECRETS.clientSecret) }, code, redirect);
|
|
381
420
|
},
|
|
382
421
|
|
|
383
|
-
|
|
384
|
-
|
|
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";
|
|
385
427
|
},
|
|
386
428
|
};
|
|
387
429
|
};
|
package/router/operators.test.ts
CHANGED
|
@@ -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) => {
|
package/router/operators.ts
CHANGED
|
@@ -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
|
-
/**
|
|
19
|
-
|
|
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",
|
|
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:
|
|
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 };
|
package/router/repos.ts
CHANGED
|
@@ -243,6 +243,13 @@ export const reactEyes = async (auth: AppAuth, repo: string, target: { issue: nu
|
|
|
243
243
|
await ok(await github("POST", path, token, { body: { content: "eyes" } }), `POST ${path}`);
|
|
244
244
|
};
|
|
245
245
|
|
|
246
|
+
/** Adds labels to an issue or a pull request. GitHub creates a label that the repo doesn't have yet. */
|
|
247
|
+
export const addLabels = async (auth: AppAuth, repo: string, issue: number, labels: string[]) => {
|
|
248
|
+
const token = await repoToken(auth, repo, { issues: "write" });
|
|
249
|
+
const path = `/repos/${repo}/issues/${issue}/labels`;
|
|
250
|
+
await ok(await github("POST", path, token, { body: { labels } }), `POST ${path}`);
|
|
251
|
+
};
|
|
252
|
+
|
|
246
253
|
const fullNames = (repos: { full_name: string }[] | undefined) => (repos ?? []).map((r) => r.full_name);
|
|
247
254
|
|
|
248
255
|
/**
|