@tg44/octokit-webhooks.js
v10.3.0
Published
GitHub webhook events toolset for Node.js
Downloads
12
Readme
@octokit/webhooks
GitHub webhook events toolset for Node.js
@octokit/webhooks
helps to handle webhook events received from GitHub.
GitHub webhooks can be registered in multiple ways
- In repository or organization settings on github.com.
- Using the REST API for repositories or organizations
- By creating a GitHub App.
Note that while setting a secret is optional on GitHub, it is required to be set in order to use @octokit/webhooks
. Content Type must be set to application/json
, application/x-www-form-urlencoded
is not supported.
Usage
// install with: npm install @octokit/webhooks
const { Webhooks, createNodeMiddleware } = require("@octokit/webhooks");
const webhooks = new Webhooks({
secret: "mysecret",
});
webhooks.onAny(({ id, name, payload }) => {
console.log(name, "event received");
});
require("http").createServer(createNodeMiddleware(webhooks)).listen(3000);
// can now receive webhook events at /api/github/webhooks
Local development
You can receive webhooks on your local machine or even browser using EventSource and smee.io.
Go to smee.io and Start a new channel. Then copy the "Webhook Proxy URL" and
- enter it in the GitHub App’s "Webhook URL" input
- pass it to the EventSource constructor, see below
const webhookProxyUrl = "https://smee.io/IrqK0nopGAOc847"; // replace with your own Webhook Proxy URL
const source = new EventSource(webhookProxyUrl);
source.onmessage = (event) => {
const webhookEvent = JSON.parse(event.data);
webhooks
.verifyAndReceive({
id: webhookEvent["x-request-id"],
name: webhookEvent["x-github-event"],
signature: webhookEvent["x-hub-signature"],
payload: webhookEvent.body,
})
.catch(console.error);
};
EventSource
is a native browser API and can be polyfilled for browsers that don’t support it. In node, you can use the eventsource
package: install with npm install eventsource
, then const EventSource = require('eventsource')
API
- Constructor
- webhooks.sign()
- webhooks.verify()
- webhooks.verifyAndReceive()
- webhooks.receive()
- webhooks.on()
- webhooks.onAny()
- webhooks.onError()
- webhooks.removeListener()
- createNodeMiddleware()
- Webhook events
- emitterEventNames
Constructor
new Webhooks({ secret /*, transform */ });
Used for internal logging. Defaults to console
with debug
and info
doing nothing.
Returns the webhooks
API.
webhooks.sign()
webhooks.sign(eventPayload);
Returns a signature
string. Throws error if eventPayload
is not passed.
The sign
method can be imported as static method from @octokit/webhooks-methods
.
webhooks.verify()
webhooks.verify(eventPayload, signature);
Returns true
or false
. Throws error if eventPayload
or signature
not passed.
The verify
method can be imported as static method from @octokit/webhooks-methods
.
webhooks.verifyAndReceive()
webhooks.verifyAndReceive({ id, name, payload, signature });
Returns a promise.
Verifies event using webhooks.verify(), then handles the event using webhooks.receive().
Additionally, if verification fails, rejects the returned promise and emits an error
event.
Example
const { Webhooks } = require("@octokit/webhooks");
const webhooks = new Webhooks({
secret: "mysecret",
});
eventHandler.on("error", handleSignatureVerificationError);
// put this inside your webhooks route handler
eventHandler
.verifyAndReceive({
id: request.headers["x-github-delivery"],
name: request.headers["x-github-event"],
payload: request.body,
signature: request.headers["x-hub-signature-256"],
})
.catch(handleErrorsFromHooks);
webhooks.receive()
webhooks.receive({ id, name, payload });
Returns a promise. Runs all handlers set with webhooks.on()
in parallel and waits for them to finish. If one of the handlers rejects or throws an error, then webhooks.receive()
rejects. The returned error has an .errors
property which holds an array of all errors caught from the handlers. If no errors occur, webhooks.receive()
resolves without passing any value.
The .receive()
method belongs to the event-handler
module which can be used standalone.
webhooks.on()
webhooks.on(eventName, handler);
webhooks.on(eventNames, handler);
The .on()
method belongs to the event-handler
module which can be used standalone.
webhooks.onAny()
webhooks.onAny(handler);
The .onAny()
method belongs to the event-handler
module which can be used standalone.
webhooks.onError()
webhooks.onError(handler);
If a webhook event handler throws an error or returns a promise that rejects, an error event is triggered. You can use this handler for logging or reporting events. The passed error object has a .event property which has all information on the event.
Asynchronous error
event handler are not blocking the .receive()
method from completing.
The .onError()
method belongs to the event-handler
module which can be used standalone.
webhooks.removeListener()
webhooks.removeListener(eventName, handler);
webhooks.removeListener(eventNames, handler);
The .removeListener()
method belongs to the event-handler
module which can be used standalone.
createNodeMiddleware()
const { createServer } = require("http");
const { Webhooks, createNodeMiddleware } = require("@octokit/webhooks");
const webhooks = new Webhooks({
secret: "mysecret",
});
const middleware = createNodeMiddleware(webhooks, { path: "/" });
createServer(middleware).listen(3000);
// can now receive user authorization callbacks at POST /
Used for internal logging. Defaults to console
with debug
and info
doing nothing.
Defaults to
function onUnhandledRequest(request, response) {
response.writeHead(400, {
"content-type": "application/json",
});
response.end(
JSON.stringify({
error: error.message,
})
);
}
Webhook events
See the full list of event types with example payloads.
If there are actions for a webhook, events are emitted for both, the webhook name as well as a combination of the webhook name and the action, e.g. installation
and installation.created
.
| Event | Actions |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| branch_protection_rule
| created
deleted
edited
|
| check_run
| completed
created
requested_action
rerequested
|
| check_suite
| completed
requested
rerequested
|
| code_scanning_alert
| appeared_in_branch
closed_by_user
created
fixed
reopened
reopened_by_user
|
| commit_comment
| created
|
| create
| |
| delete
| |
| deploy_key
| created
deleted
|
| deployment
| created
|
| deployment_status
| created
|
| discussion
| answered
category_changed
created
deleted
edited
labeled
locked
pinned
transferred
unanswered
unlabeled
unlocked
unpinned
|
| discussion_comment
| created
deleted
edited
|
| fork
| |
| github_app_authorization
| revoked
|
| gollum
| |
| installation
| created
deleted
new_permissions_accepted
suspend
unsuspend
|
| installation_repositories
| added
removed
|
| issue_comment
| created
deleted
edited
|
| issues
| assigned
closed
deleted
demilestoned
edited
labeled
locked
milestoned
opened
pinned
reopened
transferred
unassigned
unlabeled
unlocked
unpinned
|
| label
| created
deleted
edited
|
| marketplace_purchase
| cancelled
changed
pending_change
pending_change_cancelled
purchased
|
| member
| added
edited
removed
|
| membership
| added
removed
|
| meta
| deleted
|
| milestone
| closed
created
deleted
edited
opened
|
| org_block
| blocked
unblocked
|
| organization
| deleted
member_added
member_invited
member_removed
renamed
|
| package
| published
updated
|
| page_build
| |
| ping
| |
| project
| closed
created
deleted
edited
reopened
|
| project_card
| converted
created
deleted
edited
moved
|
| project_column
| created
deleted
edited
moved
|
| public
| |
| pull_request
| assigned
auto_merge_disabled
auto_merge_enabled
closed
converted_to_draft
edited
labeled
locked
opened
ready_for_review
reopened
review_request_removed
review_requested
synchronize
unassigned
unlabeled
unlocked
|
| pull_request_review
| dismissed
edited
submitted
|
| pull_request_review_comment
| created
deleted
edited
|
| pull_request_review_thread
| resolved
unresolved
|
| push
| |
| release
| created
deleted
edited
prereleased
published
released
unpublished
|
| repository
| archived
created
deleted
edited
privatized
publicized
renamed
transferred
unarchived
|
| repository_dispatch
| |
| repository_import
| |
| repository_vulnerability_alert
| create
dismiss
reopen
resolve
|
| secret_scanning_alert
| created
reopened
resolved
|
| security_advisory
| performed
published
updated
withdrawn
|
| sponsorship
| cancelled
created
edited
pending_cancellation
pending_tier_change
tier_changed
|
| star
| created
deleted
|
| status
| |
| team
| added_to_repository
created
deleted
edited
removed_from_repository
|
| team_add
| |
| watch
| started
|
| workflow_dispatch
| |
| workflow_job
| completed
in_progress
queued
|
| workflow_run
| completed
requested
|
emitterEventNames
A read only tuple containing all the possible combinations of the webhook events + actions listed above. This might be useful in GUI and input validation.
import { emitterEventNames } from "@octokit/webhooks";
emitterEventNames; // ["check_run", "check_run.completed", ...]
TypeScript
The types for the webhook payloads are sourced from @octokit/webhooks-types
,
which can be used by themselves.
In addition to these types, @octokit/webhooks
exports 2 types specific to itself:
Note that changes to the exported types are not considered breaking changes, as the changes will not impact production code, but only fail locally or during CI at build time.
EmitterWebhookEventName
A union of all possible events and event/action combinations supported by the event emitter, e.g. "check_run" | "check_run.completed" | ... many more ... | "workflow_run.requested"
.
EmitterWebhookEvent
The object that is emitted by @octokit/webhooks
as an event; made up of an id
, name
, and payload
properties.
An optional generic parameter can be passed to narrow the type of the name
and payload
properties based on event names or event/action combinations, e.g. EmitterWebhookEvent<"check_run" | "code_scanning_alert.fixed">
.