• Stars
    star
    296
  • Rank 135,208 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated 23 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

GitHub webhook events toolset for Node.js

@octokit/webhooks

GitHub webhook events toolset for Node.js

@latest Test

@octokit/webhooks helps to handle webhook events received from GitHub.

GitHub webhooks can be registered in multiple ways

  1. In repository or organization settings on github.com.
  2. Using the REST API for repositories or organizations
  3. 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

  1. enter it in the GitHub App’s "Webhook URL" input
  2. 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

  1. Constructor
  2. webhooks.sign()
  3. webhooks.verify()
  4. webhooks.verifyAndReceive()
  5. webhooks.receive()
  6. webhooks.on()
  7. webhooks.onAny()
  8. webhooks.onError()
  9. webhooks.removeListener()
  10. createNodeMiddleware()
  11. Webhook events
  12. emitterEventNames

Constructor

new Webhooks({ secret /*, transform */ });
secret (String) Required. Secret as configured in GitHub Settings.
transform (Function) Only relevant for webhooks.on. Transform emitted event before calling handlers. Can be asynchronous.
log object

Used for internal logging. Defaults to console with debug and info doing nothing.

Returns the webhooks API.

webhooks.sign()

webhooks.sign(eventPayload);
eventPayload (String) Required. Webhook request payload as received from GitHub

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);
eventPayload (Object [deprecated] or String) Required. Webhook event request payload as received from GitHub.
signature (String) Required. Signature string as calculated by webhooks.sign().

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 });
id String Unique webhook event request id
name String Required. Name of the event. (Event names are set as X-GitHub-Event header in the webhook event request.)
payload Object (deprecated) or String Required. Webhook event request payload as received from GitHub.
signature (String) Required. Signature string as calculated by webhooks.sign().

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 });
id String Unique webhook event request id
name String Required. Name of the event. (Event names are set as X-GitHub-Event header in the webhook event request.)
payload Object Required. Webhook event request payload as received from GitHub.

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);
eventName String Required. Name of the event. One of GitHub's supported event names, or (if the event has an action property) the name of an event followed by its action in the form of <event>.<action>.
eventNames Array Required. Array of event names.
handler Function Required. Method to be run each time the event with the passed name is received. the handler function can be an async function, throw an error or return a Promise. The handler is called with an event object: {id, name, payload}.

The .on() method belongs to the event-handler module which can be used standalone.

webhooks.onAny()

webhooks.onAny(handler);
handler Function Required. Method to be run each time any event is received. the handler function can be an async function, throw an error or return a Promise. The handler is called with an event object: {id, name, payload}.

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.

handler Function Required. Method to be run each time a webhook event handler throws an error or returns a promise that rejects. The handler function can be an async function, return a Promise. The handler is called with an error object that has a .event property which has all the information on the event: {id, name, payload}.

The .onError() method belongs to the event-handler module which can be used standalone.

webhooks.removeListener()

webhooks.removeListener(eventName, handler);
webhooks.removeListener(eventNames, handler);
eventName String Required. Name of the event. One of GitHub's supported event names, or (if the event has an action property) the name of an event followed by its action in the form of <event>.<action>, or '*' for the onAny() method or 'error' for the onError() method.
eventNames Array Required. Array of event names.
handler Function Required. Method which was previously passed to webhooks.on(). If the same handler was registered multiple times for the same event, only the most recent handler gets removed.

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: "/webhooks" });
createServer(async (req, res) => {
  // `middleware` returns `false` when `req` is unhandled (beyond `/webhooks`)
  if (await middleware(req, res)) return;
  res.writeHead(404);
  res.end();
}).listen(3000);
// can now receive user authorization callbacks at POST /webhooks

The middleware returned from createNodeMiddleware can also serve as an Express.js middleware directly.

webhooks Webhooks instance Required.
path string Custom path to match requests against. Defaults to /api/github/webhooks.
log object

Used for internal logging. Defaults to console with debug and info doing nothing.

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
dependabot_alert created
dismissed
fixed
reintroduced
reopened
deploy_key created
deleted
deployment created
deployment_protection_rule requested
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
installation_target renamed
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
merge_group checks_requested
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
projects_v2_item archived
converted
created
deleted
edited
reordered
restored
public
pull_request assigned
auto_merge_disabled
auto_merge_enabled
closed
converted_to_draft
demilestoned
dequeued
edited
enqueued
labeled
locked
milestoned
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
registry_package published
updated
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
revoked
secret_scanning_alert_location created
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
waiting
workflow_run completed
in_progress
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.

⚠️ Caution ⚠️: Webhooks Types are expected to be used with the strictNullChecks option enabled in your tsconfig. If you don't have this option enabled, there's the possibility that you get never as the inferred type in some use cases. See octokit/webhooks#395 for details.

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">.

License

MIT

More Repositories

1

octokit.js

The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno.
TypeScript
6,695
star
2

octokit.rb

Ruby toolkit for the GitHub API
Ruby
3,818
star
3

octokit.net

A GitHub API client library for .NET
C#
2,591
star
4

octokit.objc

GitHub API client for Objective-C
Objective-C
1,841
star
5

core.js

Extendable client for GitHub's REST & GraphQL APIs
TypeScript
1,145
star
6

rest.js

GitHub REST API client for JavaScript
JavaScript
503
star
7

graphql.js

GitHub GraphQL API client for browsers and Node
TypeScript
446
star
8

