-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathindex.ts
More file actions
1662 lines (1467 loc) · 66.3 KB
/
index.ts
File metadata and controls
1662 lines (1467 loc) · 66.3 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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {addAsync, Router} from "@awaitjs/express";
import express, {Request, Response} from "express";
import bodyParser from "body-parser";
import cookieParser from 'cookie-parser';
// @ts-ignore
import CacheManagerStore from 'express-session-cache-manager'
import passport from 'passport';
import {Strategy as CustomStrategy} from 'passport-custom';
import {
OperatorConfig,
BotConnection,
LogInfo,
CheckSummary,
RunResult,
ActionedEvent,
ActionResult, RuleResult, EventActivity, OperatorConfigWithFileContext
} from "../../Common/interfaces";
import {
buildCachePrefix,
defaultFormat, filterLogBySubreddit, filterCriteriaSummary, formatFilterData,
formatLogLineToHtml, filterLogs, getUserAgent,
intersect, isLogLineMinLevel,
LogEntry, parseInstanceLogInfoName, parseInstanceLogName, parseRedditEntity,
parseSubredditLogName, permissions,
randomId, replaceApplicationIdentifier, resultsSummary, sleep, triggeredIndicator, truncateStringToLength
} from "../../util";
import {Cache} from "cache-manager";
import session, {Session, SessionData} from "express-session";
import Snoowrap, {Subreddit} from "snoowrap";
import {getLogger} from "../../Utils/loggerFactory";
import EventEmitter from "events";
import tcpUsed from "tcp-port-used";
import http from "http";
import jwt from 'jsonwebtoken';
import {Server as SocketServer} from "socket.io";
import got, {HTTPError} from 'got';
import sharedSession from "express-socket.io-session";
import dayjs from "dayjs";
import httpProxy from 'http-proxy';
import {arrayMiddle, booleanMiddle} from "../Common/middleware";
import { URL } from "url";
import {MESSAGE} from "triple-beam";
import Autolinker from "autolinker";
import path from "path";
import {ExtendedSnoowrap} from "../../Utils/SnoowrapClients";
import ClientUser from "../Common/User/ClientUser";
import {SimpleError} from "../../Utils/Errors";
import {ErrorWithCause} from "pony-cause";
import {CMInstance} from "./CMInstance";
import {CMEvent} from "../../Common/Entities/CMEvent";
import { RulePremise } from "../../Common/Entities/RulePremise";
import { ActionPremise } from "../../Common/Entities/ActionPremise";
import {CacheStorageProvider, DatabaseStorageProvider} from "./StorageProvider";
import {nanoid} from "nanoid";
import {MigrationService} from "../../Common/MigrationService";
import {RuleResultEntity} from "../../Common/Entities/RuleResultEntity";
import {RuleSetResultEntity} from "../../Common/Entities/RuleSetResultEntity";
import { PaginationAwareObject } from "../Common/util";
import {
BotInstance,
BotStatusResponse,
BotSubredditInviteResponse,
CMInstanceInterface, HeartbeatResponse,
InviteData, SubredditInviteDataPersisted
} from "../Common/interfaces";
import {open} from "fs/promises";
import {createCacheManager} from "../../Common/Cache";
const emitter = new EventEmitter();
const app = addAsync(express());
const jsonParser = bodyParser.json();
const contentLinkingOptions = {
urls: false,
email: false,
phone: false,
mention: false,
hashtag: false,
stripPrefix: false,
sanitizeHtml: true,
};
// do not modify body if we are proxying it to server
app.use((req, res, next) => {
if(req.url.indexOf('/api') !== 0) {
jsonParser(req, res, next);
} else {
next();
}
});
const staticHeaders = (res: express.Response, path: string, stat: object) => {
res.setHeader('X-Robots-Tag', 'noindex');
}
const staticOpts = {
setHeaders: staticHeaders
}
app.use(bodyParser.urlencoded({extended: false}));
//app.use(cookieParser());
app.set('views', `${__dirname}/../assets/views`);
app.set('view engine', 'ejs');
app.use('/public', express.static(`${__dirname}/../assets/public`, staticOpts));
app.use('/monaco', express.static(`${__dirname}/../../../node_modules/monaco-editor/`, staticOpts));
app.use('/schemas', express.static(`${__dirname}/../../Schema/`, staticOpts));
app.use((req, res, next) => {
// https://developers.google.com/search/docs/advanced/crawling/block-indexing#http-response-header
res.setHeader('X-Robots-Tag', 'noindex');
next();
});
const userAgent = `web:contextBot:web`;
const proxy = httpProxy.createProxyServer({
ws: true,
//hostRewrite: true,
changeOrigin: true,
});
declare module 'express-session' {
interface SessionData {
limit?: number,
sort?: string,
level?: string,
state?: string,
scope?: string[],
botId?: string,
authBotId?: string,
}
}
interface ConnectedUserInfo {
level?: string,
user?: string,
botId: string,
logStream?: Promise<void>
logAbort?: AbortController
statInterval?: any,
}
interface ConnectUserObj {
[key: string]: ConnectedUserInfo
}
const createToken = (bot: CMInstanceInterface, user?: Express.User | any, ) => {
const payload = user !== undefined ? {...user, machine: false} : {machine: true};
return jwt.sign({
data: payload,
}, bot.secret, {
expiresIn: '1m'
});
}
const peekTrunc = truncateStringToLength(200);
const availableLevels = ['error', 'warn', 'info', 'verbose', 'debug'];
let webLogs: LogInfo[] = [];
const webClient = async (options: OperatorConfigWithFileContext) => {
const {
operator: {
name: operatorName,
display,
},
userAgent: uaFragment,
// caching: {
// provider: caching
// },
web: {
database,
databaseConfig: {
migrations
},
port,
storage: webStorage = 'database',
caching,
session: {
secret: sessionSecretFromConfig,
maxAge: sessionMaxAge,
storage: sessionStorage = 'database',
},
maxLogs,
clients,
credentials,
operators = [],
},
//database
} = options;
let clientCredentials = credentials;
let sessionSecretSynced = false;
const userAgent = getUserAgent(`web:contextBot:{VERSION}{FRAG}:dashboard`, uaFragment);
app.use((req, res, next) => {
res.locals.applicationIdentifier = replaceApplicationIdentifier('{VERSION}{FRAG}', uaFragment);
next();
});
const webOps = operators.map(x => x.toLowerCase());
const logger = getLogger({defaultLabel: 'Web', ...options.logging}, 'Web');
logger.stream().on('log', (log: LogInfo) => {
emitter.emit('log', log);
webLogs.unshift(log);
if(webLogs.length > 200) {
webLogs.splice(200);
}
});
const migrationService = new MigrationService({
type: 'web',
logger,
database,
options: migrations
});
if (await tcpUsed.check(port)) {
throw new SimpleError(`Specified port for web interface (${port}) is in use or not available. Cannot start web server.`);
}
logger.info('Initializing database...');
let [ranMigrations, migrationBlocker] = await migrationService.initDatabase();
app.use((req, res, next) => {
if(!ranMigrations && (req.url === '/' || req.url.indexOf('database') === -1)) {
return res.render('migrations', {
type: 'web',
ranMigrations: ranMigrations,
migrationBlocker: migrationBlocker,
});
} else {
next();
}
});
const storage = webStorage === 'database' ? new DatabaseStorageProvider({database, logger}) : new CacheStorageProvider({...caching, logger});
let sessionSecret: string;
if (sessionSecretFromConfig !== undefined) {
logger.debug('Using session secret defined in config');
sessionSecret = sessionSecretFromConfig;
sessionSecretSynced = true;
} else {
try {
let persistedSecret = await storage.getSessionSecret();
if (undefined === persistedSecret) {
storage.logger.debug('No session secret found in storage, generating new session secret and saving...');
sessionSecret = randomId();
await storage.setSessionSecret(sessionSecret);
} else {
storage.logger.debug('Using session secret found in from storage')
sessionSecret = persistedSecret;
}
sessionSecretSynced = true;
} catch (e) {
sessionSecret = randomId();
storage.logger.warn(new ErrorWithCause('Falling back to a random ID for session secret', {cause: e}));
}
}
const connectedUsers: ConnectUserObj = {};
//<editor-fold desc=Session and Auth>
/*
* Session and Auth
* */
passport.serializeUser(async function (data: any, done) {
const {user, subreddits, scope, token} = data;
done(null, { subreddits: subreddits.map((x: Subreddit) => x.display_name), isOperator: webOps.includes(user.toLowerCase()), name: user, scope, token, tokenExpiresAt: dayjs().unix() + (60 * 60) });
});
passport.deserializeUser(async function (obj: any, done) {
const user = new ClientUser(obj.name, obj.subreddits, {token: obj.token, scope: obj.scope, webOperator: obj.isOperator, tokenExpiresAt: obj.tokenExpiresAt});
done(null, user);
});
passport.use('snoowrap', new CustomStrategy(
async function (req, done) {
const {error, code, state} = req.query as any;
if (error !== undefined) {
let errContent: string;
switch (error) {
case 'access_denied':
errContent = 'You must <b>Allow</b> this application to connect in order to proceed.';
break;
default:
errContent = error;
}
return done(errContent);
} else if (req.session.state !== state) {
return done('Unexpected <b>state</b> value returned');
}
const client = await ExtendedSnoowrap.fromAuthCode({
userAgent,
clientId: clientCredentials.clientId,
clientSecret: clientCredentials.clientSecret,
redirectUri: clientCredentials.redirectUri as string,
code: code as string,
});
const user = await client.getMe().name as string;
let subs = await client.getModeratedSubreddits({count: 100});
while(!subs.isFinished) {
subs = await subs.fetchMore({amount: 100});
}
io.to(req.session.id).emit('authStatus', {canSaveWiki: req.session.scope?.includes('wikiedit')});
return done(null, {user, subreddits: subs, scope: req.session.scope, token: client.accessToken});
}
));
let sessionStoreProvider = storage;
if(sessionStorage !== webStorage) {
sessionStoreProvider = sessionStorage === 'database' ? new DatabaseStorageProvider({database, logger, loggerLabels: ['Session']}) : new CacheStorageProvider({...caching, logger, loggerLabels: ['Session']});
}
const sessionObj = session({
cookie: {
maxAge: sessionMaxAge * 1000,
},
store: await sessionStoreProvider.createSessionStore(sessionStorage === 'database' ? {
cleanupLimit: 2,
ttl: sessionMaxAge
} : {}),
resave: false,
saveUninitialized: false,
secret: sessionSecret,
});
app.use(sessionObj);
app.use(passport.initialize());
app.use(passport.session());
const ensureAuthenticated = async (req: express.Request, res: express.Response, next: Function) => {
if (req.isAuthenticated()) {
next();
} else {
return res.redirect('/login');
}
}
const ensureAuthenticatedApi = async (req: express.Request, res: express.Response, next: Function) => {
if (req.isAuthenticated()) {
next();
} else {
return res.status(401).send('You must be logged in to access this route');
}
}
app.postAsync('/init', async (req, res, next) => {
if (clientCredentials.clientId === undefined || clientCredentials.clientSecret === undefined) {
const {
redirect = '',
clientId = '',
clientSecret = '',
operator = '',
} = req.body as any;
if (redirect === null || redirect.trim() === '') {
return res.status(400).send('redirect cannot be empty');
}
if (clientId === null || clientId.trim() === '') {
return res.status(400).send('clientId cannot be empty');
}
if (clientSecret === null || clientSecret.trim() === '') {
return res.status(400).send('clientSecret cannot be empty');
}
if(operatorName === undefined) {
return res.status(400).send('operator cannot be empty');
}
options.fileConfig.document.setWebCredentials({redirectUri: redirect.trim(), clientId: clientId.trim(), clientSecret: clientSecret.trim()});
if(operators.length === 0 && operator !== '') {
options.fileConfig.document.setOperator(parseRedditEntity(operator, 'user').name);
}
const handle = await open(options.fileConfig.document.location as string, 'w');
await handle.writeFile(options.fileConfig.document.toString());
await handle.close();
clientCredentials = {
clientId,
clientSecret,
redirectUri: redirect
}
return res.status(200).send();
} else {
return res.status(400).send('Can only do init setup when client credentials do not already exist.');
}
});
const scopeMiddle = arrayMiddle(['scope']);
const successMiddle = booleanMiddle([{name: 'closeOnSuccess', defaultVal: undefined, required: false}]);
app.getAsync('/login', scopeMiddle, successMiddle, async (req, res, next) => {
if (clientCredentials.redirectUri === undefined) {
return res.render('error', {error: `No <b>redirectUri</b> was specified through environmental variables or program argument. This must be provided in order to use the web interface.`});
}
const {query: { scope: reqScopes = [], closeOnSuccess } } = req;
const scope = [...new Set(['identity', 'mysubreddits', ...(reqScopes as string[])])];
req.session.state = randomId();
req.session.scope = scope;
// @ts-ignore
if(closeOnSuccess === true) {
// @ts-ignore
req.session.closeOnSuccess = closeOnSuccess;
}
if(clientCredentials.clientId === undefined) {
return res.render('init', { operators: operators.join(',') });
}
const authUrl = Snoowrap.getAuthUrl({
clientId: clientCredentials.clientId,
scope: scope,
redirectUri: clientCredentials.redirectUri as string,
permanent: false,
state: req.session.state,
});
return res.redirect(authUrl);
});
const botCallback = async (req: express.Request, res: express.Response, next: Function) => {
const {state, error, code} = req.query as any;
if(state.includes('bot')) {
if (error !== undefined || state !== req.session.state) {
let errContent: string;
switch (error) {
case 'access_denied':
errContent = 'You must <b>Allow</b> this application to connect in order to proceed.';
break;
default:
if(error === undefined && state !== req.session.state) {
errContent = 'state value was unexpected';
} else {
errContent = error;
}
break;
}
return res.render('error', {error: errContent});
}
// @ts-ignore
const invite = req.session.invite as InviteData; //await storage.inviteGet(req.session.inviteId);
if(invite === undefined) {
// @ts-ignore
return res.render('error', {error: `Could not find invite in session?? This should happen!`});
}
const client = await Snoowrap.fromAuthCode({
userAgent,
clientId: invite.clientId,
clientSecret: invite.clientSecret,
redirectUri: invite.redirectUri,
code: code as string,
});
// @ts-ignore
const user = await client.getMe();
const userName = `u/${user.name}`;
// @ts-ignore
//await storage.inviteDelete(req.session.inviteId);
let data: any = {
accessToken: client.accessToken,
refreshToken: client.refreshToken,
userName,
};
// @ts-ignore
const inviteId = invite.id as string;
// @ts-ignore
const botAddResult: any = await addBot(inviteId, {
invite: inviteId,
credentials: {
reddit: {
accessToken: client.accessToken,
refreshToken: client.refreshToken,
clientId: invite.clientId,
clientSecret: invite.clientSecret,
}
},
name: userName,
});
data = {...data, ...botAddResult};
// @ts-ignore
req.session.destroy();
req.logout();
return res.render('callback', data);
} else {
return next();
}
}
app.getAsync(/.*callback$/, botCallback, (req: express.Request, res: express.Response, next: Function) => {
passport.authenticate('snoowrap', (err, user, info) => {
if(err !== null) {
return res.render('error', {error: err});
}
return req.logIn(user, (e) => {
// don't know why we'd get an error here but ¯\_(ツ)_/¯
if(e !== undefined) {
return res.render('error', {error: err});
}
// @ts-ignore
const useCloseRedir: boolean = req.session.closeOnSuccess as any
// @ts-ignore
delete req.session.closeOnSuccess;
req.session.save((err) => {
if(useCloseRedir === true) {
return res.render('close');
} else {
return res.redirect('/');
}
})
});
})(req, res, next);
});
app.getAsync('/logout', async (req, res) => {
// @ts-ignore
req.session.destroy();
req.logout();
res.send('Bye!');
});
let token = randomId();
const helperAuthed = async (req: express.Request, res: express.Response, next: Function) => {
if(!req.isAuthenticated()) {
return res.render('error', {error: 'You must be logged in to access this route.'});
}
if(operators.length === 0) {
return res.render('error', {error: '<div>You must be authenticated <b>and an Operator</b> to access this route but there are <b>no Operators specified in configuration.</b></div>' +
'<div>Refer to the <a href="https://github.com/FoxxMD/context-mod/blob/master/docs/operatorConfiguration.md">Operator Configuration Guide</a> to do this.</div>' +
'<div>TLDR:' +
'<div>Environment Variable: <span class="font-mono">OPERATOR=YourRedditUsername</span></div> ' +
'<div>or as an argument: <span class="font-mono">--operator YourRedditUsername</span></div>'});
}
// or if there is an operator and current user is operator
if(req.user?.clientData?.webOperator) {
return next();
} else {
return res.render('error', {error: 'You must be an <b>Operator</b> to access this route.'});
}
}
const createUserToken = async (req: express.Request, res: express.Response, next: Function) => {
req.token = createToken(req.instance as CMInstanceInterface, req.user);
next();
}
const instanceWithPermissions = async (req: express.Request, res: express.Response, next: Function) => {
delete req.session.botId;
delete req.session.authBotId;
const msg = 'Bot does not exist or you do not have permission to access it';
const instance = cmInstances.find(x => x.getName() === req.query.instance);
if (instance === undefined) {
return res.status(404).render('error', {error: msg});
}
if (!req.user?.clientData?.webOperator && !req.user?.canAccessInstance(instance)) {
return res.status(404).render('error', {error: msg});
}
if (req.params.subreddit !== undefined && !req.user?.canAccessSubreddit(instance,req.params.subreddit)) {
return res.status(404).render('error', {error: msg});
}
req.instance = instance;
req.session.botId = instance.getName();
req.session.authBotId = instance.getName();
return next();
}
const instancesViewData = async (req: express.Request, res: express.Response, next: Function) => {
const user = req.user as Express.User;
const instance = req.instance as CMInstance;
const shownInstances = cmInstances.reduce((acc: CMInstance[], curr) => {
const isBotOperator = user?.isInstanceOperator(curr);
if(user?.clientData?.webOperator) {
// @ts-ignore
return acc.concat({...curr.getData(), canAccessLocation: true, isOperator: isBotOperator});
}
if(!isBotOperator && !req.user?.canAccessInstance(curr)) {
return acc;
}
// @ts-ignore
return acc.concat({...curr.getData(), canAccessLocation: isBotOperator, isOperator: isBotOperator, botId: curr.getName()});
},[]);
// @ts-ignore
req.instancesViewData = {
instances: shownInstances,
instanceId: instance.getName()
};
next();
}
const initHeartbeat = async (req: express.Request, res: express.Response, next: Function) => {
if(!init) {
for(const c of clients) {
await refreshClient(c);
}
init = true;
loopHeartbeat();
}
next();
};
app.getAsync('/auth/helper', initHeartbeat, helperAuthed, instanceWithPermissions, instancesViewData, (req, res) => {
return res.render('helper', {
redirectUri: clientCredentials.redirectUri,
clientId: clientCredentials.clientId,
clientSecret: clientCredentials.clientSecret,
token: req.isAuthenticated() && req.user?.clientData?.webOperator ? token : undefined,
// @ts-ignore
...req.instancesViewData,
});
});
app.getAsync('/auth/invite/:inviteId', initHeartbeat, async (req, res) => {
const {inviteId} = req.params;
if (inviteId === undefined) {
return res.render('error', {error: '`invite` param is missing from URL'});
}
const cmInstance = cmInstances.find(x => x.invites.includes(inviteId));
if (cmInstance === undefined) {
return res.render('error', {error: 'Invite with the given id does not exist'});
}
try {
const invite = await got.get(`${cmInstance.normalUrl}/invites/${inviteId}`, {
headers: {
'Authorization': `Bearer ${cmInstance.getToken()}`,
}
}).json() as InviteData;
return res.render('invite', {
guests: invite.guests !== undefined && invite.guests !== null && invite.guests.length > 0 ? invite.guests.join(',') : '',
permissions: JSON.stringify(invite.permissions || []),
invite: inviteId,
});
} catch (err: any) {
cmInstance.logger.error(new ErrorWithCause(`Retrieving invite failed`, {cause: err}));
return res.render('error', {error: 'An error occurred while validating your invite and has been logged. Let the person who gave you this invite know! Sorry about that.'})
}
});
app.postAsync('/auth/create', helperAuthed, async (req: express.Request, res: express.Response) => {
const {
permissions,
clientId: ci,
clientSecret: ce,
redirect: redir,
instance,
subreddits,
guests: guestsVal,
} = req.body as any;
const cid = ci || clientCredentials.clientId;
if(cid === undefined || cid.trim() === '') {
return res.status(400).send('clientId is required');
}
const ced = ce || clientCredentials.clientSecret;
if(ced === undefined || ced.trim() === '') {
return res.status(400).send('clientSecret is required');
}
if(redir === undefined || redir.trim() === '') {
return res.status(400).send('redirectUrl is required');
}
let guestArr = [];
if(typeof guestsVal === 'string') {
guestArr = guestsVal.split(',');
} else if(Array.isArray(guestsVal)) {
guestArr = guestsVal;
}
guestArr = guestArr.filter(x => x.trim() !== '').map(x => parseRedditEntity(x, 'user').name);
const inviteData = {
permissions,
clientId: (ci || clientCredentials.clientId).trim(),
clientSecret: (ce || clientCredentials.clientSecret).trim(),
redirectUri: redir.trim(),
instance,
subreddits: subreddits.trim() === '' ? [] : subreddits.split(',').map((x: string) => parseRedditEntity(x).name),
creator: (req.user as Express.User).name,
guests: guestArr.length > 0 ? guestArr : undefined
};
const cmInstance = cmInstances.find(x => x.friendly === instance);
if(cmInstance === undefined) {
return res.status(400).send(`No instance found with name "${instance}"`);
}
const token = createToken(cmInstance, req.user);
try {
const resp = await got.post(`${cmInstance.normalUrl}/invites`, {
headers: {
'Authorization': `Bearer ${token}`,
},
json: inviteData,
}).json() as any;
cmInstance.invites.push(resp.id);
return res.send(resp.id);
} catch (err: any) {
cmInstance.logger.error(new ErrorWithCause(`Could not create bot invite.`, {cause: err}));
return res.status(400).send(`Error while creating invite: ${err.message}`);
}
});
app.getAsync('/auth/init/:inviteId', initHeartbeat, async (req: express.Request, res: express.Response) => {
const { inviteId } = req.params;
if(inviteId === undefined) {
return res.render('error', {error: '`invite` param is missing from URL'});
}
const cmInstance = cmInstances.find(x => x.invites.includes(inviteId));
if (cmInstance === undefined) {
return res.render('error', {error: 'Invite with the given id does not exist'});
}
let invite: InviteData;
try {
invite = await got.get(`${cmInstance.normalUrl}/invites/${inviteId}`, {
headers: {
'Authorization': `Bearer ${cmInstance.getToken()}`,
}
}).json() as InviteData;
} catch (err: any) {
cmInstance.logger.error(new ErrorWithCause(`Retrieving invite failed`, {cause: err}));
return res.render('error', {error: 'An error occurred while validating your invite and has been logged. Let the person who gave you this invite know! Sorry about that.'})
}
req.session.state = `bot_${randomId()}`;
// @ts-ignore
req.session.invite = invite;
const scope = Object.entries(invite.permissions).reduce((acc: string[], curr) => {
const [k, v] = curr as unknown as [string, boolean];
if(v) {
return acc.concat(k);
}
return acc;
},[]);
const authUrl = Snoowrap.getAuthUrl({
clientId: invite.clientId,
// @ts-ignore
clientSecret: invite.clientSecret,
scope,
// @ts-ignore
redirectUri: invite.redirectUri.trim(),
permanent: true,
state: req.session.state
});
return res.redirect(authUrl);
});
//</editor-fold>
const cmInstances: CMInstance[] = [];
let init = false;
const formatter = defaultFormat();
let server: http.Server,
io: SocketServer;
try {
server = await app.listen(port);
io = new SocketServer(server);
} catch (err: any) {
throw new ErrorWithCause('[Web] Error occurred while initializing web or socket.io server', {cause: err});
}
logger.info(`Web UI started: http://localhost:${port}`, {label: ['Web']});
const botWithPermissions = (required: boolean = false, setDefault: boolean = false) => async (req: express.Request, res: express.Response, next: Function) => {
const instance = req.instance;
if(instance === undefined) {
return res.status(401).send("Instance must be defined");
}
const msg = 'Bot does not exist or you do not have permission to access it';
const botVal = req.query.bot as string;
if(botVal === undefined && required) {
return res.status(400).render('error', {error: `"bot" param must be defined`});
}
if(botVal !== undefined || setDefault) {
let botInstance;
if(botVal === undefined) {
// find a bot they can access
botInstance = instance.bots.find(x => req.user?.canAccessBot(x));
if(botInstance !== undefined) {
req.query.bot = botInstance.botName;
}
} else {
botInstance = instance.bots.find(x => x.botName === botVal);
}
if(botInstance === undefined) {
return res.status(404).render('error', {error: msg});
}
if (!req.user?.clientData?.webOperator && !req.user?.canAccessBot(botInstance)) {
return res.status(404).render('error', {error: msg});
}
if (req.params.subreddit !== undefined && !req.user?.canAccessSubreddit(instance,req.params.subreddit)) {
return res.status(404).render('error', {error: msg});
}
req.bot = botInstance;
}
next();
}
const defaultSession = (req: express.Request, res: express.Response, next: Function) => {
if(req.session.limit === undefined) {
req.session.limit = 200;
req.session.level = 'verbose';
req.session.sort = 'descending';
req.session.save();
}
// @ts-ignore
connectedUsers[req.session.id] = {};
next();
}
// const authenticatedRouter = Router();
// authenticatedRouter.use([ensureAuthenticated, defaultSession]);
// app.use(authenticatedRouter);
//
// const botUserRouter = Router();
// botUserRouter.use([ensureAuthenticated, defaultSession, botWithPermissions, createUserToken]);
// app.use(botUserRouter);
// proxy.on('proxyReq', (req) => {
// logger.debug(`Got proxy request: ${req.path}`);
// });
// proxy.on('proxyRes', (proxyRes, req, res) => {
// logger.debug(`Got proxy response: ${res.statusCode} for ${req.url}`);
// });
app.useAsync('/api/', [ensureAuthenticatedApi, initHeartbeat, defaultSession, instanceWithPermissions, botWithPermissions(false), createUserToken], (req: express.Request, res: express.Response) => {
req.headers.Authorization = `Bearer ${req.token}`
const instance = req.instance as CMInstanceInterface;
return proxy.web(req, res, {
target: {
protocol: instance.url.protocol,
host: instance.url.hostname,
port: instance.url.port,
},
prependPath: false,
proxyTimeout: 11000,
}, (e: any) => {
logger.error(e);
res.status(500).send();
});
});
const defaultInstance = async (req: express.Request, res: express.Response, next: Function) => {
if(req.query.instance === undefined) {
if(cmInstances.length === 0) {
return res.render('error', {error: 'There are no ContextMod instances defined for this web client!'});
}
const user = req.user as Express.User;
const accessibleInstance = cmInstances.find(x => {
if(x.operators.includes(user.name)) {
return true;
}
return x.bots.some(y => y.canUserAccessBot(user.name, user.subreddits));
});
if(accessibleInstance === undefined) {
logger.warn(`User ${user.name} is not an operator and has no subreddits in common with any *running* bot instances. If you are sure they should have common subreddits then this client may not be able to access all defined CM servers or the bot may be offline.`, {user: user.name});
return res.render('noAccess');
}
return res.redirect(`/?instance=${accessibleInstance.getName()}`);
}
const instance = cmInstances.find(x => x.getName() === req.query.instance);
req.instance = instance;
next();
}
/* const defaultSubreddit = async (req: express.Request, res: express.Response, next: Function) => {
if(req.bot !== undefined && req.query.subreddit === undefined) {
const firstAccessibleSub = req.bot.managers.find(x => req.user?.isInstanceOperator(req.instance) || req.user?.subreddits.includes(x));
req.query.subreddit = firstAccessibleSub;
}
next();
}*/
const redirectBotsNotAuthed = async (req: express.Request, res: express.Response, next: Function) => {
if(cmInstances.length === 1 && cmInstances[0].error === 'Missing credentials: refreshToken, accessToken') {
// assuming user is doing first-time setup and this is the default localhost bot
return res.redirect('/auth/helper');
}
next();
}
const migrationRedirect = async (req: express.Request, res: express.Response, next: Function) => {
const user = req.user as Express.User;
const instance = req.instance as CMInstance;
if(instance.bots.length === 0 && instance?.ranMigrations === false && instance?.migrationBlocker !== undefined) {
if(!user.isInstanceOperator(instance)) {
return res.render('error-authenticated', {
error: `A database migration, which requires manual confirmation by its <strong>Operator</strong>, is required before this CM instance can finish starting up.`,
// @ts-ignore
...req.instancesViewData
})
}
return res.render('migrations', {
type: 'app',
ranMigrations: instance.ranMigrations,
migrationBlocker: instance.migrationBlocker,
instance: instance.friendly,
// @ts-ignore
...req.instancesViewData
});
}
return next();
};
const redirectNoBots = async (req: express.Request, res: express.Response, next: Function) => {
const i = req.instance as CMInstance;
if (i.bots.length === 0) {
// assuming user is doing first-time setup and this is the default localhost bot
return res.redirect(`/auth/helper?instance=${i.getName()}`);
}
next();
}
app.getAsync('/', [initHeartbeat, redirectBotsNotAuthed, ensureAuthenticated, defaultSession, defaultInstance, instanceWithPermissions, instancesViewData, migrationRedirect, redirectNoBots, botWithPermissions(false, true), createUserToken], async (req: express.Request, res: express.Response) => {
const user = req.user as Express.User;
const instance = req.instance as CMInstance;
const limit = req.session.limit;
const sort = req.session.sort;
const level = req.session.level;
let resp;
try {
resp = await got.get(`${instance.normalUrl}/status`, {
headers: {
'Authorization': `Bearer ${req.token}`,
},
searchParams: {
bot: req.query.bot as (string | undefined),
subreddit: req.query.sub as (string | undefined) ?? 'all',
limit,
sort,
level,
//bot: req.query.bot as string,
},
}).json() as any;
} catch(err: any) {
instance.logger.error(new ErrorWithCause(`Could not retrieve instance information. Will attempted to update heartbeat.`, {cause: err}));
refreshClient({host: instance.host, secret: instance.secret});
const isOp = req.user?.isInstanceOperator(instance);
return res.render('offline', {
// @ts-ignore
...req.instancesViewData,
isOperator: isOp,
// @ts-ignore
logs: filterLogs((isOp ? instance.logs : instance.logs.filter(x => x.user === undefined || x.user.includes(req.user.name))), {limit, sort, level}),
logSettings: {
limitSelect: [10, 20, 50, 100, 200].map(x => `<option ${limit === x ? 'selected' : ''} class="capitalize ${limit === x ? 'font-bold' : ''}" data-value="${x}">${x}</option>`).join(' | '),
sortSelect: ['ascending', 'descending'].map(x => `<option ${sort === x ? 'selected' : ''} class="capitalize ${sort === x ? 'font-bold' : ''}" data-value="${x}">${x}</option>`).join(' '),
levelSelect: availableLevels.map(x => `<option ${level === x ? 'selected' : ''} class="capitalize log-${x} ${level === x ? `font-bold` : ''}" data-value="${x}">${x}</option>`).join(' '),
},
})
// resp = defaultBotStatus(intersect(user.subreddits, instance.subreddits));
// resp.subreddits = resp.subreddits.map(x => {
// if(x.name === 'All') {
// x.logs = (botLogMap.get(instance.friendly) || []).map(x => formatLogLineToHtml(x[1]));
// }