Repository navigation
Expand file tree
/
Copy pathcloud-function.js
More file actions
54 lines (47 loc) · 1.91 KB
/
Copy pathcloud-function.js
File metadata and controls
54 lines (47 loc) · 1.91 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
/**
* @param {import('probot').Probot} probot
* @param {import('express').Request & { rawBody: Buffer }} request
* @param {import('express').Response} response
*/
export default async function cloudFunction (probot, request, response) {
// request.get() is case-insensitive (RFC 7230 §3.2 'Header Fields')
const id = request.get('x-github-delivery')
const name = request.get('x-github-event')
const signature = request.get('x-hub-signature-256')
const missingHeaders = []
if (!id) missingHeaders.push('X-GitHub-Delivery')
if (!name) missingHeaders.push('X-GitHub-Event')
if (!signature) missingHeaders.push('X-Hub-Signature-256')
if (missingHeaders.length > 0) {
return response.status(400).send({
error: `Missing required headers: ${missingHeaders.join(', ')}`
})
}
const rawPayload = request.rawBody?.toString('utf8') ?? ''
// Verify and parse separately from dispatch so only client errors get HTTP 400,
// even if an app handler throws an error carrying its own status.
let payload
try {
if (!rawPayload || !(await probot.webhooks.verify(rawPayload, signature))) {
console.error(`Webhook ${id} rejected: signature does not match event payload and secret`)
return response.status(400).send({ error: 'Webhook processing failed' })
}
} catch (err) {
// verify() only throws for missing configuration, such as an unset WEBHOOK_SECRET
console.error(err)
return response.status(500).send({ error: 'Webhook processing failed' })
}
try {
payload = JSON.parse(rawPayload)
} catch {
console.error(`Webhook ${id} rejected: invalid JSON`)
return response.status(400).send({ error: 'Webhook processing failed' })
}
try {
await probot.webhooks.receive({ id, name, payload })
} catch (err) {
console.error(err)
return response.status(500).send({ error: 'Webhook processing failed' })
}
return response.status(200).send({ ok: true })
}