-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
6290 lines (5387 loc) · 240 KB
/
Copy pathserver.js
File metadata and controls
6290 lines (5387 loc) · 240 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
/* Terp Notes Server - UMD Resource Sharing Platform */
process.stdin.setEncoding("utf8");
/* MongoDB Connections */
const path = require("path");
require("dotenv").config({ path: path.resolve(__dirname, './.env') });
// Check for required environment variables
const requiredEnvVars = [
'MONGO_CONNECTION_STRING',
'MONGO_DB_NAME',
'MONGO_FILECOLLECTION',
'MONGO_USERCOLLECTION',
'AWS_ACCESS_KEY_ID',
'AWS_SECRET_ACCESS_KEY',
'AWS_REGION',
'AWS_S3_BUCKET'
];
const missingVars = requiredEnvVars.filter(varName => !process.env[varName]);
if (missingVars.length > 0) {
console.error('Missing required environment variables:', missingVars.join(', '));
console.error('Please set these variables in your .env file');
}
const uri = process.env.MONGO_CONNECTION_STRING;
const fileCollection = { db: process.env.MONGO_DB_NAME, collection: process.env.MONGO_FILECOLLECTION };
const userCollection = { db: process.env.MONGO_DB_NAME, collection: process.env.MONGO_USERCOLLECTION };
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
const client = new MongoClient(uri, { serverApi: ServerApiVersion.v1 });
// Dashboard Configuration (removed - using inline config)
// Helper function to safely connect to MongoDB
async function ensureConnection() {
try {
// Check if client is already connected
if (client.topology && client.topology.isConnected()) {
return;
}
// If not connected, establish connection
await client.connect();
} catch (error) {
// If connection fails, try to create a new client
if (error.message.includes('Topology is closed') || error.message.includes('topology')) {
try {
// Close the old client first
if (client && typeof client.close === 'function') {
await client.close().catch(() => {}); // Ignore close errors
}
// Create a completely new client instance
const newClient = new MongoClient(uri, { serverApi: ServerApiVersion.v1 });
await newClient.connect();
// Replace the global client reference
Object.setPrototypeOf(client, Object.getPrototypeOf(newClient));
Object.assign(client, newClient);
} catch (newConnectionError) {
console.error('Failed to create new MongoDB connection:', newConnectionError);
throw newConnectionError;
}
} else {
throw error;
}
}
}
/* AWS Connection */
const AWS = require('aws-sdk');
if (process.env.NODE_ENV !== 'production') {
process.removeAllListeners('warning');
}
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION
});
const AWS_BUCKET = process.env.AWS_S3_BUCKET;
/* VirusTotal Configuration */
const VIRUSTOTAL_API_KEY = process.env.VIRUSTOTAL_API_KEY;
const VIRUSTOTAL_ENABLED = !!VIRUSTOTAL_API_KEY;
if (VIRUSTOTAL_ENABLED) {
console.log('VirusTotal integration enabled');
} else {
console.log('VirusTotal integration disabled (no API key found)');
}
/* UMD.io API Configuration */
const UMD_API_BASE = 'https://api.umd.io/v1';
const UMD_API_ENABLED = true; // Public API, always available
// Helper: Fetch UMD.io data with caching & fallback
async function fetchUMDData(endpoint, cacheKey, cacheDuration = 24 * 60 * 60 * 1000) {
try {
const cacheClient = new MongoClient(uri, { serverApi: ServerApiVersion.v1 });
await cacheClient.connect();
// Check cache first
const cached = await cacheClient
.db(fileCollection.db)
.collection('api_cache')
.findOne({ key: cacheKey });
const now = new Date();
if (cached && (now - new Date(cached.timestamp)) < cacheDuration) {
await cacheClient.close();
return cached.data;
}
// Fetch from API
const response = await fetch(`${UMD_API_BASE}${endpoint}`);
if (!response.ok) throw new Error(`API returned ${response.status}`);
const data = await response.json();
// Update cache
await cacheClient
.db(fileCollection.db)
.collection('api_cache')
.updateOne(
{ key: cacheKey },
{ $set: { key: cacheKey, data: data, timestamp: now } },
{ upsert: true }
);
await cacheClient.close();
return data;
} catch (error) {
console.error(`UMD.io API error (${endpoint}):`, error.message);
// Fallback to stale cache if available
try {
const fallbackClient = new MongoClient(uri, { serverApi: ServerApiVersion.v1 });
await fallbackClient.connect();
const staleCache = await fallbackClient
.db(fileCollection.db)
.collection('api_cache')
.findOne({ key: cacheKey });
await fallbackClient.close();
if (staleCache) {
return staleCache.data;
}
} catch (fallbackError) {
console.error('Fallback cache error:', fallbackError);
}
return null;
}
}
/* Port Configuration */
const portNumber = process.env.PORT || 3000;
/* Express Setup */
const express = require("express");
const { Resend } = require('resend');
const cookieParser = require('cookie-parser');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const fetch = require('node-fetch');
const FormData = require('form-data');
const emailTemplates = require('./emails/templates');
const { validatePassword, getPasswordRequirements } = require('./utils/passwordValidator');
const { sessionTimeout } = require('./middleware/sessionTimeout');
// Integration classes
const NotionIntegration = require('./integrations/notion');
const OneNoteIntegration = require('./integrations/onenote');
const GoogleDocsIntegration = require('./integrations/google-docs');
const ObsidianIntegration = require('./integrations/obsidian');
const OAuthManager = require('./integrations/oauth-manager');
const UserIntegrationsModel = require('./models/user-integrations');
const app = express();
// Dashboard configuration endpoint (removed - no longer needed)
// Trust proxy - required for Vercel/behind reverse proxy
app.set('trust proxy', 1);
// Security headers
app.use(helmet({
contentSecurityPolicy: false // Allow inline scripts for EJS
}));
// Rate limiters
const loginLimiter = rateLimit({
windowMs: 2 * 60 * 1000, // 2 minutes
max: 5, // 5 login attempts
message: 'Too many login attempts. Please try again in 5 minutes.',
standardHeaders: true,
legacyHeaders: false,
});
const registerLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 1000, // Generous limit for testing/mistakes FINDABLE
message: 'Too many registration attempts. Please try again in an hour.',
});
const uploadLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 20, // 20 upload sessions per hour
message: 'Upload limit reached. Please try again in an hour.',
});
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 API requests
message: 'Too many requests. Please slow down.',
});
// Per-user daily limits (uploads and reports)
async function getStartOfTodayUtc() {
const now = new Date();
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 0, 0, 0, 0));
}
// Account History Logging
async function logAccountHistory(userId, action, details, adminId = null, metadata = {}) {
try {
await ensureConnection();
const historyEntry = {
userId: userId,
action: action, // 'UPLOAD', 'DOWNLOAD', 'REPORT', 'BAN', 'UNBAN', 'ROLE_CHANGE', 'LOGIN', 'LOGOUT', etc.
details: details, // Human-readable description
adminId: adminId, // Who performed the action (if admin action)
metadata: metadata, // Additional data (IP, file info, etc.)
timestamp: new Date(),
createdAt: new Date()
};
await client
.db(fileCollection.db)
.collection('account_history')
.insertOne(historyEntry);
console.log(`📝 Account history logged: ${userId} - ${action} - ${details}`);
} catch (error) {
console.error('Failed to log account history:', error);
// Don't throw - history logging shouldn't break main functionality
}
}
async function countUserUploadsToday(userid) {
const startOfToday = await getStartOfTodayUtc();
return client
.db(fileCollection.db)
.collection(fileCollection.collection)
.countDocuments({ uploadedBy: userid, uploadDate: { $gte: startOfToday } });
}
async function countUserReportsToday(userid) {
const startOfToday = await getStartOfTodayUtc();
return client
.db(fileCollection.db)
.collection('reports')
.countDocuments({ reportedBy: userid, reportedAt: { $gte: startOfToday } });
}
// configurable caps
const DAILY_UPLOAD_CAP = 100; // admins/managers bypass
const DAILY_REPORT_CAP = 10; // per user per day
// Content filtering - load comprehensive profanity list
let PROFANITY_LIST = [];
// Whitelist of legitimate words that contain profanity substrings
const LEGITIMATE_WORDS = new Set([
// Names
'harshit', 'assad', 'dickinson', 'cockburn', 'butt', 'christopher', 'helen',
'dickens', 'assassin', 'classic', 'massive', 'passionate', 'assistance',
'assessment', 'assertion', 'assignment', 'assumption', 'assurance',
// Places
'dickinson', 'cockburn', 'assam', 'christchurch', 'helena',
// Common words
'classic', 'massive', 'passionate', 'assistance', 'assessment', 'assertion',
'assignment', 'assumption', 'assurance', 'assassin', 'assembly', 'assert',
'assess', 'assign', 'assist', 'assume', 'assure', 'asset', 'assets',
]);
// Content filtering - rule-based only
// Comprehensive profanity list for rule-based filtering
PROFANITY_LIST = [
{
id: 'comprehensive-filter',
match: '1 man 1 jar|1m1j|1man1jar|2 girls 1 cup|2g1c|2girls1cup|acrotomophile|acrotomophilia|alabama hot pocket|alabama tuna melt|alaskan pipeline|algophile|algophilia|anal|anal assassin|anal astronaut|anilingus|anus|ape shit|ape-shit|apeshit|apotemnophile|apotemnophilia|arse|arse bandit|arsehole|ass|ass bandit|asshole|auto erotic|autoerotic|babeland|baby batter|baby gravy|baby juice|ball batter|ball gag|ball gravy|ball kicking|ball licking|ball sack|ball sucking|ball-gag|ball-kicking|ball-licking|ball-sucking|ballcuzi|ballgag|bang bros|bang bus|bangbros|bangbus|bareback|barely legal|bastard|bastinado|batty boi|batty boy|battyboi|battyboy|bdsm|bean flicker|bean queen|bean-flicker|beaner|beaners|beanflicker|beastiality|beaver cleaver|beaver lips|beestiality|bellend|bellesa|bestiality|bicon|big boobs|big breasts|big cock|big knockers|big tits|birdlock|bitch|bitches|black cock|bloody|blow job|blow your load|blow-job|blowjob|blue waffle|bluewaffle|blumpkin|bollocks|bone smuggler|bone-smuggler|boner|bonesmuggler|boob|booty buffer|booty call|booty-buffer|boston george|breasts|brown piper|brown shower|brown showers|brown-piper|brownie king|brownie queen|brownpiper|buddha head|buddha-head|buddhahead|bufter|bufty|bugger|bukkake|bull shit|bull-shit|bulldyke|bullet vibe|bullet vibrator|bullshit|bum boy|bum chum|bum driller|bum pilot|bum pirate|bum rider|bum robber|bum rustler|bum-boy|bum-chum|bum-driller|bum-pirate|bum-robber|bumboy|bumchum|bumdriller|bumhole engineer|bumrider|bumrobber|butt boy|butt pilot|butt pirate|butt rider|butt robber|butt rustler|butt-boy|butt-pirate|butt-robber|buttboy|butthole engineer|buttrider|buttrobber|camel jockey|camel jockies|camel toe|cameljockey|cameljockies|canadian porch swing|carpet muncher|carpetmuncher|cheese eating surrender monkey|cheese-eating surrender monkey|chi chi man|chi-chi man|chicken queen|china man|china men|chinaman|chinamen|ching chong|ching-chong|chink|chinks|chinky|chocolate rosebud|chocolate rosebuds|cholerophile|cholerophilia|christ|cialis|circle-jerk|circlejerk|cishet|cissie|cissy|claustrophile|claustrophilia|cleveland accordion|cleveland hot waffle|cleveland steamer|clit|clitoris|clover clamp|clover clamps|clunge|cluster fuck|cluster-fuck|clusterfuck|cock|cockpipe cosmonaut|cockstruction worker|coimetrophile|coimetrophilia|collared|collaring|coon|coons|coprolagnia|coprophile|coprophilia|cornhole|crafty butcher|crap|cream-pie|creampie|cum|cum shot|cum shots|cumming|cumshot|cumshots|cunnilingus|cunt|cunt boy|cunt-boy|cuntboy|cunts|curry muncher|curry-muncher|currymuncher|damn|darkey|darkie|darkies|darky|date rape|daterape|ddlg|deep throat|deep-throat|deepthroat|dendrophile|dendrophilia|dick|dick girl|dick-girl|dickgirl|dildo|dildos|dingleberries|dingleberry|dipsea|dirty pillows|dirty sanchez|dishabiliophile|dishabiliophilia|dog shit|dog style|dog-shit|doggie style|doggie-style|doggiestyle|doggy style|doggy-style|doggystyle|dogshit|dolcett|domination|dominatrix|domme|dommes|donkey punch|donut muncher|donut puncher|doon coon|dooncoon|double penetration|dp action|dry hump|dune coon|dune-coon|dutch rudder|dyke|dystychiphile|dystychiphilia|edge play|edgeplay|ejaculate|ejaculated|ejaculating|ejaculation|electro-play|electroplay|emetophile|emetophilia|enby|eskimo trebuchet|eye-tie|eyetie|fag|fag bomb|fag-bomb|fagbomb|faggot|fagot|felch|felching|fellating|fellatio|female squirting|figging|finger bang|fingerbang|fingerbanging|fingered|fingering|finocchio|finoccio|finochio|fisted|fisting|foot job|foot-job|footjob|french rudder|frog eater|frog-eater|frogeater|frolic me|frolicme|frottage|frotting|fuck|fuck-wit|fucken|fucker|fuckers|fuckhead|fuckheads|fuckin|fucking|fucks|fucktard|fucktards|fuckwad|fuckwads|fuckwhit|fuckwit|fuckwits|fudge packer|fudge-packer|fudgepacker|futanari|g-spot|gang bang|gangbang|gay sex|gaysian|genitals|genitorture|gerontophile|gerontophilia|giant cock|gin jockey|gin jocky|girl on top|go-kun|goatcx|goatse|god damn|god damned|god-damn|god-damned|goddamn|goddamned|gokkun|golden shower|golden showers|golliwog|gollywog|gook|gook-eye|gookie|gooks|gooky|goregasm|gray queen|greaseball|grey queen|grope|group sex|gym bunny|gymbunny|hadji|haji|hajji|hand job|hand-job|handjob|heimie|hell|hermie|hickory switch|hippophile|hippophilia|homoerotic|honkey|honkeys|honkies|honky|horny|horse shit|horse-shit|horseshit|hot carl|hot richard|huge cock|humping|hymie|impact play|impact-play|incest|intercourse|jack off|jack-off|jail bait|jailbait|jap|jelly donut|jerk mate|jerk off|jerk-off|jerkmate|jesus|jesus christ|jigaboo|jiggerboo|jizz|juggs|jungle bunny|junglebunny|kennebunkport surprise|kentucky klondike|kentucky tractor puller|kike|kinbaku|kitty puncher|kitty-puncher|kittypuncher|knobbing|kraut|krauts|kunt|kunts|kynophile|kynophilia|lady boy|lady-boy|ladyboy|leather restraint|leather straight jacket|lemon party|lemonparty|leningrad steamer|lesbo|leso|lezzie|lezzies|light in the fedora|light in the loafers|light in the pants|limp wristed|limp-wristed|literotica|lovemaking|male squirting|male-squirting|massive cock|masterb8|masterbate|masturb8|masturbate|masturbating|masturbation|mayonnaise monkey|mayonnaise monkies|mdlb|meat masseuse|meat spin|meatspin|menage a trois|menage-a-trois|menages a trois|menages-a-trois|menophile|menophilia|mexican pancake|milwaukee blizzard|missionary position|mississippi birdbath|mound of venus|mr hands|mr. hands|mrhands|muff diver|muff diver|muff diving|muff-diver|muffdiver|muffdiver|muffdiving|muscle mary|mvtube|nambla|necrophile|necrophilia|negro|neo nazi|neo-nazi|neonazi|nig nog|nigerian hurricane|nigga|nigger|niggs|nignog|nimpho|nimphomania|nimphomaniac|nipple|nipple clamp|nipple clamps|nipples|nude|nudity|nutten|nympho|nymphomania|nymphomaniac|octopussy|oklahomo|omorashi|one cup two girls|one jar one man|one man one jar|only fans|onlyfans|orgasm|orgasmic|orgasms|paedo bear|paedobear|paedophile|paedophilia|pain slut|painslut|paki|panamanian petting zoo|pansy|panties|parthenophile|parthenophilia|pedo bear|pedobear|pedophile|pedophilia|pegging|penis|peter puffer|peter-puffer|peterpuffer|petrol sniffer|petrol-sniffer|petrolsniffer|phagophile|phagophilia|piece of shit|pieces of shit|pikey|pikeys|piss off|piss pig|piss pig|pissed off|pissing|pisspig|pisspig|playboy|pleasure chest|pnigerophile|pnigerophilia|pnigophile|pnigophilia|poinephile|poinephilia|pony boy|pony girl|pony-boy|pony-girl|pony-play|ponyboy|ponygirl|ponyplay|poof|poon|poontang|poop chute|poopchute|porn|porn hub|pornhub|porno|pornographic|pornography|pornos|potato queen|prince albert piercing|proctophile|proctophilia|pubes|punani|punany|pussy|pussy puncher|pussy-puncher|pussypuncher|queaf|queef|quim|rag head|rag heads|raghead|ragheads|raging boner|ramen yarmulke|rape|raping|rapist|rectum|retard|retarded|reverse cowgirl|rhabdophile|rhabdophilia|rhypophile|rhypophilia|rice queen|rimjob|rimming|ring raider|ringraider|rusty trombone|sand nigger|sand-nigger|sandnigger|santorum|scatophile|scatophilia|schlong|scissoring|semen|seplophile|seplophilia|sex|shaved beaver|shaved pussy|she male|she-male|sheep shagger|sheepshagger|shemale|shibari|shit|shit head|shithead|shitty|shlong|shota|shrimping|sissy|skeet|skittle harvest|skittles harvest|slant eye|slant-eye|slanteye|snatch|snowballing|sod off|sodding|sodomise|sodomist|sodomize|sodomy|spastic|spearchucker|spic|spick|spicks|spics|spicy gringo|splooge|splooge moose|spooge|spunk|strap on|strap-on|strap-on|strapon|strappado|suastika|svastika|swamp guinea|swamp-guinea|swastika|switch hitter|t-girl|taphephile|taphephilia|tea bagged|tea bagging|tea-bagged|tea-bagging|tgirl|thanatophile|thanatophilia|threesome|throating|throbbing boner|throbbing cock|thumbzilla|timber nigger|timber-nigger|timbernigger|tits|titties|titty|topless|tosser|towel head|towel-head|towelhead|trannie|tranny|transbian|traumatophile|traumatophilia|tribadism|tribbing|tub girl|tubgirl|twat|twink|two girls one cup|urethra play|urophile|urophilia|vagina|venus mound|viagra|vibrator|violet wand|vorarephile|vorarephilia|voyeurweb|wagon burner|wagon-burner|wank|wanker|wax play|wax-play|wet back|wet dream|wet-back|wetback|whigger|white power|white-power|whitepower|whore|wigga|wigger|wiitwd|wog|wogs|wolfbagging|worldsex|wrapping men|wrinkled starfish|xhamster|xnxx|xtube|xvideos|xxx|xyrophile|xyrophilia|yellow shower|yellow showers|zipper head|zipper-head|zipperhead|zippo cat|zippo-cat|zippocat|zoophile|zoophilia',
tags: ['comprehensive'],
severity: 3
}
];
// Content filtering functions - rule-based only
async function containsOffensiveContent(text) {
if (!text || typeof text !== 'string') return { found: false, entry: null };
const lowerText = text.toLowerCase()
.replace(/[^\w\s]/g, '') // Remove punctuation for better matching
.replace(/\s+/g, ' '); // Normalize whitespace
// Check if the entire text is in the legitimate words whitelist
if (LEGITIMATE_WORDS.has(lowerText.trim())) {
return { found: false, entry: null };
}
// Rule-based detection
const ruleBasedResult = ruleBasedDetection(text);
if (ruleBasedResult.found) {
return ruleBasedResult;
}
return { found: false, entry: null };
}
// Rule-based detection (existing system)
function ruleBasedDetection(text) {
const lowerText = text.toLowerCase()
.replace(/[^\w\s]/g, '') // Remove punctuation for better matching
.replace(/\s+/g, ' '); // Normalize whitespace
// Check each profanity entry
for (const entry of PROFANITY_LIST) {
const matches = entry.match.split('|');
for (const match of matches) {
// Convert wildcard pattern to regex pattern
// * means "one or more repeating characters" in this context
let regexPattern = match.toLowerCase();
// Handle wildcard matching: convert * to regex for repeating characters
// First escape special characters, then convert * to +
regexPattern = regexPattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
regexPattern = regexPattern.replace(/\\\*/g, '+');
// Check if this match has exceptions and text matches an exception
if (entry.exceptions && entry.exceptions.length > 0) {
let hasException = false;
for (const exception of entry.exceptions) {
// Exception format: * is placeholder for the matched word
// e.g., "*o" means "matched_word + o"
const baseMatch = match.toLowerCase().replace(/\*/g, '');
let exceptionPattern = exception.replace(/\*/g, baseMatch);
// Escape special regex characters
exceptionPattern = exceptionPattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
try {
const exceptionRegex = new RegExp(exceptionPattern, 'i');
if (exceptionRegex.test(lowerText)) {
hasException = true;
break;
}
} catch (e) {
// Skip invalid regex patterns
continue;
}
}
if (hasException) continue;
}
// Check for matches using the regex pattern
try {
// Use STRICT word boundary matching to avoid false positives
const wordRegex = new RegExp(`\\b${regexPattern}\\b`, 'i');
if (wordRegex.test(lowerText)) {
// Double-check: if this is a partial match in a legitimate word, skip it
const words = lowerText.split(/\s+/);
let isLegitimate = false;
for (const word of words) {
if (LEGITIMATE_WORDS.has(word)) {
isLegitimate = true;
break;
}
}
if (!isLegitimate) {
return { found: true, entry };
}
}
} catch (e) {
// Skip invalid regex patterns
continue;
}
}
}
return { found: false, entry: null };
}
async function validateContent(content, fieldName) {
const result = await containsOffensiveContent(content);
if (result.found) {
const severity = result.entry.severity;
const tags = result.entry.tags.join(', ');
const method = result.method || 'rule-based';
throw new Error(`${fieldName} contains inappropriate content (severity: ${severity}, tags: ${tags}, detected by: ${method}). Please use appropriate language.`);
}
}
// Increased body size limits for file uploads
app.use(express.urlencoded({ extended: false, limit: '50mb' }));
app.use(express.json({ limit: '50mb' }));
app.use(cookieParser());
app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs");
// Serve static files
app.use("/styles", express.static(path.join(__dirname, "styles")));
app.use(express.static(path.join(__dirname, "public"))); // Serve logo, favicon, etc.
/* Session Handling - JWT-based */
const session = require("express-session");
const jwt = require('jsonwebtoken');
// Configure session store for Vercel compatibility
const MongoStore = require('connect-mongo');
app.use(session({
secret: process.env.SECRET_KEY,
resave: false,
saveUninitialized: false,
rolling: true,
name: 'terpnotes.sid',
store: MongoStore.create({
mongoUrl: process.env.MONGO_CONNECTION_STRING,
touchAfter: 24 * 3600, // lazy session update
ttl: 24 * 60 * 60 // 24 hours
}),
cookie: {
// Secure flag: true for HTTPS (Vercel always uses HTTPS), false for HTTP (localhost)
// Vercel sets VERCEL env var, or we can check if BASE_URL is HTTPS
// Note: On Vercel preview domains, cookies MUST use secure=true because they're HTTPS
secure: process.env.VERCEL === '1' ||
(process.env.BASE_URL && process.env.BASE_URL.startsWith('https')) ||
process.env.NODE_ENV === 'production' ||
false,
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000, // 24 hours
sameSite: 'lax',
path: '/'
// Don't set domain - let it default to the request host
// This ensures cookies work on both preview and production Vercel domains
},
// Force new session for each login to prevent conflicts
genid: function(req) {
return require('crypto').randomBytes(16).toString('hex');
}
}));
/* CRON ENDPOINTS - Must be before session middleware */
// Cron endpoint for Vercel: Scan pending files
app.get('/api/cron/scan-pending-files', async (req, res) => {
// Verify request is from Vercel Cron (required for security)
const authHeader = req.get('Authorization');
if (!process.env.CRON_SECRET) {
return res.status(500).json({ error: 'CRON_SECRET not configured' });
}
if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
return res.status(401).json({ error: 'Unauthorized' });
}
if (!VIRUSTOTAL_ENABLED) {
return res.json({ message: 'VirusTotal disabled' });
}
try {
await ensureConnection();
// Find files pending scan (uploaded more than 1 minute ago to avoid race conditions)
const oneMinuteAgo = new Date();
oneMinuteAgo.setMinutes(oneMinuteAgo.getMinutes() - 1);
const pendingFiles = await client
.db(fileCollection.db)
.collection(fileCollection.collection)
.find({
virusScanStatus: 'pending',
uploadDate: { $lt: oneMinuteAgo }
})
.limit(5) // Process max 5 files per cron run (avoid timeout)
.toArray();
if (pendingFiles.length === 0) {
return res.json({ message: 'No pending scans', scanned: 0 });
}
console.log(`🔄 Cron: Processing ${pendingFiles.length} pending scan(s)...`);
// Trigger scans (they run asynchronously)
for (const file of pendingFiles) {
try {
const s3Key = file.filename;
const s3Data = await s3.getObject({ Bucket: AWS_BUCKET, Key: s3Key }).promise();
// Don't await - let it run in background
scanFileWithVirusTotal(file._id, s3Data.Body, file.originalName).catch(err => {
console.error('Cron scan error:', err);
});
} catch (s3Error) {
console.error('Error fetching file for scan:', s3Error);
}
}
res.json({
message: `Triggered ${pendingFiles.length} virus scan(s)`,
scanned: pendingFiles.length
});
} catch (error) {
console.error('Cron endpoint error:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Session timeout middleware - MUST come after session initialization
app.use(sessionTimeout);
app.use(mobileRedirect);
/* UMD.io Data Cache Helper */
async function getCachedData(filename) {
try {
const fs = require('fs').promises;
const path = require('path');
const dataPath = path.join(__dirname, 'data', filename);
const data = await fs.readFile(dataPath, 'utf8');
return JSON.parse(data);
} catch (error) {
console.warn(`⚠️ Cache file ${filename} not found or invalid:`, error.message);
return null;
}
}
async function isCacheStale(cacheData, maxAgeHours = 168) { // 1 week default
if (!cacheData || !cacheData.timestamp) return true;
const cacheTime = new Date(cacheData.timestamp);
const now = new Date();
const ageHours = (now - cacheTime) / (1000 * 60 * 60);
return ageHours > maxAgeHours;
}
/* DEPRECATED UMD.io API endpoints - using cache system only
app.get('/api/umd/search', async (req, res) => {
try {
const { professor, course, semester, year } = req.query;
// Get cached data
const cachedProfessors = await getCachedData('professors-cache.json');
const cachedCourses = await getCachedData('courses-cache.json');
if (!cachedProfessors || !cachedCourses ||
(await isCacheStale(cachedProfessors, 168)) ||
(await isCacheStale(cachedCourses, 168))) {
return res.status(503).json({ error: 'Cache unavailable, please try again later' });
}
let results = {
professors: [],
courses: [],
semesters: [],
years: []
};
// Filter professors based on criteria
if (professor) {
results.professors = cachedProfessors.professors.filter(prof =>
prof.name.toLowerCase().includes(professor.toLowerCase())
);
} else {
// If no professor filter, return all professors
results.professors = cachedProfessors.professors;
}
// Filter courses based on criteria
if (course) {
results.courses = cachedCourses.courses.filter(c =>
c.course_id.toLowerCase().includes(course.toLowerCase()) ||
(c.name && c.name.toLowerCase().includes(course.toLowerCase()))
);
} else {
// If no course filter, return all courses
results.courses = cachedCourses.courses;
}
// If we have a specific course, get its professors
if (course && !professor) {
const courseId = course.toUpperCase();
results.professors = cachedProfessors.professors.filter(prof =>
prof.semesters.some(sem => sem.course_id === courseId)
);
}
// If we have a specific professor, get their courses
if (professor && !course) {
const prof = cachedProfessors.professors.find(p =>
p.name.toLowerCase().includes(professor.toLowerCase())
);
if (prof) {
results.courses = prof.semesters.map(sem => ({
course_id: sem.course_id,
semester: sem.semester,
year: sem.year
}));
}
}
// Get available semesters and years from filtered data
const allSemesters = new Set();
const allYears = new Set();
if (results.professors.length > 0) {
results.professors.forEach(prof => {
prof.semesters.forEach(sem => {
allSemesters.add(sem.semester);
allYears.add(sem.year);
});
});
}
results.semesters = Array.from(allSemesters).sort();
results.years = Array.from(allYears).sort((a, b) => b - a); // Most recent first
res.json(results);
} catch (error) {
console.error('[FLEXIBLE SEARCH API] Error:', error);
res.status(500).json({ error: 'Failed to perform flexible search' });
}
});
/* UMD.io Professors API - Must be before session validation middleware */
app.get('/api/umd/professors', async (req, res) => {
try {
const { name, course_id, filter_semester, filter_year } = req.query;
if (course_id) {
// Fetch professors for a specific course with filtering
const courseId = course_id.toUpperCase();
const currentYear = new Date().getFullYear();
// Try to use cached professors first
const cachedProfessors = await getCachedData('professors-cache.json');
if (cachedProfessors && !(await isCacheStale(cachedProfessors, 168))) { // 1 week cache
console.log('👨🏫 Using cached professors data');
// Filter professors who taught the specific course
const courseProfessors = cachedProfessors.professors.filter(prof =>
prof.semesters.some(sem => sem.course_id === courseId)
);
// Apply semester/year filters if provided
let filteredProfessors = courseProfessors;
if (filter_semester || filter_year) {
filteredProfessors = courseProfessors.map(prof => {
const filteredSemesters = prof.semesters.filter(sem => {
if (filter_semester && sem.semester !== filter_semester) return false;
if (filter_year && sem.year !== parseInt(filter_year)) return false;
return true;
});
return {
name: prof.name,
semesters: filteredSemesters
};
}).filter(prof => prof.semesters.length > 0);
}
return res.json(filteredProfessors);
}
// Fallback to live API
console.log('🌐 Using live API for professors');
// Determine which semesters to fetch based on filters (same logic as course API)
let semestersToCheck = [];
if (filter_semester && filter_year) {
// Specific semester and year
const semesterMap = { 'Spring': '01', 'Summer': '05', 'Fall': '08', 'Winter': '12' };
const semesterId = `${filter_year}${semesterMap[filter_semester] || '01'}`;
semestersToCheck = [semesterId];
} else if (filter_semester) {
// All years for this semester
const semesterMap = { 'Spring': '01', 'Summer': '05', 'Fall': '08', 'Winter': '12' };
const semesterNum = semesterMap[filter_semester] || '01';
for (let year = 2020; year <= currentYear; year++) {
semestersToCheck.push(`${year}${semesterNum}`);
}
} else if (filter_year) {
// All semesters for this year
semestersToCheck = [`${filter_year}01`, `${filter_year}05`, `${filter_year}08`, `${filter_year}12`];
} else {
// Default: 1 year lookback for initial course search (faster)
const now = new Date();
const currentYear = now.getFullYear();
// Get semesters from 1 year ago to now for initial search
for (let year = currentYear - 1; year <= currentYear; year++) {
semestersToCheck.push(`${year}01`, `${year}05`, `${year}08`, `${year}12`);
}
}
// Fetch professor data for all required semesters
const professorData = new Map(); // name -> {name, semesters: [{semester, year, semesterId}]}
for (const semesterId of semestersToCheck) {
try {
const sectionsData = await fetchUMDData(
`/courses/sections?course_id=${courseId}&semester=${semesterId}&per_page=100`,
`sections_${courseId}_${semesterId}`,
7 * 24 * 60 * 60 * 1000
);
if (sectionsData && sectionsData.length > 0) {
const professors = [...new Set(
sectionsData
.map(section => section.instructors)
.flat()
.filter(prof => prof && prof !== 'Instructor: TBA')
)];
if (professors.length > 0) {
// Convert semester ID to readable format
const year = semesterId.substring(0, 4);
const semesterNum = semesterId.substring(4, 6);
const semesterName = {
'01': 'Spring', '05': 'Summer', '08': 'Fall', '12': 'Winter'
}[semesterNum];
// Add professors to our data structure
professors.forEach(profName => {
if (!professorData.has(profName)) {
professorData.set(profName, {
name: profName,
semesters: []
});
}
professorData.get(profName).semesters.push({
semester: semesterName,
year: parseInt(year),
semesterId: semesterId
});
});
}
}
} catch (error) {
// Silently continue if this semester fails
}
}
// Convert Map to array and sort by name
const result = Array.from(professorData.values()).sort((a, b) => a.name.localeCompare(b.name));
return res.json(result);
} else if (name) {
// Search professors by name - use the optimized UMD.io API with semester data
try {
const professors = await fetchUMDData(`/professors?name=${encodeURIComponent(name)}`, `professors_name_${name}`);
if (professors && professors.length > 0) {
const currentYear = new Date().getFullYear();
const fourYearsAgo = currentYear - 4;
const result = professors.map(prof => {
// Filter taught courses to only include last 4 years
const recentCourses = prof.taught ? prof.taught.filter(course => {
const semesterYear = parseInt(course.semester.substring(0, 4));
return semesterYear >= fourYearsAgo;
}) : [];
// Convert semester data to our format
const semesters = recentCourses.map(course => {
const semesterId = course.semester;
const year = parseInt(semesterId.substring(0, 4));
const semesterNum = semesterId.substring(4, 6);
const semesterName = {
'01': 'Spring', '05': 'Summer', '08': 'Fall', '12': 'Winter'
}[semesterNum];
return {
semester: semesterName,
year: year,
semesterId: semesterId,
course_id: course.course_id
};
});
return {
name: prof.name,
semesters: semesters
};
}).filter(p => p.name && p.name.trim());
return res.json(result);
} else {
return res.json([]);
}
} catch (error) {
console.error('Error fetching professor data:', error);
return res.json([]);
}
} else {
// No specific search - return all professors from recent semesters
// Fetch professors from last 2 years (current and previous year)
const currentYear = new Date().getFullYear();
const semestersToCheck = [];
// Add current and previous year semesters
for (let year = currentYear - 1; year <= currentYear; year++) {
semestersToCheck.push(`${year}01`, `${year}05`, `${year}08`, `${year}12`);
}
// Fetch professor data for recent semesters
const professorData = new Map(); // name -> {name, semesters: [{semester, year, semesterId}]}
for (const semesterId of semestersToCheck) {
try {
const sectionsData = await fetchUMDData(
`/courses/sections?semester=${semesterId}&per_page=100`,
`sections_${semesterId}`,
7 * 24 * 60 * 60 * 1000
);
if (sectionsData && sectionsData.length > 0) {
const professors = [...new Set(
sectionsData
.map(section => section.instructors)
.flat()
.filter(prof => prof && prof !== 'Instructor: TBA')
)];
if (professors.length > 0) {
// Convert semester ID to readable format
const year = semesterId.substring(0, 4);
const semesterNum = semesterId.substring(4, 6);
const semesterName = {
'01': 'Spring', '05': 'Summer', '08': 'Fall', '12': 'Winter'
}[semesterNum];
// Add professors to our data structure
professors.forEach(profName => {
if (!professorData.has(profName)) {
professorData.set(profName, {
name: profName,
semesters: []
});
}
professorData.get(profName).semesters.push({
semester: semesterName,
year: parseInt(year),
semesterId: semesterId
});
});
}
}
} catch (error) {
}
}
// Convert Map to array and sort by name
const result = Array.from(professorData.values()).sort((a, b) => a.name.localeCompare(b.name));
return res.json(result);
}
} catch (error) {
console.error('[PROF API] Error:', error);
res.status(500).json({ error: 'Failed to fetch professors' });
}
});
// API: Get courses taught by a specific professor
app.get('/api/umd/professor-courses', async (req, res) => {
try {
const { professor_name, filter_semester, filter_year } = req.query;
if (!professor_name || !professor_name.trim()) {
return res.json([]);
}
const professorName = professor_name.trim();
// Determine which semesters to fetch based on filters (same logic as other APIs)
let semestersToCheck = [];
if (filter_semester && filter_year) {
// Specific semester and year
const semesterMap = { 'Spring': '01', 'Summer': '05', 'Fall': '08', 'Winter': '12' };
const semesterId = `${filter_year}${semesterMap[filter_semester] || '01'}`;
semestersToCheck = [semesterId];
} else if (filter_semester) {
// All years for this semester
const semesterMap = { 'Spring': '01', 'Summer': '05', 'Fall': '08', 'Winter': '12' };
const semesterNum = semesterMap[filter_semester] || '01';
for (let year = 2020; year <= currentYear; year++) {
semestersToCheck.push(`${year}${semesterNum}`);
}
} else if (filter_year) {
// All semesters for this year
semestersToCheck = [`${filter_year}01`, `${filter_year}05`, `${filter_year}08`, `${filter_year}12`];
} else {
// Default: current semester only
const now = new Date();
const currentYear = now.getFullYear();
const currentMonth = now.getMonth() + 1;
let currentSemester;
if (currentMonth >= 1 && currentMonth <= 5) currentSemester = 'Spring';
else if (currentMonth >= 6 && currentMonth <= 7) currentSemester = 'Summer';
else if (currentMonth >= 8 && currentMonth <= 12) currentSemester = 'Fall';
const semesterMap = { 'Spring': '01', 'Summer': '05', 'Fall': '08', 'Winter': '12' };
const currentSemesterId = `${currentYear}${semesterMap[currentSemester] || '01'}`;
semestersToCheck = [currentSemesterId];
}
// Fetch course data for all required semesters
const courseData = new Map(); // course_id -> {course_id, name, semesters: [{semester, year, semesterId}]}
for (const semesterId of semestersToCheck) {
try {
const sectionsData = await fetchUMDData(
`/courses/sections?semester=${semesterId}&per_page=100`,
`sections_${semesterId}`,
7 * 24 * 60 * 60 * 1000
);
if (sectionsData && sectionsData.length > 0) {
// Filter sections taught by this professor
const professorSections = sectionsData.filter(section => {
return section.instructors && section.instructors.some(instructor =>
instructor && instructor.toLowerCase().includes(professorName.toLowerCase())
);
});
if (professorSections.length > 0) {
// Convert semester ID to readable format
const year = semesterId.substring(0, 4);
const semesterNum = semesterId.substring(4, 6);
const semesterName = {
'01': 'Spring', '05': 'Summer', '08': 'Fall', '12': 'Winter'
}[semesterNum];
// Add courses to our data structure
professorSections.forEach(section => {
const courseId = section.course_id;
if (!courseData.has(courseId)) {
courseData.set(courseId, {
course_id: courseId,
name: section.course_name || courseId,
semesters: []
});
}
courseData.get(courseId).semesters.push({
semester: semesterName,
year: parseInt(year),
semesterId: semesterId
});
});
}
}
} catch (error) {
}
}
// Convert Map to array and sort by course_id
const result = Array.from(courseData.values()).sort((a, b) => a.course_id.localeCompare(b.course_id));
return res.json(result);
} catch (error) {
console.error('[PROF-COURSES API] Error:', error);
res.status(500).json({ error: 'Failed to fetch professor courses' });
}
});
// New endpoint for getting specific professor data with 4-year lookback
app.get('/api/umd/professor-details', async (req, res) => {
try {
const { name } = req.query;
if (!name) {
return res.status(400).json({ error: 'Professor name is required' });