request-action

A GitHub Action to send arbitrary requests to GitHub's REST API
JavaScript
350
star
9

authentication-strategies.js

GitHub API authentication strategies for Browsers, Node.js, and Deno
320
star
10

go-octokit

Simple Go wrapper for the GitHub API
Go
257
star
11

request.js

Send parameterized requests to GitHub’s APIs with sensible defaults in browsers and Node
TypeScript
223
star
12

webhooks

machine-readable, always up-to-date GitHub Webhooks specifications
TypeScript
202
star
13

action.js

GitHub API client for GitHub Actions
TypeScript
173
star
14

graphql-schema

GitHub’s GraphQL Schema with validation. Automatically updated.
JavaScript
170
star
15

app.js

GitHub Apps toolset for Node.js
TypeScript
149
star
16

auth-app.js

GitHub App authentication for JavaScript
TypeScript
142
star
17

octokit.graphql.net

A GitHub GraphQL client library for .NET
C#
140
star
18

graphql-action

A GitHub Action to send queries to GitHub's GraphQL API
JavaScript
114
star
19

types.ts

Shared TypeScript definitions for Octokit projects
TypeScript
113
star
20

plugin-throttling.js

Octokit plugin for GitHub’s recommended request throttling
TypeScript
100
star
21

plugin-rest-endpoint-methods.js

Octokit plugin adding one method for all of api.github.com REST API endpoints
TypeScript
100
star
22

fixtures

Fixtures for all the octokittens
JavaScript
98
star
23

auth-token.js

GitHub API token authentication for browsers and Node.js
TypeScript
94
star
24

routes

machine-readable, always up-to-date GitHub REST API route specifications
JavaScript
84
star
25

oauth-app.js

GitHub OAuth toolset for Node.js
TypeScript
74
star
26

auth-oauth-app.js

GitHub OAuth App authentication for JavaScript
TypeScript
64
star
27

endpoint.js

Turns REST API endpoints into generic request options
TypeScript
54
star
28

go-sdk

A generated Go SDK from GitHub's OpenAPI specification.
Go
51
star
29

webhooks.net

GitHub webhook events toolset for .NET
C#
46
star
30

plugin-paginate-rest.js

Octokit plugin to paginate REST API endpoint responses
TypeScript
45
star
31

dotnet-sdk

C#
43
star
32

octopoller.rb

A micro gem for polling and retrying. Perfect for making repeating requests.
Ruby
43
star
33

auth-action.js

GitHub API token authentication for GitHub Actions
TypeScript
38
star
34

openapi

GitHub's official OpenAPI spec with Octokit extensions
JavaScript
38
star
35

openapi-types.ts

Generated TypeScript definitions based on GitHub's OpenAPI spec
JavaScript
37
star
36

plugin-paginate-graphql.js

Octokit plugin to paginate GraphQL Query responses
TypeScript
31
star
37

plugin-retry.js

Octokit plugin for GitHub’s recommended request retries
TypeScript
29
star
38

fixtures-server

Fixtures server for browser & language agnositic octokit testing
JavaScript
26
star
39

webhooks-methods.js

Methods to handle GitHub Webhook requests
TypeScript
20
star
40

plugin-enterprise-server.js

Octokit plugin for GitHub Enterprise REST APIs
TypeScript
19
star
41

octokit-next.js

JavaScript
18
star
42

oauth-authorization-url.js

Universal library to retrieve GitHub’s identity URL for the OAuth web flow
TypeScript
16
star
43

auth-oauth-user-client.js

OAuth user authentication without exposing client secret
15
star
44

create-octokit-project.js

"npm init" script to create a new Octokit JS module
JavaScript
15
star
45

auth-oauth-user.js

Octokit authentication strategy for OAuth clients
TypeScript
15
star
46

plugin-create-or-update-text-file.js

Convenience method to create/edit/delete a text file based on its current content
TypeScript
13
star
47

app-permissions

machine-readable, always up-to-date GitHub App permissions
JavaScript
10
star
48

auth-oauth-device.js

GitHub OAuth Device authentication strategy for JavaScript
TypeScript
10
star
49

request-error.js

Error class for Octokit request errors
TypeScript
9
star
50

handbook

Handbook for Octokit maintainers and GitHub integrators
9
star
51

auth-basic.js

GitHub API Basic authentication for browsers and Node.js
TypeScript
8
star
52

.github

7
star
53

discussions

discussions and planning for Octokit clients
7
star
54

plugin-request-log.js

Log all requests and request errors
TypeScript
7
star
55

source-generator

Go
6
star
56

plugin-enterprise-cloud.js

Octokit plugin for GitHub Enterprise Cloud REST APIs
TypeScript
6
star
57

tsconfig

TypeScript configuration for Octokit packages
JavaScript
5
star
58

oauth-methods.js

Request methods to create and refresh user access tokens for OAuth and GitHub Apps
TypeScript
4
star
59

auth-callback.js

GitHub API authentication using a callback method
TypeScript
4
star
60

auth-unauthenticated.js

strategy for explicitly unauthenticated Octokit instances
TypeScript
4
star
61

tf-acc-test-empty-f89p1

Terraform acceptance test f89p1
2
star
62

plugin-enterprise-compatibility.js

Octokit plugin for improving GHE compatibility
TypeScript
1
star
63

openapi-webhooks

JavaScript
1
star