forked from ancsemi/Haven
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2712 lines (2427 loc) · 115 KB
/
Copy pathserver.js
File metadata and controls
2712 lines (2427 loc) · 115 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
// ── Resolve data directory BEFORE loading .env ────────────
const { DATA_DIR, DB_PATH, ENV_PATH, CERTS_DIR, UPLOADS_DIR } = require('./src/paths');
// Bootstrap .env into the data directory if it doesn't exist yet
const fs = require('fs');
const path = require('path');
const AdmZip = require('adm-zip');
const {
addDirectoryToZip,
appendActiveUploadsToZip,
applyPendingRestoreIfPresent,
clearStorageSettings,
cleanupActiveUploads,
deleteUploadByName,
generateStoredFilename,
getPendingRestoreInfo,
getStorageConfig,
getUploadReadStream,
getUploadUrl,
isSafeUploadName,
migrateLocalUploadsToActiveStorage,
purgeDeletedAttachments,
restoreUploadsFromDirectory,
stagePendingRestore,
storeUploadBuffer,
testS3Connection
} = require('./src/storage');
if (applyPendingRestoreIfPresent()) {
console.log(`Restored pending data import into ${DATA_DIR}`);
}
function tryReadEnvFile() {
try {
return fs.existsSync(ENV_PATH) ? fs.readFileSync(ENV_PATH, 'utf-8') : '';
} catch {
return '';
}
}
function tryWriteEnvFile(content, reason) {
try {
fs.writeFileSync(ENV_PATH, content);
return true;
} catch (err) {
console.warn(`⚠️ Could not write ${ENV_PATH} while ${reason}: ${err.code || err.message}`);
return false;
}
}
if (!fs.existsSync(ENV_PATH)) {
const example = path.join(__dirname, '.env.example');
if (fs.existsSync(example)) {
try {
fs.copyFileSync(example, ENV_PATH);
console.log(`📄 Created .env in ${DATA_DIR} from template`);
} catch (err) {
console.warn(`⚠️ Could not create ${ENV_PATH} from template: ${err.code || err.message}`);
}
} else {
// Write a minimal .env so dotenv doesn't fail
tryWriteEnvFile('JWT_SECRET=change-me-to-something-random-and-long\n', 'creating default .env');
}
}
require('dotenv').config({ path: ENV_PATH });
const express = require('express');
const { createServer } = require('http');
const { createServer: createHttpsServer } = require('https');
const { Server } = require('socket.io');
const crypto = require('crypto');
const helmet = require('helmet');
const multer = require('multer');
console.log(`📂 Data directory: ${DATA_DIR}`);
// ── Auto-generate JWT secret (MUST happen before loading auth module) ──
if (process.env.JWT_SECRET === 'change-me-to-something-random-and-long' || !process.env.JWT_SECRET) {
const generated = crypto.randomBytes(48).toString('base64');
let envContent = tryReadEnvFile();
if (/^JWT_SECRET=.*$/m.test(envContent)) {
envContent = envContent.replace(/^JWT_SECRET=.*$/m, `JWT_SECRET=${generated}`);
} else {
if (envContent && !envContent.endsWith('\n')) envContent += '\n';
envContent += `JWT_SECRET=${generated}\n`;
}
tryWriteEnvFile(envContent, 'saving JWT secret');
process.env.JWT_SECRET = generated;
console.log('🔑 Auto-generated strong JWT_SECRET');
}
if (!process.env.HAVEN_SETTINGS_SECRET) {
const generated = crypto.randomBytes(48).toString('base64');
let envContent = tryReadEnvFile();
if (/^HAVEN_SETTINGS_SECRET=.*$/m.test(envContent)) {
envContent = envContent.replace(/^HAVEN_SETTINGS_SECRET=.*$/m, `HAVEN_SETTINGS_SECRET=${generated}`);
} else {
if (envContent && !envContent.endsWith('\n')) envContent += '\n';
envContent += `HAVEN_SETTINGS_SECRET=${generated}\n`;
}
tryWriteEnvFile(envContent, 'saving settings secret');
process.env.HAVEN_SETTINGS_SECRET = generated;
console.log('🔐 Auto-generated HAVEN_SETTINGS_SECRET');
}
// ── Auto-generate VAPID keys for push notifications ──────
const webpush = require('web-push');
if (!process.env.VAPID_PUBLIC_KEY || !process.env.VAPID_PRIVATE_KEY) {
const vapidKeys = webpush.generateVAPIDKeys();
let envContent = tryReadEnvFile();
if (envContent && !envContent.endsWith('\n')) envContent += '\n';
envContent += `\nVAPID_PUBLIC_KEY=${vapidKeys.publicKey}\nVAPID_PRIVATE_KEY=${vapidKeys.privateKey}\n`;
tryWriteEnvFile(envContent, 'saving VAPID keys');
process.env.VAPID_PUBLIC_KEY = vapidKeys.publicKey;
process.env.VAPID_PRIVATE_KEY = vapidKeys.privateKey;
console.log('🔔 Auto-generated VAPID keys for push notifications');
}
// Configure web-push with contact email (admin can override via VAPID_EMAIL in .env)
const vapidEmail = process.env.VAPID_EMAIL || 'mailto:admin@haven.local';
webpush.setVapidDetails(vapidEmail, process.env.VAPID_PUBLIC_KEY, process.env.VAPID_PRIVATE_KEY);
const { initDatabase, getDb } = require('./src/database');
const { router: authRoutes, authLimiter, verifyToken } = require('./src/auth');
const { setupSocketHandlers, sanitizeText } = require('./src/socketHandlers');
const { startTunnel, stopTunnel, getTunnelStatus, registerProcessCleanup } = require('./src/tunnel');
const { initFcm } = require('./src/fcm');
const app = express();
// ── Helper: verify admin from DB (don't trust JWT claims alone) ─────
// JWT isAdmin may be stale if admin was demoted since token was issued.
function verifyAdminFromDb(user) {
if (!user) return false;
try {
const { getDb } = require('./src/database');
const row = getDb().prepare('SELECT is_admin FROM users WHERE id = ?').get(user.id);
return !!(row && row.is_admin);
} catch { return false; }
}
function userHasPermission(userId, permission) {
if (!userId) return false;
try {
const { getDb } = require('./src/database');
const isAdmin = getDb().prepare('SELECT is_admin FROM users WHERE id = ?').get(userId);
if (isAdmin && isAdmin.is_admin) return true;
const row = getDb().prepare(`
SELECT 1 FROM role_permissions rp
JOIN roles r ON rp.role_id = r.id
JOIN user_roles ur ON r.id = ur.role_id
WHERE ur.user_id = ? AND rp.permission = ? AND rp.allowed = 1
LIMIT 1
`).get(userId, permission);
return !!row;
} catch { return false; }
}
// ── Security Headers (helmet) ────────────────────────────
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-eval'", "'wasm-unsafe-eval'", "https://www.youtube.com", "https://w.soundcloud.com", "https://unpkg.com"],
styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"], // inline styles + Google Fonts
imgSrc: ["'self'", "data:", "blob:", "https:"], // https: for link preview OG images + GIPHY
connectSrc: ["'self'", "ws:", "wss:", "https:"], // Socket.IO + cross-origin health checks
mediaSrc: ["'self'", "blob:", "data:"], // WebRTC audio + notification sounds
fontSrc: ["'self'", "https://fonts.gstatic.com"], // Google Fonts CDN
workerSrc: ["'self'", "blob:", "https://unpkg.com"], // service worker + Ruffle WebAssembly workers
objectSrc: ["'none'"],
frameSrc: ["'self'", "https://open.spotify.com", "https://www.youtube.com", "https://www.youtube-nocookie.com", "https://w.soundcloud.com"], // Listen Together embeds + game iframes
baseUri: ["'self'"],
formAction: ["'self'"],
frameAncestors: ["'self'"], // allow mobile app iframe, block third-party clickjacking
}
},
crossOriginEmbedderPolicy: false, // needed for WebRTC
crossOriginOpenerPolicy: false, // needed for WebRTC
hsts: (process.env.FORCE_HTTP || '').toLowerCase() === 'true' ? false : { maxAge: 31536000, includeSubDomains: false }, // force HTTPS for 1 year (disabled when FORCE_HTTP=true)
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));
// Additional security headers helmet doesn't cover
app.use((req, res, next) => {
res.setHeader('Permissions-Policy', 'camera=(self), microphone=(self), geolocation=(), payment=()');
res.setHeader('X-Content-Type-Options', 'nosniff');
next();
});
// Disable Express version disclosure
app.disable('x-powered-by');
// ── Body Parsing with size limits ────────────────────────
app.use(express.json({ limit: '16kb' })); // no reason for large JSON bodies
app.use(express.urlencoded({ extended: false, limit: '16kb' }));
// ── Static files with caching ────────────────────────────
app.use(express.static(path.join(__dirname, 'public'), {
dotfiles: 'deny', // block .env, .git, etc.
etag: true, // ETag for conditional requests
lastModified: true, // Last-Modified header
maxAge: 0, // always revalidate — prevents stale JS/CSS after deploys
}));
// ── Block access to deleted-attachments folder ──────────
// Files moved here are no longer part of any message; they should not be accessible.
app.use('/uploads/deleted-attachments', (req, res) => res.status(404).end());
// ── Serve uploads from external data directory ──────────
app.use('/uploads', express.static(UPLOADS_DIR, {
dotfiles: 'deny',
maxAge: '7d', // 7 days — avatars & images rarely change; filenames include timestamps for uniqueness
immutable: true, // tells browser the file at this URL will never change (cache-busting via new filename)
etag: true,
lastModified: true,
setHeaders: (res, filePath) => {
// Force download for non-image files (prevents HTML/SVG execution in browser)
const ext = path.extname(filePath).toLowerCase();
if (!['.jpg', '.jpeg', '.png', '.gif', '.webp'].includes(ext)) {
res.setHeader('Content-Disposition', 'attachment');
}
}
}));
app.get('/uploads/:name', async (req, res, next) => {
const name = typeof req.params.name === 'string' ? req.params.name.trim() : '';
if (!isSafeUploadName(name)) return next();
try {
const file = await getUploadReadStream(name);
if (!file) return next();
const ext = path.extname(name).toLowerCase();
if (!['.jpg', '.jpeg', '.png', '.gif', '.webp'].includes(ext)) {
res.setHeader('Content-Disposition', 'attachment');
}
if (file.contentType) res.setHeader('Content-Type', file.contentType);
if (file.contentLength) res.setHeader('Content-Length', String(file.contentLength));
if (file.lastModified) res.setHeader('Last-Modified', new Date(file.lastModified).toUTCString());
res.setHeader('Cache-Control', 'public, max-age=604800, immutable');
file.stream.pipe(res);
} catch (err) {
console.error('Upload proxy error:', err);
res.status(500).end();
}
});
// ── Plugin & Theme file serving ─────────────────────────
const PLUGINS_DIR = path.join(__dirname, 'plugins');
const THEMES_DIR = path.join(__dirname, 'themes');
if (!fs.existsSync(PLUGINS_DIR)) fs.mkdirSync(PLUGINS_DIR, { recursive: true });
if (!fs.existsSync(THEMES_DIR)) fs.mkdirSync(THEMES_DIR, { recursive: true });
app.use('/plugins', express.static(PLUGINS_DIR, { dotfiles: 'deny', maxAge: 0 }));
app.use('/themes', express.static(THEMES_DIR, { dotfiles: 'deny', maxAge: 0 }));
// API: list available plugins (*.plugin.js files)
app.get('/api/plugins', (req, res) => {
try {
const files = fs.readdirSync(PLUGINS_DIR).filter(f => f.endsWith('.plugin.js'));
const plugins = files.map(f => {
// Try to read metadata from the first comment block
const content = fs.readFileSync(path.join(PLUGINS_DIR, f), 'utf8');
const meta = {};
const metaMatch = content.match(/\/\*\*[\s\S]*?\*\//);
if (metaMatch) {
const block = metaMatch[0];
const nameM = block.match(/@name\s+(.+)/);
const descM = block.match(/@description\s+(.+)/);
const authM = block.match(/@author\s+(.+)/);
const verM = block.match(/@version\s+(.+)/);
if (nameM) meta.name = nameM[1].trim();
if (descM) meta.description = descM[1].trim();
if (authM) meta.author = authM[1].trim();
if (verM) meta.version = verM[1].trim();
}
return { file: f, ...meta };
});
res.json(plugins);
} catch { res.json([]); }
});
// API: list available themes (*.theme.css files)
app.get('/api/themes', (req, res) => {
try {
const files = fs.readdirSync(THEMES_DIR).filter(f => f.endsWith('.theme.css'));
const themes = files.map(f => {
const content = fs.readFileSync(path.join(THEMES_DIR, f), 'utf8');
const meta = {};
const metaMatch = content.match(/\/\*\*[\s\S]*?\*\//);
if (metaMatch) {
const block = metaMatch[0];
const nameM = block.match(/@name\s+(.+)/);
const descM = block.match(/@description\s+(.+)/);
const authM = block.match(/@author\s+(.+)/);
const verM = block.match(/@version\s+(.+)/);
if (nameM) meta.name = nameM[1].trim();
if (descM) meta.description = descM[1].trim();
if (authM) meta.author = authM[1].trim();
if (verM) meta.version = verM[1].trim();
}
return { file: f, ...meta };
});
res.json(themes);
} catch { res.json([]); }
});
// ── File uploads (DB-configurable limit, avatar max 5 MB) ──
const uploadStorage = multer.memoryStorage();
// Image-only upload — multer cap is high; real limit enforced per-request from DB
const upload = multer({
storage: uploadStorage,
limits: { fileSize: 2 * 1024 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
if (/^image\/(jpeg|png|gif|webp)$/.test(file.mimetype)) cb(null, true);
else cb(new Error('Only images allowed (jpg, png, gif, webp)'));
}
});
// General file upload — no MIME restrictions; safety enforced via
// Content-Disposition: attachment on non-image downloads (see /uploads handler)
const fileUpload = multer({
storage: uploadStorage,
limits: { fileSize: 2 * 1024 * 1024 * 1024 }, // hard cap 2 GB; DB-configurable limit enforced per-request
});
function decodeMultipartFilename(name = 'file') {
return Buffer.from(name, 'latin1').toString('utf8');
}
function validateImageMagic(file) {
const hdr = file?.buffer;
if (!hdr || !Buffer.isBuffer(hdr) || hdr.length < 12) return false;
if (file.mimetype === 'image/jpeg') return hdr[0] === 0xFF && hdr[1] === 0xD8 && hdr[2] === 0xFF;
if (file.mimetype === 'image/png') return hdr[0] === 0x89 && hdr[1] === 0x50 && hdr[2] === 0x4E && hdr[3] === 0x47;
if (file.mimetype === 'image/gif') return hdr.slice(0, 6).toString().startsWith('GIF8');
if (file.mimetype === 'image/webp') return hdr.slice(0, 4).toString() === 'RIFF' && hdr.slice(8, 12).toString() === 'WEBP';
return false;
}
function getValidatedImageExtension(mimetype) {
return {
'image/jpeg': '.jpg',
'image/png': '.png',
'image/gif': '.gif',
'image/webp': '.webp'
}[mimetype] || null;
}
async function persistUploadedFile(file, options = {}) {
if (!file?.buffer) throw new Error('No file uploaded');
const originalName = decodeMultipartFilename(file.originalname || 'file');
const forcedExt = options.forcedExt || '';
const filename = options.filename || generateStoredFilename(originalName, forcedExt);
return storeUploadBuffer(file.buffer, {
filename,
originalName,
forcedExt,
mimeType: options.mimeType || file.mimetype,
folder: options.folder || 'uploads',
cacheControl: options.cacheControl
});
}
// ── API routes (rate-limited) ────────────────────────────
app.use('/api/auth', authLimiter, authRoutes);
// ── Push notification VAPID public key endpoint ──────────
app.get('/api/push/vapid-key', (req, res) => {
res.json({ publicKey: process.env.VAPID_PUBLIC_KEY });
});
// ── Push notification subscription endpoints ─────────────
app.post('/api/push/subscribe', express.json(), (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const { endpoint, keys } = req.body;
if (!endpoint || !keys?.p256dh || !keys?.auth)
return res.status(400).json({ error: 'Invalid subscription object' });
try {
const { getDb } = require('./src/database');
getDb().prepare(`
INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth)
VALUES (?, ?, ?, ?)
ON CONFLICT(user_id, endpoint) DO UPDATE SET p256dh=excluded.p256dh, auth=excluded.auth
`).run(user.id, endpoint, keys.p256dh, keys.auth);
res.json({ ok: true });
} catch (err) {
console.error('[push/subscribe]', err);
res.status(500).json({ error: 'Internal server error' });
}
});
app.delete('/api/push/subscribe', express.json(), (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const { endpoint } = req.body || {};
if (!endpoint) return res.status(400).json({ error: 'Missing endpoint' });
try {
const { getDb } = require('./src/database');
getDb().prepare('DELETE FROM push_subscriptions WHERE user_id = ? AND endpoint = ?')
.run(user.id, endpoint);
res.json({ ok: true });
} catch (err) {
console.error('[push/unsubscribe]', err);
res.status(500).json({ error: 'Internal server error' });
}
});
// ── ICE servers endpoint (STUN + optional TURN) ──────────
// ── Avatar upload endpoint (saves to /uploads, updates DB) ──
app.post('/api/upload-avatar', uploadLimiter, (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const { getDb } = require('./src/database');
const ban = getDb().prepare('SELECT id FROM bans WHERE user_id = ?').get(user.id);
if (ban) return res.status(403).json({ error: 'Banned users cannot upload' });
upload.single('avatar')(req, res, (err) => {
if (err) return res.status(400).json({ error: err.message });
if (!req.file) return res.status(400).json({ error: 'No file uploaded' });
if (req.file.size > 2 * 1024 * 1024) {
return res.status(400).json({ error: 'Avatar must be under 2 MB' });
}
if (!validateImageMagic(req.file)) {
return res.status(400).json({ error: 'Failed to validate file' });
}
const safeExt = getValidatedImageExtension(req.file.mimetype);
if (!safeExt) {
return res.status(400).json({ error: 'Invalid file type' });
}
(async () => {
const saved = await persistUploadedFile(req.file, { forcedExt: safeExt, cacheControl: 'public, max-age=604800, immutable' });
const db = getDb();
db.prepare('UPDATE users SET avatar = ? WHERE id = ?').run(saved.url, user.id);
console.log(`[Avatar] ${user.username} uploaded avatar: ${saved.url}`);
res.json({ url: saved.url });
})().catch((dbErr) => {
console.error('Avatar DB update error:', dbErr);
return res.status(500).json({ error: 'Failed to save avatar' });
});
});
});
// ── Avatar remove endpoint ──
app.post('/api/remove-avatar', express.json(), (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
try {
const { getDb } = require('./src/database');
getDb().prepare('UPDATE users SET avatar = NULL WHERE id = ?').run(user.id);
res.json({ ok: true });
} catch (err) {
console.error('Avatar remove error:', err);
res.status(500).json({ error: 'Failed to remove avatar' });
}
});
app.post('/api/upload-proxy-avatar', uploadLimiter, (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const { getDb } = require('./src/database');
const ban = getDb().prepare('SELECT id FROM bans WHERE user_id = ?').get(user.id);
if (ban) return res.status(403).json({ error: 'Banned users cannot upload' });
upload.single('proxyAvatar')(req, res, (err) => {
if (err) return res.status(400).json({ error: err.message });
if (!req.file) return res.status(400).json({ error: 'No file uploaded' });
const settingRow = getDb().prepare("SELECT value FROM server_settings WHERE key = 'max_proxy_avatar_kb'").get();
const maxKb = Math.max(32, Math.min(2048, parseInt(settingRow?.value || '256', 10) || 256));
if (req.file.size > maxKb * 1024) {
return res.status(400).json({ error: `Proxy avatar must be under ${maxKb} KB` });
}
if (!validateImageMagic(req.file)) {
return res.status(400).json({ error: 'Failed to validate file' });
}
const safeExt = getValidatedImageExtension(req.file.mimetype);
if (!safeExt) {
return res.status(400).json({ error: 'Invalid file type' });
}
(async () => {
const saved = await persistUploadedFile(req.file, { forcedExt: safeExt, cacheControl: 'public, max-age=604800, immutable' });
res.json({ url: saved.url, maxKb });
})().catch((uploadErr) => {
console.error('Proxy avatar upload error:', uploadErr);
res.status(500).json({ error: 'Failed to save proxy avatar' });
});
});
});
// ── Avatar shape endpoint ──
app.post('/api/set-avatar-shape', express.json(), (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const validShapes = ['circle', 'rounded', 'squircle', 'hex', 'diamond'];
const shape = validShapes.includes(req.body.shape) ? req.body.shape : 'circle';
try {
const { getDb } = require('./src/database');
getDb().prepare('UPDATE users SET avatar_shape = ? WHERE id = ?').run(shape, user.id);
res.json({ shape });
} catch (err) {
console.error('Avatar shape error:', err);
res.status(500).json({ error: 'Failed to save shape' });
}
});
// ── Webhook/Bot avatar upload endpoint ──
app.post('/api/upload-webhook-avatar', uploadLimiter, (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
// Only admins can manage webhooks
const { getDb } = require('./src/database');
const dbUser = getDb().prepare('SELECT is_admin FROM users WHERE id = ?').get(user.id);
if (!dbUser || !dbUser.is_admin) return res.status(403).json({ error: 'Admin only' });
upload.single('avatar')(req, res, (err) => {
if (err) return res.status(400).json({ error: err.message });
if (!req.file) return res.status(400).json({ error: 'No file uploaded' });
if (!validateImageMagic(req.file)) {
return res.status(400).json({ error: 'Failed to validate file' });
}
const safeExt = getValidatedImageExtension(req.file.mimetype);
if (!safeExt) {
return res.status(400).json({ error: 'Invalid file type' });
}
(async () => {
const saved = await persistUploadedFile(req.file, { forcedExt: safeExt, cacheControl: 'public, max-age=604800, immutable' });
const webhookId = parseInt(req.body?.webhookId || req.query?.webhookId);
if (!isNaN(webhookId)) {
try {
getDb().prepare('UPDATE webhooks SET avatar_url = ? WHERE id = ?').run(saved.url, webhookId);
} catch (dbErr) {
console.error('Webhook avatar DB error:', dbErr);
}
}
res.json({ url: saved.url });
})().catch((uploadErr) => {
console.error('Webhook avatar upload error:', uploadErr);
res.status(500).json({ error: 'Failed to save avatar' });
});
});
});
// ── Serve pages ──────────────────────────────────────────
// ── Tunnel API (Admin only) ──────────────────────────────
app.get('/api/tunnel/status', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user || !verifyAdminFromDb(user)) return res.status(403).json({ error: 'Admin only' });
res.json(getTunnelStatus());
});
app.post('/api/tunnel/sync', express.json(), async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user || !verifyAdminFromDb(user)) return res.status(403).json({ error: 'Admin only' });
try {
// Use values from the request body directly (DB may not have saved yet)
const enabled = req.body.enabled === true;
const provider = req.body.provider || 'localtunnel';
if (!enabled) await stopTunnel();
else await startTunnel(PORT, provider, useSSL);
res.json(getTunnelStatus());
} catch (err) {
res.status(500).json({ error: err?.message || 'Tunnel sync failed' });
}
});
function getAdminFromRequest(req) {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
return user && verifyAdminFromDb(user) ? user : null;
}
function buildStorageStatusPayload() {
const config = getStorageConfig();
const pendingRestore = getPendingRestoreInfo();
const configured = config.provider === 's3'
&& !!config.s3.endpoint
&& !!config.s3.bucket
&& !!config.s3.accessKeyId
&& !!config.s3.secretAccessKey;
return {
provider: config.provider,
configured,
bucket: config.s3.bucket,
endpoint: config.s3.endpoint,
region: config.s3.region,
prefix: config.s3.prefix,
forcePathStyle: !!config.s3.forcePathStyle,
pendingRestore: pendingRestore.pending
};
}
app.get('/api/admin/storage/status', (req, res) => {
if (!getAdminFromRequest(req)) return res.status(403).json({ error: 'Admin only' });
res.json(buildStorageStatusPayload());
});
app.post('/api/admin/storage/configure', express.json(), async (req, res) => {
if (!getAdminFromRequest(req)) return res.status(403).json({ error: 'Admin only' });
try {
const body = req.body || {};
const provider = body.provider === 's3' ? 's3' : 'local';
if (provider === 'local') {
clearStorageSettings();
return res.json({ ok: true, ...buildStorageStatusPayload() });
}
const payload = {
endpoint: String(body.endpoint || '').trim(),
region: String(body.region || 'auto').trim() || 'auto',
bucket: String(body.bucket || '').trim(),
accessKeyId: String(body.accessKeyId || '').trim(),
secretAccessKey: String(body.secretAccessKey || '').trim(),
prefix: String(body.prefix || 'haven').trim(),
forcePathStyle: body.forcePathStyle !== false
};
await testS3Connection(payload);
db.prepare('INSERT OR REPLACE INTO server_settings (key, value) VALUES (?, ?)').run('storage_provider', 's3');
db.prepare('INSERT OR REPLACE INTO server_settings (key, value) VALUES (?, ?)').run('storage_s3_endpoint', payload.endpoint);
db.prepare('INSERT OR REPLACE INTO server_settings (key, value) VALUES (?, ?)').run('storage_s3_region', payload.region);
db.prepare('INSERT OR REPLACE INTO server_settings (key, value) VALUES (?, ?)').run('storage_s3_bucket', payload.bucket);
db.prepare('INSERT OR REPLACE INTO server_settings (key, value) VALUES (?, ?)').run('storage_s3_prefix', payload.prefix || 'haven');
db.prepare('INSERT OR REPLACE INTO server_settings (key, value) VALUES (?, ?)').run('storage_s3_force_path_style', payload.forcePathStyle ? 'true' : 'false');
const { setSecureSetting } = require('./src/storage');
setSecureSetting('storage_s3_access_key', payload.accessKeyId);
setSecureSetting('storage_s3_secret_key', payload.secretAccessKey);
res.json({ ok: true, ...buildStorageStatusPayload() });
} catch (err) {
res.status(400).json({ error: err?.message || 'Failed to save storage settings' });
}
});
app.post('/api/admin/storage/disconnect', express.json(), (req, res) => {
if (!getAdminFromRequest(req)) return res.status(403).json({ error: 'Admin only' });
try {
clearStorageSettings();
res.json({ ok: true, ...buildStorageStatusPayload() });
} catch (err) {
res.status(500).json({ error: err?.message || 'Disconnect failed' });
}
});
app.post('/api/admin/storage/test', express.json(), async (req, res) => {
if (!getAdminFromRequest(req)) return res.status(403).json({ error: 'Admin only' });
try {
const body = req.body || {};
const base = getStorageConfig();
await testS3Connection({
endpoint: String(body.endpoint || base.s3.endpoint || '').trim(),
region: String(body.region || 'auto').trim() || 'auto',
bucket: String(body.bucket || base.s3.bucket || '').trim(),
accessKeyId: String(body.accessKeyId || base.s3.accessKeyId || '').trim(),
secretAccessKey: String(body.secretAccessKey || base.s3.secretAccessKey || '').trim(),
prefix: String(body.prefix || base.s3.prefix || 'haven').trim(),
forcePathStyle: body.forcePathStyle !== false
});
res.json({ ok: true });
} catch (err) {
res.status(400).json({ error: err?.message || 'Connection test failed' });
}
});
app.post('/api/admin/storage/migrate', async (req, res) => {
if (!getAdminFromRequest(req)) return res.status(403).json({ error: 'Admin only' });
try {
const result = await migrateLocalUploadsToActiveStorage();
res.json({ ok: true, ...result });
} catch (err) {
console.error('Storage migration error:', err);
res.status(500).json({ error: err?.message || 'Migration failed' });
}
});
app.get('/api/admin/volume/backup', async (req, res) => {
if (!getAdminFromRequest(req)) return res.status(403).json({ error: 'Admin only' });
try {
const zip = new AdmZip();
const storageConfig = getStorageConfig();
addDirectoryToZip(zip, CERTS_DIR, 'certs');
if (fs.existsSync(ENV_PATH)) zip.addFile('.env', fs.readFileSync(ENV_PATH));
if (fs.existsSync(DB_PATH)) zip.addFile('haven.db', fs.readFileSync(DB_PATH));
if (fs.existsSync(`${DB_PATH}-shm`)) zip.addFile('haven.db-shm', fs.readFileSync(`${DB_PATH}-shm`));
if (fs.existsSync(`${DB_PATH}-wal`)) zip.addFile('haven.db-wal', fs.readFileSync(`${DB_PATH}-wal`));
if (storageConfig.provider === 'local') addDirectoryToZip(zip, UPLOADS_DIR, 'uploads');
else await appendActiveUploadsToZip(zip);
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', `attachment; filename="haven-data-backup-${stamp}.zip"`);
res.send(zip.toBuffer());
} catch (err) {
console.error('Volume backup error:', err);
res.status(500).json({ error: 'Failed to create backup zip' });
}
});
const volumeImportUpload = multer({
storage: multer.diskStorage({
destination: DATA_DIR,
filename: (req, file, cb) => {
cb(null, `haven-volume-import-${Date.now()}-${crypto.randomBytes(6).toString('hex')}.zip`);
}
}),
limits: { fileSize: 2 * 1024 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
const ext = path.extname(file.originalname || '').toLowerCase();
if (ext === '.zip') cb(null, true);
else cb(new Error('Only .zip files are accepted'));
}
});
function detectRestoreRoot(extractDir) {
const directSignals = ['.env', 'haven.db', 'uploads', 'certs'];
const entries = fs.readdirSync(extractDir);
if (entries.some((name) => directSignals.includes(name))) return extractDir;
if (entries.length === 1) {
const candidate = path.join(extractDir, entries[0]);
if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) return candidate;
}
return extractDir;
}
app.post('/api/admin/volume/import', uploadLimiter, (req, res) => {
if (!getAdminFromRequest(req)) return res.status(403).json({ error: 'Admin only' });
volumeImportUpload.single('file')(req, res, async (err) => {
if (err) return res.status(400).json({ error: err.message });
if (!req.file?.path) return res.status(400).json({ error: 'No zip uploaded' });
const tempRoot = path.join(DATA_DIR, `restore-upload-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`);
try {
fs.mkdirSync(tempRoot, { recursive: true });
const zip = new AdmZip(req.file.path);
zip.extractAllTo(tempRoot, true);
const restoreRoot = detectRestoreRoot(tempRoot);
const uploadsRoot = path.join(restoreRoot, 'uploads');
const uploadRestore = await restoreUploadsFromDirectory(uploadsRoot);
const pendingRoot = path.join(tempRoot, 'pending-root');
fs.mkdirSync(pendingRoot, { recursive: true });
for (const entry of fs.readdirSync(restoreRoot, { withFileTypes: true })) {
if (entry.name === 'uploads') continue;
const src = path.join(restoreRoot, entry.name);
const dst = path.join(pendingRoot, entry.name);
if (entry.isDirectory()) {
fs.cpSync(src, dst, { recursive: true, force: true });
} else {
fs.copyFileSync(src, dst);
}
}
stagePendingRestore(pendingRoot);
res.json({
ok: true,
...uploadRestore,
restartRequired: true,
message: 'Import staged. Restart Haven to apply database and config files.'
});
} catch (importErr) {
console.error('Volume import error:', importErr);
res.status(500).json({ error: importErr?.message || 'Failed to import backup zip' });
} finally {
try { fs.unlinkSync(req.file.path); } catch {}
try { fs.rmSync(tempRoot, { recursive: true, force: true }); } catch {}
}
});
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/app', (req, res) => {
res.setHeader('Cache-Control', 'no-cache');
res.sendFile(path.join(__dirname, 'public', 'app.html'));
});
app.get('/games/flappy', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'games', 'flappy.html'));
});
// ── Donors / sponsors list (loaded from donors.json) ──
app.get('/api/donors', (req, res) => {
try {
const donorsPath = path.join(__dirname, 'donors.json');
const data = JSON.parse(fs.readFileSync(donorsPath, 'utf-8'));
res.json(data);
} catch {
res.json({ sponsors: [], donors: [] });
}
});
// ── Health check (CORS allowed for multi-server status pings) ──
app.get('/api/health', (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
let name = process.env.SERVER_NAME || 'Haven';
let icon = null;
try {
const { getDb } = require('./src/database');
const db = getDb();
const row = db.prepare("SELECT value FROM server_settings WHERE key = 'server_name'").get();
if (row && row.value) name = row.value;
const iconRow = db.prepare("SELECT value FROM server_settings WHERE key = 'server_icon'").get();
if (iconRow && iconRow.value) icon = iconRow.value;
} catch {}
res.json({
status: 'online',
name,
icon
// version intentionally omitted — don't fingerprint the server for attackers
});
});
// ── Version endpoint (for update checker — authenticated users only) ──
app.get('/api/version', (req, res) => {
const pkg = require('./package.json');
try {
const row = getDb().prepare("SELECT value FROM server_settings WHERE key = 'display_version'").get();
res.json({ version: row?.value || pkg.version });
} catch {
res.json({ version: pkg.version });
}
});
// ── Public config (unauthenticated — safe, read-only aesthetics) ──
// Returns the admin-configured default theme so the login page can match
// the server's look for first-time visitors who have no localStorage preference.
app.get('/api/public-config', (req, res) => {
try {
const { getDb } = require('./src/database');
const db = getDb();
const themeRow = db.prepare("SELECT value FROM server_settings WHERE key = 'default_theme'").get();
const titleRow = db.prepare("SELECT value FROM server_settings WHERE key = 'server_title'").get();
res.json({
default_theme: themeRow?.value || '',
server_title: titleRow?.value || ''
});
} catch {
res.json({ default_theme: '', server_title: '' });
}
});
// ── Port reachability check (Admin only) ─────────────────
// Uses external services to test if this server is reachable from the internet.
// Returns { reachable: bool, publicIp: string|null, error: string|null }
app.get('/api/port-check', async (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user || !verifyAdminFromDb(user)) return res.status(403).json({ error: 'Admin only' });
const port = process.env.PORT || 3000;
const https = require('https');
const http = require('http');
// Step 1: Get public IP
let publicIp = null;
try {
publicIp = await new Promise((resolve, reject) => {
const req = https.get('https://api.ipify.org?format=json', { timeout: 5000 }, (resp) => {
let data = '';
resp.on('data', chunk => data += chunk);
resp.on('end', () => {
try { resolve(JSON.parse(data).ip); }
catch { reject(new Error('Bad response')); }
});
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('Timeout')); });
});
} catch {
return res.json({ reachable: false, publicIp: null, error: 'Could not determine public IP. You may be offline.' });
}
// Step 2: Check if port is reachable via external probe
let reachable = false;
try {
reachable = await new Promise((resolve, reject) => {
const url = `https://portchecker.io/api/v1/query?host=${publicIp}&ports=${port}`;
const req = https.get(url, { timeout: 10000 }, (resp) => {
let data = '';
resp.on('data', chunk => data += chunk);
resp.on('end', () => {
try {
const result = JSON.parse(data);
// portchecker.io returns { host, ports: [{ port, status }] }
const portResult = result.ports?.find(p => p.port === parseInt(port));
resolve(portResult?.status === 'open');
} catch { resolve(false); }
});
});
req.on('error', () => resolve(false));
req.on('timeout', () => { req.destroy(); resolve(false); });
});
} catch {
// Fallback: try to connect to ourselves from public IP
try {
const proto = useSSL ? https : http;
reachable = await new Promise((resolve) => {
const req = proto.get(`${useSSL ? 'https' : 'http'}://${publicIp}:${port}/api/health`, {
timeout: 5000,
// SECURITY NOTE: rejectUnauthorized:false is intentional here — this
// connects to OUR OWN public IP to test reachability. Self-signed certs
// used by Haven would fail standard verification. This never connects
// to third-party servers.
rejectUnauthorized: false
}, (resp) => {
let data = '';
resp.on('data', chunk => data += chunk);
resp.on('end', () => {
try { resolve(JSON.parse(data).status === 'online'); }
catch { resolve(false); }
});
});
req.on('error', () => resolve(false));
req.on('timeout', () => { req.destroy(); resolve(false); });
});
} catch { reachable = false; }
}
res.json({ reachable, publicIp, error: null });
});
// ── Upload rate limiting ─────────────────────────────────
const uploadLimitStore = new Map();
function uploadLimiter(req, res, next) {
const ip = req.ip || req.socket.remoteAddress;
const now = Date.now();
const windowMs = 60 * 1000; // 1 minute
const maxUploads = 10;
if (!uploadLimitStore.has(ip)) uploadLimitStore.set(ip, []);
const stamps = uploadLimitStore.get(ip).filter(t => now - t < windowMs);
uploadLimitStore.set(ip, stamps);
if (stamps.length >= maxUploads) return res.status(429).json({ error: 'Upload rate limit — try again in a minute' });
stamps.push(now);
next();
}
setInterval(() => { const now = Date.now(); for (const [ip, t] of uploadLimitStore) { const f = t.filter(x => now - x < 60000); if (!f.length) uploadLimitStore.delete(ip); else uploadLimitStore.set(ip, f); } }, 5 * 60 * 1000);
// ── Image upload (authenticated + not banned) ────────────
app.post('/api/upload', uploadLimiter, (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
// Check if user is banned
const { getDb } = require('./src/database');
const ban = getDb().prepare('SELECT id FROM bans WHERE user_id = ?').get(user.id);
if (ban) return res.status(403).json({ error: 'Banned users cannot upload' });
// Enforce upload_files permission (admin always allowed)
if (!verifyAdminFromDb(user)) {
const hasPerm = getDb().prepare(`
SELECT 1 FROM role_permissions rp
JOIN user_roles ur ON rp.role_id = ur.role_id
WHERE ur.user_id = ? AND rp.permission = 'upload_files' AND rp.allowed = 1 LIMIT 1
`).get(user.id);
if (!hasPerm) return res.status(403).json({ error: 'You don\'t have permission to upload files' });
}
upload.single('image')(req, res, (err) => {
if (err) return res.status(400).json({ error: err.message });
if (!req.file) return res.status(400).json({ error: 'No file uploaded' });
// Enforce DB-configurable max upload size (same setting as general file uploads)
const maxMbRow = getDb().prepare("SELECT value FROM server_settings WHERE key = 'max_upload_mb'").get();
const maxBytes = (parseInt(maxMbRow?.value) || 25) * 1024 * 1024;
if (req.file.size > maxBytes) {
return res.status(400).json({ error: `Image too large (max ${maxMbRow?.value || 25} MB)` });
}