/
application.ts
543 lines (482 loc) 路 15.5 KB
/
application.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
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
import { App as OctokitApp } from '@octokit/app'
import { Octokit } from '@octokit/rest'
import Webhooks from '@octokit/webhooks'
import express from 'express'
import { EventEmitter } from 'promise-events'
import { ApplicationFunction } from '.'
import { Cache } from './cache'
import { Context } from './context'
import { GitHubAPI, ProbotOctokit } from './github'
import { logger } from './logger'
import webhookEventCheck from './webhook-event-check'
import { LoggerWithTarget, wrapLogger } from './wrap-logger'
export interface Options {
app: OctokitApp
cache: Cache
router?: express.Router
catchErrors?: boolean
githubToken?: string
throttleOptions?: any
Octokit?: Octokit.Static
}
export type OnCallback<T> = (context: Context<T>) => Promise<void>
// Some events can't get an authenticated client (#382):
function isUnauthenticatedEvent (event: Webhooks.WebhookEvent<any>) {
return !event.payload.installation ||
(event.name === 'installation' && event.payload.action === 'deleted')
}
/**
* The `app` parameter available to `ApplicationFunction`s
*
* @property {logger} log - A logger
*/
export class Application {
public events: EventEmitter
public app: OctokitApp
public cache: Cache
public router: express.Router
public log: LoggerWithTarget
private githubToken?: string
private throttleOptions: any
private Octokit: Octokit.Static
constructor (options?: Options) {
const opts = options || {} as any
this.events = new EventEmitter()
this.log = wrapLogger(logger, logger)
this.app = opts.app
this.cache = opts.cache
this.router = opts.router || express.Router() // you can do this?
this.githubToken = opts.githubToken
this.throttleOptions = opts.throttleOptions
this.Octokit = opts.Octokit || ProbotOctokit
}
/**
* Loads an ApplicationFunction into the current Application
* @param appFn - Probot application function to load
*/
public load (appFn: ApplicationFunction | ApplicationFunction[]): Application {
if (Array.isArray(appFn)) {
appFn.forEach(a => this.load(a))
} else {
appFn(this)
}
return this
}
public async receive (event: Webhooks.WebhookEvent<any>) {
return Promise.all([
this.events.emit('*', event),
this.events.emit(event.name, event),
this.events.emit(`${ event.name }.${ event.payload.action }`, event)
])
}
/**
* Get an {@link http://expressjs.com|express} router that can be used to
* expose HTTP endpoints
*
* ```
* module.exports = app => {
* // Get an express router to expose new HTTP endpoints
* const route = app.route('/my-app');
*
* // Use any middleware
* route.use(require('express').static(__dirname + '/public'));
*
* // Add a new route
* route.get('/hello-world', (req, res) => {
* res.end('Hello World');
* });
* };
* ```
*
* @param path - the prefix for the routes
* @returns an [express.Router](http://expressjs.com/en/4x/api.html#router)
*/
public route (path?: string): express.Router {
if (path) {
const router = express.Router()
this.router.use(path, router)
return router
} else {
return this.router
}
}
/**
* Listen for [GitHub webhooks](https://developer.github.com/webhooks/),
* which are fired for almost every significant action that users take on
* GitHub.
*
* @param event - the name of the [GitHub webhook
* event](https://developer.github.com/webhooks/#events). Most events also
* include an "action". For example, the * [`issues`](
* https://developer.github.com/v3/activity/events/types/#issuesevent)
* event has actions of `assigned`, `unassigned`, `labeled`, `unlabeled`,
* `opened`, `edited`, `milestoned`, `demilestoned`, `closed`, and `reopened`.
* Often, your bot will only care about one type of action, so you can append
* it to the event name with a `.`, like `issues.closed`.
*
* ```js
* app.on('push', context => {
* // Code was just pushed.
* });
*
* app.on('issues.opened', context => {
* // An issue was just opened.
* });
* ```
*
* @param callback - a function to call when the
* webhook is received.
*/
public on (
event:
| 'check_run'
| 'check_run.completed'
| 'check_run.created'
| 'check_run.requested_action'
| 'check_run.rerequested',
callback: OnCallback<Webhooks.WebhookPayloadCheckRun>
): void
public on (
event:
| 'check_suite'
| 'check_suite.completed'
| 'check_suite.requested'
| 'check_suite.rerequested',
callback: OnCallback<Webhooks.WebhookPayloadCheckSuite>
): void
public on (
event: 'commit_comment' | 'commit_comment.created',
callback: OnCallback<Webhooks.WebhookPayloadCommitComment>
): void
public on (
event: 'create',
callback: OnCallback<Webhooks.WebhookPayloadCreate>
): void
public on (
event: 'delete',
callback: OnCallback<Webhooks.WebhookPayloadDelete>
): void
public on (
event: 'deployment',
callback: OnCallback<Webhooks.WebhookPayloadDeployment>
): void
public on (
event: 'deployment_status',
callback: OnCallback<Webhooks.WebhookPayloadDeploymentStatus>
): void
public on (
event: 'fork',
callback: OnCallback<Webhooks.WebhookPayloadFork>
): void
public on (
event: 'github_app_authorization',
callback: OnCallback<Webhooks.WebhookPayloadGithubAppAuthorization>
): void
public on (
event: 'gollum',
callback: OnCallback<Webhooks.WebhookPayloadGollum>
): void
public on (
event: 'installation' | 'installation.created' | 'installation.deleted',
callback: OnCallback<Webhooks.WebhookPayloadInstallation>
): void
public on (
event:
| 'installation_repositories'
| 'installation_repositories.added'
| 'installation_repositories.removed',
callback: OnCallback<Webhooks.WebhookPayloadInstallationRepositories>
): void
public on (
event:
| 'issue_comment'
| 'issue_comment.created'
| 'issue_comment.deleted'
| 'issue_comment.edited',
callback: OnCallback<Webhooks.WebhookPayloadIssueComment>
): void
public on (
event:
| 'issues'
| 'issues.assigned'
| 'issues.closed'
| 'issues.deleted'
| 'issues.demilestoned'
| 'issues.edited'
| 'issues.labeled'
| 'issues.milestoned'
| 'issues.opened'
| 'issues.reopened'
| 'issues.transferred'
| 'issues.unassigned'
| 'issues.unlabeled',
callback: OnCallback<Webhooks.WebhookPayloadIssues>
): void
public on (
event: 'label' | 'label.created' | 'label.deleted' | 'label.edited',
callback: OnCallback<Webhooks.WebhookPayloadLabel>
): void
public on (
event:
| 'marketplace_purchase'
| 'marketplace_purchase.cancelled'
| 'marketplace_purchase.changed'
| 'marketplace_purchase.pending_change'
| 'marketplace_purchase.pending_change_cancelled'
| 'marketplace_purchase.purchased',
callback: OnCallback<Webhooks.WebhookPayloadMarketplacePurchase>
): void
public on (
event: 'member' | 'member.added' | 'member.deleted' | 'member.edited',
callback: OnCallback<Webhooks.WebhookPayloadMember>
): void
public on (
event: 'membership' | 'membership.added' | 'membership.removed',
callback: OnCallback<Webhooks.WebhookPayloadMembership>
): void
public on (
event:
| 'milestone'
| 'milestone.closed'
| 'milestone.created'
| 'milestone.deleted'
| 'milestone.edited'
| 'milestone.opened',
callback: OnCallback<Webhooks.WebhookPayloadMilestone>
): void
public on (
event:
| 'organization'
| 'organization.member_added'
| 'organization.member_invited'
| 'organization.member_removed',
callback: OnCallback<Webhooks.WebhookPayloadOrganization>
): void
public on (
event: 'org_block' | 'org_block.blocked' | 'org_block.unblocked',
callback: OnCallback<Webhooks.WebhookPayloadOrgBlock>
): void
public on (
event: 'page_build',
callback: OnCallback<Webhooks.WebhookPayloadPageBuild>
): void
public on (
event:
| 'project_card'
| 'project_card.converted'
| 'project_card.created'
| 'project_card.deleted'
| 'project_card.edited'
| 'project_card.moved',
callback: OnCallback<Webhooks.WebhookPayloadProjectCard>
): void
public on (
event:
| 'project_column'
| 'project_column.created'
| 'project_column.deleted'
| 'project_column.edited'
| 'project_column.moved',
callback: OnCallback<Webhooks.WebhookPayloadProjectColumn>
): void
public on (
event:
| 'project'
| 'project.closed'
| 'project.created'
| 'project.deleted'
| 'project.edited'
| 'project.reopened',
callback: OnCallback<Webhooks.WebhookPayloadProject>
): void
public on (
event: 'public',
callback: OnCallback<Webhooks.WebhookPayloadPublic>
): void
public on (
event:
| 'pull_request'
| 'pull_request.assigned'
| 'pull_request.closed'
| 'pull_request.edited'
| 'pull_request.labeled'
| 'pull_request.opened'
| 'pull_request.reopened'
| 'pull_request.review_request_removed'
| 'pull_request.review_requested'
| 'pull_request.unassigned'
| 'pull_request.unlabeled'
| 'pull_request.synchronize',
callback: OnCallback<Webhooks.WebhookPayloadPullRequest>
): void
public on (
event:
| 'pull_request_review'
| 'pull_request_review.dismissed'
| 'pull_request_review.edited'
| 'pull_request_review.submitted',
callback: OnCallback<Webhooks.WebhookPayloadPullRequestReview>
): void
public on (
event:
| 'pull_request_review_comment'
| 'pull_request_review_comment.created'
| 'pull_request_review_comment.deleted'
| 'pull_request_review_comment.edited',
callback: OnCallback<Webhooks.WebhookPayloadPullRequestReviewComment>
): void
public on (
event: 'push',
callback: OnCallback<Webhooks.WebhookPayloadPush>
): void
public on (
event: 'release' | 'release.published',
callback: OnCallback<Webhooks.WebhookPayloadRelease>
): void
public on (
event:
| 'repository'
| 'repository.archived'
| 'repository.created'
| 'repository.deleted'
| 'repository.privatized'
| 'repository.publicized'
| 'repository.unarchived',
callback: OnCallback<Webhooks.WebhookPayloadRepository>
): void
public on (
event: 'repository_import',
callback: OnCallback<Webhooks.WebhookPayloadRepositoryImport>
): void
public on (
event:
| 'repository_vulnerability_alert'
| 'repository_vulnerability_alert.create'
| 'repository_vulnerability_alert.dismiss'
| 'repository_vulnerability_alert.resolve',
callback: OnCallback<Webhooks.WebhookPayloadRepositoryVulnerabilityAlert>
): void
public on (
event:
| 'security_advisory'
| 'security_advisory.performed'
| 'security_advisory.published'
| 'security_advisory.updated',
callback: OnCallback<Webhooks.WebhookPayloadSecurityAdvisory>
): void
public on (
event: 'status',
callback: OnCallback<Webhooks.WebhookPayloadStatus>
): void
public on (
event:
| 'team'
| 'team.added_to_repository'
| 'team.created'
| 'team.deleted'
| 'team.edited'
| 'team.removed_from_repository',
callback: OnCallback<Webhooks.WebhookPayloadTeam>
): void
public on (
event: 'team_add',
callback: OnCallback<Webhooks.WebhookPayloadTeamAdd>
): void
public on (
event: 'watch' | 'watch.started',
callback: OnCallback<Webhooks.WebhookPayloadWatch>
): void
public on (eventName: string | string[], callback: OnCallback<any>): void
public on (eventName: string | string[], callback: (context: Context) => Promise<void>) {
if (typeof eventName === 'string') {
void webhookEventCheck(this, eventName)
return this.events.on(eventName, async (event: Webhooks.WebhookEvent<any>) => {
const log = this.log.child({ name: 'event', id: event.id })
try {
const github = await this.authenticateEvent(event, log)
const context = new Context(event, github, log)
await callback(context)
} catch (err) {
log.error({ err, event })
throw err
}
})
} else {
eventName.forEach(e => this.on(e, callback))
}
}
/**
* Authenticate and get a GitHub client that can be used to make API calls.
*
* You'll probably want to use `context.github` instead.
*
* **Note**: `app.auth` is asynchronous, so it needs to be prefixed with a
* [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)
* to wait for the magic to happen.
*
* ```js
* module.exports = (app) => {
* app.on('issues.opened', async context => {
* const github = await app.auth();
* });
* };
* ```
*
* @param id - ID of the installation, which can be extracted from
* `context.payload.installation.id`. If called without this parameter, the
* client wil authenticate [as the app](https://developer.github.com/apps/building-integrations/setting-up-and-registering-github-apps/about-authentication-options-for-github-apps/#authenticating-as-a-github-app)
* instead of as a specific installation, which means it can only be used for
* [app APIs](https://developer.github.com/v3/apps/).
*
* @returns An authenticated GitHub API client
* @private
*/
public async auth (id?: number, log = this.log): Promise<GitHubAPI> {
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://')
}
// if installation ID passed, instantiate and authenticate Octokit, then cache the instance
// so that it can be used across received webhook events.
if (id) {
const options = {
Octokit: this.Octokit,
auth: async () => {
const accessToken = await this.app.getInstallationAccessToken({ installationId: id })
return `token ${accessToken}`
},
baseUrl: process.env.GHE_HOST && `${process.env.GHE_PROTOCOL || 'https'}://${process.env.GHE_HOST}/api/v3`,
logger: log.child({ name: 'github', installation: String(id) })
}
if (this.throttleOptions) {
return GitHubAPI({
...options,
throttle: {
id,
...this.throttleOptions
}
})
}
// Cache for 1 minute less than GitHub expiry
const installationTokenTTL = parseInt(process.env.INSTALLATION_TOKEN_TTL || '3540', 10)
return this.cache.wrap(`app:${id}`, () => GitHubAPI(options), { ttl: installationTokenTTL })
}
const token = this.githubToken || this.app.getSignedJsonWebToken()
const github = GitHubAPI({
Octokit: this.Octokit,
auth: `Bearer ${token}`,
baseUrl: process.env.GHE_HOST && `${process.env.GHE_PROTOCOL || 'https'}://${process.env.GHE_HOST}/api/v3`,
logger: log.child({ name: 'github' })
})
return github
}
private authenticateEvent (event: Webhooks.WebhookEvent<any>, log: LoggerWithTarget): Promise<GitHubAPI> {
if (this.githubToken) {
return this.auth()
}
if (isUnauthenticatedEvent(event)) {
log.debug('`context.github` is unauthenticated. See https://probot.github.io/docs/github-api/#unauthenticated-events')
return this.auth()
}
return this.auth(event.payload.installation.id, log)
}
}