Repository navigation
Expand file tree
/
Copy pathwebhook.ts
More file actions
367 lines (340 loc) · 11.1 KB
/
Copy pathwebhook.ts
File metadata and controls
367 lines (340 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/**
* Phase 5.4 — opt-in GitHub webhook listener (issue #199).
*
* The poll loop stays the default: without `--webhook-port` nothing here
* runs. With it, `watchMain` starts this listener ALONGSIDE the poll loop —
* the webhook is the fast path, the poll is the reconciliation path. Both
* funnel through the SAME `watchIssues` run-once sweep, so the state file
* remains the single idempotency source of truth and the
* maxConcurrentSessions cap is enforced identically for webhook-triggered
* and poll-triggered spawns (webhooks are at-least-once: a duplicated
* `issues.labeled` delivery is just another sweep that skips an already
* processed issue — see docs/phase5-issue-watcher.md "Webhook upgrade path").
*
* Exactly one route: `POST /hooks/github`. Authenticity is HMAC-SHA256 over
* the raw body (`X-Hub-Signature-256: sha256=<hex>`) against the
* `HEADLESSCODE_WEBHOOK_SECRET` env secret, compared with a constant-time
* compare. The secret never appears in logs, state files, or responses.
*/
import { createHmac, timingSafeEqual } from "node:crypto"
import {
createServer,
type IncomingMessage,
type Server,
type ServerResponse,
} from "node:http"
import type { Logger } from "../engine/logger.js"
import { createGhClient, type GhClient, type GitHubIssue } from "./github.js"
import { watchIssues, type WatcherConfig, type WatchResult } from "./watch.js"
/** The only route this listener serves. */
export const WEBHOOK_ROUTE = "/hooks/github"
/**
* Env var carrying the shared webhook secret (never a CLI flag:
* command lines are visible via ps).
*/
export const WEBHOOK_SECRET_ENV = "HEADLESSCODE_WEBHOOK_SECRET"
/**
* Default bind address: loopback only (a public URL is
* the operator's reverse proxy to provide).
*/
export const DEFAULT_WEBHOOK_HOST = "127.0.0.1"
/**
* Largest accepted delivery body (GitHub issues payloads
* are ~10KB; this bounds abuse).
*/
const MAX_BODY_BYTES = 1_048_576
// ─── Signature verification ─────────────────────────────────────────────────
/**
* Verify `X-Hub-Signature-256: sha256=<hex>` against `secret` with a
* constant-time compare. False on a missing/malformed header, a hex/length
* mismatch, or a wrong MAC — never throws.
*/
export function verifyWebhookSignature(
rawBody: Buffer,
signatureHeader: string | null | undefined,
secret: string,
): boolean {
if (!secret || !signatureHeader) {
return false
}
const match = /^sha256=([0-9a-fA-F]+)$/.exec(signatureHeader.trim())
if (!match) {
return false
}
let actual: Buffer
try {
actual = Buffer.from(match[1], "hex")
} catch {
return false
}
const expected = createHmac("sha256", secret).update(rawBody).digest()
if (actual.length !== expected.length) {
return false
}
return timingSafeEqual(actual, expected)
}
// ─── Payload → poller issue ─────────────────────────────────────────────────
/**
* Convert a GitHub `issues` webhook payload into the SAME `GitHubIssue`
* shape the poll path hands to `splitIssues`, but ONLY when the delivery is
* actionable: `action === "labeled"` AND the added label is the watcher's
* target label. Everything else returns null (acknowledged, ignored).
*/
/** Label names from a GitHub `labels` array (objects or strings). */
function labelNames(labels: Array<unknown>): string[] {
return labels
.map((l) => (typeof l === "string" ? l : labelName(l)))
.filter((l): l is string => typeof l === "string")
}
function labelName(value: unknown): unknown {
if (value !== null && typeof value === "object") {
return (value as Record<string, unknown>).name
}
return undefined
}
export function webhookIssueForLabel(
payload: unknown,
targetLabel: string,
): GitHubIssue | null {
if (
payload === null ||
typeof payload !== "object" ||
Array.isArray(payload)
) {
return null
}
const event = payload as Record<string, unknown>
if (event.action !== "labeled") {
return null
}
const label = event.label as Record<string, unknown> | undefined
if (!label || label.name !== targetLabel) {
return null
}
const raw = event.issue as Record<string, unknown> | undefined
if (!raw || typeof raw !== "object") {
return null
}
const number = Number(raw.number)
if (!Number.isInteger(number) || number <= 0) {
return null
}
const labels = Array.isArray(raw.labels)
? labelNames(raw.labels as Array<unknown>)
: []
const issue: GitHubIssue = {
number,
title: typeof raw.title === "string" ? raw.title : `issue ${number}`,
...(typeof raw.body === "string" ? { body: raw.body } : {}),
labels,
...(typeof raw.updated_at === "string" ? { updated_at: raw.updated_at } : {}),
...(typeof raw.html_url === "string" ? { html_url: raw.html_url } : {}),
}
return issue
}
// ─── Poller reuse: the webhook is a thin trigger ────────────────────────────
function singleIssueClient(
base: WatcherConfig,
issue: GitHubIssue,
): GhClient {
const fallback =
base.gh ??
createGhClient({ token: base.token, baseUrl: base.ghBaseUrl })
return { ...fallback, listIssues: async () => [issue] }
}
/**
* Build the delivery trigger: one `watchIssues` run-once sweep whose GitHub
* client returns just the webhook issue. Idempotency state
* (load/markProcessed/save), the maxPerSweep + maxConcurrentSessions caps,
* spawn, and onBatch are ALL the poller's — zero duplicated logic. The
* poll loop's abort signal is NOT inherited: a shutdown-initiated abort must
* not instantly break an in-flight delivery (the server stops accepting new
* ones via close() instead). `dryRun` IS inherited, so a dry-run base can
* never spawn through this trigger.
*/
export function createWatcherWebhookTrigger(
base: WatcherConfig,
): (issue: GitHubIssue) => Promise<WatchResult> {
return (issue: GitHubIssue) => {
const gh = singleIssueClient(base, issue)
return watchIssues({ ...base, gh, runOnce: true, signal: undefined })
}
}
// ─── HTTP listener (one route) ──────────────────────────────────────────────
export interface WebhookServerOptions {
/** TCP port to listen on (required — the listener is opt-in). */
port: number
/** Bind address (default: 127.0.0.1 loopback). */
host?: string
/**
* Shared secret; defaults to $HEADLESSCODE_WEBHOOK_SECRET.
* Empty → throws (fail closed).
*/
secret?: string
/**
* The watcher's target label (only matching
* `labeled` deliveries dispatch).
*/
targetLabel: string
/** Dispatch one actionable issue (usually createWatcherWebhookTrigger). */
trigger: (issue: GitHubIssue) => Promise<WatchResult>
/** Optional logger for dispatch/ignore lines (never logs the secret). */
logger?: Logger
}
export interface WebhookServer {
host: string
port: number
close(): Promise<void>
}
function readBody(req: IncomingMessage, maxBytes: number): Promise<Buffer> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = []
let size = 0
let settled = false
req.on("data", (chunk: Buffer) => {
if (settled) {
return
}
size += chunk.length
if (size > maxBytes) {
settled = true
reject(new Error(`delivery body exceeds ${maxBytes} bytes`))
return
}
chunks.push(chunk)
})
req.on("end", () => {
if (!settled) {
settled = true
resolve(Buffer.concat(chunks))
}
})
req.on("error", (error) => {
if (!settled) {
settled = true
reject(error)
}
})
})
}
function respond(
res: ServerResponse,
status: number,
body: Record<string, unknown>,
): void {
const text = JSON.stringify(body)
res.writeHead(status, {
"content-type": "application/json",
"content-length": Buffer.byteLength(text),
})
res.end(text)
}
function resolveSecret(explicit?: string): string {
const secret = explicit ?? process.env[WEBHOOK_SECRET_ENV] ?? ""
if (!secret) {
throw new Error(
`webhook listener requires a shared secret: set ${WEBHOOK_SECRET_ENV}`,
)
}
return secret
}
/**
* Start the opt-in listener. Resolves once the socket is bound; `close()`
* stops accepting deliveries and resolves when in-flight ones finish.
* Deliveries are serialized through a promise chain so two concurrent
* deliveries never interleave their state-file read/modify/write cycles.
*/
interface DeliveryDeps {
secret: string
targetLabel: string
trigger: WebhookServerOptions["trigger"]
logger: Logger | undefined
}
async function handleDelivery(
req: IncomingMessage,
res: ServerResponse,
deps: DeliveryDeps,
): Promise<void> {
const url = (req.url ?? "").split("?")[0]
if (req.method !== "POST" || url !== WEBHOOK_ROUTE) {
respond(res, 404, { ok: false, error: "not found" })
return
}
let raw: Buffer
try {
raw = await readBody(req, MAX_BODY_BYTES)
} catch {
respond(res, 413, { ok: false, error: "delivery too large" })
return
}
const signature = req.headers["x-hub-signature-256"]
const header = Array.isArray(signature) ? signature[0] : signature
if (!verifyWebhookSignature(raw, header ?? null, deps.secret)) {
respond(res, 401, { ok: false, error: "invalid signature" })
return
}
let payload: unknown
try {
payload = JSON.parse(raw.toString("utf-8"))
} catch {
respond(res, 400, { ok: false, error: "invalid JSON" })
return
}
const issue = webhookIssueForLabel(payload, deps.targetLabel)
if (!issue) {
deps.logger?.info("webhook: delivery ignored (not labeled)", {})
respond(res, 200, { ok: true, ignored: true })
return
}
try {
const result = await deps.trigger(issue)
const spawned = result.sweeps.reduce((n, sweep) => n + sweep.spawned, 0)
deps.logger?.info(
`webhook: issue #${issue.number} swept (${spawned} spawned)`,
{},
)
respond(res, 200, { ok: true, ignored: false, spawned })
} catch (error) {
const reason = error instanceof Error ? error.message : String(error)
deps.logger?.error(`webhook: sweep #${issue.number} failed: ${reason}`, {})
respond(res, 500, { ok: false, error: "sweep failed" })
}
}
export async function startWebhookServer(
options: WebhookServerOptions,
): Promise<WebhookServer> {
const secret = resolveSecret(options.secret)
const host = options.host ?? DEFAULT_WEBHOOK_HOST
const deps: DeliveryDeps = {
secret,
targetLabel: options.targetLabel,
trigger: options.trigger,
logger: options.logger,
}
let chain: Promise<void> = Promise.resolve()
const server: Server = createServer((req, res) => {
const pending = chain.then(() => handleDelivery(req, res, deps))
chain = pending.catch(() => undefined)
pending.catch(() => undefined)
})
await new Promise<void>((resolve, reject) => {
server.once("error", reject)
server.listen(options.port, host, () => {
server.off("error", reject)
resolve()
})
})
const address = server.address()
if (!address || typeof address === "string") {
server.close()
throw new Error("webhook listener bound to an unexpected address")
}
return {
host,
port: address.port,
close: () =>
new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()))
}),
}
}