forked from OpenUserJS/OpenUserJS.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.js
495 lines (435 loc) · 19.9 KB
/
routes.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
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
'use strict';
// Define some pseudo module globals
var isPro = require('./libs/debug').isPro;
var isDev = require('./libs/debug').isDev;
var isDbg = require('./libs/debug').isDbg;
var rateLimit = require('express-rate-limit');
var MongoStore = require('rate-limit-mongo');
var exec = require('child_process').exec;
var hcaptcha = require('express-hcaptcha');
var SITEKEY = process.env.HCAPTCHA_SITE_KEY;
var SECRET = process.env.HCAPTCHA_SECRET_KEY;
//
var main = require('./controllers/index');
var authentication = require('./controllers/auth');
var admin = require('./controllers/admin');
var user = require('./controllers/user');
var script = require('./controllers/script');
var flag = require('./controllers/flag');
var vote = require('./controllers/vote');
var remove = require('./controllers/remove');
var moderation = require('./controllers/moderation');
var group = require('./controllers/group');
var discussion = require('./controllers/discussion');
var issue = require('./controllers/issue');
var scriptStorage = require('./controllers/scriptStorage');
var document = require('./controllers/document');
var svgCaptcha = require('svg-captcha');
var isSameOrigin = require('./libs/helpers').isSameOrigin;
var statusCodePage = require('./libs/templateHelpers').statusCodePage;
//--- Configuration inclusions
var settings = require('./models/settings.json');
//--
var limiter = process.env.LIMITER_STRING || settings.limiter;
// WATCHPOINT: ~60 second poll time in MongoDB
var fudgeMin = 60;
var fudgeSec = 6;
var waitInstallCapMin = isDev ? 1 : 60;
var installCapLimiter = rateLimit({
store: (isDev ? undefined : new MongoStore({
uri: limiter + '/installCapLimiter',
resetExpireDateOnChange: true, // Rolling
expireTimeMs: waitInstallCapMin * 60 * 1000 // n minutes for mongo store
})),
windowMs: waitInstallCapMin * 60 * 1000, // n minutes for all stores
max: 50, // limit each IP to n requests per windowMs for memory store or expireTimeMs for mongo store
handler: function (aReq, aRes, aNext, aOptions) {
aRes.header('Retry-After', waitInstallCapMin * 60 + (isDev ? fudgeSec : fudgeMin));
aRes.status(429).send();
},
skip: function (aReq, aRes) {
var authedUser = aReq.session.user;
if (authedUser && authedUser.isMod) {
this.store.resetKey(this.keyGenerator);
return true;
}
}
});
var waitRateInstallSec = isDev ? 30 : 60;
var installRateLimiter = rateLimit({
store: (isDev ? undefined : new MongoStore({
uri: limiter + '/installRateLimiter',
resetExpireDateOnChange: true, // Rolling
expireTimeMs: waitRateInstallSec * 1000 // n seconds for mongo store
})),
windowMs: waitRateInstallSec * 1000, // n seconds for all stores
max: 2, // limit each IP to n requests per windowMs for memory store or expireTimeMs for mongo store
handler: function (aReq, aRes, aNext, aOptions) {
aRes.header('Retry-After', waitRateInstallSec + (isDev ? fudgeSec : fudgeMin));
if (isSameOrigin(aReq.get('Referer')).result) {
if (aReq.rateLimit.current <= aReq.rateLimit.limit + 2) {
statusCodePage(aReq, aRes, aNext, {
statusCode: 429,
statusMessage: 'Too many requests.',
suppressNavigation: true,
isCustomView: true,
statusData: {
isListView: true,
retryAfter: waitRateInstallSec + (isDev ? fudgeSec : fudgeMin)
}
});
return;
}
}
aRes.status(429).send();
},
keyGenerator: function (aReq, aRes, aNext) {
return aReq.ip + aReq._parsedUrl.pathname;
},
skip: function (aReq, aRes) {
var authedUser = aReq.session.user;
if (aReq.params.type === 'libs') {
return true;
}
if (authedUser && authedUser.isAdmin) {
this.store.resetKey(this.keyGenerator);
return true;
}
}
});
var waitRateMetaSec = isDev ? 30 : 60;
var metaRateLimiter = rateLimit({
store: (isDev ? undefined : new MongoStore({
uri: limiter + '/metaRateLimiter',
resetExpireDateOnChange: true, // Rolling
expireTimeMs: waitRateMetaSec * 1000 // n seconds for mongo store
})),
windowMs: waitRateMetaSec * 1000, // n seconds for all stores
max: 2, // limit each IP to n requests per windowMs for memory store or expireTimeMs for mongo store
handler: function (aReq, aRes, aNext, aOptions) {
aRes.header('Retry-After', waitRateMetaSec + (isDev ? fudgeSec : fudgeMin));
if (isSameOrigin(aReq.get('Referer')).result) {
if (aReq.rateLimit.current <= aReq.rateLimit.limit + 2) {
statusCodePage(aReq, aRes, aNext, {
statusCode: 429,
statusMessage: 'Too many requests.',
suppressNavigation: true,
isCustomView: true,
statusData: {
isListView: true,
retryAfter: waitRateMetaSec + (isDev ? fudgeSec : fudgeMin)
}
});
return;
}
}
aRes.status(429).send();
},
keyGenerator: function (aReq, aRes, aNext) {
return aReq.ip + aReq._parsedUrl.pathname;
},
skip: function (aReq, aRes) {
var authedUser = aReq.session.user;
if (/\.meta\.json$/.test(aReq._parsedUrl.pathname)) {
return true;
}
if (authedUser && authedUser.isAdmin) {
this.store.resetKey(this.keyGenerator);
return true;
}
}
});
var waitApiCapMin = isDev ? 1: 15;
var apiCapLimiter = rateLimit({
store: (isDev ? undefined : new MongoStore({
uri: limiter + '/apiCapLimiter',
resetExpireDateOnChange: true, // Rolling
expireTimeMs: waitApiCapMin * 60 * 1000 // n minutes for mongo store
})),
windowMs: waitApiCapMin * 60 * 1000, // n minutes for all stores
max: 100, // limit each IP to n requests per windowMs for memory store or expireTimeMs for mongo store
handler: function (aReq, aRes, aNext, aOptions) {
aRes.header('Retry-After', waitApiCapMin * 60 + (isDev ? fudgeSec : fudgeMin));
aRes.status(429).send();
},
skip: function (aReq, aRes) {
var authedUser = aReq.session.user;
if (authedUser && authedUser.isMod) {
this.store.resetKey(this.keyGenerator);
return true;
}
}
});
var waitAuthCapMin = isDev ? 1: 1440;
var authCapLimiter = rateLimit({
store: (isDev ? undefined : new MongoStore({
uri: limiter + '/authCapLimiter',
resetExpireDateOnChange: true, // Rolling
expireTimeMs: waitAuthCapMin * 60 * 1000 // n minutes for mongo store
})),
windowMs: waitAuthCapMin * 60 * 1000, // n minutes for all stores
max: 1, // limit each IP to n requests per windowMs for memory store or expireTimeMs for mongo store
handler: function (aReq, aRes, aNext, aOptions) {
aRes.header('Retry-After', waitAuthCapMin * 60 + (isDev ? fudgeSec : fudgeMin));
statusCodePage(aReq, aRes, aNext, {
statusCode: 429,
statusMessage: 'Too many requests.',
suppressNavigation: true,
isCustomView: true,
statusData: {
isListView: true,
retryAfter: waitAuthCapMin * 60 + (isDev ? fudgeSec : fudgeMin)
}
});
}
});
var waitCaptchaCapMin = isDev ? 1: 1440;
var captchaCapLimiter = rateLimit({
store: (isDev ? undefined : new MongoStore({
uri: limiter + '/captchaCapLimiter',
resetExpireDateOnChange: true, // Rolling
expireTimeMs: waitCaptchaCapMin * 60 * 1000 // n minutes for mongo store
})),
windowMs: waitCaptchaCapMin * 60 * 1000, // n minutes for all stores
max: 1, // limit each IP to n requests per windowMs for memory store or expireTimeMs for mongo store
handler: function (aReq, aRes, aNext, aOptions) {
aRes.type('svg').status(200).send(
svgCaptcha('429 Too Many Requests', Object.assign(settings.captchaOpts, {
width: 350
}))
);
},
skip: function (aReq, aRes) {
var authedUser = aReq.session.user;
if (authedUser) {
if (authedUser.isMod) {
this.store.resetKey(this.keyGenerator);
return true;
}
if (!authedUser._probationary) {
// NOTE: Still counting by design
return true;
}
}
}
});
var waitListCapMin = isDev ? 1: 60;
var listCapLimiter = rateLimit({
store: (isDev ? undefined : new MongoStore({
uri: limiter + '/listCapLimiter',
resetExpireDateOnChange: true, // Rolling
expireTimeMs: waitListCapMin * 60 * 1000 // n minutes for mongo store
})),
windowMs: waitListCapMin * 60 * 1000, // n minutes for all stores
max: 115, // limit each IP to n requests per windowMs for memory store or expireTimeMs for mongo store
handler: function (aReq, aRes, aNext, aOptions) {
var cmd = null;
if (aReq.rateLimit.current < aReq.rateLimit.limit + 4) {
// Midddlware options
if (!aRes.oujsOptions) {
aRes.oujsOptions = {};
}
aRes.oujsOptions.showReminderListLimit = 4 - (aReq.rateLimit.current - aReq.rateLimit.limit);
aNext();
} else if (aReq.rateLimit.current < aReq.rateLimit.limit + 10) {
aRes.header('Retry-After', waitListCapMin * 60 + (isDev ? fudgeSec : fudgeMin));
statusCodePage(aReq, aRes, aNext, {
statusCode: 429,
statusMessage: 'Too many requests.',
suppressNavigation: true,
isCustomView: true,
statusData: {
isListView: true,
retryAfter: waitListCapMin * 60 + (isDev ? fudgeSec : fudgeMin)
}
});
} else if (aReq.rateLimit.current < aReq.rateLimit.limit + 15) {
aRes.header('Retry-After', waitListCapMin * 60 + (isDev ? fudgeSec : fudgeMin));
aRes.status(429).send('Too many requests. Please try again later');
} else if (aReq.rateLimit.current < aReq.rateLimit.limit + 20) {
aRes.header('Retry-After', waitListCapMin * 60 + (isDev ? fudgeSec : fudgeMin));
aRes.status(429).send();
} else {
cmd = (isPro && process.env.AUTOBAN ? process.env.AUTOBAN : 'echo SIMULATING AUTOBAN') +
' ' + aReq.connection.remoteAddress;
exec(cmd, function (aErr, aStdout, aStderr) {
if (aErr) {
console.error('FAIL AUTOBAN', cmd);
// fallthrough
} else {
console.log('AUTOBAN', aReq.connection.remoteAddress);
// fallthrough
}
aRes.connection.destroy();
});
}
},
skip: function (aReq, aRes) {
var authedUser = aReq.session.user;
if (authedUser && authedUser.isMod) {
this.store.resetKey(this.keyGenerator);
return true;
}
}
});
var waitListRateSec = isDev ? parseInt(4 / 2) : 4;
var listRateLimiter = rateLimit({
store: (isDev ? undefined : undefined),
windowMs: waitListRateSec * 1000, // n seconds for all stores
max: 1, // limit each IP to n requests per windowMs for memory store or expireTimeMs for mongo store
handler: function (aReq, aRes, aNext, aOptions) {
aRes.header('Retry-After', waitListRateSec + fudgeSec);
if (aReq.rateLimit.current <= aReq.rateLimit.limit + 1) {
statusCodePage(aReq, aRes, aNext, {
statusCode: 429,
statusMessage: 'Too many requests.',
suppressNavigation: true,
isCustomView: true,
statusData: {
isListView: true,
retryAfter: waitListRateSec + fudgeSec
}
});
return;
}
aRes.status(429).send();
},
keyGenerator: function (aReq, aRes, aNext) {
return aReq.ip + aReq._parsedUrl.pathname;
},
skip: function (aReq, aRes) {
var authedUser = aReq.session.user;
if (/\.meta\.json$/.test(aReq._parsedUrl.pathname)) {
return true;
}
if (authedUser && authedUser.isAdmin) {
this.store.resetKey(this.keyGenerator);
return true;
}
}
});
module.exports = function (aApp) {
//--- Middleware
//--- Routes
// Authentication routes
aApp.route('/login').get(main.register);
aApp.route('/register').get(function (aReq, aRes) {
aRes.redirect(301, '/login');
});
aApp.route('/auth/').post(
authentication.preauth,
authCapLimiter,
hcaptcha.middleware.validate(SECRET, SITEKEY),
authentication.errauth,
authentication.auth
);
aApp.route('/auth/:strategy').get(authentication.auth);
aApp.route('/auth/:strategy/callback/:junk?').get(authentication.callback);
aApp.route('/logout').get(main.logout);
// User routes
aApp.route('/users').get(listRateLimiter, listCapLimiter, user.userListPage);
aApp.route('/users/:username').get(user.view);
aApp.route('/users/:username/scripts').get(listRateLimiter, listCapLimiter, user.userScriptListPage);
aApp.route('/users/:username/syncs').get(listRateLimiter, listCapLimiter, user.userSyncListPage);
aApp.route('/users/:username/comments').get(listRateLimiter, listCapLimiter, user.userCommentListPage);
aApp.route('/users/:username/github/repos').get(authentication.validateUser, user.userGitHubRepoListPage);
aApp.route('/users/:username/github/repo').get(authentication.validateUser, user.userGitHubRepoPage);
aApp.route('/users/:username/github/import').post(authentication.validateUser, user.userGitHubImportScriptPage);
aApp.route('/users/:username/profile/edit').get(authentication.validateUser, user.userEditProfilePage).post(authentication.validateUser, user.update);
aApp.route('/users/:username/profile/captcha').get(captchaCapLimiter, authentication.validateUser, user.userEditProfilePageCaptcha);
aApp.route('/users/:username/update').post(authentication.validateUser, admin.adminUserUpdate);
// NOTE: Some below inconsistent with priors
aApp.route('/user/preferences').get(authentication.validateUser, user.userEditPreferencesPage);
aApp.route('/user').get(function (aReq, aRes) {
aRes.redirect(302, '/users');
});
aApp.route('/api/user/exist/:username').head(apiCapLimiter, user.exist);
aApp.route('/api/user/session/extend').post(apiCapLimiter, authentication.validateUser, user.extend);
aApp.route('/api/user/session/destroyOne').post(apiCapLimiter, authentication.validateUser, user.destroyOne);
// Adding script/library routes
aApp.route('/user/add/scripts').get(listRateLimiter, listCapLimiter, authentication.validateUser, user.newScriptPage);
aApp.route('/user/add/scripts/new').get(authentication.validateUser, script.new(user.editScript)).post(authentication.validateUser, script.new(user.submitSource));
aApp.route('/user/add/scripts/upload').post(authentication.validateUser, user.uploadScript);
aApp.route('/user/add/lib').get(authentication.validateUser, user.newLibraryPage);
aApp.route('/user/add/lib/new').get(authentication.validateUser, script.new(script.lib(user.editScript))).post(authentication.validateUser, script.new(script.lib(user.submitSource)));
aApp.route('/user/add/lib/upload').post(authentication.validateUser, script.lib(user.uploadScript));
aApp.route('/user/add').get(function (aReq, aRes) {
aRes.redirect(301, '/user/add/scripts');
});
// Script routes
aApp.route('/scripts/:username/:scriptname').get(script.view);
aApp.route('/scripts/:username/:scriptname/edit').get(authentication.validateUser, script.edit).post(authentication.validateUser, script.edit);
aApp.route('/scripts/:username/:scriptname/source').get(user.editScript);
aApp.route('/scripts/:username').get(function (aReq, aRes) {
aRes.redirect(301, '/users/' + aReq.params.username + '/scripts'); // NOTE: Watchpoint
});
aApp.route('/install/:username/:scriptname').get(installRateLimiter, installCapLimiter, scriptStorage.unlockScript, scriptStorage.sendScript);
aApp.route('/meta/:username/:scriptname').get(metaRateLimiter, scriptStorage.sendMeta);
// Github hook routes
aApp.route('/github/hook').post(scriptStorage.webhook);
aApp.route('/github/service').post(function (aReq, aRes, aNext) { aNext(); });
// Library routes
aApp.route('/libs/:username/:scriptname').get(script.lib(script.view));
aApp.route('/libs/:username/:scriptname/edit').get(authentication.validateUser, script.lib(script.edit)).post(authentication.validateUser, script.lib(script.edit));
aApp.route('/libs/:username/:scriptname/source').get(script.lib(user.editScript));
// Raw source
aApp.route('/src/:type(scripts|libs)/:username/:scriptname').get(installRateLimiter, installCapLimiter, scriptStorage.unlockScript, scriptStorage.sendScript);
// Issues routes
aApp.route('/:type(scripts|libs)/:username/:scriptname/issues/:open(open|closed|all)?').get(listRateLimiter, listCapLimiter, issue.list);
aApp.route('/:type(scripts|libs)/:username/:scriptname/issue/new').get(authentication.validateUser, issue.open).post(authentication.validateUser, issue.open);
aApp.route('/:type(scripts|libs)/:username/:scriptname/issues/:topic').get(listRateLimiter, listCapLimiter, issue.view).post(authentication.validateUser, issue.comment);
aApp.route('/:type(scripts|libs)/:username/:scriptname/issues/:topic/:action(close|reopen)').get(authentication.validateUser, issue.changeStatus);
// Admin routes
aApp.route('/admin').get(authentication.validateUser, admin.adminPage);
aApp.route('/admin/npm/version').get(authentication.validateUser, admin.adminNpmVersionView);
aApp.route('/admin/git/short').get(authentication.validateUser, admin.adminGitShortView);
aApp.route('/admin/git/branch').get(authentication.validateUser, admin.adminGitBranchView);
aApp.route('/admin/process/clone').get(authentication.validateUser, admin.adminProcessCloneView);
aApp.route('/admin/session/active').get(authentication.validateUser, admin.adminSessionActiveView);
aApp.route('/admin/npm/package').get(authentication.validateUser, admin.adminNpmPackageView);
aApp.route('/admin/npm/list').get(authentication.validateUser, admin.adminNpmListView);
aApp.route('/admin/api').get(authentication.validateUser, admin.adminApiKeysPage);
aApp.route('/admin/authas').get(authentication.validateUser, admin.authAsUser);
aApp.route('/admin/json').get(authentication.validateUser, admin.adminJsonView);
aApp.route('/admin/api/update').post(authentication.validateUser, admin.apiAdminUpdate);
// Moderation routes
aApp.route('/mod').get(authentication.validateUser, moderation.modPage);
aApp.route('/mod/removed').get(authentication.validateUser, moderation.removedItemListPage);
aApp.route('/mod/removed/:id').get(authentication.validateUser, moderation.removedItemPage);
// Vote route
aApp.route(/^\/vote\/(scripts|libs)\/((.+?)(?:\/(.+))?)$/).post(authentication.validateUser, vote.vote);
// Flag route
aApp.route(/^\/flag\/(users|scripts|libs)\/((.+?)(?:\/(.+))?)$/).post(authentication.validateUser, flag.flag);
// Remove route
aApp.route(/^\/remove\/(users|scripts|libs)\/((.+?)(?:\/(.+))?)$/).post(authentication.validateUser, remove.rm);
// Group routes
aApp.route('/groups').get(listRateLimiter, listCapLimiter, group.list);
aApp.route('/group/:groupname').get(listRateLimiter, listCapLimiter, group.view);
aApp.route('/group').get(function (aReq, aRes) { aRes.redirect('/groups'); });
aApp.route('/api/group/search/:term/:addTerm?').get(group.search);
// Discussion routes
// TODO: Update templates for new discussion routes
aApp.route('/forum').get(listRateLimiter, listCapLimiter, discussion.categoryListPage);
aApp.route('/:p(forum)?/:category(announcements|corner|garage|discuss|issues|all)').get(listRateLimiter, listCapLimiter, discussion.list);
aApp.route('/:p(forum)?/:category(announcements|corner|garage|discuss)/:topic').get(listRateLimiter, listCapLimiter, discussion.show).post(authentication.validateUser, discussion.createComment);
aApp.route('/:p(forum)?/:category(announcements|corner|garage|discuss)/new').get(authentication.validateUser, discussion.newTopic).post(authentication.validateUser, discussion.createTopic);
// dupe
aApp.route('/post/:category(announcements|corner|garage|discuss)').get(authentication.validateUser, discussion.newTopic).post(authentication.validateUser, discussion.createTopic);
// About document routes
aApp.route('/about/:document?').get(document.view);
// Home route
aApp.route('/').get(listRateLimiter, listCapLimiter, main.home);
// Misc API
aApp.route('/api').head(function (aReq, aRes, aNext) {
aRes.status(200).send();
});
// Static Routes
require('./routesStatic')(aApp);
// Fallback routes
aApp.use(function (aReq, aRes, aNext) {
statusCodePage(aReq, aRes, aNext, {
statusCode: 404,
statusMessage: 'This is not the page you\'re are looking for.'
});
});
};