Repository navigation
Expand file tree
/
Copy pathlibrary.js
More file actions
555 lines (526 loc) · 18.6 KB
/
Copy pathlibrary.js
File metadata and controls
555 lines (526 loc) · 18.6 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
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
544
545
546
547
548
549
550
551
552
553
554
555
'use strict';
const winston = require.main.require('winston');
const nconf = require.main.require('nconf');
const db = require.main.require('./src/database');
const posts = require.main.require('./src/posts');
const user = require.main.require('./src/user');
const groups = require.main.require('./src/groups');
const privileges = require.main.require('./src/privileges');
const notifications = require.main.require('./src/notifications');
const translator = require.main.require('./src/translator');
const routeHelpers = require.main.require('./src/routes/helpers');
const SocketPlugins = require.main.require('./src/socket.io/plugins');
const SocketAdmin = require.main.require('./src/socket.io/admin');
const websockets = require.main.require('./src/socket.io');
const pubsub = require.main.require('./src/pubsub');
const common = require('./lib/common');
const notify = require('./lib/notify');
const webhook = require('./lib/webhook');
const poll = require('./lib/poll');
const issues = require('./lib/issues');
const plugin = {};
const {
CONFIG_KEY, PID_KEY_PREFIX, TID_KEY_PREFIX, PRIVILEGE, DAY_MS,
getConfig, getExpiresAt, clearConfigCache, apiUrlFromIssueUrl,
} = common;
const WARN_BEFORE_DAYS = 10;
const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
const STATE_TTL_MS = 10 * 60 * 1000;
async function buildStatus() {
const config = await getConfig();
const expiresAt = getExpiresAt(config);
const now = Date.now();
return {
title: '[[github-issue:admin.title]]',
repo: config.repo || '',
labels: config.labels || '',
expiryDays: config.expiryDays || '',
publicSidebar: parseInt(config.publicSidebar, 10) === 1,
tokenSet: !!config.token,
tokenSetAt: config.tokenSetAt ? new Date(parseInt(config.tokenSetAt, 10)).toISOString().slice(0, 10) : '',
hasExpiry: !!expiresAt,
expiresAtDate: expiresAt ? new Date(expiresAt).toISOString().slice(0, 10) : '',
daysLeft: expiresAt ? Math.max(0, Math.ceil((expiresAt - now) / DAY_MS)) : 0,
expired: !!expiresAt && now >= expiresAt,
webhookUrl: nconf.get('url') + webhook.ROUTE,
webhookSecretSet: !!config.webhookSecret,
notifyEvents: common.NOTIFY_EVENTS.map(event => ({
name: event,
label: `[[github-issue:admin.notify-${event}]]`,
enabled: common.isNotifyEnabled(config, event),
})),
pollEnabled: poll.isEnabled(config),
pollMinutes: poll.getIntervalMinutes(config),
mergeSeconds: notify.getMergeSeconds(config),
};
}
const CONFIG_CHANGED = 'github-issue:config-changed';
function applyConfigChange() {
clearConfigCache();
poll.reschedule().catch(err => common.logError('poll rescheduling failed', err));
}
pubsub.on(CONFIG_CHANGED, applyConfigChange);
plugin.init = async function ({ router }) {
routeHelpers.setupAdminPageRoute(router, '/admin/plugins/github-issue', async (req, res) => {
res.render('admin/plugins/github-issue', await buildStatus());
});
// no CSRF middleware: NodeBB applies it per route, and GitHub authenticates
// the delivery with an HMAC over the raw body instead
router.post(webhook.ROUTE, (req, res) => {
webhook.handler(req, res).catch((err) => {
common.logError('webhook failed', err);
res.sendStatus(500);
});
});
SocketAdmin.plugins.githubIssue = {
getStatus: async () => buildStatus(),
save: async (socket, data) => {
data = data || {};
const repo = String(data.repo || '').trim();
if (repo && !/^[\w.-]+\/[\w.-]+$/.test(repo)) {
throw new Error('[[github-issue:error.invalid-repo]]');
}
const expiryRaw = String(data.expiryDays === undefined || data.expiryDays === null ? '' : data.expiryDays).trim();
if (expiryRaw && (!/^\d+$/.test(expiryRaw) || parseInt(expiryRaw, 10) <= 0)) {
throw new Error('[[github-issue:error.invalid-expiry]]');
}
const config = await getConfig();
const newToken = typeof data.token === 'string' ? data.token.trim() : '';
const pollMinutesRaw = String(data.pollMinutes === undefined || data.pollMinutes === null ? '' : data.pollMinutes).trim();
if (pollMinutesRaw && (!/^\d+$/.test(pollMinutesRaw) || parseInt(pollMinutesRaw, 10) <= 0)) {
throw new Error('[[github-issue:error.invalid-interval]]');
}
const mergeSecondsRaw = String(data.mergeSeconds === undefined || data.mergeSeconds === null ? '' : data.mergeSeconds).trim();
if (mergeSecondsRaw && !/^\d+$/.test(mergeSecondsRaw)) {
throw new Error('[[github-issue:error.invalid-merge]]');
}
const requestedEvents = Array.isArray(data.notifyEvents) ? data.notifyEvents : [];
const update = {
repo: repo,
labels: String(data.labels || '').trim(),
expiryDays: expiryRaw,
publicSidebar: data.publicSidebar ? 1 : 0,
notifyEvents: common.NOTIFY_EVENTS.filter(event => requestedEvents.includes(event)).join(','),
pollEnabled: data.pollEnabled ? 1 : 0,
pollMinutes: pollMinutesRaw,
mergeSeconds: mergeSecondsRaw,
};
if (newToken) {
update.token = newToken;
update.tokenSetAt = Date.now();
}
const newSecret = typeof data.webhookSecret === 'string' ? data.webhookSecret.trim() : '';
if (newSecret) {
update.webhookSecret = newSecret;
} else if (data.clearWebhookSecret) {
update.webhookSecret = '';
}
// a new repository has its own issue numbers and its own history:
// start polling it from now rather than from the old cursor
if (repo !== String(config.repo || '')) {
update.pollIssuesSince = '';
update.pollIssuesEtag = '';
update.pollCommentsSince = '';
update.pollCommentsEtag = '';
}
// any token/expiry change re-arms the warning notifications
if (newToken || expiryRaw !== String(config.expiryDays || '')) {
update.warned10 = 0;
update.warnedExpired = 0;
}
await db.setObject(CONFIG_KEY, update);
// every process caches the config, and only the primary runs the
// poller, so the change has to reach all of them
pubsub.publish(CONFIG_CHANGED);
applyConfigChange();
checkExpiry().catch(err => common.logError('expiry check failed', err));
return buildStatus();
},
};
SocketPlugins.githubIssue = {
create: async (socket, data) => {
if (!socket.uid) {
throw new Error('[[error:not-logged-in]]');
}
data = data || {};
const pid = data.pid;
const title = String(data.title || '').trim();
const body = String(data.body || '');
if (!pid || !title) {
throw new Error('[[error:invalid-data]]');
}
if (title.length > 256 || body.length > 65536) {
throw new Error('[[error:invalid-data]]');
}
const [allowed, canRead] = await Promise.all([
privileges.global.can(PRIVILEGE, socket.uid),
privileges.posts.can('topics:read', pid, socket.uid),
]);
if (!allowed || !canRead) {
throw new Error('[[error:no-privileges]]');
}
const config = await getConfig();
if (!config.token || !config.repo) {
throw new Error('[[github-issue:error.not-configured]]');
}
const expiresAt = getExpiresAt(config);
if (expiresAt && Date.now() >= expiresAt) {
throw new Error('[[github-issue:error.token-expired]]');
}
const labels = String(config.labels || '')
.split(',')
.map(l => l.trim())
.filter(Boolean);
const payload = { title: title, body: body };
if (labels.length) {
// GitHub silently drops `labels` when the token lacks push/triage
// access, so also embed a marker the repo can act on via a
// workflow (see README) to apply the labels with its own token.
payload.labels = labels;
payload.body += `\n\n<!-- forum-labels: ${labels.join(', ')} -->`;
}
let response;
try {
response = await fetch(`https://api.github.com/repos/${config.repo}/issues`, {
method: 'POST',
headers: {
Authorization: `Bearer ${config.token}`,
Accept: 'application/vnd.github+json',
'Content-Type': 'application/json',
'User-Agent': 'nodebb-plugin-github-issue',
'X-GitHub-Api-Version': '2022-11-28',
},
body: JSON.stringify(payload),
});
} catch (err) {
winston.error(`[github-issue] request failed: ${err.stack}`);
throw new Error('[[github-issue:error.request-failed]]');
}
if (!response.ok) {
const text = await response.text().catch(() => '');
winston.error(`[github-issue] GitHub API ${response.status}: ${text.slice(0, 500)}`);
throw new Error(`[[github-issue:error.github, ${response.status}]]`);
}
const issue = await response.json();
const tid = parseInt(await posts.getPostField(pid, 'tid'), 10) || 0;
const timestamp = Date.now();
// make sure a post that still holds a single legacy issue keeps it
// once a second one is opened from the same post
await issues.listForPid(pid);
const stored = await issues.add({
pid: pid,
tid: tid,
uid: socket.uid,
repo: config.repo,
url: issue.html_url,
number: issue.number,
title: issue.title || title,
timestamp: timestamp,
});
if (tid) {
await db.sortedSetAdd(TID_KEY_PREFIX + tid, timestamp, pid);
}
const result = {
id: stored.id,
url: stored.url,
number: stored.number,
title: stored.title,
pid: stored.pid,
timestamp: stored.timestamp,
state: stored.state,
stateReason: stored.stateReason,
};
if (tid) {
websockets.in(`topic_${tid}`).emit('event:github-issue.created', { tid: tid, issue: result });
}
const actor = await user.getUserField(socket.uid, 'displayname');
notify.issueEvent({
issue: stored,
skipUid: socket.uid,
...notify.build.opened(stored, actor || '[[global:guest]]'),
}).catch(err => common.logError('opened notification failed', err));
return result;
},
findDuplicates: async (socket, data) => {
if (!socket.uid) {
throw new Error('[[error:not-logged-in]]');
}
const title = String((data && data.title) || '').trim();
if (!title || title.length > 256) {
throw new Error('[[error:invalid-data]]');
}
const allowed = await privileges.global.can(PRIVILEGE, socket.uid);
if (!allowed) {
throw new Error('[[error:no-privileges]]');
}
const config = await getConfig();
if (!config.token || !config.repo) {
return [];
}
return await findIssuesByTitle(config, title);
},
getExisting: async (socket, data) => {
if (!socket.uid) {
throw new Error('[[error:not-logged-in]]');
}
const pid = data && data.pid;
if (!pid) {
throw new Error('[[error:invalid-data]]');
}
const [allowed, canRead] = await Promise.all([
privileges.global.can(PRIVILEGE, socket.uid),
privileges.posts.can('topics:read', pid, socket.uid),
]);
if (!allowed || !canRead) {
throw new Error('[[error:no-privileges]]');
}
const existing = await issues.listForPid(pid);
return existing.map(issue => ({ url: issue.url, number: issue.number }));
},
};
// jobs only run on the primary process, otherwise every worker in a cluster
// would duplicate the notifications
if (!nconf.get('runJobs')) {
return;
}
backfillIndexes().catch(err => common.logError('index backfill failed', err));
poll.reschedule().catch(err => common.logError('poll scheduling failed', err));
setInterval(() => {
checkExpiry().catch(err => common.logError('expiry check failed', err));
notify.pruneSent().catch(err => common.logError('pruning sent notifications failed', err));
}, CHECK_INTERVAL_MS);
setTimeout(() => {
checkExpiry().catch(err => common.logError('expiry check failed', err));
}, 30 * 1000);
};
plugin.mergeNotifications = async function (data) {
return notify.mergeNotifications(data);
};
plugin.addPrivilege = async function (data) {
data.privileges.set(PRIVILEGE, {
label: '[[github-issue:privilege-label]]',
type: 'other',
});
};
plugin.addPostTool = async function (data) {
if (!data.uid) {
return data;
}
const config = await getConfig();
if (!config.token || !config.repo) {
return data;
}
const allowed = await privileges.global.can(PRIVILEGE, data.uid);
if (allowed) {
data.tools.push({
action: 'post/github-issue',
html: '[[github-issue:open-issue]]',
icon: 'fa-github',
});
}
return data;
};
plugin.addAdminNavigation = async function (header) {
header.plugins.push({
route: '/plugins/github-issue',
icon: 'fa-github',
name: '[[github-issue:admin.title]]',
});
return header;
};
async function getTopicIssues(tid) {
if (!tid) {
return [];
}
const pids = await db.getSortedSetRange(TID_KEY_PREFIX + tid, 0, -1);
if (!pids.length) {
return [];
}
const list = await issues.listForPids(pids);
list.sort((a, b) => a.timestamp - b.timestamp);
await refreshIssueStates(list);
return list.map(issue => ({
id: issue.id,
pid: issue.pid,
url: issue.url,
number: issue.number,
title: issue.title,
timestamp: issue.timestamp,
state: issue.state,
stateReason: issue.stateReason,
}));
}
function normalizeTitle(title) {
return String(title || '').trim().toLowerCase().replace(/\s+/g, ' ');
}
// GitHub's search API has no exact-title operator, so ask for an `in:title`
// phrase match and keep only the hits whose title is actually identical.
// A failed/rate-limited search returns an empty list on purpose: the duplicate
// check is advisory and must never block issue creation.
async function findIssuesByTitle(config, title) {
// quotes and backslashes would break out of the quoted search phrase
const phrase = title.replace(/["\\]/g, ' ').trim();
if (!phrase) {
return [];
}
const query = `repo:${config.repo} is:issue in:title "${phrase}"`;
let response;
try {
response = await fetch(`https://api.github.com/search/issues?per_page=20&q=${encodeURIComponent(query)}`, {
headers: {
Authorization: `Bearer ${config.token}`,
Accept: 'application/vnd.github+json',
'User-Agent': 'nodebb-plugin-github-issue',
'X-GitHub-Api-Version': '2022-11-28',
},
});
} catch (err) {
winston.warn(`[github-issue] duplicate search failed: ${err.message}`);
return [];
}
if (!response.ok) {
winston.warn(`[github-issue] duplicate search returned ${response.status}`);
return [];
}
const body = await response.json().catch(() => null);
const items = (body && Array.isArray(body.items)) ? body.items : [];
const wanted = normalizeTitle(title);
return items
.filter(item => item && !item.pull_request && normalizeTitle(item.title) === wanted)
.map(item => ({
number: item.number,
url: item.html_url,
title: item.title,
state: item.state || '',
stateReason: item.state_reason || '',
}));
}
async function refreshIssueStates(list) {
const config = await getConfig();
if (!config.token) {
return;
}
const now = Date.now();
const stale = list.filter(issue => now - issue.stateCheckedAt >= STATE_TTL_MS && apiUrlFromIssueUrl(issue.url));
if (!stale.length) {
return;
}
await Promise.all(stale.map(async (issue) => {
let fetched = null;
try {
const response = await common.ghFetch(apiUrlFromIssueUrl(issue.url), { config: config });
if (response.ok) {
fetched = await response.json();
} else {
common.logWarn(`state check for #${issue.number} returned ${response.status}`);
}
} catch (err) {
common.logWarn(`state check for #${issue.number} failed: ${err.message}`);
}
if (!fetched || !fetched.state) {
// stamp even on failure so a broken token doesn't delay page loads
// with a GitHub round-trip on every visit
await issues.update(issue.id, { stateCheckedAt: now });
return;
}
// go through the shared snapshot handler rather than writing the new
// state directly: otherwise a change first observed on a page load
// would be silently absorbed and never notified about
const changed = await notify.applySnapshot(issue, fetched);
if (!changed) {
await issues.update(issue.id, { stateCheckedAt: now });
}
}));
}
plugin.addTopicIssues = async function (data) {
const templateData = data && data.templateData;
const uid = (data.req && data.req.uid) || 0;
if (!templateData || !templateData.tid || !uid) {
return data;
}
const config = await getConfig();
const isPublic = parseInt(config.publicSidebar, 10) === 1;
const allowed = isPublic || await privileges.global.can(PRIVILEGE, uid);
if (!allowed) {
return data;
}
templateData.githubIssues = await getTopicIssues(templateData.tid);
return data;
};
// issues opened before these indexes existed are only keyed by pid: the topic
// index powers the sidebar, the issue-number index maps an incoming GitHub
// event back to the post it came from
async function backfillIndexes() {
const config = await getConfig();
const needTopics = !parseInt(config.tidIndexBuilt, 10);
const needNumbers = !parseInt(config.numberIndexBuilt, 10);
if (!needTopics && !needNumbers) {
return;
}
const keys = await db.scan({ match: `${PID_KEY_PREFIX}*` });
let topics = 0;
let numbers = 0;
for (const key of keys) {
const issue = await db.getObject(key);
if (!issue || !issue.url) {
continue;
}
const pid = key.slice(PID_KEY_PREFIX.length);
if (needTopics && !parseInt(issue.tid, 10)) {
const tid = parseInt(await posts.getPostField(pid, 'tid'), 10) || 0;
if (tid) {
await Promise.all([
db.setObjectField(key, 'tid', tid),
db.sortedSetAdd(TID_KEY_PREFIX + tid, parseInt(issue.timestamp, 10) || Date.now(), pid),
]);
topics += 1;
}
}
const repo = common.repoFromIssueUrl(issue.url);
if (needNumbers && repo && issue.number) {
await common.indexIssue(repo, issue.number, pid);
numbers += 1;
}
}
await db.setObject(CONFIG_KEY, { tidIndexBuilt: 1, numberIndexBuilt: 1 });
clearConfigCache();
if (topics || numbers) {
winston.info(`[github-issue] indexed ${topics} issue(s) by topic and ${numbers} by issue number`);
}
}
async function checkExpiry() {
const config = await getConfig();
const expiresAt = getExpiresAt(config);
if (!expiresAt) {
return;
}
const now = Date.now();
if (now >= expiresAt && !parseInt(config.warnedExpired, 10)) {
await notifyAdmins('expired', 0, config);
await db.setObjectField(CONFIG_KEY, 'warnedExpired', 1);
clearConfigCache();
} else if (now < expiresAt && now >= expiresAt - (WARN_BEFORE_DAYS * DAY_MS) && !parseInt(config.warned10, 10)) {
const daysLeft = Math.ceil((expiresAt - now) / DAY_MS);
await notifyAdmins('expiring', daysLeft, config);
await db.setObjectField(CONFIG_KEY, 'warned10', 1);
clearConfigCache();
}
}
async function notifyAdmins(type, daysLeft, config) {
const uids = await groups.getMembers('administrators', 0, -1);
if (!uids.length) {
return;
}
const bodyShort = type === 'expired' ?
translator.compile('github-issue:notify.expired') :
translator.compile('github-issue:notify.expiring', daysLeft);
const notification = await notifications.create({
type: 'github-issue-token',
bodyShort: bodyShort,
nid: `github-issue:token:${type}:${config.tokenSetAt}`,
path: '/admin/plugins/github-issue',
});
await notifications.push(notification, uids);
winston.info(`[github-issue] notified ${uids.length} admin(s): token ${type}`);
}
module.exports = plugin;