Build a GitHub webhook receiver
An HTTPS endpoint that receives GitHub webhooks, checks each delivery's signature against a shared secret, and records the event in a SQLite database. The same shape works for any service that signs its webhooks with HMAC-SHA256.
It takes about fifteen minutes. If you haven't installed the CLI yet, do steps 1 and 2 of the quick start first (ribo install and ribo login). You also need a GitHub repository where you can change the settings.
How webhook signatures work
A webhook URL is public, so anyone who finds it can post to it. To prove a delivery came from GitHub, you give GitHub a secret when you create the webhook. GitHub computes an HMAC-SHA256 of each request body with that secret and sends it in the X-Hub-Signature-256 header as sha256= followed by the hex digest. Your code computes the same HMAC over the raw body it received and accepts the delivery only if the two match.
The check has to run on the body exactly as it arrived, before any JSON parsing, because re-serialized JSON won't produce the same bytes.
1. Create the database and the secret
mkdir gh-hooks && cd gh-hooks
ribo db create gh-eventsGenerate a secret, keep a copy for step 5, and store it in the Cell's vault:
openssl rand -hex 32
ribo vault set gh-hooks GITHUB_WEBHOOK_SECRETribo vault set prompts for the value with hidden input. Set it before the first deploy: a vault value that's missing at deploy time reaches the Cell as a placeholder string, and every real delivery would then fail the signature check with nothing to say why.
2. Write the config
ribo.toml
[cell]
name = "gh-hooks"
js = "./cell.js"
[[bindings]]
type = "c3"
binding = "DB"
database = "gh-events"
[[bindings]]
type = "vault"
binding = "GITHUB_WEBHOOK_SECRET"3. Write the Cell
cell.js
const SCHEMA = `
CREATE TABLE IF NOT EXISTS events (
delivery TEXT PRIMARY KEY,
event TEXT NOT NULL,
action TEXT,
repo TEXT,
sender TEXT,
received_at TEXT NOT NULL DEFAULT (datetime('now'))
)
`;
// A vault value that was never set arrives as this placeholder.
const VAULT_UNSET = "***REMOVED***";
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname !== "/github") return new Response("Not found", { status: 404 });
if (request.method !== "POST") return new Response("Method not allowed", { status: 405 });
const secret = env.GITHUB_WEBHOOK_SECRET;
if (typeof secret !== "string" || secret === "" || secret === VAULT_UNSET) {
return new Response("Webhook secret is not configured", { status: 503 });
}
// Verify the raw bytes before parsing anything.
const body = await request.arrayBuffer();
const signature = request.headers.get("x-hub-signature-256") ?? "";
if (!(await validSignature(secret, body, signature))) {
return new Response("Bad signature", { status: 401 });
}
const event = request.headers.get("x-github-event") ?? "unknown";
const delivery = request.headers.get("x-github-delivery") ?? crypto.randomUUID();
let payload;
try {
payload = JSON.parse(new TextDecoder().decode(body));
} catch {
return new Response("Set the webhook's content type to application/json", { status: 415 });
}
await env.DB.exec(SCHEMA);
// A redelivery from GitHub carries the same delivery id, so it is
// recorded once.
await env.DB.prepare(
"INSERT OR IGNORE INTO events (delivery, event, action, repo, sender) VALUES (?, ?, ?, ?, ?)"
).bind(
delivery,
event,
payload.action ?? null,
payload.repository?.full_name ?? null,
payload.sender?.login ?? null
).run();
return new Response("ok");
},
};
async function validSignature(secret, body, header) {
if (!header.startsWith("sha256=")) return false;
const hex = header.slice("sha256=".length);
if (!/^[0-9a-f]{64}$/.test(hex)) return false;
const sig = new Uint8Array(32);
for (let i = 0; i < 32; i++) sig[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["verify"]
);
// verify() compares in constant time, so a wrong signature takes as long to
// reject as a nearly right one.
return crypto.subtle.verify("HMAC", key, sig, body);
}The handler answers quickly and does one insert. GitHub expects a fast answer, so if you later add slow work (calling another API, sending a message), keep the insert in the request and do the rest from a scheduled pulse that reads new rows, or after the response with ctx.waitUntil().
4. Deploy
ribo deploydeployed gh-hooks
address 33ed412f8r6yb
kind js
url https://gh-hooks.strand-9c.tissue.dev
c3 DB→gh-events
vault GITHUB_WEBHOOK_SECRETBefore involving GitHub, check the signature code with a delivery you sign yourself:
HOOK=https://gh-hooks.strand-9c.tissue.dev/github # your url, plus /github
SECRET=... # the hex string from step 1
BODY='{"zen":"testing","repository":{"full_name":"me/test"}}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $NF}')
curl -s $HOOK -H "x-github-event: ping" -H "x-hub-signature-256: sha256=$SIG" \
-H 'content-type: application/json' -d "$BODY"
# ok
curl -s $HOOK -H "x-hub-signature-256: sha256=0000" -d "$BODY"
# Bad signature5. Connect GitHub
In the repository on GitHub, open Settings, then Webhooks, then Add webhook:
- Payload URL: your
urlwith/githubon the end - Content type:
application/json - Secret: the hex string from step 1
Choose which events to send, and save. GitHub sends a ping event straight away. Push a commit or open an issue, then look at what arrived:
ribo db exec gh-events "SELECT received_at, event, action, repo, sender FROM events ORDER BY received_at DESC LIMIT 20"GitHub's webhook settings page also lists each recent delivery with the response your Cell gave, which is the first place to look if a row is missing. A 401 there means the secret in GitHub and the one in the vault differ.
What you have
A public HTTPS webhook endpoint that rejects anything not signed with your secret and records every GitHub event once, by delivery id, in a SQLite table you can query. To change the secret, update it in GitHub and run ribo vault set gh-hooks GITHUB_WEBHOOK_SECRET with the same value.
If you'd rather keep the signing secret out of your code altogether and get retries and replay, Tissue Cloud's webhook inbox can sit in front of the Cell. A vesicle endpoint created with --verify github:GITHUB_WEBHOOK_SECRET checks the same header before it stores the delivery, then forwards it to the Cell's /github route, which can drop its own signature check.
Next steps
- Vesicle: webhook inbox: capture, verification, retries and replay
- What is a webhook?: the pattern in general
- c3 API reference
- Vault security: how secrets are stored and injected