@briefkasten/adapter-github 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +46 -2
- package/dist/index.d.mts +605 -0
- package/dist/index.mjs +978 -0
- package/package.json +58 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,978 @@
|
|
|
1
|
+
import { builtSample, defineBinding, numberField, recordOf, stringField } from "briefkasten";
|
|
2
|
+
import { createHmac, createSign, timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
//#region src/github-schemas.ts
|
|
6
|
+
/**
|
|
7
|
+
* Curated subsets of the GitHub webhook payloads. Keeping the schemas in
|
|
8
|
+
* their own module keeps the adapter file under the line budget; the event
|
|
9
|
+
* table drives the SDK's typed hooks and the webhook registration defaults.
|
|
10
|
+
*/
|
|
11
|
+
const authorSchema = z.object({
|
|
12
|
+
name: z.string(),
|
|
13
|
+
email: z.string().nullish(),
|
|
14
|
+
username: z.string().nullish()
|
|
15
|
+
});
|
|
16
|
+
const commitSchema = z.object({
|
|
17
|
+
id: z.string(),
|
|
18
|
+
message: z.string(),
|
|
19
|
+
timestamp: z.string(),
|
|
20
|
+
url: z.string(),
|
|
21
|
+
author: authorSchema,
|
|
22
|
+
committer: authorSchema,
|
|
23
|
+
added: z.array(z.string()).default([]),
|
|
24
|
+
removed: z.array(z.string()).default([]),
|
|
25
|
+
modified: z.array(z.string()).default([])
|
|
26
|
+
});
|
|
27
|
+
const repositorySchema = z.object({
|
|
28
|
+
id: z.number(),
|
|
29
|
+
full_name: z.string(),
|
|
30
|
+
html_url: z.string(),
|
|
31
|
+
default_branch: z.string(),
|
|
32
|
+
private: z.boolean().optional(),
|
|
33
|
+
description: z.string().nullish()
|
|
34
|
+
});
|
|
35
|
+
const userSchema = z.object({
|
|
36
|
+
login: z.string(),
|
|
37
|
+
html_url: z.string().nullish(),
|
|
38
|
+
type: z.string().nullish()
|
|
39
|
+
});
|
|
40
|
+
/** A push's sender is a GitHub user; its pusher is a name and an email. */
|
|
41
|
+
const pushSchema = z.object({
|
|
42
|
+
ref: z.string(),
|
|
43
|
+
before: z.string(),
|
|
44
|
+
after: z.string(),
|
|
45
|
+
created: z.boolean().optional(),
|
|
46
|
+
deleted: z.boolean().optional(),
|
|
47
|
+
forced: z.boolean().optional(),
|
|
48
|
+
pusher: authorSchema.nullish(),
|
|
49
|
+
repository: repositorySchema,
|
|
50
|
+
commits: z.array(commitSchema).default([]),
|
|
51
|
+
head_commit: commitSchema.nullish(),
|
|
52
|
+
sender: userSchema.nullish()
|
|
53
|
+
});
|
|
54
|
+
/**
|
|
55
|
+
* A pull request as its events carry it: what a consumer applies to the pull request it holds
|
|
56
|
+
* (its state, title, labels, the reviews asked, its sizes, when it was last updated), so a change
|
|
57
|
+
* shows before any call to GitHub.
|
|
58
|
+
*/
|
|
59
|
+
const pullRequestSchema = z.object({
|
|
60
|
+
html_url: z.string(),
|
|
61
|
+
title: z.string(),
|
|
62
|
+
body: z.string().nullish(),
|
|
63
|
+
state: z.string(),
|
|
64
|
+
merged: z.boolean().nullish(),
|
|
65
|
+
mergeable: z.boolean().nullish(),
|
|
66
|
+
draft: z.boolean().optional(),
|
|
67
|
+
number: z.number(),
|
|
68
|
+
updated_at: z.string().optional(),
|
|
69
|
+
additions: z.number().optional(),
|
|
70
|
+
deletions: z.number().optional(),
|
|
71
|
+
changed_files: z.number().optional(),
|
|
72
|
+
comments: z.number().optional(),
|
|
73
|
+
labels: z.array(z.object({
|
|
74
|
+
name: z.string(),
|
|
75
|
+
color: z.string().nullish()
|
|
76
|
+
})).optional(),
|
|
77
|
+
requested_reviewers: z.array(z.object({ login: z.string() })).optional(),
|
|
78
|
+
requested_teams: z.array(z.object({ slug: z.string() })).optional(),
|
|
79
|
+
base: z.object({ ref: z.string() }),
|
|
80
|
+
head: z.object({
|
|
81
|
+
ref: z.string(),
|
|
82
|
+
sha: z.string().nullish()
|
|
83
|
+
}),
|
|
84
|
+
user: userSchema.nullish()
|
|
85
|
+
});
|
|
86
|
+
const pullRequestEventSchema = z.object({
|
|
87
|
+
action: z.string(),
|
|
88
|
+
number: z.number(),
|
|
89
|
+
repository: repositorySchema,
|
|
90
|
+
pull_request: pullRequestSchema,
|
|
91
|
+
sender: userSchema.nullish()
|
|
92
|
+
});
|
|
93
|
+
const issueSchema = z.object({
|
|
94
|
+
html_url: z.string(),
|
|
95
|
+
title: z.string(),
|
|
96
|
+
body: z.string().nullish(),
|
|
97
|
+
state: z.string(),
|
|
98
|
+
number: z.number(),
|
|
99
|
+
user: userSchema.nullish(),
|
|
100
|
+
/** Present when the issue is a pull request: a comment on a pull request's conversation. */
|
|
101
|
+
pull_request: z.object({ html_url: z.string().nullish() }).nullish()
|
|
102
|
+
});
|
|
103
|
+
const issuesEventSchema = z.object({
|
|
104
|
+
action: z.string(),
|
|
105
|
+
issue: issueSchema,
|
|
106
|
+
repository: repositorySchema,
|
|
107
|
+
sender: userSchema.nullish(),
|
|
108
|
+
/** Present on `labeled` / `unlabeled` actions — consumers route on it. */
|
|
109
|
+
label: z.object({ name: z.string() }).nullish()
|
|
110
|
+
});
|
|
111
|
+
/** The pull requests a check or a workflow run names: those whose head is its commit (none for a fork's). */
|
|
112
|
+
const checkPullRequestsSchema = z.array(z.object({ number: z.number() })).default([]);
|
|
113
|
+
const workflowRunSchema = z.object({
|
|
114
|
+
id: z.number(),
|
|
115
|
+
name: z.string().nullish(),
|
|
116
|
+
head_branch: z.string().nullish(),
|
|
117
|
+
head_sha: z.string(),
|
|
118
|
+
status: z.string(),
|
|
119
|
+
conclusion: z.string().nullish(),
|
|
120
|
+
html_url: z.string(),
|
|
121
|
+
run_number: z.number(),
|
|
122
|
+
event: z.string(),
|
|
123
|
+
pull_requests: checkPullRequestsSchema
|
|
124
|
+
});
|
|
125
|
+
const workflowRunEventSchema = z.object({
|
|
126
|
+
action: z.string(),
|
|
127
|
+
repository: repositorySchema,
|
|
128
|
+
workflow_run: workflowRunSchema,
|
|
129
|
+
sender: userSchema.nullish()
|
|
130
|
+
});
|
|
131
|
+
const pingSchema = z.object({
|
|
132
|
+
zen: z.string().optional(),
|
|
133
|
+
hook_id: z.number().optional(),
|
|
134
|
+
repository: repositorySchema.optional()
|
|
135
|
+
});
|
|
136
|
+
const commentSchema$1 = z.object({
|
|
137
|
+
id: z.number(),
|
|
138
|
+
body: z.string().nullish(),
|
|
139
|
+
html_url: z.string().nullish(),
|
|
140
|
+
user: userSchema.nullish()
|
|
141
|
+
});
|
|
142
|
+
const issueCommentEventSchema = z.object({
|
|
143
|
+
action: z.string(),
|
|
144
|
+
issue: issueSchema,
|
|
145
|
+
comment: commentSchema$1,
|
|
146
|
+
repository: repositorySchema,
|
|
147
|
+
sender: userSchema.nullish()
|
|
148
|
+
});
|
|
149
|
+
const reviewCommentEventSchema = z.object({
|
|
150
|
+
action: z.string(),
|
|
151
|
+
pull_request: pullRequestSchema,
|
|
152
|
+
comment: commentSchema$1,
|
|
153
|
+
repository: repositorySchema,
|
|
154
|
+
sender: userSchema.nullish()
|
|
155
|
+
});
|
|
156
|
+
const reviewEventSchema = z.object({
|
|
157
|
+
action: z.string(),
|
|
158
|
+
pull_request: pullRequestSchema,
|
|
159
|
+
review: z.object({
|
|
160
|
+
state: z.string(),
|
|
161
|
+
body: z.string().nullish(),
|
|
162
|
+
user: userSchema.nullish()
|
|
163
|
+
}),
|
|
164
|
+
repository: repositorySchema,
|
|
165
|
+
sender: userSchema.nullish()
|
|
166
|
+
});
|
|
167
|
+
/** A review thread resolved or opened again. */
|
|
168
|
+
const reviewThreadEventSchema = z.object({
|
|
169
|
+
action: z.string(),
|
|
170
|
+
pull_request: pullRequestSchema,
|
|
171
|
+
thread: z.object({ node_id: z.string().nullish() }).nullish(),
|
|
172
|
+
repository: repositorySchema,
|
|
173
|
+
sender: userSchema.nullish()
|
|
174
|
+
});
|
|
175
|
+
const checkSuiteSchema = z.object({
|
|
176
|
+
id: z.number(),
|
|
177
|
+
head_branch: z.string().nullish(),
|
|
178
|
+
head_sha: z.string(),
|
|
179
|
+
status: z.string().nullish(),
|
|
180
|
+
conclusion: z.string().nullish(),
|
|
181
|
+
pull_requests: checkPullRequestsSchema
|
|
182
|
+
});
|
|
183
|
+
const checkSuiteEventSchema = z.object({
|
|
184
|
+
action: z.string(),
|
|
185
|
+
check_suite: checkSuiteSchema,
|
|
186
|
+
repository: repositorySchema,
|
|
187
|
+
sender: userSchema.nullish()
|
|
188
|
+
});
|
|
189
|
+
const checkRunEventSchema = z.object({
|
|
190
|
+
action: z.string(),
|
|
191
|
+
check_run: z.object({
|
|
192
|
+
id: z.number(),
|
|
193
|
+
name: z.string(),
|
|
194
|
+
head_sha: z.string(),
|
|
195
|
+
status: z.string(),
|
|
196
|
+
conclusion: z.string().nullish(),
|
|
197
|
+
html_url: z.string().nullish(),
|
|
198
|
+
check_suite: z.object({
|
|
199
|
+
id: z.number(),
|
|
200
|
+
head_branch: z.string().nullish()
|
|
201
|
+
}).nullish(),
|
|
202
|
+
pull_requests: checkPullRequestsSchema
|
|
203
|
+
}),
|
|
204
|
+
repository: repositorySchema,
|
|
205
|
+
sender: userSchema.nullish()
|
|
206
|
+
});
|
|
207
|
+
/** A commit status (the older checks API): it names a commit and its branches, no pull request. */
|
|
208
|
+
const statusEventSchema = z.object({
|
|
209
|
+
sha: z.string(),
|
|
210
|
+
state: z.string(),
|
|
211
|
+
context: z.string(),
|
|
212
|
+
description: z.string().nullish(),
|
|
213
|
+
target_url: z.string().nullish(),
|
|
214
|
+
branches: z.array(z.object({ name: z.string() })).default([]),
|
|
215
|
+
repository: repositorySchema,
|
|
216
|
+
sender: userSchema.nullish()
|
|
217
|
+
});
|
|
218
|
+
const events = {
|
|
219
|
+
ping: pingSchema,
|
|
220
|
+
push: pushSchema,
|
|
221
|
+
pull_request: pullRequestEventSchema,
|
|
222
|
+
issues: issuesEventSchema,
|
|
223
|
+
workflow_run: workflowRunEventSchema,
|
|
224
|
+
issue_comment: issueCommentEventSchema,
|
|
225
|
+
pull_request_review: reviewEventSchema,
|
|
226
|
+
pull_request_review_comment: reviewCommentEventSchema,
|
|
227
|
+
pull_request_review_thread: reviewThreadEventSchema,
|
|
228
|
+
check_suite: checkSuiteEventSchema,
|
|
229
|
+
check_run: checkRunEventSchema,
|
|
230
|
+
status: statusEventSchema
|
|
231
|
+
};
|
|
232
|
+
/** Record-typed view of the event table for runtime lookup by header name. */
|
|
233
|
+
const eventTable = events;
|
|
234
|
+
//#endregion
|
|
235
|
+
//#region src/app-auth.ts
|
|
236
|
+
/**
|
|
237
|
+
* GitHub App authentication: sign a short-lived RS256 JWT with the app's
|
|
238
|
+
* private key, exchange it for a per-installation access token, and cache that
|
|
239
|
+
* token until shortly before it expires (installation tokens live one hour).
|
|
240
|
+
*
|
|
241
|
+
* Hand-rolled on `node:crypto` + `fetch` on purpose: the adapter stays free of
|
|
242
|
+
* a large Octokit dependency tree, and the two steps are small enough to test.
|
|
243
|
+
*/
|
|
244
|
+
const DEFAULT_API_URL = "https://api.github.com";
|
|
245
|
+
/** Under GitHub's 10-minute cap, with room for clock skew. */
|
|
246
|
+
const JWT_LIFETIME_SECONDS = 540;
|
|
247
|
+
/** Backdate `iat` so a slightly slow client clock is not rejected as "not yet valid". */
|
|
248
|
+
const JWT_CLOCK_SKEW_SECONDS = 60;
|
|
249
|
+
/** Re-mint when less than this remains; installation tokens expire after one hour. */
|
|
250
|
+
const INSTALLATION_TOKEN_MARGIN_MS = 3e5;
|
|
251
|
+
const API_VERSION = "2022-11-28";
|
|
252
|
+
const githubAppAuthSchema = z.object({
|
|
253
|
+
/** The numeric app id, as a string. */
|
|
254
|
+
appId: z.string().min(1),
|
|
255
|
+
/** PEM-encoded RSA private key. */
|
|
256
|
+
privateKey: z.string().min(1).optional(),
|
|
257
|
+
/** Absolute path to the PEM private key; the source reads it once. */
|
|
258
|
+
privateKeyPath: z.string().min(1).optional(),
|
|
259
|
+
/** Pin the installation; omit to resolve it per repository. */
|
|
260
|
+
installationId: z.number().int().positive().optional(),
|
|
261
|
+
/** API base URL override (GitHub Enterprise Server). */
|
|
262
|
+
apiUrl: z.string().optional()
|
|
263
|
+
}).refine((value) => value.privateKey === void 0 !== (value.privateKeyPath === void 0), { message: "provide exactly one of `privateKey` or `privateKeyPath`" });
|
|
264
|
+
function base64url(value) {
|
|
265
|
+
return Buffer.from(value).toString("base64url");
|
|
266
|
+
}
|
|
267
|
+
/** A signed app JWT. `now` is epoch seconds and defaults to the current time. */
|
|
268
|
+
function signJwt(input) {
|
|
269
|
+
const now = input.now ?? Math.floor(Date.now() / 1e3);
|
|
270
|
+
const header = base64url(JSON.stringify({
|
|
271
|
+
alg: "RS256",
|
|
272
|
+
typ: "JWT"
|
|
273
|
+
}));
|
|
274
|
+
const payload = base64url(JSON.stringify({
|
|
275
|
+
iat: now - JWT_CLOCK_SKEW_SECONDS,
|
|
276
|
+
exp: now + JWT_LIFETIME_SECONDS,
|
|
277
|
+
iss: input.appId
|
|
278
|
+
}));
|
|
279
|
+
return `${header}.${payload}.${createSign("RSA-SHA256").update(`${header}.${payload}`).sign(input.privateKey, "base64url")}`;
|
|
280
|
+
}
|
|
281
|
+
function apiMessage(parsed, status) {
|
|
282
|
+
const message = stringField(recordOf(parsed), "message");
|
|
283
|
+
return message === "" ? `HTTP ${status}` : `${message} (${status})`;
|
|
284
|
+
}
|
|
285
|
+
function resolvePrivateKey(input) {
|
|
286
|
+
if (input.privateKey !== void 0) return input.privateKey;
|
|
287
|
+
if (input.privateKeyPath !== void 0) return readFileSync(input.privateKeyPath, "utf8");
|
|
288
|
+
throw new Error("github app: one of `privateKey` or `privateKeyPath` is required");
|
|
289
|
+
}
|
|
290
|
+
function githubAppTokenSource(input) {
|
|
291
|
+
const apiBase = (input.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, "");
|
|
292
|
+
let cachedPrivateKey;
|
|
293
|
+
const privateKeyOf = () => {
|
|
294
|
+
cachedPrivateKey ??= resolvePrivateKey(input);
|
|
295
|
+
return cachedPrivateKey;
|
|
296
|
+
};
|
|
297
|
+
const tokens = /* @__PURE__ */ new Map();
|
|
298
|
+
const installations = /* @__PURE__ */ new Map();
|
|
299
|
+
async function request(path, method) {
|
|
300
|
+
const response = await fetch(`${apiBase}${path}`, {
|
|
301
|
+
method,
|
|
302
|
+
headers: {
|
|
303
|
+
authorization: `Bearer ${signJwt({
|
|
304
|
+
appId: input.appId,
|
|
305
|
+
privateKey: privateKeyOf()
|
|
306
|
+
})}`,
|
|
307
|
+
accept: "application/vnd.github+json",
|
|
308
|
+
"x-github-api-version": API_VERSION,
|
|
309
|
+
"user-agent": "@briefkasten/adapter-github"
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
const text = await response.text();
|
|
313
|
+
let parsed = void 0;
|
|
314
|
+
if (text.length > 0) try {
|
|
315
|
+
parsed = JSON.parse(text);
|
|
316
|
+
} catch {
|
|
317
|
+
parsed = text;
|
|
318
|
+
}
|
|
319
|
+
if (!response.ok) throw new Error(`github app: ${method} ${path} failed: ${apiMessage(parsed, response.status)}`);
|
|
320
|
+
return parsed;
|
|
321
|
+
}
|
|
322
|
+
async function mint(installationId) {
|
|
323
|
+
const parsed = recordOf(await request(`/app/installations/${installationId}/access_tokens`, "POST"));
|
|
324
|
+
const token = stringField(parsed, "token");
|
|
325
|
+
const expiresAtMs = Date.parse(stringField(parsed, "expires_at"));
|
|
326
|
+
if (token === "" || Number.isNaN(expiresAtMs)) throw new Error("github app: installation token response is missing token/expires_at");
|
|
327
|
+
return {
|
|
328
|
+
token,
|
|
329
|
+
expiresAtMs
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
async function installationFor(repo) {
|
|
333
|
+
const cached = installations.get(repo);
|
|
334
|
+
if (cached !== void 0) return cached;
|
|
335
|
+
const parsed = recordOf(await request(`/repos/${repo}/installation`, "GET"));
|
|
336
|
+
const id = numberField(parsed, "id");
|
|
337
|
+
if (id === 0) throw new Error(`github app: no installation found for ${repo}`);
|
|
338
|
+
installations.set(repo, id);
|
|
339
|
+
return id;
|
|
340
|
+
}
|
|
341
|
+
const tokenFor = async (repo) => {
|
|
342
|
+
const installationId = input.installationId ?? await installationFor(repo);
|
|
343
|
+
const cached = tokens.get(installationId);
|
|
344
|
+
if (cached !== void 0 && cached.expiresAtMs - Date.now() > INSTALLATION_TOKEN_MARGIN_MS) return cached.token;
|
|
345
|
+
const minted = await mint(installationId);
|
|
346
|
+
tokens.set(installationId, minted);
|
|
347
|
+
return minted.token;
|
|
348
|
+
};
|
|
349
|
+
return {
|
|
350
|
+
tokenFor,
|
|
351
|
+
signJwt: (now) => signJwt({
|
|
352
|
+
appId: input.appId,
|
|
353
|
+
privateKey: privateKeyOf(),
|
|
354
|
+
now
|
|
355
|
+
}),
|
|
356
|
+
mint
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
//#endregion
|
|
360
|
+
//#region src/samples.ts
|
|
361
|
+
/**
|
|
362
|
+
* GitHub's deliveries, typed: a builder per event makes a realistic payload, with the fields a
|
|
363
|
+
* caller gives (`deliveries.pullRequest.opened({ repo: "acme/shop", number: 42 })`), signed the
|
|
364
|
+
* way GitHub signs (`x-hub-signature-256`). `source test` sends them as the samples, `send` and
|
|
365
|
+
* `briefkasten send` post them to a hook URL.
|
|
366
|
+
*/
|
|
367
|
+
const SHA = "6dcb09b5b57875f334f61aebed695e2e4193db5e";
|
|
368
|
+
const BEFORE = "0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c";
|
|
369
|
+
const NOW = "2026-12-03T12:00:00.000Z";
|
|
370
|
+
const DEFAULTS = {
|
|
371
|
+
repo: "acme/shop",
|
|
372
|
+
pull: 42,
|
|
373
|
+
issue: 7,
|
|
374
|
+
pullTitle: "Letterbox jams on Mondays",
|
|
375
|
+
issueTitle: "Parcels pile up behind the door",
|
|
376
|
+
author: "octocat"
|
|
377
|
+
};
|
|
378
|
+
/** Signs a payload as GitHub does: HMAC-SHA256 of the raw body, hex, in `x-hub-signature-256`. */
|
|
379
|
+
function signer(header) {
|
|
380
|
+
return (payload, context) => {
|
|
381
|
+
const body = JSON.stringify(payload);
|
|
382
|
+
const signature = createHmac("sha256", context.secret).update(body).digest("hex");
|
|
383
|
+
return {
|
|
384
|
+
headers: {
|
|
385
|
+
"content-type": "application/json",
|
|
386
|
+
"user-agent": "GitHub-Hookshot/7c3a1f2",
|
|
387
|
+
"x-github-event": header,
|
|
388
|
+
"x-github-delivery": context.id,
|
|
389
|
+
"x-hub-signature-256": `sha256=${signature}`
|
|
390
|
+
},
|
|
391
|
+
body
|
|
392
|
+
};
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
function delivery(header, event, payload) {
|
|
396
|
+
return {
|
|
397
|
+
adapter: "github",
|
|
398
|
+
event,
|
|
399
|
+
payload,
|
|
400
|
+
sign: signer(header)
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
function repository(fields) {
|
|
404
|
+
const full = fields.repo ?? DEFAULTS.repo;
|
|
405
|
+
return {
|
|
406
|
+
id: 712334908,
|
|
407
|
+
name: full.split("/").at(-1),
|
|
408
|
+
full_name: full,
|
|
409
|
+
private: true,
|
|
410
|
+
html_url: `https://github.com/${full}`,
|
|
411
|
+
default_branch: "main"
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
function user(fields) {
|
|
415
|
+
const login = fields.author ?? DEFAULTS.author;
|
|
416
|
+
return {
|
|
417
|
+
login,
|
|
418
|
+
html_url: `https://github.com/${login}`,
|
|
419
|
+
type: "User"
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
function pull(fields, merged) {
|
|
423
|
+
const number = fields.number ?? DEFAULTS.pull;
|
|
424
|
+
return {
|
|
425
|
+
number,
|
|
426
|
+
state: merged ? "closed" : "open",
|
|
427
|
+
merged,
|
|
428
|
+
title: fields.title ?? DEFAULTS.pullTitle,
|
|
429
|
+
body: "Sorts the Monday mail first.",
|
|
430
|
+
html_url: `https://github.com/${fields.repo ?? DEFAULTS.repo}/pull/${number}`,
|
|
431
|
+
draft: false,
|
|
432
|
+
user: user(fields),
|
|
433
|
+
head: {
|
|
434
|
+
ref: "fix/monday-jam",
|
|
435
|
+
sha: SHA
|
|
436
|
+
},
|
|
437
|
+
base: { ref: "main" },
|
|
438
|
+
updated_at: NOW
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
function issue(fields) {
|
|
442
|
+
const number = fields.number ?? DEFAULTS.issue;
|
|
443
|
+
return {
|
|
444
|
+
number,
|
|
445
|
+
title: fields.title ?? DEFAULTS.issueTitle,
|
|
446
|
+
body: "Since Tuesday the slot is full.",
|
|
447
|
+
state: "open",
|
|
448
|
+
html_url: `https://github.com/${fields.repo ?? DEFAULTS.repo}/issues/${number}`,
|
|
449
|
+
user: user(fields)
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
const push = (fields = {}) => {
|
|
453
|
+
const author = fields.author ?? DEFAULTS.author;
|
|
454
|
+
const person = {
|
|
455
|
+
name: author,
|
|
456
|
+
email: `${author}@example.com`,
|
|
457
|
+
username: author
|
|
458
|
+
};
|
|
459
|
+
const commit = {
|
|
460
|
+
id: SHA,
|
|
461
|
+
message: fields.title ?? "Sort the Monday mail first",
|
|
462
|
+
timestamp: NOW,
|
|
463
|
+
url: `https://github.com/${fields.repo ?? DEFAULTS.repo}/commit/${SHA}`,
|
|
464
|
+
author: person,
|
|
465
|
+
committer: person,
|
|
466
|
+
added: [],
|
|
467
|
+
removed: [],
|
|
468
|
+
modified: ["src/sort.ts"]
|
|
469
|
+
};
|
|
470
|
+
return delivery("push", "push", {
|
|
471
|
+
ref: "refs/heads/main",
|
|
472
|
+
before: BEFORE,
|
|
473
|
+
after: SHA,
|
|
474
|
+
created: false,
|
|
475
|
+
deleted: false,
|
|
476
|
+
forced: false,
|
|
477
|
+
pusher: {
|
|
478
|
+
name: author,
|
|
479
|
+
email: person.email
|
|
480
|
+
},
|
|
481
|
+
repository: repository(fields),
|
|
482
|
+
commits: [commit],
|
|
483
|
+
head_commit: commit,
|
|
484
|
+
sender: user(fields)
|
|
485
|
+
});
|
|
486
|
+
};
|
|
487
|
+
function pullRequest(action) {
|
|
488
|
+
return (fields = {}) => delivery("pull_request", `pull_request.${action}`, {
|
|
489
|
+
action,
|
|
490
|
+
number: fields.number ?? DEFAULTS.pull,
|
|
491
|
+
pull_request: pull(fields, action === "closed"),
|
|
492
|
+
repository: repository(fields),
|
|
493
|
+
sender: user(fields)
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
const issueOpened = (fields = {}) => delivery("issues", "issues.opened", {
|
|
497
|
+
action: "opened",
|
|
498
|
+
issue: issue(fields),
|
|
499
|
+
repository: repository(fields),
|
|
500
|
+
sender: user(fields)
|
|
501
|
+
});
|
|
502
|
+
const commentCreated = (fields = {}) => {
|
|
503
|
+
const number = fields.number ?? DEFAULTS.issue;
|
|
504
|
+
const url = `https://github.com/${fields.repo ?? DEFAULTS.repo}/issues/${number}`;
|
|
505
|
+
return delivery("issue_comment", "issue_comment.created", {
|
|
506
|
+
action: "created",
|
|
507
|
+
issue: issue(fields),
|
|
508
|
+
comment: {
|
|
509
|
+
id: 1840112337,
|
|
510
|
+
body: "Seen it too, on the second floor.",
|
|
511
|
+
html_url: `${url}#issuecomment-1840112337`,
|
|
512
|
+
user: user(fields)
|
|
513
|
+
},
|
|
514
|
+
repository: repository(fields),
|
|
515
|
+
sender: user(fields)
|
|
516
|
+
});
|
|
517
|
+
};
|
|
518
|
+
const checkRunCompleted = (fields = {}) => delivery("check_run", "check_run.completed", {
|
|
519
|
+
action: "completed",
|
|
520
|
+
check_run: {
|
|
521
|
+
id: 21830441112,
|
|
522
|
+
name: fields.title ?? "test",
|
|
523
|
+
head_sha: SHA,
|
|
524
|
+
status: "completed",
|
|
525
|
+
conclusion: "success",
|
|
526
|
+
html_url: `https://github.com/${fields.repo ?? DEFAULTS.repo}/runs/21830441112`,
|
|
527
|
+
check_suite: {
|
|
528
|
+
id: 30118224901,
|
|
529
|
+
head_branch: "fix/monday-jam"
|
|
530
|
+
},
|
|
531
|
+
pull_requests: [{ number: fields.number ?? DEFAULTS.pull }]
|
|
532
|
+
},
|
|
533
|
+
repository: repository(fields),
|
|
534
|
+
sender: user(fields)
|
|
535
|
+
});
|
|
536
|
+
const workflowRunCompleted = (fields = {}) => delivery("workflow_run", "workflow_run.completed", {
|
|
537
|
+
action: "completed",
|
|
538
|
+
workflow_run: {
|
|
539
|
+
id: 12093884201,
|
|
540
|
+
name: fields.title ?? "CI",
|
|
541
|
+
head_branch: "main",
|
|
542
|
+
head_sha: SHA,
|
|
543
|
+
status: "completed",
|
|
544
|
+
conclusion: "failure",
|
|
545
|
+
html_url: `https://github.com/${fields.repo ?? DEFAULTS.repo}/actions/runs/12093884201`,
|
|
546
|
+
run_number: fields.number ?? 318,
|
|
547
|
+
event: "push",
|
|
548
|
+
pull_requests: []
|
|
549
|
+
},
|
|
550
|
+
repository: repository(fields),
|
|
551
|
+
sender: user(fields)
|
|
552
|
+
});
|
|
553
|
+
/** GitHub's typed event builders: `github.events.pullRequest.opened({ repo, number, title })`. */
|
|
554
|
+
const deliveries = {
|
|
555
|
+
push,
|
|
556
|
+
pullRequest: {
|
|
557
|
+
opened: pullRequest("opened"),
|
|
558
|
+
closed: pullRequest("closed")
|
|
559
|
+
},
|
|
560
|
+
issues: { opened: issueOpened },
|
|
561
|
+
issueComment: { created: commentCreated },
|
|
562
|
+
checkRun: { completed: checkRunCompleted },
|
|
563
|
+
workflowRun: { completed: workflowRunCompleted }
|
|
564
|
+
};
|
|
565
|
+
const samples = [
|
|
566
|
+
builtSample("push", "Commits pushed to main", deliveries.push),
|
|
567
|
+
builtSample("pull_request.opened", "A pull request was opened", deliveries.pullRequest.opened),
|
|
568
|
+
builtSample("pull_request.closed", "A pull request was merged", deliveries.pullRequest.closed),
|
|
569
|
+
builtSample("issues.opened", "An issue was opened", deliveries.issues.opened),
|
|
570
|
+
builtSample("issue_comment.created", "A comment on an issue", deliveries.issueComment.created),
|
|
571
|
+
builtSample("check_run.completed", "A CI check finished", deliveries.checkRun.completed),
|
|
572
|
+
builtSample("workflow_run.completed", "A workflow run finished", deliveries.workflowRun.completed)
|
|
573
|
+
];
|
|
574
|
+
//#endregion
|
|
575
|
+
//#region src/webhooks.ts
|
|
576
|
+
/**
|
|
577
|
+
* Declarative webhook registration for the github adapter (when the gateway
|
|
578
|
+
* starts a source). Given the adapter options and the source's hook URL, ensure
|
|
579
|
+
* a webhook pointing at that URL exists per repo in `repos`. Idempotent: creating is a no-op when a hook with the same URL
|
|
580
|
+
* already exists; an existing hook is repaired (events/active) but foreign
|
|
581
|
+
* hooks are never touched and a "*" (all events) subscription is never
|
|
582
|
+
* downgraded.
|
|
583
|
+
*/
|
|
584
|
+
const GITHUB_API = "https://api.github.com";
|
|
585
|
+
function githubApiRequest(baseUrl, token, method, path, body) {
|
|
586
|
+
const init = {
|
|
587
|
+
method,
|
|
588
|
+
headers: {
|
|
589
|
+
authorization: `token ${token}`,
|
|
590
|
+
accept: "application/vnd.github+json",
|
|
591
|
+
"user-agent": "briefkasten",
|
|
592
|
+
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
593
|
+
},
|
|
594
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
595
|
+
};
|
|
596
|
+
return fetch(`${baseUrl.replace(/\/+$/, "")}${path}`, init).then(async (response) => {
|
|
597
|
+
const text = await response.text();
|
|
598
|
+
let parsed = void 0;
|
|
599
|
+
if (text.length > 0) try {
|
|
600
|
+
parsed = JSON.parse(text);
|
|
601
|
+
} catch {
|
|
602
|
+
parsed = text;
|
|
603
|
+
}
|
|
604
|
+
if (!response.ok) {
|
|
605
|
+
const message = typeof parsed === "object" && parsed !== null && "message" in parsed ? String(parsed.message) : `HTTP ${response.status}`;
|
|
606
|
+
throw new Error(`${method} ${path}: ${message} (${response.status})`);
|
|
607
|
+
}
|
|
608
|
+
return parsed;
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
function registeredWebhookEvents(table) {
|
|
612
|
+
return Object.keys(table).filter((name) => name !== "ping").toSorted();
|
|
613
|
+
}
|
|
614
|
+
function sameEvents(a, b) {
|
|
615
|
+
const sortedA = a.toSorted();
|
|
616
|
+
const sortedB = b.toSorted();
|
|
617
|
+
return sortedA.length === sortedB.length && sortedA.every((value, i) => value === sortedB[i]);
|
|
618
|
+
}
|
|
619
|
+
function coversAll(names) {
|
|
620
|
+
return names.includes("*");
|
|
621
|
+
}
|
|
622
|
+
function hookField(entry, field) {
|
|
623
|
+
return recordOf(entry)[field];
|
|
624
|
+
}
|
|
625
|
+
function hookId(entry) {
|
|
626
|
+
const id = hookField(entry, "id");
|
|
627
|
+
return typeof id === "number" ? id : void 0;
|
|
628
|
+
}
|
|
629
|
+
function hookActive(entry) {
|
|
630
|
+
return hookField(entry, "active") === true;
|
|
631
|
+
}
|
|
632
|
+
function hookUrl(entry) {
|
|
633
|
+
return stringField(recordOf(hookField(entry, "config")), "url");
|
|
634
|
+
}
|
|
635
|
+
function hookEvents(entry) {
|
|
636
|
+
const raw = hookField(entry, "events");
|
|
637
|
+
return Array.isArray(raw) ? raw.filter((value) => typeof value === "string") : [];
|
|
638
|
+
}
|
|
639
|
+
function repoPath(repo) {
|
|
640
|
+
const segments = repo.split("/");
|
|
641
|
+
const owner = segments[0] ?? "";
|
|
642
|
+
const name = segments.slice(1).join("/");
|
|
643
|
+
return `${encodeURIComponent(owner)}/${encodeURIComponent(name)}`;
|
|
644
|
+
}
|
|
645
|
+
async function registerWebhooks(input, context) {
|
|
646
|
+
const webhookUrl = context.hookUrl;
|
|
647
|
+
if (webhookUrl === void 0 || webhookUrl.length === 0) throw new Error("github: registerWebhooks needs server.publicUrl (declare it in the config)");
|
|
648
|
+
const subscribedEvents = (input.webhookEvents ?? registeredWebhookEvents(input.eventsTable)).filter((name) => name !== "ping").toSorted();
|
|
649
|
+
const apiBase = input.apiUrl ?? GITHUB_API;
|
|
650
|
+
for (const repo of input.repos ?? []) {
|
|
651
|
+
const token = await input.tokenFor(repo);
|
|
652
|
+
const ctx = repoPath(repo);
|
|
653
|
+
const existing = await githubApiRequest(apiBase, token, "GET", `/repos/${ctx}/hooks`);
|
|
654
|
+
const found = Array.isArray(existing) ? existing.find((entry) => hookUrl(entry) === webhookUrl) : void 0;
|
|
655
|
+
const payload = {
|
|
656
|
+
name: "web",
|
|
657
|
+
config: {
|
|
658
|
+
url: webhookUrl,
|
|
659
|
+
content_type: "json",
|
|
660
|
+
secret: input.webhookSecret
|
|
661
|
+
},
|
|
662
|
+
events: subscribedEvents,
|
|
663
|
+
active: true
|
|
664
|
+
};
|
|
665
|
+
if (found === void 0) await githubApiRequest(apiBase, token, "POST", `/repos/${ctx}/hooks`, payload);
|
|
666
|
+
else if (!hookActive(found) || !coversAll(hookEvents(found)) && !sameEvents(hookEvents(found), subscribedEvents)) {
|
|
667
|
+
const id = hookId(found);
|
|
668
|
+
if (id !== void 0) await githubApiRequest(apiBase, token, "PATCH", `/repos/${ctx}/hooks/${id}`, payload);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
//#endregion
|
|
673
|
+
//#region src/github.ts
|
|
674
|
+
const HTTP_OK = 200;
|
|
675
|
+
const HTTP_ACCEPTED = 202;
|
|
676
|
+
const HTTP_BAD_REQUEST = 400;
|
|
677
|
+
const HTTP_UNAUTHORIZED = 401;
|
|
678
|
+
const HEX_RADIX = 16;
|
|
679
|
+
const SHA256_ALGORITHM = "sha256";
|
|
680
|
+
const SIGNATURE_HEADER = "x-hub-signature-256";
|
|
681
|
+
function hmacSha256Hex(secret, bytes) {
|
|
682
|
+
return createHmac(SHA256_ALGORITHM, secret).update(bytes).digest("hex");
|
|
683
|
+
}
|
|
684
|
+
function hexToBytes(hex) {
|
|
685
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
686
|
+
for (let index = 0; index < bytes.length; index++) bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), HEX_RADIX);
|
|
687
|
+
return bytes;
|
|
688
|
+
}
|
|
689
|
+
function sameBytes(a, b) {
|
|
690
|
+
return timingSafeEqual(a, b);
|
|
691
|
+
}
|
|
692
|
+
/** Constant-time comparison of two "sha256=…" signature strings. */
|
|
693
|
+
function signaturesEqual(expected, provided) {
|
|
694
|
+
if (expected.length !== provided.length || expected.length === 0) return false;
|
|
695
|
+
return sameBytes(hexToBytes(expected), hexToBytes(provided));
|
|
696
|
+
}
|
|
697
|
+
function verifySignature(raw, header, secret) {
|
|
698
|
+
if (header === null) return false;
|
|
699
|
+
return signaturesEqual(`${SHA256_ALGORITHM}=${hmacSha256Hex(secret, raw)}`, header);
|
|
700
|
+
}
|
|
701
|
+
const dispatchSchema = z.object({
|
|
702
|
+
workflow_file: z.string().min(1),
|
|
703
|
+
ref: z.string().default("main"),
|
|
704
|
+
inputs: z.record(z.string(), z.string()).optional()
|
|
705
|
+
});
|
|
706
|
+
const commentSchema = z.object({
|
|
707
|
+
number: z.number(),
|
|
708
|
+
body: z.string().min(1)
|
|
709
|
+
});
|
|
710
|
+
function actionsFor(tokenFor, apiUrl) {
|
|
711
|
+
const apiBase = (apiUrl ?? "https://api.github.com").replace(/\/+$/, "");
|
|
712
|
+
async function postJson(repo, path, body) {
|
|
713
|
+
const url = `${apiBase}/repos/${encodeURIComponent(repo)}/${path}`;
|
|
714
|
+
const token = await tokenFor(repo);
|
|
715
|
+
const response = await fetch(url, {
|
|
716
|
+
method: "POST",
|
|
717
|
+
headers: {
|
|
718
|
+
authorization: `Bearer ${token}`,
|
|
719
|
+
accept: "application/vnd.github+json",
|
|
720
|
+
"content-type": "application/json",
|
|
721
|
+
"user-agent": "@briefkasten/adapter-github"
|
|
722
|
+
},
|
|
723
|
+
body: JSON.stringify(body)
|
|
724
|
+
});
|
|
725
|
+
if (!response.ok) {
|
|
726
|
+
const text = await response.text().catch(() => "");
|
|
727
|
+
throw new Error(`github action failed (${response.status}): ${text}`);
|
|
728
|
+
}
|
|
729
|
+
return response.json().catch(() => void 0);
|
|
730
|
+
}
|
|
731
|
+
return {
|
|
732
|
+
dispatchWorkflow: {
|
|
733
|
+
inputSchema: dispatchSchema,
|
|
734
|
+
run: (input) => {
|
|
735
|
+
const parsed = dispatchSchema.safeParse(input.args);
|
|
736
|
+
if (!parsed.success) throw new Error(`invalid dispatchWorkflow args: ${JSON.stringify(parsed.error)}`);
|
|
737
|
+
const { workflow_file, ref, inputs } = parsed.data;
|
|
738
|
+
const body = inputs === void 0 ? { ref } : {
|
|
739
|
+
ref,
|
|
740
|
+
inputs
|
|
741
|
+
};
|
|
742
|
+
return postJson(input.target, `actions/workflows/${encodeURIComponent(workflow_file)}/dispatches`, body);
|
|
743
|
+
}
|
|
744
|
+
},
|
|
745
|
+
createComment: {
|
|
746
|
+
inputSchema: commentSchema,
|
|
747
|
+
run: (input) => {
|
|
748
|
+
const parsed = commentSchema.safeParse(input.args);
|
|
749
|
+
if (!parsed.success) throw new Error(`invalid createComment args: ${JSON.stringify(parsed.error)}`);
|
|
750
|
+
return postJson(input.target, `issues/${parsed.data.number}/comments`, { body: parsed.data.body });
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
/** The auth half of the options: a static PAT or a GitHub App. */
|
|
756
|
+
const githubAuthSchema = z.union([z.object({
|
|
757
|
+
kind: z.literal("token"),
|
|
758
|
+
token: z.string().min(1)
|
|
759
|
+
}), z.object({
|
|
760
|
+
kind: z.literal("app"),
|
|
761
|
+
app: githubAppAuthSchema
|
|
762
|
+
})]);
|
|
763
|
+
const githubOptionsSchema = z.object({
|
|
764
|
+
/**
|
|
765
|
+
* How the adapter calls GitHub: a static token or a GitHub App. Receiving webhooks needs only
|
|
766
|
+
* the source's secret; the actions and `registerWebhooks` need this.
|
|
767
|
+
*/
|
|
768
|
+
auth: githubAuthSchema.optional(),
|
|
769
|
+
/** Optional allowlist of "owner/repo" — events for other repos are acked but dropped. */
|
|
770
|
+
repos: z.array(z.string().min(1)).optional(),
|
|
771
|
+
/**
|
|
772
|
+
* When true, starting the source provisions the repository webhooks declared by `repos`
|
|
773
|
+
* (creates missing, repairs events/active on existing) at the source's hook URL, so the
|
|
774
|
+
* wiring is declarative instead of manual API calls.
|
|
775
|
+
*/
|
|
776
|
+
registerWebhooks: z.boolean().optional(),
|
|
777
|
+
/** Events to subscribe when auto-registering. Default: the event table minus `ping`. */
|
|
778
|
+
webhookEvents: z.array(z.string().min(1)).optional(),
|
|
779
|
+
/** API base URL override (GitHub Enterprise Server). Default: https://api.github.com */
|
|
780
|
+
apiUrl: z.string().optional()
|
|
781
|
+
}).refine((options) => options.registerWebhooks !== true || options.auth !== void 0, {
|
|
782
|
+
message: "registerWebhooks needs auth: a token or a GitHub App to create the webhooks with",
|
|
783
|
+
path: ["auth"]
|
|
784
|
+
});
|
|
785
|
+
/**
|
|
786
|
+
* Turns an auth declaration into a per-repo token source. A GitHub App source
|
|
787
|
+
* caches installation tokens, so it is created once and shared.
|
|
788
|
+
*/
|
|
789
|
+
function tokenSourceFor(auth) {
|
|
790
|
+
if (auth === void 0) return () => Promise.reject(/* @__PURE__ */ new Error("this GitHub source has no auth: set auth to call GitHub"));
|
|
791
|
+
if (auth.kind === "token") {
|
|
792
|
+
const token = auth.token;
|
|
793
|
+
return () => Promise.resolve(token);
|
|
794
|
+
}
|
|
795
|
+
return githubAppTokenSource(auth.app).tokenFor;
|
|
796
|
+
}
|
|
797
|
+
function pushBody(body) {
|
|
798
|
+
return pushSchema.parse(body);
|
|
799
|
+
}
|
|
800
|
+
function workflowBody(body) {
|
|
801
|
+
return workflowRunEventSchema.parse(body);
|
|
802
|
+
}
|
|
803
|
+
function pullRequestNumber(body) {
|
|
804
|
+
const top = body["number"];
|
|
805
|
+
if (typeof top === "number") return top;
|
|
806
|
+
const parsed = pullRequestEventSchema.safeParse(body);
|
|
807
|
+
if (parsed.success) return parsed.data.number;
|
|
808
|
+
return pullRequestSchema.parse(recordOf(body["pull_request"])).number;
|
|
809
|
+
}
|
|
810
|
+
function issueNumber(body) {
|
|
811
|
+
return issuesEventSchema.parse(body).issue.number;
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* A check's address: its pull request when it names exactly one, else its commit, which the
|
|
815
|
+
* consumer maps to the pull requests whose head it is (a fork's checks name none, a commit on
|
|
816
|
+
* two pull requests names both).
|
|
817
|
+
*/
|
|
818
|
+
function checkTarget(repo, check) {
|
|
819
|
+
const [only, ...more] = check.pull_requests;
|
|
820
|
+
return only !== void 0 && more.length === 0 ? `${repo}:pull:${only.number}` : `${repo}:commit:${check.head_sha}`;
|
|
821
|
+
}
|
|
822
|
+
/** A comment's address: its pull request's when the issue is one, else the issue's. */
|
|
823
|
+
function commentTarget(repo, body) {
|
|
824
|
+
const { issue } = issueCommentEventSchema.parse(body);
|
|
825
|
+
return `${repo}:${issue.pull_request === void 0 || issue.pull_request === null ? "issue" : "pull"}:${issue.number}`;
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* The event's name: GitHub's `X-GitHub-Event` and, where the payload has one, its `action`
|
|
829
|
+
* (`pull_request.opened`, `issues.labeled`, `push`), so a pattern can name the action.
|
|
830
|
+
*/
|
|
831
|
+
function eventName(header, body) {
|
|
832
|
+
const action = body["action"];
|
|
833
|
+
return typeof action === "string" && action !== "" ? `${header}.${action}` : header;
|
|
834
|
+
}
|
|
835
|
+
function targetFor(event, body) {
|
|
836
|
+
const repo = stringField(recordOf(body["repository"]), "full_name");
|
|
837
|
+
const repoLabel = repo.length > 0 ? repo : "unknown";
|
|
838
|
+
switch (event) {
|
|
839
|
+
case "push": return `${repoLabel}:${pushBody(body).ref}`;
|
|
840
|
+
case "pull_request": return `${repoLabel}:pull:${pullRequestNumber(body)}`;
|
|
841
|
+
case "issues": return `${repoLabel}:issue:${issueNumber(body)}`;
|
|
842
|
+
case "workflow_run": return `${repoLabel}:run:${workflowBody(body).workflow_run.id}`;
|
|
843
|
+
case "issue_comment": return commentTarget(repoLabel, body);
|
|
844
|
+
case "pull_request_review":
|
|
845
|
+
case "pull_request_review_comment":
|
|
846
|
+
case "pull_request_review_thread": return `${repoLabel}:pull:${pullRequestNumber(body)}`;
|
|
847
|
+
case "check_suite": return checkTarget(repoLabel, checkSuiteEventSchema.parse(body).check_suite);
|
|
848
|
+
case "check_run": return checkTarget(repoLabel, checkRunEventSchema.parse(body).check_run);
|
|
849
|
+
case "status": return `${repoLabel}:commit:${statusEventSchema.parse(body).sha}`;
|
|
850
|
+
default: return `${repo}:${event}`;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
var GithubInstance = class {
|
|
854
|
+
options;
|
|
855
|
+
context;
|
|
856
|
+
actions;
|
|
857
|
+
tokenFor;
|
|
858
|
+
constructor(options, context) {
|
|
859
|
+
this.options = options;
|
|
860
|
+
this.context = context;
|
|
861
|
+
this.tokenFor = tokenSourceFor(options.auth);
|
|
862
|
+
this.actions = actionsFor(this.tokenFor, options.apiUrl);
|
|
863
|
+
}
|
|
864
|
+
async handleWebhook(request) {
|
|
865
|
+
const raw = new Uint8Array(await request.arrayBuffer());
|
|
866
|
+
if (!verifySignature(raw, request.headers.get(SIGNATURE_HEADER), this.context.secret)) return {
|
|
867
|
+
response: new Response(JSON.stringify({ error: "invalid signature" }), {
|
|
868
|
+
status: HTTP_UNAUTHORIZED,
|
|
869
|
+
headers: { "content-type": "application/json" }
|
|
870
|
+
}),
|
|
871
|
+
events: []
|
|
872
|
+
};
|
|
873
|
+
const event = request.headers.get("x-github-event") ?? "";
|
|
874
|
+
const schema = eventTable[event];
|
|
875
|
+
if (schema === void 0) return {
|
|
876
|
+
response: new Response(JSON.stringify({
|
|
877
|
+
accepted: true,
|
|
878
|
+
event
|
|
879
|
+
}), {
|
|
880
|
+
status: HTTP_OK,
|
|
881
|
+
headers: { "content-type": "application/json" }
|
|
882
|
+
}),
|
|
883
|
+
events: []
|
|
884
|
+
};
|
|
885
|
+
const parsed = JSON.parse(new TextDecoder().decode(raw));
|
|
886
|
+
if (typeof parsed !== "object" || parsed === null) return {
|
|
887
|
+
response: new Response(JSON.stringify({ error: "invalid payload" }), {
|
|
888
|
+
status: HTTP_BAD_REQUEST,
|
|
889
|
+
headers: { "content-type": "application/json" }
|
|
890
|
+
}),
|
|
891
|
+
events: []
|
|
892
|
+
};
|
|
893
|
+
const bodyRecord = recordOf(parsed);
|
|
894
|
+
const validated = schema.safeParse(bodyRecord);
|
|
895
|
+
if (!validated.success) return {
|
|
896
|
+
response: new Response(JSON.stringify({ error: "payload failed validation" }), {
|
|
897
|
+
status: HTTP_BAD_REQUEST,
|
|
898
|
+
headers: { "content-type": "application/json" }
|
|
899
|
+
}),
|
|
900
|
+
events: []
|
|
901
|
+
};
|
|
902
|
+
const body = recordOf(validated.data);
|
|
903
|
+
const repo = stringField(recordOf(body["repository"]), "full_name");
|
|
904
|
+
const allowlist = this.options.repos;
|
|
905
|
+
if (allowlist !== void 0 && allowlist.length > 0 && !allowlist.includes(repo)) return {
|
|
906
|
+
response: new Response(JSON.stringify({
|
|
907
|
+
accepted: true,
|
|
908
|
+
ignored: "repo"
|
|
909
|
+
}), {
|
|
910
|
+
status: HTTP_OK,
|
|
911
|
+
headers: { "content-type": "application/json" }
|
|
912
|
+
}),
|
|
913
|
+
events: []
|
|
914
|
+
};
|
|
915
|
+
const newEvent = {
|
|
916
|
+
event: eventName(event, body),
|
|
917
|
+
target: targetFor(event, body),
|
|
918
|
+
body
|
|
919
|
+
};
|
|
920
|
+
return {
|
|
921
|
+
response: new Response(JSON.stringify({ accepted: true }), {
|
|
922
|
+
status: HTTP_ACCEPTED,
|
|
923
|
+
headers: { "content-type": "application/json" }
|
|
924
|
+
}),
|
|
925
|
+
events: [newEvent]
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Declarative webhook registration: for each repo in `repos`, ensure a
|
|
930
|
+
* webhook pointing at the source's hook URL exists with
|
|
931
|
+
* the configured secret and event set. Idempotent: creating is a no-op
|
|
932
|
+
* when a hook with the same URL already exists; an existing hook is
|
|
933
|
+
* repaired (events/active) but foreign hooks are never touched.
|
|
934
|
+
*/
|
|
935
|
+
async start(context) {
|
|
936
|
+
if (this.options.registerWebhooks !== true) return;
|
|
937
|
+
await registerWebhooks({
|
|
938
|
+
tokenFor: this.tokenFor,
|
|
939
|
+
webhookSecret: this.context.secret,
|
|
940
|
+
eventsTable: events,
|
|
941
|
+
...this.options.apiUrl === void 0 ? {} : { apiUrl: this.options.apiUrl },
|
|
942
|
+
...this.options.repos === void 0 ? {} : { repos: this.options.repos },
|
|
943
|
+
...this.options.webhookEvents === void 0 ? {} : { webhookEvents: this.options.webhookEvents }
|
|
944
|
+
}, context);
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
/** The `github` adapter's definition, which a JSON config names as `"adapter": "github"`. */
|
|
948
|
+
const adapter = {
|
|
949
|
+
id: "github",
|
|
950
|
+
name: "GitHub",
|
|
951
|
+
samples,
|
|
952
|
+
optionsSchema: githubOptionsSchema,
|
|
953
|
+
events,
|
|
954
|
+
create: (options, context) => new GithubInstance(options, context)
|
|
955
|
+
};
|
|
956
|
+
/**
|
|
957
|
+
* The `github` adapter builder, for a source in a TypeScript config or an embedded app:
|
|
958
|
+
*
|
|
959
|
+
* sources: {
|
|
960
|
+
* github: github({ secret: env("GITHUB_WEBHOOK_SECRET"), auth: { kind: "token", token: env("GITHUB_TOKEN") } }),
|
|
961
|
+
* }
|
|
962
|
+
*
|
|
963
|
+
* `github.events` builds GitHub's deliveries, typed and signed the way GitHub signs:
|
|
964
|
+
* `send({ url, secret, delivery: github.events.pullRequest.opened({ repo: "acme/shop" }) })`.
|
|
965
|
+
*/
|
|
966
|
+
const github = Object.assign((input) => {
|
|
967
|
+
const { secret, ...options } = input;
|
|
968
|
+
return defineBinding({
|
|
969
|
+
id: "github",
|
|
970
|
+
events,
|
|
971
|
+
options,
|
|
972
|
+
secret,
|
|
973
|
+
definition: adapter,
|
|
974
|
+
actions: actionsFor(tokenSourceFor(options.auth), options.apiUrl)
|
|
975
|
+
});
|
|
976
|
+
}, { events: deliveries });
|
|
977
|
+
//#endregion
|
|
978
|
+
export { adapter, github, githubAppTokenSource, githubAuthSchema, githubOptionsSchema, signJwt };
|