-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver.js
More file actions
2262 lines (1887 loc) · 79.5 KB
/
Copy pathserver.js
File metadata and controls
2262 lines (1887 loc) · 79.5 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
const express = require('express');
const { Pool } = require('pg');
const cors = require('cors');
const path = require('path');
const axios = require('axios');
const { randomBytes } = require('crypto');
const ffmpeg = require('fluent-ffmpeg');
require('dotenv').config();
const app = express();
app.use(cors({
origin: ['https://webdemonlist.org', 'https://impossible.webdemonlist.org'],
credentials: true
}));
app.use(express.json());
app.use(express.static('public'));
app.use((req, res, next) => {
const host = req.headers.host || '';
if (host.startsWith('impossible.')) {
req.currentList = 'impossible';
} else {
req.currentList = 'main';
}
next();
});
const { Resend } = require('resend');
const resend = new Resend(process.env.RESEND_API_KEY);
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false }
});
const validateUsername = (username) => {
if (!username || username.length < 3 || username.length > 20) {
return "Username must be between 3 and 20 characters long.";
}
const usernameRegex = /^[a-zA-Z0-9._-]+$/;
if (!usernameRegex.test(username)) {
return "Usernames can only contain letters, numbers, underscores, dashes, and periods.";
}
return null;
};
const validatePassword = (password) => {
if (!password || password.length < 6) {
return "Password must be at least 6 characters.";
}
return null;
};
const PROFILE_ICON_TYPES = new Set(['cube', 'ship', 'ball', 'ufo', 'wave', 'robot', 'spider', 'swing', 'jetpack']);
const cleanProfileText = (value, maxLength) => {
const text = String(value ?? '').trim();
return text.length > maxLength ? text.slice(0, maxLength) : text;
};
const readProfileInt = (value, fallback) => {
const parsed = parseInt(value, 10);
return Number.isNaN(parsed) ? fallback : parsed;
};
const cleanProfileIcon = (icon = {}) => {
const type = PROFILE_ICON_TYPES.has(icon.type) ? icon.type : 'cube';
const parsedId = parseInt(icon.id, 10);
const parsedColor1 = parseInt(icon.color1, 10);
const parsedColor2 = parseInt(icon.color2, 10);
const parsedGlow = parseInt(icon.glow, 10);
const id = Number.isNaN(parsedId) ? 1 : Math.min(999, Math.max(1, parsedId));
const color1 = Number.isNaN(parsedColor1) ? 12 : Math.min(999, Math.max(0, parsedColor1));
const color2 = Number.isNaN(parsedColor2) ? 3 : Math.min(999, Math.max(0, parsedColor2));
const glow = Number.isNaN(parsedGlow) ? -1 : Math.min(999, Math.max(-1, parsedGlow));
return { type, id, color1, color2, glow };
};
function getLevelUpdateFromId(levelId) {
const id = parseInt(levelId, 10);
if (Number.isNaN(id)) return null;
const ranges = [
{ version: '1.0', min: 128, max: 1941 },
{ version: '1.1', min: 1942, max: 10043 },
{ version: '1.2', min: 10049, max: 63415 },
{ version: '1.3', min: 63419, max: 121068 },
{ version: '1.4', min: 121074, max: 184425 },
{ version: '1.5', min: 184440, max: 420780 },
{ version: '1.6', min: 420781, max: 827308 },
{ version: '1.7', min: 827316, max: 1627362 },
{ version: '1.8', min: 1627371, max: 2810918 },
{ version: '1.9', min: 2810991, max: 11020426 },
{ version: '2.0', min: 11020438, max: 28356225 },
{ version: '2.1', min: 28356243, max: 97454397 },
{ version: '2.2', min: 97454398, max: Infinity },
];
const match = ranges.find(range => id >= range.min && id <= range.max);
return match ? match.version : null;
}
async function getEstimatedLevelUploadDate(levelId) {
const id = parseInt(levelId, 10);
if (Number.isNaN(id)) return null;
try {
const response = await axios.get(`https://history.geometrydash.eu/api/v1/date/level/${id}`, {
timeout: 4500,
validateStatus: status => status >= 200 && status < 500
});
if (response.status !== 200 || !response.data) return null;
return response.data;
} catch (err) {
console.error(`GDHistory lookup failed for level ${id}:`, err.message);
return null;
}
}
function parseTimeMachineDate(value) {
const raw = String(value || '').trim();
if (!/^\d{4}-\d{2}-\d{2}$/.test(raw)) return null;
const selected = new Date(`${raw}T23:59:59.999Z`);
const now = new Date();
if (Number.isNaN(selected.getTime()) || selected > now) return null;
return selected;
}
function getDateInputValue(date) {
if (!(date instanceof Date) || Number.isNaN(date.getTime())) return null;
return date.toISOString().slice(0, 10);
}
async function getTimeMachineMinDateValue(list) {
const result = await pool.query(`
SELECT MIN(created_at) AS first_created_at
FROM changelog
WHERE list_type = $1
AND change_type IN ('added', 'moved', 'deleted')
`, [list]);
const firstCreatedAt = result.rows[0]?.first_created_at;
if (!firstCreatedAt) return null;
const minDate = new Date(firstCreatedAt);
if (Number.isNaN(minDate.getTime())) return null;
minDate.setUTCDate(minDate.getUTCDate() - 1);
return getDateInputValue(minDate);
}
function isTimeMachineDateAllowed(selectedDate, minDateValue) {
if (!selectedDate || !minDateValue) return false;
const minDate = new Date(`${minDateValue}T00:00:00.000Z`);
if (Number.isNaN(minDate.getTime())) return false;
return selectedDate >= minDate;
}
function normalizeDemonSnapshotRows(rows = []) {
return rows
.map(row => ({
...row,
id: row.id == null ? null : Number(row.id),
position: Number(row.position),
time_machine_deleted_placeholder: Boolean(row.time_machine_deleted_placeholder),
}))
.filter(row => Number.isFinite(row.position))
.sort((a, b) => a.position - b.position);
}
function normalizeHistoricalPositions(rows = []) {
return rows
.sort((a, b) => Number(a.position) - Number(b.position))
.map((row, index) => ({
...row,
position: index + 1,
}));
}
function removeHistoricalEntry(rows, demonId) {
const id = Number(demonId);
const index = rows.findIndex(row => Number(row.id) === id);
if (index === -1) return null;
const [removed] = rows.splice(index, 1);
return removed;
}
function undoHistoricalAdd(rows, log) {
const newPosition = Number(log.new_position);
if (!Number.isFinite(newPosition)) return rows;
const removed = removeHistoricalEntry(rows, log.demon_id);
rows.forEach(row => {
if (Number(row.position) > newPosition) {
row.position = Number(row.position) - 1;
}
});
if (!removed) {
rows = normalizeHistoricalPositions(rows);
}
return rows;
}
function undoHistoricalDelete(rows, log) {
const oldPosition = Number(log.old_position);
if (!Number.isFinite(oldPosition)) return rows;
rows.forEach(row => {
if (Number(row.position) >= oldPosition) {
row.position = Number(row.position) + 1;
}
});
rows.push({
id: null,
name: log.demon_name || 'Deleted Level',
author: 'Unknown',
position: oldPosition,
requirement: 0,
level_id: null,
showcase_url: null,
showcase_link: null,
records: [],
list_type: log.list_type,
time_machine_deleted_placeholder: true,
time_machine_original_demon_id: log.demon_id,
});
return rows;
}
function undoHistoricalMove(rows, log) {
const oldPosition = Number(log.old_position);
const newPosition = Number(log.new_position);
if (!Number.isFinite(oldPosition) || !Number.isFinite(newPosition)) return rows;
const moved = removeHistoricalEntry(rows, log.demon_id) || {
id: log.demon_id == null ? null : Number(log.demon_id),
name: log.demon_name || 'Archived Level',
author: 'Unknown',
position: oldPosition,
requirement: 0,
level_id: null,
showcase_url: null,
showcase_link: null,
records: [],
list_type: log.list_type,
time_machine_deleted_placeholder: true,
time_machine_original_demon_id: log.demon_id,
};
if (newPosition < oldPosition) {
rows.forEach(row => {
if (Number(row.position) > newPosition && Number(row.position) <= oldPosition) {
row.position = Number(row.position) - 1;
}
});
} else if (newPosition > oldPosition) {
rows.forEach(row => {
if (Number(row.position) >= oldPosition && Number(row.position) < newPosition) {
row.position = Number(row.position) + 1;
}
});
}
moved.position = oldPosition;
rows.push(moved);
return rows;
}
async function queryCurrentDemonSnapshotRows(list) {
const result = await pool.query(`
SELECT
d.*,
CASE
WHEN $1 = 'impossible' THEN d.showcase_url
ELSE (
SELECT r.video_url
FROM records r
WHERE r.demon_id = d.id
AND r.status = 'accepted'
AND r.percentage = 100
ORDER BY r.id ASC
LIMIT 1
)
END AS showcase_link,
COALESCE(
(
SELECT json_agg(json_build_object('percentage', r.percentage))
FROM records r
WHERE r.demon_id = d.id AND r.status = 'accepted'
),
'[]'::json
) AS records
FROM demons d
WHERE d.list_type = $1
ORDER BY d.position ASC
`, [list]);
return result.rows;
}
async function buildHistoricalDemonSnapshot(currentRows, list, targetDate) {
let rows = normalizeDemonSnapshotRows(currentRows);
const changelogResult = await pool.query(`
SELECT demon_id, demon_name, change_type, old_position, new_position, created_at, list_type
FROM changelog
WHERE list_type = $1
AND created_at > $2
AND change_type IN ('added', 'moved', 'deleted')
ORDER BY created_at DESC, id DESC
`, [list, targetDate]);
for (const log of changelogResult.rows) {
if (log.change_type === 'added') {
rows = undoHistoricalAdd(rows, log);
} else if (log.change_type === 'deleted') {
rows = undoHistoricalDelete(rows, log);
} else if (log.change_type === 'moved') {
rows = undoHistoricalMove(rows, log);
}
rows = normalizeHistoricalPositions(rows);
}
return normalizeHistoricalPositions(rows).map(row => ({
...row,
time_machine_snapshot: true,
}));
}
const serializeProfileUser = (user) => ({
displayName: user.display_name || '',
bio: user.bio || '',
pronouns: user.pronouns || '',
country: user.country || '',
discordUsername: user.discord_username || '',
socialLinks: {
youtube: user.social_youtube || '',
twitter: user.social_twitter || '',
twitch: user.social_twitch || '',
discord: user.discord_username || '',
reddit: user.social_reddit || '',
gdbrowser: user.social_gdbrowser || '',
},
icon: {
type: user.icon_type || 'cube',
id: readProfileInt(user.icon_id, 1),
color1: readProfileInt(user.color1, 12),
color2: readProfileInt(user.color2, 3),
glow: readProfileInt(user.glow, -1),
},
});
app.get('/api/demons', async (req, res) => {
const list = req.currentList === 'impossible' ? 'impossible' : 'primary';
const timeMachineDate = parseTimeMachineDate(req.query.date || req.query.time_machine_date);
try {
const currentRows = await queryCurrentDemonSnapshotRows(list);
if (timeMachineDate) {
const minDateValue = await getTimeMachineMinDateValue(list);
if (isTimeMachineDateAllowed(timeMachineDate, minDateValue)) {
const historicalRows = await buildHistoricalDemonSnapshot(currentRows, list, timeMachineDate);
return res.json(historicalRows);
}
}
res.json(currentRows);
} catch (err) {
console.error(err);
res.status(500).json({ error: "Database error" });
}
});
app.get('/api/time-machine/min-date', async (req, res) => {
const list = req.currentList === 'impossible' ? 'impossible' : 'primary';
try {
const minDate = await getTimeMachineMinDateValue(list);
res.json({ min_date: minDate });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to fetch time machine minimum date' });
}
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'login.html'));
});
app.get('/register', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'register.html'));
});
app.get('/demon/:id', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'demon.html'));
});
app.get('/submit', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'submit.html'));
});
app.get('/profile', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'profile.html'));
});
app.get('/leaderboard', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'leaderboard.html'));
});
app.get('/account-settings', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'settings.html'));
});
app.get('/notifications', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'notifications.html'));
});
app.get('/verify', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'verify.html'));
});
app.get('/changelog', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'changelog.html'));
});
app.get('/guidelines', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'guidelines.html'));
});
app.get('/staff', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'staff.html'));
});
app.get('/about', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'about.html'));
});
app.get('/forgot-password', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'forgot-password.html'));
});
app.get('/reset-password', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'reset-password.html'));
});
const bcrypt = require('bcrypt');
const session = require('cookie-session');
const sessionConfig = {
name: 'session',
keys: [process.env.SESSION_SECRET],
maxAge: 24 * 60 * 60 * 1000,
sameSite: 'lax'
};
if (process.env.NODE_ENV === 'production') {
sessionConfig.domain = '.webdemonlist.org';
}
app.use(session(sessionConfig));
require('./discord')(app, pool);
async function sendVerificationEmail(targetEmail, username, link) {
await resend.emails.send({
from: 'Web Browser Demonlist <verify@webdemonlist.org>',
to: targetEmail,
subject: 'Verify your WBDL Account',
html: `
<div style="font-family: Comfortaa, Arial, sans-serif; background-color: #181b1e; color: #f2f3f5; padding: 40px; border-radius: 12px; max-width: 600px; margin: auto; border: 1px solid #2a2f36;">
<h1 style="font-family: Comfortaa, Arial, sans-serif; color: #00e676; text-align: center; margin: 0 0 22px; font-size: 28px; line-height: 1.2;">
Welcome, ${username}!
</h1>
<p style="font-size: 16px; line-height: 1.6; text-align: center; color: #8b929c; margin: 0;">
Thanks for signing up for the Web Browser Demonlist! To get started, activate your account by clicking the button below.
</p>
<div style="text-align: center; margin: 30px 0;">
<a href="${link}" style="background-color: #00e676; color: #000; padding: 14px 28px; font-weight: 800; text-decoration: none; border-radius: 8px; display: inline-block; font-size: 15px;">
Verify my Account
</a>
</div>
<div style="background-color: #20242a; padding: 20px; border-radius: 8px; text-align: center; margin-top: 20px; border: 1px solid #2a2f36;">
<p style="margin: 0 0 10px 0; color: #f2f3f5; font-size: 14px;">
Also, feel free to join the discord!
</p>
<a href="https://discord.gg/Pz8TehUPmP" style="color: #5865F2; text-decoration: none; font-weight: bold; font-size: 16px;">
discord.gg/Pz8TehUPmP
</a>
</div>
<hr style="border: 0; border-top: 1px solid #2a2f36; margin: 24px 0;">
<p style="font-size: 12px; color: #5a616b; text-align: center; margin: 0;">
If you didn't create an account, simply ignore this email.
</p>
</div>
`
});
}
async function sendResetEmail(targetEmail, username, link) {
await resend.emails.send({
from: 'Web Browser Demonlist <support@webdemonlist.org>',
to: targetEmail,
subject: 'WBDL Password Reset',
html: `
<div style="font-family: Nunito, Arial, sans-serif; background-color: #181b1e; color: #f2f3f5; padding: 40px; border-radius: 12px; max-width: 600px; margin: auto; border: 1px solid #2a2f36;">
<h1 style="font-family: Comfortaa, Arial, sans-serif; color: #00e676; text-align: center; margin: 0 0 22px; font-size: 28px; line-height: 1.2;">
Password Reset Request
</h1>
<p style="text-align: center; color: #8b929c; font-size: 16px; line-height: 1.6; margin: 0;">
Hello ${username}, we received a request to reset your account's password. Click the button below to proceed.
</p>
<div style="text-align: center; margin: 30px 0;">
<a href="${link}" style="background-color: #00e676; color: #000; padding: 14px 28px; font-weight: 800; text-decoration: none; border-radius: 8px; display: inline-block; font-size: 15px;">
Reset Password
</a>
</div>
<p style="font-size: 12px; color: #5a616b; text-align: center; margin: 0;">
This link will expire in 1 hour. If you didn't request this, you can safely ignore this email.
</p>
</div>
`
});
}
app.post('/api/register', async (req, res) => {
const { username, password, email, captchaToken } = req.body;
const SECRET_KEY = process.env.RECAPTCHA_SECRET;
try {
const params = new URLSearchParams();
params.append('secret', SECRET_KEY);
params.append('response', captchaToken);
const googleRes = await axios.post(
'https://www.google.com/recaptcha/api/siteverify',
params
);
if (!googleRes.data.success) {
return res.status(400).json({ error: "bro is a bot" });
}
} catch (err) {
return res.status(500).json({ error: "Error verifying CAPTCHA." });
}
if (!email || !email.includes('@')) {
return res.status(400).json({ error: "Please enter a valid email address." });
}
const userError = validateUsername(username);
if (userError) return res.status(400).json({ error: userError });
const passError = validatePassword(password);
if (passError) return res.status(400).json({ error: passError });
try {
const usernameCheck = await pool.query(
`SELECT id FROM users WHERE LOWER(username) = LOWER($1)
UNION
SELECT 1 FROM pending_users WHERE LOWER(username) = LOWER($1)`,
[username]
);
if (usernameCheck.rows.length > 0) {
return res.status(400).json({ error: "That username is already taken." });
}
const emailCheck = await pool.query(
`SELECT id FROM users WHERE LOWER(email) = LOWER($1)
UNION
SELECT 1 FROM pending_users WHERE LOWER(email) = LOWER($1)`,
[email]
);
if (emailCheck.rows.length > 0) {
return res.status(400).json({ error: "That email is already in use." });
}
const token = randomBytes(32).toString('hex');
const hashedPassword = await bcrypt.hash(password, 10);
await pool.query(
'INSERT INTO pending_users (token, username, password_hash, email) VALUES ($1, $2, $3, $4)',
[token, username, hashedPassword, email]
);
const verifyLink = `https://webdemonlist.org/verify?token=${token}`;
await sendVerificationEmail(email, username, verifyLink);
res.json({ message: "Verification email sent! Please check your inbox (and spam folder)." });
} catch (err) {
console.error(err);
res.status(500).json({ error: "An error occurred during registration." });
}
});
app.get('/api/verify', async (req, res) => {
const { token } = req.query;
try {
const pending = await pool.query('SELECT * FROM pending_users WHERE token = $1', [token]);
if (pending.rows.length === 0) {
return res.status(400).send("This link is invalid or has already been used.");
}
const user = pending.rows[0];
await pool.query(
'INSERT INTO users (username, password_hash, email) VALUES ($1, $2, $3)',
[user.username, user.password_hash, user.email]
);
await pool.query('DELETE FROM pending_users WHERE token = $1', [token]);
res.status(200).send("Success");
} catch (err) {
console.error(err);
res.status(500).send("Internal server error during verification.");
}
});
app.post('/api/login', async (req, res) => {
const { username, password } = req.body;
const userResult = await pool.query('SELECT * FROM users WHERE LOWER(username) = LOWER($1)', [username]);
if (userResult.rows.length > 0) {
const user = userResult.rows[0];
const validPassword = await bcrypt.compare(password, user.password_hash);
if (validPassword) {
req.session.userId = user.id;
req.session.username = user.username;
return res.json({ message: "Logged in!", username: user.username });
}
}
res.status(401).json({ error: "Invalid credentials" });
});
app.get('/api/me', async (req, res) => {
if (req.session.userId) {
try {
const user = await pool.query(
'SELECT username, role, display_name, icon_type, icon_id, color1, color2, glow FROM users WHERE id = $1',
[req.session.userId]
);
if (user.rows.length > 0) {
const userData = user.rows[0];
res.json({
loggedIn: true,
username: userData.username,
role: userData.role,
displayName: userData.display_name || '',
icon: {
type: userData.icon_type || 'cube',
id: readProfileInt(userData.icon_id, 1),
color1: readProfileInt(userData.color1, 12),
color2: readProfileInt(userData.color2, 3),
glow: readProfileInt(userData.glow, -1),
},
});
} else {
res.json({ loggedIn: false });
}
} catch (err) {
console.error(err);
res.status(500).json({ error: "Database error" });
}
} else {
res.json({ loggedIn: false });
}
});
app.post('/api/logout', (req, res) => {
req.session = null;
res.json({ message: "Logged out" });
});
app.post('/api/submit', async (req, res) => {
if (!req.session.userId) {
return res.status(401).json({ error: "You must be logged in!" });
}
const { demonId, percentage, videoUrl } = req.body;
const newPercent = parseInt(percentage);
const list = req.currentList === 'impossible' ? 'impossible' : 'primary';
if (isNaN(newPercent) || newPercent <= 0) {
return res.status(400).json({ error: "Percentage must be a valid number greater than 0%." });
}
if (newPercent > 100) {
return res.status(400).json({ error: "Percentage cannot be higher than 100%." });
}
const urlPattern = new RegExp('^(https?:\\/\\/)?' +
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' +
'((\\d{1,3}\\.){3}\\d{1,3}))' +
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' +
'(\\?[;&a-z\\d%_.~+=-]*)?' +
'(\\#[-a-z\\d_]*)?$', 'i');
if (!urlPattern.test(videoUrl)) {
return res.status(400).json({ error: "Please enter a valid URL." });
}
try {
const demonQuery = await pool.query(
'SELECT position, requirement, list_type FROM demons WHERE id = $1',
[demonId]
);
if (demonQuery.rows.length === 0) return res.status(404).json({ error: "Level not found." });
const { position, requirement, list_type } = demonQuery.rows[0];
if (list_type === 'primary' && position > 150) {
return res.status(400).json({ error: "Submissions for the Legacy List are disabled." });
}
if (list_type !== list) {
return res.status(400).json({ error: "This level does not belong to the active list." });
}
if (list === 'primary') {
if (position > 75) {
if (newPercent < 100) {
return res.status(400).json({
error: "This level is on the Extended List, you must get 100% lol"
});
}
} else {
if (newPercent < requirement) {
return res.status(400).json({ error: `Level requires at least ${requirement}%.` });
}
}
}
const existingRecord = await pool.query(
`SELECT id, percentage FROM records
WHERE user_id = $1 AND demon_id = $2 AND list_type = $3 AND status != 'rejected'`,
[req.session.userId, demonId, list]
);
if (existingRecord.rows.length > 0) {
const oldPercent = existingRecord.rows[0].percentage;
if (newPercent <= oldPercent) {
return res.status(400).json({
error: `You already have an active ${oldPercent}% record. New entries must be a higher percentage.`
});
}
await pool.query(
`UPDATE records
SET percentage = $1, video_url = $2, status = 'pending'
WHERE id = $3`,
[newPercent, videoUrl, existingRecord.rows[0].id]
);
return res.json({ message: "Record updated and awaiting review!" });
}
await pool.query(
'INSERT INTO records (user_id, demon_id, percentage, video_url, list_type, status) VALUES ($1, $2, $3, $4, $5, \'pending\')',
[req.session.userId, demonId, newPercent, videoUrl, list]
);
res.json({ message: "Record submitted successfully!" });
} catch (err) {
console.error(err);
res.status(500).json({ error: "Server error." });
}
});
const isOwner = async (req, res, next) => {
if (!req.session.userId) return res.status(401).send("Not logged in");
try {
const user = await pool.query('SELECT role FROM users WHERE id = $1', [req.session.userId]);
const userRole = user.rows[0]?.role;
if (userRole === 'owner') {
next();
} else {
res.status(403).send("Access Denied :)");
}
} catch (err) {
console.error("Auth middleware error:", err);
res.status(500).send("Internal Server Error");
}
};
const isAdmin = async (req, res, next) => {
if (!req.session.userId) return res.status(401).send("Not logged in");
try {
const user = await pool.query('SELECT role FROM users WHERE id = $1', [req.session.userId]);
const userRole = user.rows[0]?.role;
if (userRole === 'admin' || userRole === 'owner') {
next();
} else {
res.status(403).send("Access Denied :)");
}
} catch (err) {
console.error("Auth middleware error:", err);
res.status(500).send("Internal Server Error");
}
};
const isMod = async (req, res, next) => {
if (!req.session.userId) return res.status(401).send("Not logged in");
try {
const user = await pool.query('SELECT role FROM users WHERE id = $1', [req.session.userId]);
const userRole = user.rows[0]?.role;
const allowedRoles = ['moderator', 'admin', 'owner'];
if (allowedRoles.includes(userRole)) {
next();
} else {
res.status(403).send("Access Denied :)");
}
} catch (err) {
console.error("Mod middleware error:", err);
res.status(500).send("Internal Server Error");
}
};
app.get('/api/admin/pending', isMod, async (req, res) => {
const list = req.currentList === 'impossible' ? 'impossible' : 'primary';
try {
const result = await pool.query(`
SELECT records.*, users.username, demons.name as demon_name
FROM records
JOIN users ON records.user_id = users.id
JOIN demons ON records.demon_id = demons.id
WHERE records.status = 'pending' AND records.list_type = $1
ORDER BY records.id ASC
`, [list]);
res.json(result.rows);
} catch (err) {
console.error(err);
res.status(500).json({ error: "Failed to fetch pending records" });
}
});
app.post('/api/admin/update-record', isMod, async (req, res) => {
const { recordId, status, reason } = req.body;
const actorId = req.session.userId;
const activeSubdomainList = req.currentList === 'impossible' ? 'impossible' : 'primary';
try {
await pool.query('BEGIN');
const actorQuery = await pool.query('SELECT role FROM users WHERE id = $1', [actorId]);
const actorRole = actorQuery.rows[0]?.role;
const recordQuery = await pool.query('SELECT user_id, list_type FROM records WHERE id = $1', [recordId]);
if (recordQuery.rows.length === 0) {
await pool.query('ROLLBACK');
return res.status(404).json({ error: "Record not found" });
}
const { user_id: recordOwnerId, list_type } = recordQuery.rows[0];
if (list_type !== activeSubdomainList) {
await pool.query('ROLLBACK');
return res.status(400).json({ error: "This record does not belong to the active list layout configuration." });
}
if (recordOwnerId === actorId && actorRole !== 'owner') {
await pool.query('ROLLBACK');
return res.status(403).json({ error: "You cannot verify your own record!" });
}
const result = await pool.query(
'UPDATE records SET status = $1 WHERE id = $2 RETURNING user_id',
[status, recordId]
);
const targetUserId = result.rows[0].user_id;
await pool.query(
`INSERT INTO notifications (user_id, actor_id, record_id, type, reason, list_type)
VALUES ($1, $2, $3, $4, $5, $6)`,
[targetUserId, actorId, recordId, status, reason || null, list_type]
);
await pool.query('COMMIT');
res.json({ message: `Record ${status}.` });
} catch (err) {
if (pool) await pool.query('ROLLBACK');
console.error(err);
res.status(500).json({ error: "Failed to update record" });
}
});
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL;
async function sendDiscordNotification(content) {
if (!DISCORD_WEBHOOK_URL) return;
try {
await fetch(DISCORD_WEBHOOK_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: "List Changes",
avatar_url: "https://webdemonlist.org/assets/icon.png",
content: `<@&1493780241628528730> ${content}`
})
});
} catch (err) {
console.error("Discord notification failed:", err);
}
}
app.post('/api/admin/add-demon', isAdmin, async (req, res) => {
const { name, author, position, level_id, requirement, showcase_url } = req.body;
const list = req.currentList === 'impossible' ? 'impossible' : 'primary';
const actorId = req.session.userId;
const targetPos = parseInt(position);
const client = await pool.connect();
try {
const userRes = await client.query('SELECT role FROM users WHERE id = $1', [actorId]);
const userRole = userRes.rows[0]?.role;
if (targetPos > 150 && userRole !== 'owner') {
client.release();
return res.status(403).json({ error: "Only the owner can place levels in the Legacy List (> 150)." });
}
await client.query('BEGIN');
const boundaries = await client.query(
`SELECT position, name FROM demons WHERE list_type = $1 AND position IN (75, 150)`,
[list]
);
const old75 = boundaries.rows.find(r => r.position === 75)?.name;
const old150 = boundaries.rows.find(r => r.position === 150)?.name;
await client.query(
'UPDATE demons SET position = position + 1 WHERE list_type = $2 AND position >= $1',
[targetPos, list]
);
const newLevel = await client.query(
`INSERT INTO demons (name, author, position, level_id, requirement, list_type, showcase_url)
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id`,
[name, author, targetPos, level_id, requirement || 0, list, showcase_url || null]
);
const newDemonId = newLevel.rows[0].id;
await client.query(
`INSERT INTO changelog (demon_id, demon_name, change_type, old_position, new_position, list_type)
VALUES ($1, $2, 'added', null, $3, $4)`,
[newDemonId, name, targetPos, list]
);
const neighborsRes = await client.query(
`SELECT name, position FROM demons WHERE list_type = $1 AND position IN ($2, $3)`,
[list, targetPos - 1, targetPos + 1]
);
await client.query('COMMIT');
if (list === 'primary') {
const above = neighborsRes.rows.find(r => r.position == targetPos - 1)?.name;
const below = neighborsRes.rows.find(r => r.position == targetPos + 1)?.name;
let msg = `**${name}** has been placed at **#${targetPos}**`;
let context = [];
if (below) context.push(`above **${below}**`);