-
Notifications
You must be signed in to change notification settings - Fork 949
/
index.ts
253 lines (221 loc) · 8.53 KB
/
index.ts
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
// tslint:disable-next-line: no-var-requires
require('dotenv').config()
import { App as OctokitApp } from '@octokit/app'
import { Octokit } from '@octokit/rest'
import Webhooks from '@octokit/webhooks'
import Bottleneck from 'bottleneck'
import Logger from 'bunyan'
import express from 'express'
import Redis from 'ioredis'
import { Server } from 'http'
import { Application } from './application'
import setupApp from './apps/setup'
import { createDefaultCache } from './cache'
import { Context } from './context'
import { GitHubAPI, ProbotOctokit } from './github'
import { logger } from './logger'
import { logRequestErrors } from './middleware/log-request-errors'
import { findPrivateKey } from './private-key'
import { resolve } from './resolver'
import { createServer } from './server'
import { createWebhookProxy } from './webhook-proxy'
const cache = createDefaultCache()
// tslint:disable:no-var-requires
const defaultAppFns: ApplicationFunction[] = [
require('./apps/default'),
require('./apps/sentry'),
require('./apps/stats')
]
// tslint:enable:no-var-requires
export class Probot {
public static async run (appFn: ApplicationFunction | string[]) {
const pkgConf = require('pkg-conf')
const program = require('commander')
const readOptions = (): Options => {
if (Array.isArray(appFn)) {
program
.usage('[options] <apps...>')
.option('-p, --port <n>', 'Port to start the server on', process.env.PORT || 3000)
.option('-W, --webhook-proxy <url>', 'URL of the webhook proxy service.`', process.env.WEBHOOK_PROXY_URL)
.option('-w, --webhook-path <path>', 'URL path which receives webhooks. Ex: `/webhook`', process.env.WEBHOOK_PATH)
.option('-a, --app <id>', 'ID of the GitHub App', process.env.APP_ID)
.option('-s, --secret <secret>', 'Webhook secret of the GitHub App', process.env.WEBHOOK_SECRET)
.option('-P, --private-key <file>', 'Path to certificate of the GitHub App', process.env.PRIVATE_KEY_PATH)
.parse(appFn)
return {
cert: findPrivateKey(program.privateKey) || undefined,
id: program.app,
port: program.port,
secret: program.secret,
webhookPath: program.webhookPath,
webhookProxy: program.webhookProxy
}
}
const privateKey = findPrivateKey()
return {
cert: (privateKey && privateKey.toString()) || undefined,
id: Number(process.env.APP_ID),
port: Number(process.env.PORT) || 3000,
secret: process.env.WEBHOOK_SECRET,
webhookPath: process.env.WEBHOOK_PATH,
webhookProxy: process.env.WEBHOOK_PROXY_URL
}
}
const options = readOptions()
const probot = new Probot(options)
if (!options.id || !options.cert) {
if (process.env.NODE_ENV === 'production') {
if (!options.id) {
throw new Error(
'Application ID is missing, and is required to run in production mode. ' +
'To resolve, ensure the APP_ID environment variable is set.'
)
} else if (!options.cert) {
throw new Error(
'Certificate is missing, and is required to run in production mode. ' +
'To resolve, ensure either the PRIVATE_KEY or PRIVATE_KEY_PATH environment variable is set and contains a valid certificate'
)
}
}
probot.load(setupApp)
} else if (Array.isArray(appFn)) {
const pkg = await pkgConf('probot')
probot.setup(program.args.concat(pkg.apps || pkg.plugins || []))
} else {
probot.load(appFn)
}
probot.start()
return probot
}
public server: express.Application
public httpServer?: Server
public webhook: Webhooks
public logger: Logger
// These 3 need to be public for the tests to work.
public options: Options
public app?: OctokitApp
public throttleOptions: any
private apps: Application[]
private githubToken?: string
private Octokit: Octokit.Static
constructor (options: Options) {
options.webhookPath = options.webhookPath || '/'
options.secret = options.secret || 'development'
this.options = options
this.logger = logger
this.apps = []
this.webhook = new Webhooks({
path: options.webhookPath,
secret: options.secret
})
this.githubToken = options.githubToken
this.Octokit = options.Octokit || ProbotOctokit
if (this.options.id) {
if (process.env.GHE_HOST && /^https?:\/\//.test(process.env.GHE_HOST)) {
throw new Error('Your \`GHE_HOST\` environment variable should not begin with https:// or http://')
}
this.app = new OctokitApp({
baseUrl: process.env.GHE_HOST && `${process.env.GHE_PROTOCOL || 'https'}://${process.env.GHE_HOST}/api/v3`,
id: options.id as number,
privateKey: options.cert as string
})
}
this.throttleOptions = options.throttleOptions
this.server = createServer({ webhook: (this.webhook as any).middleware, logger })
// Log all received webhooks
this.webhook.on('*', async (event: Webhooks.WebhookEvent<any>) => {
await this.receive(event)
})
// Log all webhook errors
this.webhook.on('error', this.errorHandler)
if (options.redisConfig || process.env.REDIS_URL) {
let client
if (options.redisConfig) {
client = new Redis(options.redisConfig)
} else if (process.env.REDIS_URL) {
client = new Redis(process.env.REDIS_URL)
}
const connection = new Bottleneck.IORedisConnection({ client })
connection.on('error', this.logger.error)
this.throttleOptions = Object.assign({
Bottleneck,
connection
}, this.throttleOptions)
}
}
public errorHandler (err: Error) {
const errMessage = (err.message || '').toLowerCase()
if (errMessage.includes('x-hub-signature')) {
logger.error({ err }, 'Go to https://github.com/settings/apps/YOUR_APP and verify that the Webhook secret matches the value of the WEBHOOK_SECRET environment variable.')
} else if (errMessage.includes('pem') || errMessage.includes('json web token')) {
logger.error({ err }, 'Your private key (usually a .pem file) is not correct. Go to https://github.com/settings/apps/YOUR_APP and generate a new PEM file. If you\'re deploying to Now, visit https://probot.github.io/docs/deployment/#now.')
} else {
logger.error(err)
}
}
public receive (event: Webhooks.WebhookEvent<any>) {
this.logger.debug({ event }, 'Webhook received')
return Promise.all(this.apps.map(app => app.receive(event)))
}
public load (appFn: string | ApplicationFunction) {
if (typeof appFn === 'string') {
appFn = resolve(appFn) as ApplicationFunction
}
const app = new Application({
Octokit: this.Octokit,
app: this.app as OctokitApp,
cache,
githubToken: this.githubToken,
throttleOptions: this.throttleOptions
})
// Connect the router from the app to the server
this.server.use(app.router)
// Initialize the ApplicationFunction
app.load(appFn)
this.apps.push(app)
return app
}
public setup (appFns: Array<string | ApplicationFunction>) {
// Log all unhandled rejections
(process as NodeJS.EventEmitter).on('unhandledRejection', this.errorHandler)
// Load the given appFns along with the default ones
appFns.concat(defaultAppFns).forEach(appFn => this.load(appFn))
// Register error handler as the last middleware
this.server.use(logRequestErrors)
}
public start () {
return this.httpServer = this.server.listen(this.options.port, () => {
if (this.options.webhookProxy) {
createWebhookProxy({
logger,
path: this.options.webhookPath,
port: this.options.port,
url: this.options.webhookProxy
})
}
logger.info('Listening on http://localhost:' + this.options.port)
}).on('error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EADDRINUSE') {
logger.error(`Port ${this.options.port} is already in use. You can define the PORT environment variable to use a different port.`)
} else {
logger.error(err)
}
process.exit(1)
})
}
}
export const createProbot = (options: Options) => new Probot(options)
export type ApplicationFunction = (app: Application) => void
export interface Options {
webhookPath?: string
secret?: string,
id?: number,
cert?: string,
githubToken?: string,
webhookProxy?: string,
port?: number,
redisConfig?: Redis.RedisOptions,
Octokit?: Octokit.Static
throttleOptions?: any
}
export { Logger, Context, Application, Octokit, GitHubAPI }