forked from microfeedback/microfeedback-github
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
200 lines (173 loc) · 5.48 KB
/
index.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
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
const assert = require('assert');
const parseUserAgent = require('ua-parser-js');
const truncate = require('truncate');
const table = require('markdown-table');
const axios = require('axios');
const mustache = require('mustache');
const { createError } = require('micro');
const microfeedback = require('microfeedback-core');
const pkg = require('./package.json');
const { GH_TOKEN, REPO } = process.env;
assert(GH_TOKEN, 'GH_TOKEN not set');
const HEADER_WHITELIST = ['user-agent', 'origin', 'referer'];
const makeTable = (headers, entries, sort = true) => {
if (entries.length === 0) {
return '';
}
const ret = [headers];
const orderedEntries = sort ? entries.sort((a, b) => a[0] > b[0]) : entries;
orderedEntries.forEach(each => {
ret.push(each);
});
return table(ret);
};
const issueTemplate = `
{{body}}
{{#screenshotURL}}
## Screenshot
![Screenshot]({{&screenshotURL}})
{{/screenshotURL}}
<details><summary>Client Details</summary><p>
{{#headerTable}}
### Headers
{{&headerTable}}
{{/headerTable}}
{{#browserTable}}
### Browser
{{&browserTable}}
{{/browserTable}}
{{#osTable}}
### Operating System
{{&osTable}}
{{/osTable}}
{{#perspectiveTable}}
### Perspective API
{{&perspectiveTable}}
{{/perspectiveTable}}
{{#extraTable}}
### Extra information
{{&extraTable}}
{{/extraTable}}
</p></details>
`;
mustache.parse(issueTemplate);
const makeIssue = ({ body, title, extra, perspective, screenshotURL }, req) => {
let suffix = '';
if (req && req.headers.referer) {
suffix = ` on ${req.headers.referer}`;
}
const view = {
suffix,
body,
extra,
screenshotURL,
pkg,
};
// Format headers as table
if (req && req.headers) {
const entries = Object.entries(req.headers).filter(
e => HEADER_WHITELIST.indexOf(e[0]) >= 0
);
view.headerTable = makeTable(['Header', 'Value'], entries);
}
// Format user agent info as table
if (req && req.headers && req.headers['user-agent']) {
const userAgent = parseUserAgent(req.headers['user-agent']);
const browserEntries = Object.entries(userAgent.browser).filter(e => e[1]);
view.browserTable = makeTable(['Key', 'Value'], browserEntries, false);
const osEntries = Object.entries(userAgent.os).filter(e => e[1]);
view.osTable = makeTable(['Key', 'Value'], osEntries, false);
}
// Format perspective information as table
if (perspective) {
view.perspectiveTable = makeTable(['Key', 'Value'], Object.entries(perspective));
}
// Format extra information as table
if (extra) {
view.extraTable = makeTable(['Key', 'Value'], Object.entries(extra));
}
// TODO: Add spam label if akismet.spam is true
return { title, body: mustache.render(issueTemplate, view) };
};
function getAllowedRepos() {
if (!process.env.ALLOWED_REPOS || process.env.ALLOWED_REPOS === '*') {
return '*';
}
return process.env.ALLOWED_REPOS.split(',').map(each => each.trim());
}
async function checkIfTitleExists({ repo, body, title, token }) {
const githubUrl = 'https://api.github.com/graphql'
// Your personal access token
// The Authorization in the header of the request
const oauth = { Authorization: 'bearer ' + token }
// The GraphQL query, a string
const query = `
{
search(query: "repo:${repo} sort:author-date-desc in:title ${title}", type: ISSUE, first: 100) {
nodes {
... on Issue {
number
title
body
number
}
}
}
}
`
// Post request, axios.post() return a Promise
try {
const res = (await axios.post(githubUrl, { query: query }, { headers: oauth }))
return res.data.data.search.nodes.filter.filter(i=>i.title===title)
} catch (error) {
}
return []
}
const GitHubBackend = async ({ input, perspective, akismet }, req) => {
// Match /<username>/<repo>/ in the URL
// TODO: Allow base64-encoded repo URL
// const { pathname } = url.parse(req.url);
// Trim trailing slashes to get GitHub repo
const repo = REPO//trim(pathname, '/');
const allowedRepos = getAllowedRepos();
if (allowedRepos !== '*' && allowedRepos.indexOf(repo) === -1) {
throw createError(400, `Repo "${repo}" not allowed.`);
}
let issueURL = `https://api.github.com/repos/${repo}/issues`;
let { body, title, extra, screenshotURL } = input;
title = title || `${truncate(
body,
25
)}`;
const issuesThatAlreadyExist = await checkIfTitleExists({ repo, body, title, token: GH_TOKEN })
if (issuesThatAlreadyExist.length > 0) {
const issueNumber = issuesThatAlreadyExist[0].number
issueURL = `https://api.github.com/repos/${repo}/issues/${issueNumber}/comments`;
}
try {
const { data } = await axios({
headers: { "Authorization": `token ${GH_TOKEN}` },
method: 'POST',
url: issueURL,
data: makeIssue({
body,
title,
extra,
screenshotURL,
perspective,
akismet,
}, req),
});
return data;
} catch (err) {
const { status, data } = err.response;
console.log(err);
throw createError(status, data.message, err);
}
};
module.exports = microfeedback(GitHubBackend, {
name: 'github',
version: pkg.version,
allowedRepos: getAllowedRepos(),
});
Object.assign(module.exports, { GitHubBackend, makeIssue });