Repository navigation
Expand file tree
/
Copy pathgithub-webhook.js
More file actions
executable file
·290 lines (232 loc) · 6.92 KB
/
Copy pathgithub-webhook.js
File metadata and controls
executable file
·290 lines (232 loc) · 6.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env node
import http from 'node:http'
import os from 'node:os'
import fs from 'node:fs'
import { spawn } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import createHandler from 'github-webhook-handler'
import debug from 'debug'
import matchme from 'matchme'
import split2 from 'split2'
import through2 from 'through2'
import minimist from 'minimist'
const serverDebug = debug('github-webhook:server')
const eventsDebug = debug('github-webhook:events')
// Handle symlinks (npm global install creates symlinks)
function resolveRealPath (p) {
try {
return fs.realpathSync(p)
} catch {
return p
}
}
const isMain = resolveRealPath(process.argv[1]) === fileURLToPath(import.meta.url)
if (isMain) {
const argv = minimist(process.argv.slice(2))
let config = {}
if (typeof argv.config === 'string') {
config = JSON.parse(fs.readFileSync(argv.config))
}
if (argv.port !== undefined) {
config.port = argv.port
} else if (process.env.PORT !== undefined) {
config.port = process.env.PORT
}
if (argv.host !== undefined) {
config.host = String(argv.host)
}
if (argv.secret !== undefined) {
config.secret = String(argv.secret)
}
if (argv.path !== undefined) {
config.path = String(argv.path)
}
if (argv.log !== undefined) {
config.log = String(argv.log)
}
if (!Array.isArray(config.rules)) {
config.rules = []
}
if (argv.rule) {
config.rules = config.rules.concat(
collectRules(Array.isArray(argv.rule) ? argv.rule : [argv.rule])
)
}
const listening = function listening (err) {
if (err) {
throw err
}
serverDebug(`Listening on http://${this.address().address}:${this.address().port}`)
}
const server = createServer(config)
server.listen.apply(server, config.host
? [config.port, config.host, listening]
: [config.port, listening]
)
// as PID 1 (e.g. in a container) Node gets no default signal handling, so exit explicitly
for (const signal of ['SIGINT', 'SIGTERM']) {
process.once(signal, () => {
serverDebug('Received %s, exiting', signal)
process.exit(128 + os.constants.signals[signal])
})
}
}
function collectRules (rules) {
return rules.map((rule) => {
let c = rule.indexOf(':')
if (c < 0) {
return null
}
const event = rule.substring(0, c)
rule = rule.substring(c + 1)
c = rule.indexOf(':')
if (c < 0) {
return null
}
const match = rule.substring(0, c)
const exec = rule.substring(c + 1)
if (!event || !match || !exec) {
return null
}
return { event, match, exec }
}).filter(Boolean)
}
function createServer (options) {
if (options.port === undefined) {
throw new TypeError('must provide a \'port\' option')
}
if (!Array.isArray(options.rules)) {
options.rules = []
}
const server = http.createServer()
const handler = createHandler(options)
const logStream = typeof options.log === 'string' && (
options.log === 'stdout'
? process.stdout
: options.log === 'stderr'
? process.stderr
: fs.createWriteStream(options.log)
)
server.webhookHandler = handler
server.on('request', (req, res) => {
serverDebug(`Connection from ${req.socket.address().address}:${req.socket.address().port}`)
handler(req, res, (err) => {
function response (code, msg) {
if (res.headersSent) {
return
}
const address = req.socket.address()
serverDebug('Response to %s:%s: %d "%s"',
address ? address.address : 'unknown',
address ? address.port : '??',
code,
msg
)
res.writeHead(code, { 'content-type': 'text/json' })
res.end(JSON.stringify({ error: msg }))
}
if (err) {
return response(500, `Internal server error: ${err.message}`)
}
response(404, 'Resource not found on this server')
})
})
handler.on('error', (err) => {
eventsDebug('Non-fatal error: ' + JSON.stringify(err.message))
})
handler.on('*', (event) => {
eventsDebug(JSON.stringify(event))
handleRules(logStream, options.rules, event)
})
return server
}
function prefixStream (stream, prefix) {
return stream.pipe(split2()).pipe(through2((data, enc, callback) => {
callback(null, `${prefix}${data}\n`)
}))
}
function envFromPayload (payload, prefix, env) {
if (!env) {
env = {}
}
// Add branch as an env var without mutating the payload
if (payload.ref && payload.ref.startsWith('refs/heads/')) {
env[prefix + 'branch'] = payload.ref.substring('refs/heads/'.length)
}
Object.keys(payload).forEach((k) => {
const val = payload[k]
switch (typeof val) {
case 'boolean':
case 'number':
case 'string':
env[prefix + k] = val
break
case 'object':
if (val) {
envFromPayload(val, prefix + k + '_', env)
}
break
}
})
return env
}
function executeRule (logStream, rule, event) {
if (rule.executing === true) {
// coalesce runs requested while busy into one, using the newest event
rule.pending = event
return
}
rule.executing = true
const startTs = Date.now()
const eventStr = `event="${rule.event}", match="${rule.match}", exec="${rule.exec}"`
const [cmd, ...args] = Array.isArray(rule.exec) ? rule.exec : ['sh', '-c', rule.exec]
eventsDebug('Matched rule for %s', eventStr)
function finish () {
rule.executing = false
const pending = rule.pending
if (pending) {
rule.pending = null
executeRule(logStream, rule, pending)
}
}
let cp
try {
cp = spawn(cmd, args, {
env: Object.assign(envFromPayload(event.payload, 'gh_'), process.env),
// unread pipes fill and block the child
stdio: logStream ? 'pipe' : 'ignore'
})
} catch (err) {
// invalid arguments or env (e.g. a NUL byte in a payload value) throw synchronously
eventsDebug('Error executing command [%s]: %s', rule.exec, err.message)
finish()
return
}
cp.on('error', (err) => {
return eventsDebug('Error executing command [%s]: %s', rule.exec, err.message)
})
cp.on('close', (code) => {
eventsDebug('Executed command [%s] exited with [%d]', rule.exec, code)
if (logStream) {
logStream.write(eventStr + '\n')
logStream.write(new Date() + '\n')
logStream.write('Took ' + (Date.now() - startTs) + ' ms\n')
}
finish()
})
if (logStream) {
prefixStream(cp.stdout, 'stdout: ').pipe(logStream, { end: false })
prefixStream(cp.stderr, 'stderr: ').pipe(logStream, { end: false })
}
}
function handleRules (logStream, rules, event) {
const matched = rules.filter((rule) =>
(rule.event === '*' || rule.event === event.event) && matchme(event.payload, rule.match)
)
if (matched.length === 0) {
eventsDebug('Unmatched event="%s", id="%s"', event.event, event.id)
return
}
matched.forEach((rule) => executeRule(logStream, rule, event))
}
export default createServer