{"name":"github-webhooks","title":"GitHub webhooks","description":"Adopt and manage GitHub webhook handling in an app: endpoint setup, signature verification, event routing, and a working reference for every event type you route. Use when an app has to react to activity on a GitHub repository or organization, an endpoint is gaining an event type or its verification is in doubt, or deliveries are lost, time out or are processed twice. Not for outbound GitHub API calls, Actions workflow triggers or polling.","compatibility":"Any server that can expose one publicly reachable HTTPS route and read a raw request body. Verification needs an HMAC-SHA256 primitive and a constant-time comparison, both of which every mainstream runtime has in its standard library. Repository, organization, and GitHub App webhooks are all covered; App webhooks differ only in where the hook is configured and in the extra installation fields on the payload. Local delivery testing assumes the GitHub CLI.","allowedTools":"Read Write Edit Grep Glob Bash","license":"MIT","kind":"signals","useWhen":"receiving, verifying or replaying GitHub webhook deliveries","group":"workflow","lifecycle":"release","version":"1.0.1","author":"crissmoldovan","install":["npx skills add crissmoldovan/agent-skills --skill github-webhooks"],"asks":["Set up GitHub webhook handling in this app. Audit anything that exists first,\nthen implement the endpoint: raw body, HMAC-SHA256 verification with a\nconstant-time compare, routing on the event header plus action, and a handler\nthat enqueues. Only subscribe to pull_request and push for now.","We already receive pull_request events but the handler returns early unless the\ntitle matches our ticket convention. I need every merged PR. Show me how many\ndeliveries that filter discards, then add a second consumer beside it rather\nthan inside it.","Add check_run to our event map. Route only completed check runs whose conclusion\nis failure or timed_out, on the default branch, and tell me which payload fields\nthe predicate reads."],"commands":[],"documents":[{"path":"references/event-types.md","slug":"event-types","title":"GitHub webhook event reference","body":"# GitHub webhook event reference\n\nThe events worth routing, their activity types, the payload fields that carry the\nmeaning, and when you would subscribe. Field paths are relative to the JSON body\nunless stated otherwise.\n\nVerify field names against the current GitHub documentation before shipping a\npredicate that depends on one. GitHub adds activity types and payload fields over\ntime; a router that returns 200 for anything it does not recognise stays correct\nwhen it does.\n\n## Delivery envelope\n\nEvery delivery carries these headers:\n\n| Header | Contents |\n|---|---|\n| `X-GitHub-Event` | The event name — `pull_request`, `push`, `ping`, … |\n| `X-GitHub-Delivery` | A GUID for the delivery. Log it; do not use it as a uniqueness key. |\n| `X-Hub-Signature-256` | `sha256=` followed by the hex HMAC-SHA256 of the raw body. This is the one to verify. |\n| `X-Hub-Signature` | The legacy SHA-1 signature. Present for compatibility. Do not accept it as an alternative. |\n| `X-GitHub-Hook-ID` | The id of the hook that produced the delivery. |\n| `X-GitHub-Hook-Installation-Target-Type` | `repository`, `organization`, `integration`, … |\n| `X-GitHub-Hook-Installation-Target-ID` | The id of that target. |\n| `User-Agent` | `GitHub-Hookshot/` plus a build identifier. |\n\nAlmost every payload also carries `repository` (with `full_name`, `default_branch`,\n`private`), `sender` (the user who caused it), `organization` for org-owned\nrepositories, and `installation` for GitHub App deliveries. The per-event sections\nbelow list only what is specific to the event.\n\nTwo structural facts a router depends on:\n\n- **Most events carry an `action` field**; some do not. `push`, `status`,\n  `create`, `delete`, `fork`, `gollum`, `public`, and `ping` have none.\n- **`ping`** is delivered once when the hook is created. Payload: `zen` (a random\n  aphorism), `hook_id`, and `hook` — the hook's own configuration, including its\n  subscribed `events` and its target URL. Answer it 200.\n\n## Pull requests and review\n\n### `pull_request`\n\n**Actions:** `opened`, `edited`, `closed`, `reopened`, `assigned`, `unassigned`,\n`review_requested`, `review_request_removed`, `labeled`, `unlabeled`,\n`synchronize`, `converted_to_draft`, `ready_for_review`, `locked`, `unlocked`,\n`milestoned`, `demilestoned`, `auto_merge_enabled`, `auto_merge_disabled`,\n`enqueued`, `dequeued`.\n\n**Fields that matter:**\n\n- `number` — the pull request number. With `repository.full_name` this is the\n  natural key for deduplication.\n- `pull_request.merged` — boolean. **The only way to tell a merge from a plain\n  close**; both arrive as `action: \"closed\"`.\n- `pull_request.merged_at`, `pull_request.merge_commit_sha`,\n  `pull_request.merged_by.login` — populated only on a merge.\n- `pull_request.base.ref` / `pull_request.head.ref` / `pull_request.head.sha` —\n  the branches and the commit the checks ran against.\n- `pull_request.title`, `pull_request.body`, `pull_request.labels[].name`,\n  `pull_request.draft`, `pull_request.html_url`, `pull_request.user.login`.\n- `pull_request.additions`, `pull_request.deletions`,\n  `pull_request.changed_files` — size of the change, without a second API call.\n- `changes` — on `edited` only, e.g. `changes.title.from`, `changes.body.from`.\n\n**Route it when:** you care about proposed or merged work. This is the event a\nrelease ledger captures, filtered to `action === \"closed\" && pull_request.merged`.\n\n### `pull_request_review`\n\n**Actions:** `submitted`, `edited`, `dismissed`.\n\n**Fields that matter:** `review.state` (`approved`, `changes_requested`,\n`commented`, `dismissed`), `review.body`, `review.user.login`, `review.commit_id`,\n`review.submitted_at`, `review.html_url`, and the whole `pull_request` object.\n\n`review.state` arrives lower-cased in the webhook payload where the REST API\nreturns it upper-cased. Normalise before comparing.\n\n**Route it when:** approvals gate something of yours — a deployment, a merge bot,\na review-latency metric.\n\n### `pull_request_review_comment`\n\n**Actions:** `created`, `edited`, `deleted`.\n\n**Fields that matter:** `comment.body`, `comment.path`, `comment.line` and\n`comment.start_line`, `comment.side`, `comment.diff_hunk`, `comment.commit_id`,\n`comment.in_reply_to_id`, `comment.pull_request_review_id`, `comment.user.login`,\nplus `pull_request`.\n\n**Route it when:** you need line-anchored review discussion — a bot replying in a\nthread, or mining where review effort concentrates. Note that comments on the pull\nrequest as a whole are `issue_comment`, not this event.\n\n## Commits and refs\n\n### `push`\n\n**No actions.**\n\n**Fields that matter:**\n\n- `ref` — the full ref, e.g. `refs/heads/main` or `refs/tags/v2.1.0`.\n- `before` / `after` — the SHAs bracketing the push. `after` of all zeros means\n  the ref was deleted.\n- `created`, `deleted`, `forced` — booleans describing what happened to the ref.\n- `base_ref` — the ref the branch was created from, when `created` is true.\n- `commits[]` — each with `id`, `message`, `timestamp`, `url`, `author`, and the\n  `added` / `removed` / `modified` path arrays. **Truncated for large pushes**;\n  read the range from the API if you need all of them.\n- `head_commit` — the last commit of the push, or null when the ref was deleted.\n- `pusher.name`, `compare`.\n\n**Route it when:** you react to commits rather than to pull requests — tag\nreleases, direct pushes to a protected branch, path-triggered rebuilds.\n\n### `create`\n\n**No actions.** Fields: `ref`, `ref_type` (`branch` or `tag`), `master_branch`,\n`description`, `pusher_type`.\n\n**Route it when:** you want tag creation without parsing `push` refs, or you track\nbranch creation. It does not fire for a repository's initial branch creation.\n\n### `delete`\n\n**No actions.** Fields: `ref`, `ref_type`, `pusher_type`.\n\n**Route it when:** you keep per-branch state — preview environments, ephemeral\ndatabases — and need to tear it down.\n\n## Issues\n\n### `issues`\n\n**Actions:** `opened`, `edited`, `deleted`, `transferred`, `pinned`, `unpinned`,\n`closed`, `reopened`, `assigned`, `unassigned`, `labeled`, `unlabeled`, `locked`,\n`unlocked`, `milestoned`, `demilestoned`.\n\n**Fields that matter:** `issue.number`, `issue.title`, `issue.body`,\n`issue.state`, `issue.state_reason` (`completed`, `not_planned`, `reopened`),\n`issue.labels[].name`, `issue.assignees[].login`, `issue.user.login`,\n`issue.html_url`; plus `label` on the label actions, `assignee` on the assignment\nactions, and `changes` on `edited`.\n\n**Route it when:** you mirror issues into another tracker, or you drive workflow\nfrom labels.\n\n### `issue_comment`\n\n**Actions:** `created`, `edited`, `deleted`.\n\n**Fields that matter:** `comment.body`, `comment.id`, `comment.user.login`,\n`comment.html_url`, `comment.created_at`; `issue.number`; and critically\n**`issue.pull_request`** — present only when the commented-on issue is a pull\nrequest. That key is how you tell the two apart, because GitHub delivers pull\nrequest conversation comments as `issue_comment`.\n\n**Route it when:** you implement comment commands (`/deploy`, `/rerun`) or thread\nmirroring. Guard on `issue.pull_request` first.\n\n## Checks and status\n\n### `check_run`\n\n**Actions:** `created`, `completed`, `rerequested`, `requested_action`.\n\n**Fields that matter:** `check_run.name`, `check_run.head_sha`,\n`check_run.status` (`queued`, `in_progress`, `completed`), `check_run.conclusion`\n(`success`, `failure`, `neutral`, `cancelled`, `timed_out`, `action_required`,\n`stale`, `skipped`), `check_run.started_at` / `completed_at`,\n`check_run.output.title` and `output.summary`, `check_run.details_url`,\n`check_run.pull_requests[]`, `check_run.app.slug` (which integration produced it),\nand `requested_action.identifier` on `requested_action`.\n\n**Route it when:** you react to an individual check — posting a failure summary,\nrerunning a flaky job, gating on one named check rather than the whole suite.\n\n### `check_suite`\n\n**Actions:** `completed`, `requested`, `rerequested`.\n\n**Fields that matter:** `check_suite.head_branch`, `check_suite.head_sha`,\n`check_suite.status`, `check_suite.conclusion`, `check_suite.before` /\n`check_suite.after`, `check_suite.pull_requests[]`,\n`check_suite.latest_check_runs_count`, `check_suite.app.slug`.\n\n**Route it when:** you want one signal per commit rather than one per check. A\nGitHub App uses `requested` and `rerequested` as its cue to create check runs.\n\n### `status`\n\n**No actions.** This is the older Commit Status API, which many external CI\nsystems still write to.\n\n**Fields that matter:** `sha`, `context` (the status name, e.g.\n`ci/build`), `state` (`pending`, `success`, `failure`, `error`), `description`,\n`target_url`, `branches[]` (the branches whose head is this commit), `commit`.\n\n**Route it when:** an integration you depend on reports through statuses rather\nthan checks. Do not route both `status` and `check_run` for the same signal\nwithout deduplicating — some tools emit both.\n\n## Actions and deployment\n\n### `workflow_run`\n\n**Actions:** `requested`, `in_progress`, `completed`.\n\n**Fields that matter:** `workflow_run.name`, `workflow_run.head_branch`,\n`workflow_run.head_sha`, `workflow_run.event` (what triggered the workflow),\n`workflow_run.status`, `workflow_run.conclusion`, `workflow_run.run_number`,\n`workflow_run.run_attempt`, `workflow_run.workflow_id`, `workflow_run.html_url`,\n`workflow_run.pull_requests[]`, and the `workflow` object with the workflow's\n`path`.\n\n**Route it when:** you need whole-workflow outcomes outside Actions — a release\ngate, a notification on a failing scheduled workflow, or the fact that a deploy\nworkflow finished.\n\n### `workflow_job`\n\n**Actions:** `queued`, `in_progress`, `completed`, `waiting`.\n\n**Fields that matter:** `workflow_job.run_id` (joins back to `workflow_run`),\n`workflow_job.workflow_name`, `workflow_job.name`, `workflow_job.head_sha`,\n`workflow_job.status`, `workflow_job.conclusion`, `workflow_job.labels[]` (the\n`runs-on` labels), `workflow_job.runner_name`, `workflow_job.steps[]`,\n`workflow_job.started_at` / `completed_at`.\n\n**Route it when:** you autoscale self-hosted runners — `queued` with the requested\nlabels is the scale-up trigger — or you measure per-job queue time.\n\n### `deployment`\n\n**Actions:** `created`.\n\n**Fields that matter:** `deployment.id`, `deployment.sha`, `deployment.ref`,\n`deployment.environment`, `deployment.task`, `deployment.description`,\n`deployment.payload` (the arbitrary object the creator attached),\n`deployment.creator.login`, `deployment.production_environment` and\n`deployment.transient_environment`.\n\n**Route it when:** an external deployer listens for deployment requests. The\ndeployment record is a *request*; the outcome arrives as `deployment_status`.\n\n### `deployment_status`\n\n**Actions:** `created`.\n\n**Fields that matter:** `deployment_status.state` (`queued`, `pending`,\n`in_progress`, `success`, `failure`, `error`, `inactive`),\n`deployment_status.environment`, `deployment_status.environment_url`,\n`deployment_status.log_url`, `deployment_status.description`,\n`deployment_status.creator.login`, plus the originating `deployment` object.\n\n**Route it when:** you announce deployments or gate on one having succeeded.\n`state === \"success\"` on the environment you care about is the usual predicate.\n\n## Distribution\n\n### `release`\n\n**Actions:** `published`, `unpublished`, `created`, `edited`, `deleted`,\n`prereleased`, `released`.\n\n**Fields that matter:** `release.tag_name`, `release.name`, `release.body` (the\nrelease notes, markdown), `release.draft`, `release.prerelease`,\n`release.target_commitish`, `release.published_at`, `release.html_url`,\n`release.assets[]` (each with `name`, `size`, `download_count`,\n`browser_download_url`), `release.author.login`, and `changes` on `edited`.\n\n**Route it when:** you announce releases or trigger downstream publication.\n`published` fires for both a release and a prerelease; `released` fires only for a\nnon-prerelease, so pick according to whether prereleases should be announced.\n\n### `package`\n\n**Actions:** `published`, `updated`.\n\n**Fields that matter:** `package.name`, `package.namespace`,\n`package.package_type` (`npm`, `container`, `maven`, …), `package.owner.login`,\nand `package.package_version` with its `version`, `target_commitish`, and\n`html_url`.\n\n**Route it when:** publishing an artifact should trigger something downstream —\na deployment, an internal registry mirror, a version bump elsewhere.\n\n## Discussion and community\n\n### `discussion`\n\n**Actions include:** `created`, `edited`, `deleted`, `pinned`, `unpinned`,\n`locked`, `unlocked`, `transferred`, `category_changed`, `labeled`, `unlabeled`,\n`answered`, `unanswered`.\n\n**Fields that matter:** `discussion.number`, `discussion.title`,\n`discussion.body`, `discussion.category.name` and `category.slug`,\n`discussion.state`, `discussion.answer_html_url`, `discussion.user.login`, and\n`answer` on the `answered` action.\n\n**Route it when:** you mirror community Q&A, or route new discussions in a\nparticular category to a team.\n\n### `fork`\n\n**No actions.** Fields: `forkee` — the complete repository object of the new fork,\nincluding `full_name`, `owner.login`, and `private`.\n\n**Route it when:** you track downstream copies of a repository. Nothing else fires\non a fork.\n\n### `star`\n\n**Actions:** `created`, `deleted`.\n\n**Fields that matter:** `starred_at` — the timestamp on `created`, null on\n`deleted` — and `sender.login`, the user who starred.\n\n**Route it when:** you track repository popularity. The older `watch` event\n(single action `started`) fires for the same user action and is still delivered;\nsubscribe to one of the two, not both.\n\n## Administration\n\n### `member`\n\n**Actions:** `added`, `edited`, `removed`.\n\n**Fields that matter:** `member.login`, `member.id`, `repository.full_name`, and\n`changes` — carrying the permission that was assigned or changed, present on\n`edited` and on `added` when a role was specified.\n\n**Route it when:** repository collaborator changes must be mirrored into your own\naccess model, or audited.\n\n### `repository`\n\n**Actions:** `created`, `deleted`, `archived`, `unarchived`, `edited`, `renamed`,\n`transferred`, `publicized`, `privatized`.\n\n**Fields that matter:** the full `repository` object — `full_name`,\n`default_branch`, `private`, `archived`, `topics[]` — and `changes`, which on\n`renamed` carries the previous name and on `edited` carries the previous default\nbranch, description, homepage, or topics.\n\n**Route it when:** you keep a repository inventory. `renamed` and `transferred`\nare the two that break anything keyed on `full_name`, which is why keying on\n`repository.id` is safer.\n\n## Choosing a subscription set\n\nSubscribe to the smallest set that answers your questions:\n\n| You want | Subscribe to |\n|---|---|\n| Merged work, for a changelog or ledger | `pull_request` |\n| Commits, including direct pushes and tags | `push` |\n| Release announcements | `release` |\n| CI outcome per commit | `check_suite`, or `status` for older integrations |\n| CI outcome per named job | `check_run` |\n| Deployment outcomes | `deployment_status` |\n| Comment-driven commands | `issue_comment` |\n| Repository inventory | `repository`, `create`, `delete` |\n\nEverything else is volume you will discard. Add an event when a handler for it\nexists, not before.\n","bodyHtml":"<h2 id=\"github-webhook-event-reference\">GitHub webhook event reference</h2>\n<p>The events worth routing, their activity types, the payload fields that carry the\nmeaning, and when you would subscribe. Field paths are relative to the JSON body\nunless stated otherwise.</p>\n<p>Verify field names against the current GitHub documentation before shipping a\npredicate that depends on one. GitHub adds activity types and payload fields over\ntime; a router that returns 200 for anything it does not recognise stays correct\nwhen it does.</p>\n<h3 id=\"delivery-envelope\">Delivery envelope</h3>\n<p>Every delivery carries these headers:</p>\n<table>\n<thead>\n<tr>\n<th>Header</th>\n<th>Contents</th>\n</tr>\n</thead>\n<tbody><tr>\n<td><code>X-GitHub-Event</code></td>\n<td>The event name — <code>pull_request</code>, <code>push</code>, <code>ping</code>, …</td>\n</tr>\n<tr>\n<td><code>X-GitHub-Delivery</code></td>\n<td>A GUID for the delivery. Log it; do not use it as a uniqueness key.</td>\n</tr>\n<tr>\n<td><code>X-Hub-Signature-256</code></td>\n<td><code>sha256=</code> followed by the hex HMAC-SHA256 of the raw body. This is the one to verify.</td>\n</tr>\n<tr>\n<td><code>X-Hub-Signature</code></td>\n<td>The legacy SHA-1 signature. Present for compatibility. Do not accept it as an alternative.</td>\n</tr>\n<tr>\n<td><code>X-GitHub-Hook-ID</code></td>\n<td>The id of the hook that produced the delivery.</td>\n</tr>\n<tr>\n<td><code>X-GitHub-Hook-Installation-Target-Type</code></td>\n<td><code>repository</code>, <code>organization</code>, <code>integration</code>, …</td>\n</tr>\n<tr>\n<td><code>X-GitHub-Hook-Installation-Target-ID</code></td>\n<td>The id of that target.</td>\n</tr>\n<tr>\n<td><code>User-Agent</code></td>\n<td><code>GitHub-Hookshot/</code> plus a build identifier.</td>\n</tr>\n</tbody></table>\n<p>Almost every payload also carries <code>repository</code> (with <code>full_name</code>, <code>default_branch</code>,\n<code>private</code>), <code>sender</code> (the user who caused it), <code>organization</code> for org-owned\nrepositories, and <code>installation</code> for GitHub App deliveries. The per-event sections\nbelow list only what is specific to the event.</p>\n<p>Two structural facts a router depends on:</p>\n<ul>\n<li><strong>Most events carry an <code>action</code> field</strong>; some do not. <code>push</code>, <code>status</code>,\n<code>create</code>, <code>delete</code>, <code>fork</code>, <code>gollum</code>, <code>public</code>, and <code>ping</code> have none.</li>\n<li><strong><code>ping</code></strong> is delivered once when the hook is created. Payload: <code>zen</code> (a random\naphorism), <code>hook_id</code>, and <code>hook</code> — the hook&#39;s own configuration, including its\nsubscribed <code>events</code> and its target URL. Answer it 200.</li>\n</ul>\n<h3 id=\"pull-requests-and-review\">Pull requests and review</h3>\n<h4 id=\"pull_request\"><code>pull_request</code></h4>\n<p><strong>Actions:</strong> <code>opened</code>, <code>edited</code>, <code>closed</code>, <code>reopened</code>, <code>assigned</code>, <code>unassigned</code>,\n<code>review_requested</code>, <code>review_request_removed</code>, <code>labeled</code>, <code>unlabeled</code>,\n<code>synchronize</code>, <code>converted_to_draft</code>, <code>ready_for_review</code>, <code>locked</code>, <code>unlocked</code>,\n<code>milestoned</code>, <code>demilestoned</code>, <code>auto_merge_enabled</code>, <code>auto_merge_disabled</code>,\n<code>enqueued</code>, <code>dequeued</code>.</p>\n<p><strong>Fields that matter:</strong></p>\n<ul>\n<li><code>number</code> — the pull request number. With <code>repository.full_name</code> this is the\nnatural key for deduplication.</li>\n<li><code>pull_request.merged</code> — boolean. <strong>The only way to tell a merge from a plain\nclose</strong>; both arrive as <code>action: &quot;closed&quot;</code>.</li>\n<li><code>pull_request.merged_at</code>, <code>pull_request.merge_commit_sha</code>,\n<code>pull_request.merged_by.login</code> — populated only on a merge.</li>\n<li><code>pull_request.base.ref</code> / <code>pull_request.head.ref</code> / <code>pull_request.head.sha</code> —\nthe branches and the commit the checks ran against.</li>\n<li><code>pull_request.title</code>, <code>pull_request.body</code>, <code>pull_request.labels[].name</code>,\n<code>pull_request.draft</code>, <code>pull_request.html_url</code>, <code>pull_request.user.login</code>.</li>\n<li><code>pull_request.additions</code>, <code>pull_request.deletions</code>,\n<code>pull_request.changed_files</code> — size of the change, without a second API call.</li>\n<li><code>changes</code> — on <code>edited</code> only, e.g. <code>changes.title.from</code>, <code>changes.body.from</code>.</li>\n</ul>\n<p><strong>Route it when:</strong> you care about proposed or merged work. This is the event a\nrelease ledger captures, filtered to <code>action === &quot;closed&quot; &amp;&amp; pull_request.merged</code>.</p>\n<h4 id=\"pull_request_review\"><code>pull_request_review</code></h4>\n<p><strong>Actions:</strong> <code>submitted</code>, <code>edited</code>, <code>dismissed</code>.</p>\n<p><strong>Fields that matter:</strong> <code>review.state</code> (<code>approved</code>, <code>changes_requested</code>,\n<code>commented</code>, <code>dismissed</code>), <code>review.body</code>, <code>review.user.login</code>, <code>review.commit_id</code>,\n<code>review.submitted_at</code>, <code>review.html_url</code>, and the whole <code>pull_request</code> object.</p>\n<p><code>review.state</code> arrives lower-cased in the webhook payload where the REST API\nreturns it upper-cased. Normalise before comparing.</p>\n<p><strong>Route it when:</strong> approvals gate something of yours — a deployment, a merge bot,\na review-latency metric.</p>\n<h4 id=\"pull_request_review_comment\"><code>pull_request_review_comment</code></h4>\n<p><strong>Actions:</strong> <code>created</code>, <code>edited</code>, <code>deleted</code>.</p>\n<p><strong>Fields that matter:</strong> <code>comment.body</code>, <code>comment.path</code>, <code>comment.line</code> and\n<code>comment.start_line</code>, <code>comment.side</code>, <code>comment.diff_hunk</code>, <code>comment.commit_id</code>,\n<code>comment.in_reply_to_id</code>, <code>comment.pull_request_review_id</code>, <code>comment.user.login</code>,\nplus <code>pull_request</code>.</p>\n<p><strong>Route it when:</strong> you need line-anchored review discussion — a bot replying in a\nthread, or mining where review effort concentrates. Note that comments on the pull\nrequest as a whole are <code>issue_comment</code>, not this event.</p>\n<h3 id=\"commits-and-refs\">Commits and refs</h3>\n<h4 id=\"push\"><code>push</code></h4>\n<p><strong>No actions.</strong></p>\n<p><strong>Fields that matter:</strong></p>\n<ul>\n<li><code>ref</code> — the full ref, e.g. <code>refs/heads/main</code> or <code>refs/tags/v2.1.0</code>.</li>\n<li><code>before</code> / <code>after</code> — the SHAs bracketing the push. <code>after</code> of all zeros means\nthe ref was deleted.</li>\n<li><code>created</code>, <code>deleted</code>, <code>forced</code> — booleans describing what happened to the ref.</li>\n<li><code>base_ref</code> — the ref the branch was created from, when <code>created</code> is true.</li>\n<li><code>commits[]</code> — each with <code>id</code>, <code>message</code>, <code>timestamp</code>, <code>url</code>, <code>author</code>, and the\n<code>added</code> / <code>removed</code> / <code>modified</code> path arrays. <strong>Truncated for large pushes</strong>;\nread the range from the API if you need all of them.</li>\n<li><code>head_commit</code> — the last commit of the push, or null when the ref was deleted.</li>\n<li><code>pusher.name</code>, <code>compare</code>.</li>\n</ul>\n<p><strong>Route it when:</strong> you react to commits rather than to pull requests — tag\nreleases, direct pushes to a protected branch, path-triggered rebuilds.</p>\n<h4 id=\"create\"><code>create</code></h4>\n<p><strong>No actions.</strong> Fields: <code>ref</code>, <code>ref_type</code> (<code>branch</code> or <code>tag</code>), <code>master_branch</code>,\n<code>description</code>, <code>pusher_type</code>.</p>\n<p><strong>Route it when:</strong> you want tag creation without parsing <code>push</code> refs, or you track\nbranch creation. It does not fire for a repository&#39;s initial branch creation.</p>\n<h4 id=\"delete\"><code>delete</code></h4>\n<p><strong>No actions.</strong> Fields: <code>ref</code>, <code>ref_type</code>, <code>pusher_type</code>.</p>\n<p><strong>Route it when:</strong> you keep per-branch state — preview environments, ephemeral\ndatabases — and need to tear it down.</p>\n<h3 id=\"issues\">Issues</h3>\n<h4 id=\"issues\"><code>issues</code></h4>\n<p><strong>Actions:</strong> <code>opened</code>, <code>edited</code>, <code>deleted</code>, <code>transferred</code>, <code>pinned</code>, <code>unpinned</code>,\n<code>closed</code>, <code>reopened</code>, <code>assigned</code>, <code>unassigned</code>, <code>labeled</code>, <code>unlabeled</code>, <code>locked</code>,\n<code>unlocked</code>, <code>milestoned</code>, <code>demilestoned</code>.</p>\n<p><strong>Fields that matter:</strong> <code>issue.number</code>, <code>issue.title</code>, <code>issue.body</code>,\n<code>issue.state</code>, <code>issue.state_reason</code> (<code>completed</code>, <code>not_planned</code>, <code>reopened</code>),\n<code>issue.labels[].name</code>, <code>issue.assignees[].login</code>, <code>issue.user.login</code>,\n<code>issue.html_url</code>; plus <code>label</code> on the label actions, <code>assignee</code> on the assignment\nactions, and <code>changes</code> on <code>edited</code>.</p>\n<p><strong>Route it when:</strong> you mirror issues into another tracker, or you drive workflow\nfrom labels.</p>\n<h4 id=\"issue_comment\"><code>issue_comment</code></h4>\n<p><strong>Actions:</strong> <code>created</code>, <code>edited</code>, <code>deleted</code>.</p>\n<p><strong>Fields that matter:</strong> <code>comment.body</code>, <code>comment.id</code>, <code>comment.user.login</code>,\n<code>comment.html_url</code>, <code>comment.created_at</code>; <code>issue.number</code>; and critically\n<strong><code>issue.pull_request</code></strong> — present only when the commented-on issue is a pull\nrequest. That key is how you tell the two apart, because GitHub delivers pull\nrequest conversation comments as <code>issue_comment</code>.</p>\n<p><strong>Route it when:</strong> you implement comment commands (<code>/deploy</code>, <code>/rerun</code>) or thread\nmirroring. Guard on <code>issue.pull_request</code> first.</p>\n<h3 id=\"checks-and-status\">Checks and status</h3>\n<h4 id=\"check_run\"><code>check_run</code></h4>\n<p><strong>Actions:</strong> <code>created</code>, <code>completed</code>, <code>rerequested</code>, <code>requested_action</code>.</p>\n<p><strong>Fields that matter:</strong> <code>check_run.name</code>, <code>check_run.head_sha</code>,\n<code>check_run.status</code> (<code>queued</code>, <code>in_progress</code>, <code>completed</code>), <code>check_run.conclusion</code>\n(<code>success</code>, <code>failure</code>, <code>neutral</code>, <code>cancelled</code>, <code>timed_out</code>, <code>action_required</code>,\n<code>stale</code>, <code>skipped</code>), <code>check_run.started_at</code> / <code>completed_at</code>,\n<code>check_run.output.title</code> and <code>output.summary</code>, <code>check_run.details_url</code>,\n<code>check_run.pull_requests[]</code>, <code>check_run.app.slug</code> (which integration produced it),\nand <code>requested_action.identifier</code> on <code>requested_action</code>.</p>\n<p><strong>Route it when:</strong> you react to an individual check — posting a failure summary,\nrerunning a flaky job, gating on one named check rather than the whole suite.</p>\n<h4 id=\"check_suite\"><code>check_suite</code></h4>\n<p><strong>Actions:</strong> <code>completed</code>, <code>requested</code>, <code>rerequested</code>.</p>\n<p><strong>Fields that matter:</strong> <code>check_suite.head_branch</code>, <code>check_suite.head_sha</code>,\n<code>check_suite.status</code>, <code>check_suite.conclusion</code>, <code>check_suite.before</code> /\n<code>check_suite.after</code>, <code>check_suite.pull_requests[]</code>,\n<code>check_suite.latest_check_runs_count</code>, <code>check_suite.app.slug</code>.</p>\n<p><strong>Route it when:</strong> you want one signal per commit rather than one per check. A\nGitHub App uses <code>requested</code> and <code>rerequested</code> as its cue to create check runs.</p>\n<h4 id=\"status\"><code>status</code></h4>\n<p><strong>No actions.</strong> This is the older Commit Status API, which many external CI\nsystems still write to.</p>\n<p><strong>Fields that matter:</strong> <code>sha</code>, <code>context</code> (the status name, e.g.\n<code>ci/build</code>), <code>state</code> (<code>pending</code>, <code>success</code>, <code>failure</code>, <code>error</code>), <code>description</code>,\n<code>target_url</code>, <code>branches[]</code> (the branches whose head is this commit), <code>commit</code>.</p>\n<p><strong>Route it when:</strong> an integration you depend on reports through statuses rather\nthan checks. Do not route both <code>status</code> and <code>check_run</code> for the same signal\nwithout deduplicating — some tools emit both.</p>\n<h3 id=\"actions-and-deployment\">Actions and deployment</h3>\n<h4 id=\"workflow_run\"><code>workflow_run</code></h4>\n<p><strong>Actions:</strong> <code>requested</code>, <code>in_progress</code>, <code>completed</code>.</p>\n<p><strong>Fields that matter:</strong> <code>workflow_run.name</code>, <code>workflow_run.head_branch</code>,\n<code>workflow_run.head_sha</code>, <code>workflow_run.event</code> (what triggered the workflow),\n<code>workflow_run.status</code>, <code>workflow_run.conclusion</code>, <code>workflow_run.run_number</code>,\n<code>workflow_run.run_attempt</code>, <code>workflow_run.workflow_id</code>, <code>workflow_run.html_url</code>,\n<code>workflow_run.pull_requests[]</code>, and the <code>workflow</code> object with the workflow&#39;s\n<code>path</code>.</p>\n<p><strong>Route it when:</strong> you need whole-workflow outcomes outside Actions — a release\ngate, a notification on a failing scheduled workflow, or the fact that a deploy\nworkflow finished.</p>\n<h4 id=\"workflow_job\"><code>workflow_job</code></h4>\n<p><strong>Actions:</strong> <code>queued</code>, <code>in_progress</code>, <code>completed</code>, <code>waiting</code>.</p>\n<p><strong>Fields that matter:</strong> <code>workflow_job.run_id</code> (joins back to <code>workflow_run</code>),\n<code>workflow_job.workflow_name</code>, <code>workflow_job.name</code>, <code>workflow_job.head_sha</code>,\n<code>workflow_job.status</code>, <code>workflow_job.conclusion</code>, <code>workflow_job.labels[]</code> (the\n<code>runs-on</code> labels), <code>workflow_job.runner_name</code>, <code>workflow_job.steps[]</code>,\n<code>workflow_job.started_at</code> / <code>completed_at</code>.</p>\n<p><strong>Route it when:</strong> you autoscale self-hosted runners — <code>queued</code> with the requested\nlabels is the scale-up trigger — or you measure per-job queue time.</p>\n<h4 id=\"deployment\"><code>deployment</code></h4>\n<p><strong>Actions:</strong> <code>created</code>.</p>\n<p><strong>Fields that matter:</strong> <code>deployment.id</code>, <code>deployment.sha</code>, <code>deployment.ref</code>,\n<code>deployment.environment</code>, <code>deployment.task</code>, <code>deployment.description</code>,\n<code>deployment.payload</code> (the arbitrary object the creator attached),\n<code>deployment.creator.login</code>, <code>deployment.production_environment</code> and\n<code>deployment.transient_environment</code>.</p>\n<p><strong>Route it when:</strong> an external deployer listens for deployment requests. The\ndeployment record is a <em>request</em>; the outcome arrives as <code>deployment_status</code>.</p>\n<h4 id=\"deployment_status\"><code>deployment_status</code></h4>\n<p><strong>Actions:</strong> <code>created</code>.</p>\n<p><strong>Fields that matter:</strong> <code>deployment_status.state</code> (<code>queued</code>, <code>pending</code>,\n<code>in_progress</code>, <code>success</code>, <code>failure</code>, <code>error</code>, <code>inactive</code>),\n<code>deployment_status.environment</code>, <code>deployment_status.environment_url</code>,\n<code>deployment_status.log_url</code>, <code>deployment_status.description</code>,\n<code>deployment_status.creator.login</code>, plus the originating <code>deployment</code> object.</p>\n<p><strong>Route it when:</strong> you announce deployments or gate on one having succeeded.\n<code>state === &quot;success&quot;</code> on the environment you care about is the usual predicate.</p>\n<h3 id=\"distribution\">Distribution</h3>\n<h4 id=\"release\"><code>release</code></h4>\n<p><strong>Actions:</strong> <code>published</code>, <code>unpublished</code>, <code>created</code>, <code>edited</code>, <code>deleted</code>,\n<code>prereleased</code>, <code>released</code>.</p>\n<p><strong>Fields that matter:</strong> <code>release.tag_name</code>, <code>release.name</code>, <code>release.body</code> (the\nrelease notes, markdown), <code>release.draft</code>, <code>release.prerelease</code>,\n<code>release.target_commitish</code>, <code>release.published_at</code>, <code>release.html_url</code>,\n<code>release.assets[]</code> (each with <code>name</code>, <code>size</code>, <code>download_count</code>,\n<code>browser_download_url</code>), <code>release.author.login</code>, and <code>changes</code> on <code>edited</code>.</p>\n<p><strong>Route it when:</strong> you announce releases or trigger downstream publication.\n<code>published</code> fires for both a release and a prerelease; <code>released</code> fires only for a\nnon-prerelease, so pick according to whether prereleases should be announced.</p>\n<h4 id=\"package\"><code>package</code></h4>\n<p><strong>Actions:</strong> <code>published</code>, <code>updated</code>.</p>\n<p><strong>Fields that matter:</strong> <code>package.name</code>, <code>package.namespace</code>,\n<code>package.package_type</code> (<code>npm</code>, <code>container</code>, <code>maven</code>, …), <code>package.owner.login</code>,\nand <code>package.package_version</code> with its <code>version</code>, <code>target_commitish</code>, and\n<code>html_url</code>.</p>\n<p><strong>Route it when:</strong> publishing an artifact should trigger something downstream —\na deployment, an internal registry mirror, a version bump elsewhere.</p>\n<h3 id=\"discussion-and-community\">Discussion and community</h3>\n<h4 id=\"discussion\"><code>discussion</code></h4>\n<p><strong>Actions include:</strong> <code>created</code>, <code>edited</code>, <code>deleted</code>, <code>pinned</code>, <code>unpinned</code>,\n<code>locked</code>, <code>unlocked</code>, <code>transferred</code>, <code>category_changed</code>, <code>labeled</code>, <code>unlabeled</code>,\n<code>answered</code>, <code>unanswered</code>.</p>\n<p><strong>Fields that matter:</strong> <code>discussion.number</code>, <code>discussion.title</code>,\n<code>discussion.body</code>, <code>discussion.category.name</code> and <code>category.slug</code>,\n<code>discussion.state</code>, <code>discussion.answer_html_url</code>, <code>discussion.user.login</code>, and\n<code>answer</code> on the <code>answered</code> action.</p>\n<p><strong>Route it when:</strong> you mirror community Q&amp;A, or route new discussions in a\nparticular category to a team.</p>\n<h4 id=\"fork\"><code>fork</code></h4>\n<p><strong>No actions.</strong> Fields: <code>forkee</code> — the complete repository object of the new fork,\nincluding <code>full_name</code>, <code>owner.login</code>, and <code>private</code>.</p>\n<p><strong>Route it when:</strong> you track downstream copies of a repository. Nothing else fires\non a fork.</p>\n<h4 id=\"star\"><code>star</code></h4>\n<p><strong>Actions:</strong> <code>created</code>, <code>deleted</code>.</p>\n<p><strong>Fields that matter:</strong> <code>starred_at</code> — the timestamp on <code>created</code>, null on\n<code>deleted</code> — and <code>sender.login</code>, the user who starred.</p>\n<p><strong>Route it when:</strong> you track repository popularity. The older <code>watch</code> event\n(single action <code>started</code>) fires for the same user action and is still delivered;\nsubscribe to one of the two, not both.</p>\n<h3 id=\"administration\">Administration</h3>\n<h4 id=\"member\"><code>member</code></h4>\n<p><strong>Actions:</strong> <code>added</code>, <code>edited</code>, <code>removed</code>.</p>\n<p><strong>Fields that matter:</strong> <code>member.login</code>, <code>member.id</code>, <code>repository.full_name</code>, and\n<code>changes</code> — carrying the permission that was assigned or changed, present on\n<code>edited</code> and on <code>added</code> when a role was specified.</p>\n<p><strong>Route it when:</strong> repository collaborator changes must be mirrored into your own\naccess model, or audited.</p>\n<h4 id=\"repository\"><code>repository</code></h4>\n<p><strong>Actions:</strong> <code>created</code>, <code>deleted</code>, <code>archived</code>, <code>unarchived</code>, <code>edited</code>, <code>renamed</code>,\n<code>transferred</code>, <code>publicized</code>, <code>privatized</code>.</p>\n<p><strong>Fields that matter:</strong> the full <code>repository</code> object — <code>full_name</code>,\n<code>default_branch</code>, <code>private</code>, <code>archived</code>, <code>topics[]</code> — and <code>changes</code>, which on\n<code>renamed</code> carries the previous name and on <code>edited</code> carries the previous default\nbranch, description, homepage, or topics.</p>\n<p><strong>Route it when:</strong> you keep a repository inventory. <code>renamed</code> and <code>transferred</code>\nare the two that break anything keyed on <code>full_name</code>, which is why keying on\n<code>repository.id</code> is safer.</p>\n<h3 id=\"choosing-a-subscription-set\">Choosing a subscription set</h3>\n<p>Subscribe to the smallest set that answers your questions:</p>\n<table>\n<thead>\n<tr>\n<th>You want</th>\n<th>Subscribe to</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>Merged work, for a changelog or ledger</td>\n<td><code>pull_request</code></td>\n</tr>\n<tr>\n<td>Commits, including direct pushes and tags</td>\n<td><code>push</code></td>\n</tr>\n<tr>\n<td>Release announcements</td>\n<td><code>release</code></td>\n</tr>\n<tr>\n<td>CI outcome per commit</td>\n<td><code>check_suite</code>, or <code>status</code> for older integrations</td>\n</tr>\n<tr>\n<td>CI outcome per named job</td>\n<td><code>check_run</code></td>\n</tr>\n<tr>\n<td>Deployment outcomes</td>\n<td><code>deployment_status</code></td>\n</tr>\n<tr>\n<td>Comment-driven commands</td>\n<td><code>issue_comment</code></td>\n</tr>\n<tr>\n<td>Repository inventory</td>\n<td><code>repository</code>, <code>create</code>, <code>delete</code></td>\n</tr>\n</tbody></table>\n<p>Everything else is volume you will discard. Add an event when a handler for it\nexists, not before.</p>\n","words":1814},{"path":"references/payload-cookbook.md","slug":"payload-cookbook","title":"GitHub webhook payload cookbook","body":"# GitHub webhook payload cookbook\n\nWorked predicates. Each recipe states the event, the condition, and the exact\nfields the condition reads, so a reviewer can check it against\n[the event reference](event-types.md) without running anything.\n\nField names follow the JSON payload. Examples are JavaScript for concreteness;\nthe logic ports unchanged.\n\n## 0. The gate every recipe sits behind\n\nVerification runs before any predicate, over the raw bytes.\n\n```js\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\nexport function isSignedByGitHub(rawBody, signatureHeader) {\n  const key = process.env.GITHUB_WEBHOOK_SIGNING_VALUE;\n  if (!key || !signatureHeader) return false;\n\n  const expected = Buffer.from(\n    `sha256=${createHmac('sha256', key).update(rawBody).digest('hex')}`,\n    'utf8',\n  );\n  const received = Buffer.from(signatureHeader, 'utf8');\n\n  // timingSafeEqual throws on a length mismatch, so check length first.\n  return expected.length === received.length && timingSafeEqual(expected, received);\n}\n```\n\n`rawBody` is a `Buffer` or the exact string the request carried. Re-serializing a\nparsed object produces different bytes and the comparison will never succeed.\n\n## 1. A pull request merged into the default branch\n\nThe capture predicate for a release ledger. It must not fire for a pull request\nthat was closed without merging, nor for merges into a release or feature branch.\n\n```js\nfunction isMergeToDefaultBranch(payload) {\n  return payload.action === 'closed'\n    && payload.pull_request.merged === true\n    && payload.pull_request.base.ref === payload.repository.default_branch;\n}\n```\n\n**Reads:** `action`, `pull_request.merged`, `pull_request.base.ref`,\n`repository.default_branch`.\n\n**Natural key for deduplication:** `repository.full_name` plus `number`.\n\n**Why not `merged_at`:** it is populated on a merge, so testing it works, but\n`merged` states the intent directly and does not require a null check.\n\n## 2. A tag push\n\nTag creation arrives two ways. Prefer `create`; use the `push` form only when you\nalso need the commit the tag points at.\n\n```js\n// event: create\nfunction isTagCreated(payload) {\n  return payload.ref_type === 'tag';\n}\n\n// event: push  — same fact, with the target SHA\nfunction isTagPush(payload) {\n  return payload.ref.startsWith('refs/tags/')\n    && payload.created === true;\n}\n```\n\n**Reads:** `ref_type` and `ref` on `create`; `ref` and `created` on `push`.\n\n**Trap:** on a `push` that deletes a ref, `after` is forty zeros and `head_commit`\nis null. Test `deleted` before dereferencing `head_commit` anywhere.\n\n```js\nconst isRefDeletion = payload.deleted === true\n  || payload.after === '0'.repeat(40);\n```\n\n## 3. A check regression on the default branch\n\n\"Something that used to pass now fails.\" Route only completed runs with a bad\nconclusion, and only for the branch that matters.\n\n```js\nconst FAILING = new Set(['failure', 'timed_out', 'action_required']);\n\nfunction isCheckRegression(payload) {\n  const run = payload.check_run;\n  return payload.action === 'completed'\n    && run.status === 'completed'\n    && FAILING.has(run.conclusion)\n    && run.check_suite.head_branch === payload.repository.default_branch;\n}\n```\n\n**Reads:** `action`, `check_run.status`, `check_run.conclusion`,\n`check_run.check_suite.head_branch`, `repository.default_branch`.\n\n**Deliberately excluded conclusions:** `cancelled` (someone stopped it),\n`neutral`, `skipped`, and `stale` (superseded by a newer run). Alerting on those\ntrains people to ignore the alert.\n\n**Natural key:** `check_run.head_sha` plus `check_run.name`. A rerun of the same\ncheck on the same commit is the same fact.\n\n## 4. The same signal from the older Commit Status API\n\nSome integrations never moved to checks. This is the equivalent predicate.\n\n```js\nfunction isStatusFailure(payload) {\n  return (payload.state === 'failure' || payload.state === 'error')\n    && payload.branches.some((b) => b.name === payload.repository.default_branch);\n}\n```\n\n**Reads:** `state`, `branches[].name`, `repository.default_branch`.\n\n`status` has no `action` field. `branches` lists the branches whose head is this\ncommit, which is how you scope a commit-keyed event to a branch.\n\n## 5. An approving review\n\n```js\nfunction isApproval(payload) {\n  return payload.action === 'submitted'\n    && payload.review.state.toLowerCase() === 'approved';\n}\n```\n\n**Reads:** `action`, `review.state`.\n\n**Trap:** the webhook delivers `review.state` lower-cased where the REST API\nreturns it upper-cased. Lower-case both sides rather than remembering which\nsource a value came from.\n\n## 6. A comment command, on a pull request only\n\n```js\nfunction parseCommand(payload) {\n  if (payload.action !== 'created') return null;\n  if (!payload.issue.pull_request) return null;      // an issue, not a PR\n\n  const match = /^\\/(\\w+)(?:\\s+(.*))?$/m.exec(payload.comment.body.trim());\n  return match ? { name: match[1], args: match[2] ?? '' } : null;\n}\n```\n\n**Reads:** `action`, `issue.pull_request` (presence only), `comment.body`.\n\n**Trap:** `issue_comment` covers both issues and pull requests. The `pull_request`\nkey on `issue` is present only for the latter, and that presence check is the only\nreliable discriminator. Also ignore comments whose `sender.type` is `Bot` unless\nyou want a command loop.\n\n## 7. A successful deployment to a named environment\n\n```js\nfunction isProductionDeploySucceeded(payload) {\n  return payload.deployment_status.state === 'success'\n    && payload.deployment.environment === 'production';\n}\n```\n\n**Reads:** `deployment_status.state`, `deployment.environment`.\n\n**Trap:** read the environment from `deployment`, not from `deployment_status`.\nBoth carry the field, and the deployment record is the authoritative one.\n\n## 8. A workflow run that finished, for a specific workflow\n\n```js\nfunction isReleaseWorkflowCompleted(payload) {\n  return payload.action === 'completed'\n    && payload.workflow_run.conclusion === 'success'\n    && payload.workflow.path === '.github/workflows/release.yml';\n}\n```\n\n**Reads:** `action`, `workflow_run.conclusion`, `workflow.path`.\n\n**Trap:** match on `workflow.path`, not on `workflow_run.name`. The display name\nis editable in the workflow file and changing it silently unsubscribes you.\n\n## 9. A published release that is not a prerelease\n\n```js\nfunction isStableRelease(payload) {\n  return payload.action === 'published'\n    && payload.release.draft === false\n    && payload.release.prerelease === false;\n}\n```\n\n**Reads:** `action`, `release.draft`, `release.prerelease`.\n\n**Alternative:** subscribe to the `released` action instead, which fires only for\nnon-prereleases. Use one approach or the other; using both double-fires.\n\n## 10. A push that touched a path\n\nFor path-scoped rebuilds without a full checkout.\n\n```js\nfunction touchesPath(payload, prefix) {\n  return payload.commits.some((c) =>\n    [...c.added, ...c.removed, ...c.modified].some((p) => p.startsWith(prefix)));\n}\n```\n\n**Reads:** `commits[].added`, `commits[].removed`, `commits[].modified`.\n\n**Trap:** the `commits` array is truncated on large pushes, so a negative answer\nis not proof. When the push is large — or when `commits.length` equals whatever\ncap you observe — fall back to comparing `before..after` through the API.\n\n## Recording the routing decision\n\nWhatever the predicates, log one line per delivery with the event name, the\naction, the delivery id, the predicate that matched (or `unrouted`), and the\nresponse code. That log is what turns \"we think we missed a merge\" into a\nfive-minute answer, and it is the only place the delivery id belongs.\n","bodyHtml":"<h2 id=\"github-webhook-payload-cookbook\">GitHub webhook payload cookbook</h2>\n<p>Worked predicates. Each recipe states the event, the condition, and the exact\nfields the condition reads, so a reviewer can check it against\n<a href=\"event-types.md\">the event reference</a> without running anything.</p>\n<p>Field names follow the JSON payload. Examples are JavaScript for concreteness;\nthe logic ports unchanged.</p>\n<h3 id=\"0-the-gate-every-recipe-sits-behind\">0. The gate every recipe sits behind</h3>\n<p>Verification runs before any predicate, over the raw bytes.</p>\n<pre><code class=\"language-js\">import { createHmac, timingSafeEqual } from &#39;node:crypto&#39;;\n\nexport function isSignedByGitHub(rawBody, signatureHeader) {\n  const key = process.env.GITHUB_WEBHOOK_SIGNING_VALUE;\n  if (!key || !signatureHeader) return false;\n\n  const expected = Buffer.from(\n    `sha256=${createHmac(&#39;sha256&#39;, key).update(rawBody).digest(&#39;hex&#39;)}`,\n    &#39;utf8&#39;,\n  );\n  const received = Buffer.from(signatureHeader, &#39;utf8&#39;);\n\n  // timingSafeEqual throws on a length mismatch, so check length first.\n  return expected.length === received.length &amp;&amp; timingSafeEqual(expected, received);\n}\n</code></pre>\n<p><code>rawBody</code> is a <code>Buffer</code> or the exact string the request carried. Re-serializing a\nparsed object produces different bytes and the comparison will never succeed.</p>\n<h3 id=\"1-a-pull-request-merged-into-the-default-branch\">1. A pull request merged into the default branch</h3>\n<p>The capture predicate for a release ledger. It must not fire for a pull request\nthat was closed without merging, nor for merges into a release or feature branch.</p>\n<pre><code class=\"language-js\">function isMergeToDefaultBranch(payload) {\n  return payload.action === &#39;closed&#39;\n    &amp;&amp; payload.pull_request.merged === true\n    &amp;&amp; payload.pull_request.base.ref === payload.repository.default_branch;\n}\n</code></pre>\n<p><strong>Reads:</strong> <code>action</code>, <code>pull_request.merged</code>, <code>pull_request.base.ref</code>,\n<code>repository.default_branch</code>.</p>\n<p><strong>Natural key for deduplication:</strong> <code>repository.full_name</code> plus <code>number</code>.</p>\n<p><strong>Why not <code>merged_at</code>:</strong> it is populated on a merge, so testing it works, but\n<code>merged</code> states the intent directly and does not require a null check.</p>\n<h3 id=\"2-a-tag-push\">2. A tag push</h3>\n<p>Tag creation arrives two ways. Prefer <code>create</code>; use the <code>push</code> form only when you\nalso need the commit the tag points at.</p>\n<pre><code class=\"language-js\">// event: create\nfunction isTagCreated(payload) {\n  return payload.ref_type === &#39;tag&#39;;\n}\n\n// event: push  — same fact, with the target SHA\nfunction isTagPush(payload) {\n  return payload.ref.startsWith(&#39;refs/tags/&#39;)\n    &amp;&amp; payload.created === true;\n}\n</code></pre>\n<p><strong>Reads:</strong> <code>ref_type</code> and <code>ref</code> on <code>create</code>; <code>ref</code> and <code>created</code> on <code>push</code>.</p>\n<p><strong>Trap:</strong> on a <code>push</code> that deletes a ref, <code>after</code> is forty zeros and <code>head_commit</code>\nis null. Test <code>deleted</code> before dereferencing <code>head_commit</code> anywhere.</p>\n<pre><code class=\"language-js\">const isRefDeletion = payload.deleted === true\n  || payload.after === &#39;0&#39;.repeat(40);\n</code></pre>\n<h3 id=\"3-a-check-regression-on-the-default-branch\">3. A check regression on the default branch</h3>\n<p>&quot;Something that used to pass now fails.&quot; Route only completed runs with a bad\nconclusion, and only for the branch that matters.</p>\n<pre><code class=\"language-js\">const FAILING = new Set([&#39;failure&#39;, &#39;timed_out&#39;, &#39;action_required&#39;]);\n\nfunction isCheckRegression(payload) {\n  const run = payload.check_run;\n  return payload.action === &#39;completed&#39;\n    &amp;&amp; run.status === &#39;completed&#39;\n    &amp;&amp; FAILING.has(run.conclusion)\n    &amp;&amp; run.check_suite.head_branch === payload.repository.default_branch;\n}\n</code></pre>\n<p><strong>Reads:</strong> <code>action</code>, <code>check_run.status</code>, <code>check_run.conclusion</code>,\n<code>check_run.check_suite.head_branch</code>, <code>repository.default_branch</code>.</p>\n<p><strong>Deliberately excluded conclusions:</strong> <code>cancelled</code> (someone stopped it),\n<code>neutral</code>, <code>skipped</code>, and <code>stale</code> (superseded by a newer run). Alerting on those\ntrains people to ignore the alert.</p>\n<p><strong>Natural key:</strong> <code>check_run.head_sha</code> plus <code>check_run.name</code>. A rerun of the same\ncheck on the same commit is the same fact.</p>\n<h3 id=\"4-the-same-signal-from-the-older-commit-status-api\">4. The same signal from the older Commit Status API</h3>\n<p>Some integrations never moved to checks. This is the equivalent predicate.</p>\n<pre><code class=\"language-js\">function isStatusFailure(payload) {\n  return (payload.state === &#39;failure&#39; || payload.state === &#39;error&#39;)\n    &amp;&amp; payload.branches.some((b) =&gt; b.name === payload.repository.default_branch);\n}\n</code></pre>\n<p><strong>Reads:</strong> <code>state</code>, <code>branches[].name</code>, <code>repository.default_branch</code>.</p>\n<p><code>status</code> has no <code>action</code> field. <code>branches</code> lists the branches whose head is this\ncommit, which is how you scope a commit-keyed event to a branch.</p>\n<h3 id=\"5-an-approving-review\">5. An approving review</h3>\n<pre><code class=\"language-js\">function isApproval(payload) {\n  return payload.action === &#39;submitted&#39;\n    &amp;&amp; payload.review.state.toLowerCase() === &#39;approved&#39;;\n}\n</code></pre>\n<p><strong>Reads:</strong> <code>action</code>, <code>review.state</code>.</p>\n<p><strong>Trap:</strong> the webhook delivers <code>review.state</code> lower-cased where the REST API\nreturns it upper-cased. Lower-case both sides rather than remembering which\nsource a value came from.</p>\n<h3 id=\"6-a-comment-command-on-a-pull-request-only\">6. A comment command, on a pull request only</h3>\n<pre><code class=\"language-js\">function parseCommand(payload) {\n  if (payload.action !== &#39;created&#39;) return null;\n  if (!payload.issue.pull_request) return null;      // an issue, not a PR\n\n  const match = /^\\/(\\w+)(?:\\s+(.*))?$/m.exec(payload.comment.body.trim());\n  return match ? { name: match[1], args: match[2] ?? &#39;&#39; } : null;\n}\n</code></pre>\n<p><strong>Reads:</strong> <code>action</code>, <code>issue.pull_request</code> (presence only), <code>comment.body</code>.</p>\n<p><strong>Trap:</strong> <code>issue_comment</code> covers both issues and pull requests. The <code>pull_request</code>\nkey on <code>issue</code> is present only for the latter, and that presence check is the only\nreliable discriminator. Also ignore comments whose <code>sender.type</code> is <code>Bot</code> unless\nyou want a command loop.</p>\n<h3 id=\"7-a-successful-deployment-to-a-named-environment\">7. A successful deployment to a named environment</h3>\n<pre><code class=\"language-js\">function isProductionDeploySucceeded(payload) {\n  return payload.deployment_status.state === &#39;success&#39;\n    &amp;&amp; payload.deployment.environment === &#39;production&#39;;\n}\n</code></pre>\n<p><strong>Reads:</strong> <code>deployment_status.state</code>, <code>deployment.environment</code>.</p>\n<p><strong>Trap:</strong> read the environment from <code>deployment</code>, not from <code>deployment_status</code>.\nBoth carry the field, and the deployment record is the authoritative one.</p>\n<h3 id=\"8-a-workflow-run-that-finished-for-a-specific-workflow\">8. A workflow run that finished, for a specific workflow</h3>\n<pre><code class=\"language-js\">function isReleaseWorkflowCompleted(payload) {\n  return payload.action === &#39;completed&#39;\n    &amp;&amp; payload.workflow_run.conclusion === &#39;success&#39;\n    &amp;&amp; payload.workflow.path === &#39;.github/workflows/release.yml&#39;;\n}\n</code></pre>\n<p><strong>Reads:</strong> <code>action</code>, <code>workflow_run.conclusion</code>, <code>workflow.path</code>.</p>\n<p><strong>Trap:</strong> match on <code>workflow.path</code>, not on <code>workflow_run.name</code>. The display name\nis editable in the workflow file and changing it silently unsubscribes you.</p>\n<h3 id=\"9-a-published-release-that-is-not-a-prerelease\">9. A published release that is not a prerelease</h3>\n<pre><code class=\"language-js\">function isStableRelease(payload) {\n  return payload.action === &#39;published&#39;\n    &amp;&amp; payload.release.draft === false\n    &amp;&amp; payload.release.prerelease === false;\n}\n</code></pre>\n<p><strong>Reads:</strong> <code>action</code>, <code>release.draft</code>, <code>release.prerelease</code>.</p>\n<p><strong>Alternative:</strong> subscribe to the <code>released</code> action instead, which fires only for\nnon-prereleases. Use one approach or the other; using both double-fires.</p>\n<h3 id=\"10-a-push-that-touched-a-path\">10. A push that touched a path</h3>\n<p>For path-scoped rebuilds without a full checkout.</p>\n<pre><code class=\"language-js\">function touchesPath(payload, prefix) {\n  return payload.commits.some((c) =&gt;\n    [...c.added, ...c.removed, ...c.modified].some((p) =&gt; p.startsWith(prefix)));\n}\n</code></pre>\n<p><strong>Reads:</strong> <code>commits[].added</code>, <code>commits[].removed</code>, <code>commits[].modified</code>.</p>\n<p><strong>Trap:</strong> the <code>commits</code> array is truncated on large pushes, so a negative answer\nis not proof. When the push is large — or when <code>commits.length</code> equals whatever\ncap you observe — fall back to comparing <code>before..after</code> through the API.</p>\n<h3 id=\"recording-the-routing-decision\">Recording the routing decision</h3>\n<p>Whatever the predicates, log one line per delivery with the event name, the\naction, the delivery id, the predicate that matched (or <code>unrouted</code>), and the\nresponse code. That log is what turns &quot;we think we missed a merge&quot; into a\nfive-minute answer, and it is the only place the delivery id belongs.</p>\n","words":957}],"body":"# GitHub webhooks\n\nA webhook endpoint is three things that get confused with each other: a verifier,\na router, and a set of handlers. Most broken integrations are broken because those\nthree were written as one function — the verifier trusts a parsed body, the router\nis an `if` chain nobody can enumerate, and a handler's slow work happens inside the\nten seconds GitHub allows before it calls the delivery failed.\n\nThis skill separates them, and carries a reference for what each event type\nactually contains so a handler is written against real fields rather than\nremembered ones.\n\nIt composes with two companions in the same pack: **`release-ledger`** orchestrates\na since-you-were-away ledger and consumes captured merge events, and\n**`describe-changes`** turns one of those changes into prose. Install either with\n`npx skills add crissmoldovan/agent-skills`.\n\n## When to Use\n\n- An application needs to react to activity on a GitHub repository or\n  organization, and no endpoint exists yet.\n- An endpoint exists and you are adding an event type, or auditing whether its\n  verification is real.\n- Deliveries are arriving and being lost, timing out, or processed twice.\n- You need to know which event carries a field before designing a feature around\n  it — that is what the event reference is for.\n\nDo not use it for outbound calls to the GitHub API; that is the REST or GraphQL\nAPI and needs a credential this endpoint deliberately does not hold. Do not use it\nfor GitHub Actions workflow triggers — `on: pull_request` in a workflow file is a\ndifferent mechanism with a different payload shape and no endpoint of yours.\nDo not use it to poll: if you find yourself scheduling a fetch of recent merges,\nyou are building a poller, and a poller has different idempotency and rate-limit\nconcerns than anything here.\n\n## Prerequisites\n\n1. **A publicly reachable HTTPS URL** that GitHub can POST to, or a tunnel to a\n   local port for development.\n   **Complete when:** an unauthenticated POST from outside your network reaches\n   your handler.\n2. **A shared verification value, stored as a secret.** Generate a long random\n   value; place it with your platform's secret mechanism, never in the repository.\n   **Complete when:** the running process reads it from the environment and the\n   value has never appeared in a file, a log line, or a chat message.\n3. **Access to the raw request body.** HMAC is computed over the exact bytes\n   GitHub sent. A framework that hands you a parsed object has already destroyed\n   the thing you need to verify.\n   **Complete when:** you can log the byte length of the body and it matches the\n   `Content-Length` header.\n4. **Somewhere to put work that is not the request.** A queue, a job runner, or at\n   minimum a durable table the response does not wait on.\n   **Complete when:** you can enqueue and return in the same request, and see the\n   work complete afterwards.\n5. **Admin rights on the repository, organization, or App** whose settings hold\n   the hook.\n   **Complete when:** you can open the webhook settings page and see the Recent\n   Deliveries tab.\n\n## Procedure\n\n1. **Audit what already exists.** Search for a route matching `webhook`, `hooks`,\n   or `github` and read it end to end before adding anything. Answer four\n   questions: does it verify, does it verify against the raw body, which events\n   does it already subscribe to, and does it filter events before doing work? The\n   fourth matters most when you are adding a consumer: a handler that returns\n   early for events it does not care about will discard yours too if you nest\n   inside it.\n2. **Design the event map before writing code.** A table of event, actions you\n   care about, the predicate that selects them, and the handler. Keep it in the\n   repository — it is the document that answers \"why are we subscribed to that?\"\n   in a year. [The event reference](references/event-types.md) is the raw material;\n   [the payload cookbook](references/payload-cookbook.md) has the predicates for\n   the common cases already written.\n3. **Implement the endpoint in four layers, in this order.**\n   - Read the raw body as bytes.\n   - Verify `X-Hub-Signature-256` with HMAC-SHA256 and a constant-time compare.\n     Reject with 401 on mismatch, and reject when the header is absent — an\n     endpoint that skips verification when the header is missing is unverified.\n   - Route on `X-GitHub-Event` and, where the event has one, `payload.action`.\n   - Hand off to a handler that enqueues and returns. Respond 2xx within a\n     second or two; GitHub's delivery timeout is ten seconds and a timed-out\n     delivery is retried, which is how one merge becomes three ledger rows.\n4. **Handle the `ping` event explicitly.** GitHub sends it when the hook is\n   created. Returning 200 with no special case is fine, but returning 400 for an\n   unknown event means the hook shows a red delivery from the moment it exists.\n5. **Register the hook.** Create it against the repository or organization, select\n   only the events in the map, set the content type to `application/json`, and set\n   the verification value. Selecting \"send me everything\" is how an endpoint ends\n   up receiving thousands of deliveries it discards.\n6. **Verify with a real delivery.** Cause the event, then open Recent Deliveries\n   and read the request and response. A 200 you produced by hand-posting a\n   fixture proves your parser works and proves nothing about the hook.\n7. **Write the event map into the host repository's docs** with the endpoint URL\n   path, the events subscribed, and how to rotate the verification value.\n\n### Managing evolution\n\n- **Adding an event** is three steps in one change: extend the map, add the\n  handler, then update the hook's subscription list. Doing the third first means\n  live deliveries hitting a router that does not know them.\n- **Idempotency comes from a natural key, not from the delivery id.** GitHub's\n  `X-GitHub-Delivery` is unique per *attempt group* and a manual redelivery\n  reuses it — but a second, genuinely separate delivery of the same underlying\n  fact (a `synchronize` after a `synchronize`) has a new one. Deduplicate on what\n  the fact is: repository plus pull request number, or the head SHA plus check\n  name. Keep the delivery id in the log line, not in the unique constraint.\n- **Replay is the debugging tool.** Recent Deliveries has a Redeliver button, and\n  the API exposes the same thing, so a fixed handler can be tested against the\n  exact bytes that broke it.\n- **Local development uses forwarding, not a fixture.** `gh webhook forward`\n  (from the `cli/gh-webhook` extension) relays live deliveries to a local port\n  with real signatures, which exercises the verifier that a saved JSON file never\n  will.\n\n## Usage Examples\n\n```text\nSet up GitHub webhook handling in this app. Audit anything that exists first,\nthen implement the endpoint: raw body, HMAC-SHA256 verification with a\nconstant-time compare, routing on the event header plus action, and a handler\nthat enqueues. Only subscribe to pull_request and push for now.\n```\n\n```text\nWe already receive pull_request events but the handler returns early unless the\ntitle matches our ticket convention. I need every merged PR. Show me how many\ndeliveries that filter discards, then add a second consumer beside it rather\nthan inside it.\n```\n\n```text\nAdd check_run to our event map. Route only completed check runs whose conclusion\nis failure or timed_out, on the default branch, and tell me which payload fields\nthe predicate reads.\n```\n\n## Pitfalls\n\n- **Verifying a re-serialized body.** `JSON.stringify(await req.json())` is not the\n  bytes GitHub signed. Key order, whitespace, and unicode escaping all differ, and\n  the signature will never match — or worse, will match in development and fail\n  in production behind a proxy that reformats.\n- **Comparing signatures with `===`.** Use a constant-time comparison. Compare\n  fixed-length buffers, and check the length before comparing, because most\n  constant-time helpers throw on a length mismatch rather than returning false.\n- **Trusting `X-Hub-Signature`.** The unsuffixed header is the legacy SHA-1\n  signature. Verify the `-256` one; accepting either lets a caller choose the\n  weaker algorithm.\n- **Doing the work inline.** Anything that calls a model, another API, or a slow\n  query belongs behind a queue. A ten-second timeout means a slow handler turns\n  into retries, and retries turn into duplicates.\n- **Returning a non-2xx for events you do not handle.** GitHub retries failures.\n  An unrouted event should return 200 and be counted, not rejected.\n- **Assuming every event has an `action`.** `push`, `status`, `create`, `delete`,\n  `fork`, `gollum`, and `public` have none. A router that reads `payload.action`\n  unconditionally routes them all to the same undefined branch.\n- **Assuming a merge.** `pull_request` with `action: \"closed\"` fires for closed\n  and for merged. `payload.pull_request.merged` is the field that distinguishes\n  them, and it is a boolean on the pull request, not on the event.\n- **Assuming the push commit list is complete.** Large pushes truncate the\n  `commits` array; the payload is a notification, not an archive. Read the range\n  with the API if you need every commit.\n- **A payload that is a delete.** `push` with `after` equal to all zeros is a\n  branch deletion arriving as a push. Handlers that diff `before..after` produce\n  nonsense on it.\n- **Subscribing to everything \"to be safe\".** Every unwanted event is delivery\n  volume, log noise, and a payload you did not review for the data it carries.\n- **Placing the endpoint behind the app's authentication.** It has no session and\n  no bearer token; its authentication *is* the signature. Exempt the route\n  deliberately and narrowly, and make sure the exemption does not extend to the\n  routes you add next.\n\n## Verification\n\n- [ ] The endpoint reads the raw request body and verifies HMAC-SHA256 over those exact bytes.\n- [ ] Comparison is constant-time, and a missing signature header is rejected rather than skipped.\n- [ ] A deliberately corrupted signature was sent and produced 401.\n- [ ] The router handles events without an `action` field.\n- [ ] `ping` returns 200.\n- [ ] Unrouted events return 200 and are counted.\n- [ ] Handlers enqueue; nothing slow runs inside the request.\n- [ ] Median response time to GitHub is well under the ten-second delivery timeout.\n- [ ] Deduplication uses a natural key, and a redelivery was replayed to prove it.\n- [ ] The hook subscribes only to the events in the map.\n- [ ] A real delivery was inspected in Recent Deliveries, request and response.\n- [ ] The verification value lives in a secret store and appears in no file, log, or message.\n- [ ] The event map is documented in the host repository, with the rotation procedure.\n\n## Deeper reading\n\n- [Event types](references/event-types.md): every event this skill routes, its\n  actions, the payload fields that carry the meaning, and one line on when you\n  would subscribe to it.\n- [Payload cookbook](references/payload-cookbook.md): worked predicates —\n  merged-PR-to-default-branch, tag push, check regression, review approval,\n  successful deployment — each written as a condition plus the exact fields it\n  reads.\n","bodyHtml":"<h2 id=\"github-webhooks\">GitHub webhooks</h2>\n<p>A webhook endpoint is three things that get confused with each other: a verifier,\na router, and a set of handlers. Most broken integrations are broken because those\nthree were written as one function — the verifier trusts a parsed body, the router\nis an <code>if</code> chain nobody can enumerate, and a handler&#39;s slow work happens inside the\nten seconds GitHub allows before it calls the delivery failed.</p>\n<p>This skill separates them, and carries a reference for what each event type\nactually contains so a handler is written against real fields rather than\nremembered ones.</p>\n<p>It composes with two companions in the same pack: <strong><code>release-ledger</code></strong> orchestrates\na since-you-were-away ledger and consumes captured merge events, and\n<strong><code>describe-changes</code></strong> turns one of those changes into prose. Install either with\n<code>npx skills add crissmoldovan/agent-skills</code>.</p>\n<h3 id=\"when-to-use\">When to Use</h3>\n<ul>\n<li>An application needs to react to activity on a GitHub repository or\norganization, and no endpoint exists yet.</li>\n<li>An endpoint exists and you are adding an event type, or auditing whether its\nverification is real.</li>\n<li>Deliveries are arriving and being lost, timing out, or processed twice.</li>\n<li>You need to know which event carries a field before designing a feature around\nit — that is what the event reference is for.</li>\n</ul>\n<p>Do not use it for outbound calls to the GitHub API; that is the REST or GraphQL\nAPI and needs a credential this endpoint deliberately does not hold. Do not use it\nfor GitHub Actions workflow triggers — <code>on: pull_request</code> in a workflow file is a\ndifferent mechanism with a different payload shape and no endpoint of yours.\nDo not use it to poll: if you find yourself scheduling a fetch of recent merges,\nyou are building a poller, and a poller has different idempotency and rate-limit\nconcerns than anything here.</p>\n<h3 id=\"prerequisites\">Prerequisites</h3>\n<ol>\n<li><strong>A publicly reachable HTTPS URL</strong> that GitHub can POST to, or a tunnel to a\nlocal port for development.\n<strong>Complete when:</strong> an unauthenticated POST from outside your network reaches\nyour handler.</li>\n<li><strong>A shared verification value, stored as a secret.</strong> Generate a long random\nvalue; place it with your platform&#39;s secret mechanism, never in the repository.\n<strong>Complete when:</strong> the running process reads it from the environment and the\nvalue has never appeared in a file, a log line, or a chat message.</li>\n<li><strong>Access to the raw request body.</strong> HMAC is computed over the exact bytes\nGitHub sent. A framework that hands you a parsed object has already destroyed\nthe thing you need to verify.\n<strong>Complete when:</strong> you can log the byte length of the body and it matches the\n<code>Content-Length</code> header.</li>\n<li><strong>Somewhere to put work that is not the request.</strong> A queue, a job runner, or at\nminimum a durable table the response does not wait on.\n<strong>Complete when:</strong> you can enqueue and return in the same request, and see the\nwork complete afterwards.</li>\n<li><strong>Admin rights on the repository, organization, or App</strong> whose settings hold\nthe hook.\n<strong>Complete when:</strong> you can open the webhook settings page and see the Recent\nDeliveries tab.</li>\n</ol>\n<h3 id=\"procedure\">Procedure</h3>\n<ol>\n<li><strong>Audit what already exists.</strong> Search for a route matching <code>webhook</code>, <code>hooks</code>,\nor <code>github</code> and read it end to end before adding anything. Answer four\nquestions: does it verify, does it verify against the raw body, which events\ndoes it already subscribe to, and does it filter events before doing work? The\nfourth matters most when you are adding a consumer: a handler that returns\nearly for events it does not care about will discard yours too if you nest\ninside it.</li>\n<li><strong>Design the event map before writing code.</strong> A table of event, actions you\ncare about, the predicate that selects them, and the handler. Keep it in the\nrepository — it is the document that answers &quot;why are we subscribed to that?&quot;\nin a year. <a href=\"references/event-types.md\">The event reference</a> is the raw material;\n<a href=\"references/payload-cookbook.md\">the payload cookbook</a> has the predicates for\nthe common cases already written.</li>\n<li><strong>Implement the endpoint in four layers, in this order.</strong><ul>\n<li>Read the raw body as bytes.</li>\n<li>Verify <code>X-Hub-Signature-256</code> with HMAC-SHA256 and a constant-time compare.\nReject with 401 on mismatch, and reject when the header is absent — an\nendpoint that skips verification when the header is missing is unverified.</li>\n<li>Route on <code>X-GitHub-Event</code> and, where the event has one, <code>payload.action</code>.</li>\n<li>Hand off to a handler that enqueues and returns. Respond 2xx within a\nsecond or two; GitHub&#39;s delivery timeout is ten seconds and a timed-out\ndelivery is retried, which is how one merge becomes three ledger rows.</li>\n</ul>\n</li>\n<li><strong>Handle the <code>ping</code> event explicitly.</strong> GitHub sends it when the hook is\ncreated. Returning 200 with no special case is fine, but returning 400 for an\nunknown event means the hook shows a red delivery from the moment it exists.</li>\n<li><strong>Register the hook.</strong> Create it against the repository or organization, select\nonly the events in the map, set the content type to <code>application/json</code>, and set\nthe verification value. Selecting &quot;send me everything&quot; is how an endpoint ends\nup receiving thousands of deliveries it discards.</li>\n<li><strong>Verify with a real delivery.</strong> Cause the event, then open Recent Deliveries\nand read the request and response. A 200 you produced by hand-posting a\nfixture proves your parser works and proves nothing about the hook.</li>\n<li><strong>Write the event map into the host repository&#39;s docs</strong> with the endpoint URL\npath, the events subscribed, and how to rotate the verification value.</li>\n</ol>\n<h4 id=\"managing-evolution\">Managing evolution</h4>\n<ul>\n<li><strong>Adding an event</strong> is three steps in one change: extend the map, add the\nhandler, then update the hook&#39;s subscription list. Doing the third first means\nlive deliveries hitting a router that does not know them.</li>\n<li><strong>Idempotency comes from a natural key, not from the delivery id.</strong> GitHub&#39;s\n<code>X-GitHub-Delivery</code> is unique per <em>attempt group</em> and a manual redelivery\nreuses it — but a second, genuinely separate delivery of the same underlying\nfact (a <code>synchronize</code> after a <code>synchronize</code>) has a new one. Deduplicate on what\nthe fact is: repository plus pull request number, or the head SHA plus check\nname. Keep the delivery id in the log line, not in the unique constraint.</li>\n<li><strong>Replay is the debugging tool.</strong> Recent Deliveries has a Redeliver button, and\nthe API exposes the same thing, so a fixed handler can be tested against the\nexact bytes that broke it.</li>\n<li><strong>Local development uses forwarding, not a fixture.</strong> <code>gh webhook forward</code>\n(from the <code>cli/gh-webhook</code> extension) relays live deliveries to a local port\nwith real signatures, which exercises the verifier that a saved JSON file never\nwill.</li>\n</ul>\n<h3 id=\"usage-examples\">Usage Examples</h3>\n<pre><code class=\"language-text\">Set up GitHub webhook handling in this app. Audit anything that exists first,\nthen implement the endpoint: raw body, HMAC-SHA256 verification with a\nconstant-time compare, routing on the event header plus action, and a handler\nthat enqueues. Only subscribe to pull_request and push for now.\n</code></pre>\n<pre><code class=\"language-text\">We already receive pull_request events but the handler returns early unless the\ntitle matches our ticket convention. I need every merged PR. Show me how many\ndeliveries that filter discards, then add a second consumer beside it rather\nthan inside it.\n</code></pre>\n<pre><code class=\"language-text\">Add check_run to our event map. Route only completed check runs whose conclusion\nis failure or timed_out, on the default branch, and tell me which payload fields\nthe predicate reads.\n</code></pre>\n<h3 id=\"pitfalls\">Pitfalls</h3>\n<ul>\n<li><strong>Verifying a re-serialized body.</strong> <code>JSON.stringify(await req.json())</code> is not the\nbytes GitHub signed. Key order, whitespace, and unicode escaping all differ, and\nthe signature will never match — or worse, will match in development and fail\nin production behind a proxy that reformats.</li>\n<li><strong>Comparing signatures with <code>===</code>.</strong> Use a constant-time comparison. Compare\nfixed-length buffers, and check the length before comparing, because most\nconstant-time helpers throw on a length mismatch rather than returning false.</li>\n<li><strong>Trusting <code>X-Hub-Signature</code>.</strong> The unsuffixed header is the legacy SHA-1\nsignature. Verify the <code>-256</code> one; accepting either lets a caller choose the\nweaker algorithm.</li>\n<li><strong>Doing the work inline.</strong> Anything that calls a model, another API, or a slow\nquery belongs behind a queue. A ten-second timeout means a slow handler turns\ninto retries, and retries turn into duplicates.</li>\n<li><strong>Returning a non-2xx for events you do not handle.</strong> GitHub retries failures.\nAn unrouted event should return 200 and be counted, not rejected.</li>\n<li><strong>Assuming every event has an <code>action</code>.</strong> <code>push</code>, <code>status</code>, <code>create</code>, <code>delete</code>,\n<code>fork</code>, <code>gollum</code>, and <code>public</code> have none. A router that reads <code>payload.action</code>\nunconditionally routes them all to the same undefined branch.</li>\n<li><strong>Assuming a merge.</strong> <code>pull_request</code> with <code>action: &quot;closed&quot;</code> fires for closed\nand for merged. <code>payload.pull_request.merged</code> is the field that distinguishes\nthem, and it is a boolean on the pull request, not on the event.</li>\n<li><strong>Assuming the push commit list is complete.</strong> Large pushes truncate the\n<code>commits</code> array; the payload is a notification, not an archive. Read the range\nwith the API if you need every commit.</li>\n<li><strong>A payload that is a delete.</strong> <code>push</code> with <code>after</code> equal to all zeros is a\nbranch deletion arriving as a push. Handlers that diff <code>before..after</code> produce\nnonsense on it.</li>\n<li><strong>Subscribing to everything &quot;to be safe&quot;.</strong> Every unwanted event is delivery\nvolume, log noise, and a payload you did not review for the data it carries.</li>\n<li><strong>Placing the endpoint behind the app&#39;s authentication.</strong> It has no session and\nno bearer token; its authentication <em>is</em> the signature. Exempt the route\ndeliberately and narrowly, and make sure the exemption does not extend to the\nroutes you add next.</li>\n</ul>\n<h3 id=\"verification\">Verification</h3>\n<ul>\n<li><input disabled=\"\" type=\"checkbox\"> The endpoint reads the raw request body and verifies HMAC-SHA256 over those exact bytes.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Comparison is constant-time, and a missing signature header is rejected rather than skipped.</li>\n<li><input disabled=\"\" type=\"checkbox\"> A deliberately corrupted signature was sent and produced 401.</li>\n<li><input disabled=\"\" type=\"checkbox\"> The router handles events without an <code>action</code> field.</li>\n<li><input disabled=\"\" type=\"checkbox\"> <code>ping</code> returns 200.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Unrouted events return 200 and are counted.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Handlers enqueue; nothing slow runs inside the request.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Median response time to GitHub is well under the ten-second delivery timeout.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Deduplication uses a natural key, and a redelivery was replayed to prove it.</li>\n<li><input disabled=\"\" type=\"checkbox\"> The hook subscribes only to the events in the map.</li>\n<li><input disabled=\"\" type=\"checkbox\"> A real delivery was inspected in Recent Deliveries, request and response.</li>\n<li><input disabled=\"\" type=\"checkbox\"> The verification value lives in a secret store and appears in no file, log, or message.</li>\n<li><input disabled=\"\" type=\"checkbox\"> The event map is documented in the host repository, with the rotation procedure.</li>\n</ul>\n<h3 id=\"deeper-reading\">Deeper reading</h3>\n<ul>\n<li><a href=\"references/event-types.md\">Event types</a>: every event this skill routes, its\nactions, the payload fields that carry the meaning, and one line on when you\nwould subscribe to it.</li>\n<li><a href=\"references/payload-cookbook.md\">Payload cookbook</a>: worked predicates —\nmerged-PR-to-default-branch, tag push, check regression, review approval,\nsuccessful deployment — each written as a condition plus the exact fields it\nreads.</li>\n</ul>\n","outline":["When to Use","Prerequisites","Procedure","Usage Examples","Pitfalls","Verification","Deeper reading"],"words":1807}
