github-webhook 2.0.2 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: 'github-actions'
4
+ directory: '/'
5
+ schedule:
6
+ interval: 'weekly'
7
+ commit-message:
8
+ prefix: 'chore'
9
+ include: 'scope'
10
+ cooldown:
11
+ default-days: 5
12
+ - package-ecosystem: 'npm'
13
+ directory: '/'
14
+ schedule:
15
+ interval: 'weekly'
16
+ commit-message:
17
+ prefix: 'chore'
18
+ include: 'scope'
19
+ cooldown:
20
+ default-days: 5
@@ -0,0 +1,46 @@
1
+ name: Test & Maybe Release
2
+ on: [push, pull_request]
3
+ jobs:
4
+ test:
5
+ strategy:
6
+ fail-fast: false
7
+ matrix:
8
+ node: [lts/*, current]
9
+ os: [macos-latest, ubuntu-latest, windows-latest]
10
+ runs-on: ${{ matrix.os }}
11
+ steps:
12
+ - name: Checkout Repository
13
+ uses: actions/checkout@v6
14
+ - name: Use Node.js ${{ matrix.node }}
15
+ uses: actions/setup-node@v6
16
+ with:
17
+ node-version: ${{ matrix.node }}
18
+ - name: Install Dependencies
19
+ run: npm install --no-progress
20
+ - name: Run tests
21
+ run: npm test
22
+ release:
23
+ name: Release
24
+ permissions:
25
+ contents: write
26
+ id-token: write
27
+ needs: test
28
+ runs-on: ubuntu-latest
29
+ if: github.event_name == 'push' && github.ref == 'refs/heads/master'
30
+ steps:
31
+ - name: Checkout
32
+ uses: actions/checkout@v6
33
+ with:
34
+ fetch-depth: 0
35
+ - name: Setup Node.js
36
+ uses: actions/setup-node@v6
37
+ with:
38
+ node-version: lts/*
39
+ registry-url: 'https://registry.npmjs.org'
40
+ - name: Install dependencies
41
+ run: npm install --no-progress
42
+ - name: Release
43
+ env:
44
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
45
+ NPM_CONFIG_PROVENANCE: true
46
+ run: npx semantic-release
package/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ ## [3.0.1](https://github.com/rvagg/github-webhook/compare/v3.0.0...v3.0.1) (2026-01-24)
2
+
3
+ ### Bug Fixes
4
+
5
+ * perform symlink-safe isMain check ([#23](https://github.com/rvagg/github-webhook/issues/23)) ([1f9efdd](https://github.com/rvagg/github-webhook/commit/1f9efdd1ce3bcfc6d766c1d0ab809f55e31c88af))
6
+
7
+ ## [3.0.0](https://github.com/rvagg/github-webhook/compare/v2.0.2...v3.0.0) (2026-01-24)
8
+
9
+ ### ⚠ BREAKING CHANGES
10
+
11
+ * Requires Node.js 20 or later. Uses ESM imports
12
+ instead of CommonJS require().
13
+
14
+ ### Features
15
+
16
+ * modernise to ESM with Node.js 20+ ([#22](https://github.com/rvagg/github-webhook/issues/22)) ([09b04ad](https://github.com/rvagg/github-webhook/commit/09b04ad8db951627fc55f865558d887b57435c5e))
package/README.md CHANGED
@@ -1,23 +1,44 @@
1
1
  # github-webhook
2
2
 
3
- [![Build Status](https://travis-ci.com/rvagg/github-webhook.svg?branch=master)](https://travis-ci.com/rvagg/github-webhook)
3
+ [![NPM](https://nodei.co/npm/github-webhook.svg?style=flat&data=n,v&color=blue)](https://nodei.co/npm/github-webhook/)
4
4
 
5
- [![NPM](https://nodei.co/npm/github-webhook.svg)](https://nodei.co/npm/github-webhook/)
5
+ A lightweight server that listens for GitHub Webhook events and executes commands when specific conditions are matched. Useful for automated deployments, CI triggers, and other GitHub-driven workflows.
6
6
 
7
- A stand-alone GitHub Webhook end-point server.
7
+ ## Installation
8
8
 
9
- ## Example
9
+ ```sh
10
+ npm install -g github-webhook
11
+ ```
12
+
13
+ ## Quick Start
14
+
15
+ ```sh
16
+ github-webhook \
17
+ --port=9999 \
18
+ --path=/webhook \
19
+ --secret=mygithubsecret \
20
+ --rule='push:ref == "refs/heads/master" && repository.name == "myrepo":./deploy.sh'
21
+ ```
10
22
 
11
- ```text
23
+ Then configure your GitHub repository's webhook settings to point to `http://yourserver:9999/webhook` with the matching secret.
24
+
25
+ ## Configuration
26
+
27
+ You can configure github-webhook via command-line arguments or a JSON config file (or both - command-line overrides the config file).
28
+
29
+ ### Command-line
30
+
31
+ ```sh
12
32
  github-webhook \
33
+ --config=/etc/github-webhook.json \
13
34
  --port=9999 \
14
35
  --path=/webhook \
15
36
  --secret=mygithubsecret \
16
37
  --log=/var/log/webhook.log \
17
- --rule='push:ref == refs/heads/master && repository.name == myrepo:echo "yay!"'
38
+ --rule='push:ref == "refs/heads/master":./deploy.sh'
18
39
  ```
19
40
 
20
- You can also specify a `--config <file>` where *file* is a JSON file containing the same properties as are available as commandline options. The commandline will always override properties in the config file though.
41
+ ### Config file
21
42
 
22
43
  ```json
23
44
  {
@@ -25,40 +46,182 @@ You can also specify a `--config <file>` where *file* is a JSON file containing
25
46
  "path": "/webhook",
26
47
  "secret": "mygithubsecret",
27
48
  "log": "/var/log/webhook.log",
28
- "rules": [{
29
- "event": "push",
30
- "match": "ref == \"refs/heads/master\" && repository.name == \"myrepo\"",
31
- "exec": "echo yay!"
32
- }]
49
+ "rules": [
50
+ {
51
+ "event": "push",
52
+ "match": "ref == \"refs/heads/master\" && repository.full_name == \"myuser/myrepo\"",
53
+ "exec": "/var/www/deploy.sh"
54
+ }
55
+ ]
33
56
  }
34
57
  ```
35
58
 
36
- ## Options
59
+ ### Options
37
60
 
38
- * **port** (required): the port for the server to listen to (also respects `PORT` env var), should match what you tell GitHub
39
- * **path** (required): the path / route to listen to webhook requests on, should match what you tell GitHub
40
- * **secret** (required): the key used to hash the payload by GitHub that we verify against, should match what you tell GitHub
41
- * **host** (optional): if you want to restrict `listen()` to a specific host
42
- * **log** (optional): a file to print logs to, each command execution will be logged, also note that you can set the `DEBUG` env var to see debug output (see [debug](https://github.com/visionmedia/debug)). Note that the special strings 'stdout' and 'stderr' will redirect log output to standard out and standard error respectively rather than files with those names.
43
- * **rules** (optional): an array of objects representing rules to match against and commands to execute, can also be supplied as individual `--rule` commandline arguments where the 3 properties are separated by `:` (details below)
61
+ | Option | Required | Description |
62
+ |--------|----------|-------------|
63
+ | `port` | Yes | Port to listen on (also respects `PORT` env var) |
64
+ | `path` | Yes | URL path to receive webhooks (e.g., `/webhook`) |
65
+ | `secret` | Yes | Webhook secret for payload verification (configure the same value in GitHub) |
66
+ | `host` | No | Bind to a specific host/IP address |
67
+ | `log` | No | Log file path, or `stdout`/`stderr` for console output |
68
+ | `rules` | No | Array of rules to match and execute (see below) |
44
69
 
45
- ### Rules
70
+ ## Rules
46
71
 
47
- When reacting to valid GitHub Webhook payloads, you can specify any number of rules that will be matched and execute commands in a forked shell. Rules have three components:
72
+ Rules define what commands to execute when specific webhook events are received.
48
73
 
49
- * `"event"`: the event type to match, see the [GitHub Webhooks documentation](https://developer.github.com/webhooks/) for more details on the events you can receive
50
- * `"match"`: a basic object matching rule that will be applied against the payload received from GitHub. Should be flexible enough to match very specific parts of the PayLoad. See [matchme](https://github.com/DamonOehlman/matchme) for how this works.
51
- * `"exec"`: a system command to execute if this rule is matched, should obviously be something related to the event, perhaps a deploy on `"push"` events? **Note**: if you provide a string it will be run with `sh -c "<string>"` (unlikely to be Windows-friendly), however if you provide an array of strings then the first element will be executed with the remaining elements as its arguments.
74
+ ### Rule properties
52
75
 
53
- You can either specify these rules in an array on the `"rules"` property in the config file, or as separate `--rule` commandline arguments where the components are separated by `:`, e.g.: `--rule event:match:exec` (you will generally want to quote the rule to prevent shell trickery).
76
+ | Property | Description |
77
+ |----------|-------------|
78
+ | `event` | GitHub event type to match (`push`, `pull_request`, `issues`, etc.). Use `*` to match all events. See [GitHub Webhooks documentation](https://docs.github.com/en/webhooks) for available events. |
79
+ | `match` | Expression to match against the webhook payload. Uses [matchme](https://github.com/DamonOehlman/matchme) syntax. |
80
+ | `exec` | Command to execute. A string runs via `sh -c "..."`. An array executes directly (first element is the command, rest are arguments). |
81
+
82
+ ### Command-line rule syntax
83
+
84
+ Rules can be specified on the command line as `--rule 'event:match:exec'`:
85
+
86
+ ```sh
87
+ --rule 'push:ref == "refs/heads/master":./deploy.sh'
88
+ ```
54
89
 
55
- ## Programatic usage
90
+ ### Environment variables
56
91
 
57
- You can `var server = require('github-webhook')(options)` and you'll receive a `http.Server` object that has been prepared but not started.
92
+ Commands receive the entire webhook payload as environment variables with a `gh_` prefix:
93
+
94
+ - `gh_ref` - The git ref (e.g., `refs/heads/master`)
95
+ - `gh_branch` - The branch name (extracted from ref for convenience)
96
+ - `gh_repository_name` - Repository name
97
+ - `gh_repository_full_name` - Full repository name (e.g., `owner/repo`)
98
+ - `gh_sender_login` - Username of the person who triggered the event
99
+ - ... and all other payload fields
100
+
101
+ Nested objects become underscore-separated (e.g., `gh_repository_owner_login`).
102
+
103
+ ### Example rules
104
+
105
+ Deploy on push to master:
106
+ ```json
107
+ {
108
+ "event": "push",
109
+ "match": "ref == \"refs/heads/master\" && repository.full_name == \"myuser/myrepo\"",
110
+ "exec": "/var/www/deploy.sh"
111
+ }
112
+ ```
113
+
114
+ Run tests on pull request:
115
+ ```json
116
+ {
117
+ "event": "pull_request",
118
+ "match": "action == \"opened\" || action == \"synchronize\"",
119
+ "exec": ["./run-tests.sh", "--pr"]
120
+ }
121
+ ```
122
+
123
+ Log all events:
124
+ ```json
125
+ {
126
+ "event": "*",
127
+ "match": "true",
128
+ "exec": "echo \"Received $gh_event\" >> /var/log/webhooks.log"
129
+ }
130
+ ```
131
+
132
+ ## Running as a Service
133
+
134
+ ### systemd (recommended)
135
+
136
+ Create `/etc/systemd/system/github-webhook.service`:
137
+
138
+ ```ini
139
+ [Unit]
140
+ Description=GitHub Webhook Server
141
+ After=network.target
142
+
143
+ [Service]
144
+ Type=simple
145
+ User=www-data
146
+ ExecStart=/usr/bin/github-webhook --config /etc/github-webhook.json
147
+ Restart=on-failure
148
+ RestartSec=5
149
+
150
+ [Install]
151
+ WantedBy=multi-user.target
152
+ ```
153
+
154
+ Then enable and start:
155
+
156
+ ```sh
157
+ sudo systemctl daemon-reload
158
+ sudo systemctl enable github-webhook
159
+ sudo systemctl start github-webhook
160
+ sudo systemctl status github-webhook
161
+ ```
162
+
163
+ View logs:
164
+
165
+ ```sh
166
+ sudo journalctl -u github-webhook -f
167
+ ```
168
+
169
+ ### Running behind a reverse proxy
170
+
171
+ For production, run github-webhook behind nginx or another reverse proxy that handles TLS:
172
+
173
+ ```nginx
174
+ location /webhook {
175
+ proxy_pass http://127.0.0.1:9999;
176
+ proxy_set_header Host $host;
177
+ proxy_set_header X-Real-IP $remote_addr;
178
+ }
179
+ ```
180
+
181
+ Then configure github-webhook with `--host=127.0.0.1` to only accept local connections.
182
+
183
+ ## Programmatic Usage
184
+
185
+ ```js
186
+ import webhook from 'github-webhook'
187
+
188
+ const server = webhook({
189
+ port: 9999,
190
+ path: '/webhook',
191
+ secret: 'mygithubsecret',
192
+ rules: [
193
+ {
194
+ event: 'push',
195
+ match: 'ref == "refs/heads/master"',
196
+ exec: './deploy.sh'
197
+ }
198
+ ]
199
+ })
200
+
201
+ server.listen(9999, () => {
202
+ console.log('Webhook server listening on port 9999')
203
+ })
204
+ ```
205
+
206
+ The function returns an `http.Server` instance with an attached `webhookHandler` for custom event handling:
207
+
208
+ ```js
209
+ server.webhookHandler.on('push', (event) => {
210
+ console.log('Push event:', event.payload)
211
+ })
212
+ ```
213
+
214
+ ## Debugging
215
+
216
+ Enable debug output with the `DEBUG` environment variable:
217
+
218
+ ```sh
219
+ DEBUG=github-webhook:* github-webhook --config /etc/github-webhook.json
220
+ ```
58
221
 
59
- ## More information
222
+ ## More Information
60
223
 
61
- **github-webhook** is powered by [github-webhook-handler](https://github.com/rvagg/github-webhook-handler), see that for more details.
224
+ **github-webhook** is powered by [github-webhook-handler](https://github.com/rvagg/github-webhook-handler).
62
225
 
63
226
  ## License
64
227
 
package/github-webhook.js CHANGED
@@ -1,18 +1,32 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const http = require('http')
4
- const fs = require('fs')
5
- const spawn = require('child_process').spawn
6
- const createHandler = require('github-webhook-handler')
7
- const debug = require('debug')
8
- const matchme = require('matchme')
9
- const split2 = require('split2')
10
- const through2 = require('through2')
11
- const argv = require('minimist')(process.argv.slice(2))
3
+ import http from 'node:http'
4
+ import fs from 'node:fs'
5
+ import { spawn } from 'node:child_process'
6
+ import { fileURLToPath } from 'node:url'
7
+ import createHandler from 'github-webhook-handler'
8
+ import debug from 'debug'
9
+ import matchme from 'matchme'
10
+ import split2 from 'split2'
11
+ import through2 from 'through2'
12
+ import minimist from 'minimist'
13
+
12
14
  const serverDebug = debug('github-webhook:server')
13
15
  const eventsDebug = debug('github-webhook:events')
14
16
 
15
- if (require.main === module) {
17
+ // Handle symlinks (npm global install creates symlinks)
18
+ function resolveRealPath (p) {
19
+ try {
20
+ return fs.realpathSync(p)
21
+ } catch {
22
+ return p
23
+ }
24
+ }
25
+
26
+ const isMain = resolveRealPath(process.argv[1]) === fileURLToPath(import.meta.url)
27
+
28
+ if (isMain) {
29
+ const argv = minimist(process.argv.slice(2))
16
30
  let config = {}
17
31
 
18
32
  if (typeof argv.config === 'string') {
@@ -71,7 +85,7 @@ function collectRules (rules) {
71
85
  return rules.map((rule) => {
72
86
  let c = rule.indexOf(':')
73
87
  if (c < 0) {
74
- return
88
+ return null
75
89
  }
76
90
 
77
91
  const event = rule.substring(0, c)
@@ -79,17 +93,17 @@ function collectRules (rules) {
79
93
  rule = rule.substring(c + 1)
80
94
  c = rule.indexOf(':')
81
95
  if (c < 0) {
82
- return
96
+ return null
83
97
  }
84
98
 
85
99
  const match = rule.substring(0, c)
86
100
  const exec = rule.substring(c + 1)
87
101
 
88
- return event && match && exec && {
89
- event: event,
90
- match: match,
91
- exec: exec
102
+ if (!event || !match || !exec) {
103
+ return null
92
104
  }
105
+
106
+ return { event, match, exec }
93
107
  }).filter(Boolean)
94
108
  }
95
109
 
@@ -119,13 +133,17 @@ function createServer (options) {
119
133
 
120
134
  handler(req, res, (err) => {
121
135
  function response (code, msg) {
136
+ if (res.headersSent) {
137
+ return
138
+ }
139
+
122
140
  const address = req.socket.address()
123
141
 
124
- serverDebug('Response to %s:%s: %d "%s"'
125
- , address ? address.address : 'unknown'
126
- , address ? address.port : '??'
127
- , code
128
- , msg
142
+ serverDebug('Response to %s:%s: %d "%s"',
143
+ address ? address.address : 'unknown',
144
+ address ? address.port : '??',
145
+ code,
146
+ msg
129
147
  )
130
148
 
131
149
  res.writeHead(code, { 'content-type': 'text/json' })
@@ -163,10 +181,9 @@ function envFromPayload (payload, prefix, env) {
163
181
  env = {}
164
182
  }
165
183
 
184
+ // Add branch as an env var without mutating the payload
166
185
  if (payload.ref && payload.ref.startsWith('refs/heads/')) {
167
- payload.branch = payload.ref.substring('refs/heads/'.length)
168
- } else {
169
- payload.branch = null
186
+ env[prefix + 'branch'] = payload.ref.substring('refs/heads/'.length)
170
187
  }
171
188
 
172
189
  Object.keys(payload).forEach((k) => {
@@ -246,4 +263,4 @@ function handleRules (logStream, rules, event) {
246
263
  })
247
264
  }
248
265
 
249
- module.exports = createServer
266
+ export default createServer
package/package.json CHANGED
@@ -1,11 +1,17 @@
1
1
  {
2
2
  "name": "github-webhook",
3
- "version": "2.0.2",
3
+ "version": "3.0.1",
4
4
  "description": "A flexible web server for reacting GitHub Webhooks",
5
+ "type": "module",
5
6
  "main": "github-webhook.js",
7
+ "exports": "./github-webhook.js",
8
+ "engines": {
9
+ "node": ">=20"
10
+ },
6
11
  "scripts": {
7
- "lint": "standard *.js",
8
- "test": "npm run lint && node test.js"
12
+ "lint": "standard",
13
+ "test:unit": "node --test test.js",
14
+ "test": "npm run lint && npm run test:unit"
9
15
  },
10
16
  "bin": {
11
17
  "github-webhook": "./github-webhook.js"
@@ -21,17 +27,103 @@
21
27
  },
22
28
  "license": "MIT",
23
29
  "devDependencies": {
24
- "bl": "^4.0.1",
25
- "standard": "^14.3.3",
26
- "supertest": "^4.0.2",
27
- "tape": "^4.13.2"
30
+ "@semantic-release/changelog": "^6.0.3",
31
+ "@semantic-release/commit-analyzer": "^13.0.0",
32
+ "@semantic-release/git": "^10.0.1",
33
+ "@semantic-release/github": "^12.0.0",
34
+ "@semantic-release/npm": "^13.0.0",
35
+ "@semantic-release/release-notes-generator": "^14.0.1",
36
+ "conventional-changelog-conventionalcommits": "^9.0.0",
37
+ "semantic-release": "^25.0.0",
38
+ "standard": "^17.1.2"
28
39
  },
29
40
  "dependencies": {
30
- "debug": "^4.1.1",
41
+ "debug": "^4.4.3",
31
42
  "github-webhook-handler": "^1.0.0",
32
43
  "matchme": "^2.0.1",
33
- "minimist": "^1.2.5",
34
- "split2": "^3.1.1",
35
- "through2": "^3.0.1"
44
+ "minimist": "^1.2.8",
45
+ "split2": "^4.2.0",
46
+ "through2": "^4.0.2"
47
+ },
48
+ "release": {
49
+ "branches": [
50
+ "master"
51
+ ],
52
+ "plugins": [
53
+ [
54
+ "@semantic-release/commit-analyzer",
55
+ {
56
+ "preset": "conventionalcommits",
57
+ "releaseRules": [
58
+ {
59
+ "breaking": true,
60
+ "release": "major"
61
+ },
62
+ {
63
+ "revert": true,
64
+ "release": "patch"
65
+ },
66
+ {
67
+ "type": "feat",
68
+ "release": "minor"
69
+ },
70
+ {
71
+ "type": "fix",
72
+ "release": "patch"
73
+ },
74
+ {
75
+ "type": "chore",
76
+ "release": "patch"
77
+ },
78
+ {
79
+ "type": "docs",
80
+ "release": "patch"
81
+ },
82
+ {
83
+ "type": "test",
84
+ "release": "patch"
85
+ },
86
+ {
87
+ "scope": "no-release",
88
+ "release": false
89
+ }
90
+ ]
91
+ }
92
+ ],
93
+ [
94
+ "@semantic-release/release-notes-generator",
95
+ {
96
+ "preset": "conventionalcommits",
97
+ "presetConfig": {
98
+ "types": [
99
+ {
100
+ "type": "feat",
101
+ "section": "Features"
102
+ },
103
+ {
104
+ "type": "fix",
105
+ "section": "Bug Fixes"
106
+ },
107
+ {
108
+ "type": "chore",
109
+ "section": "Trivial Changes"
110
+ },
111
+ {
112
+ "type": "docs",
113
+ "section": "Trivial Changes"
114
+ },
115
+ {
116
+ "type": "test",
117
+ "section": "Tests"
118
+ }
119
+ ]
120
+ }
121
+ }
122
+ ],
123
+ "@semantic-release/changelog",
124
+ "@semantic-release/npm",
125
+ "@semantic-release/github",
126
+ "@semantic-release/git"
127
+ ]
36
128
  }
37
129
  }
package/test.js CHANGED
@@ -1,54 +1,84 @@
1
- const fs = require('fs')
2
- const path = require('path')
3
- const crypto = require('crypto')
4
- const test = require('tape')
5
- const supertest = require('supertest')
6
- const webhook = require('./')
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import crypto from 'node:crypto'
4
+ import { test } from 'node:test'
5
+ import assert from 'node:assert'
6
+ import { fileURLToPath } from 'node:url'
7
+ import webhook from './github-webhook.js'
8
+
9
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
7
10
 
8
11
  function signBlob (key, blob) {
9
12
  return `sha1=${crypto.createHmac('sha1', key).update(blob).digest('hex')}`
10
13
  }
11
14
 
12
- test('invalid url gets 404', (t) => {
13
- t.plan(1)
15
+ async function makeRequest (server, { method = 'POST', path = '/', headers = {}, body = '{}' }) {
16
+ return new Promise((resolve, reject) => {
17
+ server.listen(0, '127.0.0.1', () => {
18
+ const { port } = server.address()
19
+ const url = new URL(path, `http://127.0.0.1:${port}`)
20
+
21
+ fetch(url, {
22
+ method,
23
+ headers: {
24
+ 'Content-Type': 'application/json',
25
+ ...headers
26
+ },
27
+ body
28
+ })
29
+ .then(async (res) => {
30
+ const text = await res.text()
31
+ let json
32
+ try {
33
+ json = JSON.parse(text)
34
+ } catch {}
35
+ server.close()
36
+ resolve({ status: res.status, headers: res.headers, text, json })
37
+ })
38
+ .catch((err) => {
39
+ server.close()
40
+ reject(err)
41
+ })
42
+ })
43
+ })
44
+ }
14
45
 
46
+ test('invalid url gets 404', async () => {
15
47
  const options = { port: 0, path: '/webhook', secret: 'foofaa' }
16
48
  const server = webhook(options)
17
49
 
18
- supertest(server)
19
- .post('/')
20
- .set('X-Hub-Signature', signBlob('foofaa', '{}'))
21
- .set('X-Github-Event', 'issues')
22
- .set('X-Github-Delivery', '123abc')
23
- .expect('Content-Type', /json/)
24
- .expect(404)
25
- .send('{}')
26
- .end((err) => {
27
- t.error(err)
28
- })
29
- })
50
+ const res = await makeRequest(server, {
51
+ path: '/',
52
+ headers: {
53
+ 'X-Hub-Signature': signBlob('foofaa', '{}'),
54
+ 'X-Github-Event': 'issues',
55
+ 'X-Github-Delivery': '123abc'
56
+ },
57
+ body: '{}'
58
+ })
30
59
 
31
- test('valid url, incomplete data gets 400', (t) => {
32
- t.plan(1)
60
+ assert.strictEqual(res.status, 404)
61
+ assert.ok(res.headers.get('content-type').includes('json'))
62
+ })
33
63
 
64
+ test('valid url, incomplete data gets 400', async () => {
34
65
  const options = { port: 0, path: '/webhook', secret: 'foofaa' }
35
66
  const server = webhook(options)
36
67
 
37
- supertest(server)
38
- .post('/webhook')
39
- .set('X-Github-Event', 'issues')
40
- .set('X-Github-Delivery', '123abc')
41
- .expect('Content-Type', /json/)
42
- .expect(400)
43
- .send('{}')
44
- .end((err) => {
45
- t.error(err)
46
- })
47
- })
68
+ const res = await makeRequest(server, {
69
+ path: '/webhook',
70
+ headers: {
71
+ 'X-Github-Event': 'issues',
72
+ 'X-Github-Delivery': '123abc'
73
+ },
74
+ body: '{}'
75
+ })
48
76
 
49
- test('valid url, complete data gets 200', (t) => {
50
- t.plan(2)
77
+ assert.strictEqual(res.status, 400)
78
+ assert.ok(res.headers.get('content-type').includes('json'))
79
+ })
51
80
 
81
+ test('valid url, complete data gets 200', async () => {
52
82
  const options = { port: 0, path: '/webhook', secret: 'foofaa' }
53
83
  const server = webhook(options)
54
84
  const obj = { some: 'github', object: 'with', properties: true }
@@ -56,40 +86,46 @@ test('valid url, complete data gets 200', (t) => {
56
86
  const id = '123abc'
57
87
  const eventType = 'issues'
58
88
 
59
- server.webhookHandler.on(eventType, (event) => {
60
- delete event.host // too hard
61
- t.deepEqual(event, { event: eventType, id: id, payload: obj, protocol: undefined, url: '/webhook', path: '/webhook' })
89
+ const eventPromise = new Promise((resolve) => {
90
+ server.webhookHandler.on(eventType, (event) => {
91
+ delete event.host
92
+ resolve(event)
93
+ })
62
94
  })
63
95
 
64
- supertest(server)
65
- .post('/webhook')
66
- .set('X-Hub-Signature', signBlob('foofaa', json))
67
- .set('X-Github-Event', eventType)
68
- .set('X-Github-Delivery', id)
69
- .send(json)
70
- .expect('Content-Type', /json/)
71
- .expect(200)
72
- .end((err) => {
73
- t.error(err)
74
- })
75
- })
96
+ const res = await makeRequest(server, {
97
+ path: '/webhook',
98
+ headers: {
99
+ 'X-Hub-Signature': signBlob('foofaa', json),
100
+ 'X-Github-Event': eventType,
101
+ 'X-Github-Delivery': id
102
+ },
103
+ body: json
104
+ })
105
+
106
+ assert.strictEqual(res.status, 200)
107
+ assert.ok(res.headers.get('content-type').includes('json'))
76
108
 
77
- test('valid request triggers rule', (t) => {
78
- t.plan(5)
109
+ const event = await eventPromise
110
+ assert.strictEqual(event.event, eventType)
111
+ assert.strictEqual(event.id, id)
112
+ assert.deepStrictEqual(event.payload, obj)
113
+ })
79
114
 
80
- const tmpfile = path.join(__dirname, '/__test_data.' + Math.random())
115
+ test('valid request triggers rule', { skip: process.platform === 'win32' }, async () => {
116
+ const tmpfile = path.join(__dirname, '__test_data.' + Math.random())
81
117
  const eventType = 'issues'
82
118
  const options = {
83
119
  port: 0,
84
120
  path: '/webhook',
85
121
  secret: 'foofaa',
86
122
  rules: [
87
- { // should not trigger this event
123
+ {
88
124
  event: eventType,
89
125
  match: 'some == xxgithub',
90
126
  exec: ['sh', '-c', `echo "w00t!" > ${tmpfile}2`]
91
127
  },
92
- { // should trigger this event
128
+ {
93
129
  event: eventType,
94
130
  match: 'some == github',
95
131
  exec: `echo "w00t!" > ${tmpfile}`
@@ -101,33 +137,39 @@ test('valid request triggers rule', (t) => {
101
137
  const json = JSON.stringify(obj)
102
138
  const id = '123abc'
103
139
 
104
- t.on('end', () => {
105
- fs.unlink(tmpfile, () => {})
140
+ const eventPromise = new Promise((resolve) => {
141
+ server.webhookHandler.on(eventType, (event) => {
142
+ delete event.host
143
+ resolve(event)
144
+ })
106
145
  })
107
146
 
108
- server.webhookHandler.on(eventType, (event) => {
109
- delete event.host // too hard
110
- t.deepEqual(event, { event: eventType, id: id, payload: obj, protocol: undefined, url: '/webhook', path: '/webhook' })
111
- setTimeout(() => {
112
- fs.readFile(tmpfile, 'utf8', (err, data) => {
113
- t.error(err)
114
- t.equal(data, 'w00t!\n')
115
- })
116
- fs.stat(`${tmpfile}2`, (err) => {
117
- t.ok(err, 'does not exist, didn\'t trigger second event')
118
- })
119
- }, 100)
147
+ const res = await makeRequest(server, {
148
+ path: '/webhook',
149
+ headers: {
150
+ 'X-Hub-Signature': signBlob('foofaa', json),
151
+ 'X-Github-Event': eventType,
152
+ 'X-Github-Delivery': id
153
+ },
154
+ body: json
120
155
  })
121
156
 
122
- supertest(server)
123
- .post('/webhook')
124
- .set('X-Hub-Signature', signBlob('foofaa', json))
125
- .set('X-Github-Event', eventType)
126
- .set('X-Github-Delivery', id)
127
- .send(json)
128
- .expect('Content-Type', /json/)
129
- .expect(200)
130
- .end((err) => {
131
- t.error(err)
132
- })
157
+ assert.strictEqual(res.status, 200)
158
+
159
+ const event = await eventPromise
160
+ assert.strictEqual(event.event, eventType)
161
+ assert.strictEqual(event.id, id)
162
+ assert.deepStrictEqual(event.payload, obj)
163
+
164
+ // Wait for the rule to execute
165
+ await new Promise((resolve) => setTimeout(resolve, 200))
166
+
167
+ const data = fs.readFileSync(tmpfile, 'utf8')
168
+ assert.strictEqual(data, 'w00t!\n')
169
+
170
+ // Verify second rule did not trigger
171
+ assert.throws(() => fs.statSync(`${tmpfile}2`), { code: 'ENOENT' })
172
+
173
+ // Cleanup
174
+ fs.unlinkSync(tmpfile)
133
175
  })