-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
78 lines (66 loc) · 2.09 KB
/
app.js
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
const express = require('express')
const bodyParser = require('body-parser')
const {HttpClient} = require('@actions/http-client')
const {ErrorHandler, BadRequestError} = require('express-json-api-error-handler')
const createComment = async (http, params) => {
const {repoToken, owner, repo, issueNumber, body} = params
return http.postJson(
`https://api.github.com/repos/${owner}/${repo}/issues/${issueNumber}/comments`,
{body},
{
accept: 'application/vnd.github.v3+json',
authorization: `token ${repoToken}`,
}
)
}
const checkToken = async (http, token) => {
if (!token) {
return false
}
if (token === process.env.GITHUB_TOKEN) {
// Assume the use of this token is intentional
return true
}
try {
await http.getJson(`https://api.github.com/user/repos`, {
accept: 'application/vnd.github.v3+json',
authorization: `token ${token}`,
})
return false
} catch (err) {
// Far from perfect, temporary tokens are difficult to identify
// A bad token returns 401, and a personal token returns 200
return (
err.statusCode === 403 &&
err.result.message &&
err.result.message.startsWith('Resource not accessible by integration')
)
}
}
const app = express()
app.use((req, res, next) => {
req.httpClient = new HttpClient('http-client-add-pr-comment-bot')
next()
})
app.use(bodyParser.json())
app.post('/repos/:owner/:repo/issues/:issueNumber/comments', async (req, res, next) => {
try {
const isTokenValid = await checkToken(req.httpClient, req.header('temporary-github-token'))
if (!isTokenValid) {
throw new BadRequestError('must provide a valid temporary github token')
}
const response = await createComment(req.httpClient, {
...req.params,
...req.body,
repoToken: process.env.GITHUB_TOKEN,
})
res.status(200).send(response).end()
} catch (err) {
next(err)
}
})
// Must use last
const errorHandler = new ErrorHandler()
errorHandler.setErrorEventHandler(err => console.log(JSON.stringify(err)))
app.use(errorHandler.handle)
app.listen(process.env.PORT || 3000)