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
4597 lines (4159 loc) · 207 KB
/
Copy pathserver.js
File metadata and controls
4597 lines (4159 loc) · 207 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');
// ── Node.js version guard ─────────────────────────────────
const nodeMajor = parseInt(process.versions.node.split('.')[0], 10);
if (nodeMajor < 22 || nodeMajor > 26) {
console.error(`\n Haven requires Node.js 22-26. You have v${process.versions.node}.`);
console.error(' If you installed Node.js from nodejs.org, make sure you picked the');
console.error(' LTS version (v22.x), not an older or unsupported version.');
console.error(' LTS download: https://nodejs.org/en/download (choose "LTS")\n');
process.exit(1);
}
// Bootstrap .env into the data directory if it doesn't exist yet
const fs = require('fs');
const path = require('path');
if (!fs.existsSync(ENV_PATH)) {
const example = path.join(__dirname, '.env.example');
if (fs.existsSync(example)) {
fs.copyFileSync(example, ENV_PATH);
console.log(`📄 Created .env in ${DATA_DIR} from template`);
} else {
// Write a minimal .env so dotenv doesn't fail
fs.writeFileSync(ENV_PATH, 'JWT_SECRET=change-me-to-something-random-and-long\n');
}
}
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 = fs.readFileSync(ENV_PATH, 'utf-8');
envContent = envContent.replace(/JWT_SECRET=.*/, `JWT_SECRET=${generated}`);
fs.writeFileSync(ENV_PATH, envContent);
process.env.JWT_SECRET = generated;
console.log('🔑 Auto-generated strong JWT_SECRET (saved to .env)');
}
// ── 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 = fs.readFileSync(ENV_PATH, 'utf-8');
envContent += `\nVAPID_PUBLIC_KEY=${vapidKeys.publicKey}\nVAPID_PRIVATE_KEY=${vapidKeys.privateKey}\n`;
fs.writeFileSync(ENV_PATH, envContent);
process.env.VAPID_PUBLIC_KEY = vapidKeys.publicKey;
process.env.VAPID_PRIVATE_KEY = vapidKeys.privateKey;
console.log('🔔 Auto-generated VAPID keys for push notifications (saved to .env)');
}
// 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 } = 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 { startDdns, getDdnsStatus, triggerDdnsNow } = require('./src/ddns');
const { initFcm } = require('./src/fcm');
const app = express();
const UPLOAD_PATH_RE = /\/uploads\/((?!(?:deleted-attachments|stickers)\/)(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_.-]+)/g;
function isSafeUploadRelPath(relPath) {
if (typeof relPath !== 'string' || !relPath) return false;
if (!/^((?!\.\.)(?!\.\/)(?!\/)[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+$/.test(relPath)) return false;
const parts = relPath.split('/');
if (parts.some(p => !p || p === '.' || p === '..')) return false;
return true;
}
function moveUploadToDeleted(relPath, srcRoot = UPLOADS_DIR) {
if (!isSafeUploadRelPath(relPath)) return;
const src = path.join(srcRoot, relPath);
if (!fs.existsSync(src)) return;
let stat;
try {
stat = fs.statSync(src);
} catch {
return;
}
if (!stat.isFile()) return;
const dst = path.join(DELETED_ATTACHMENTS_DIR, relPath);
try {
fs.mkdirSync(path.dirname(dst), { recursive: true });
fs.renameSync(src, dst);
} catch { /* file locked or already moved */ }
}
// Trust proxy configuration — controls how many reverse-proxy hops to trust
// when reading the real client IP from X-Forwarded-For.
//
// TRUST_PROXY=1 (default) — trust the first hop (nginx/Traefik/Cloudflare)
// TRUST_PROXY=0 — direct exposure; do NOT trust XFF headers
// (prevents attackers from spoofing their IP to
// bypass the auth rate limiter)
// TRUST_PROXY=2 — two proxy hops, etc.
//
// Without this every user behind a reverse proxy shares the loopback IP in
// the auth rate limiter, causing innocent users to hit the limit on their
// very first login/register attempt.
const _trustProxy = process.env.TRUST_PROXY !== undefined
? (isNaN(Number(process.env.TRUST_PROXY)) ? process.env.TRUST_PROXY : Number(process.env.TRUST_PROXY))
: 1;
app.set('trust proxy', _trustProxy);
// ── IP ban gate (v3.20.0) ─────────────────────────────────
// Run before anything else (parsers, helmet, static) so banned addresses
// can't consume server resources. Cached for 30s so we aren't hitting SQLite
// on every static asset request from a normal page load. Cache is invalidated
// from the moderation socket handlers whenever the table changes.
let _ipBanCache = { set: new Set(), expires: 0 };
function _refreshIpBanCache() {
try {
const { getDb } = require('./src/database');
const rows = getDb().prepare('SELECT ip FROM ip_bans').all();
_ipBanCache = { set: new Set(rows.map(r => r.ip)), expires: Date.now() + 30000 };
} catch { _ipBanCache = { set: new Set(), expires: Date.now() + 30000 }; }
}
function invalidateIpBanCache() { _ipBanCache.expires = 0; }
function isIpBanned(ip) {
if (!ip) return false;
if (Date.now() > _ipBanCache.expires) _refreshIpBanCache();
return _ipBanCache.set.has(ip);
}
app.use((req, res, next) => {
if (isIpBanned(req.ip)) {
return res.status(403).type('text/plain').send('Your IP has been banned from this server.');
}
next();
});
// Expose the invalidator on the app so socket handlers can poke it.
app.set('invalidateIpBanCache', invalidateIpBanCache);
app.set('isIpBanned', isIpBanned);
// ── 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'", "blob:", "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:", "http:"], // link preview OG images + GIPHY (http: for local/self-hosted services)
connectSrc: ["'self'", "ws:", "wss:", "https:"], // Socket.IO + cross-origin health checks
mediaSrc: ["'self'", "blob:", "data:", "https:", "http:"], // WebRTC audio + notification sounds + link preview video embeds
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
...(process.env.FORCE_HTTP?.toLowerCase() === 'true' ? { upgradeInsecureRequests: null } : {}), // helmet 8.x auto-appends upgrade-insecure-requests; disable when FORCE_HTTP=true
}
},
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 ────────────────────────
// Global limit bumped to 128kb so legit large-but-bounded payloads like the
// per-user saved server list (PUT /api/auth/user-servers, ~40kb at 100+
// servers) aren't rejected by the global parser before per-route parsers
// can apply their own limits. Individual routes still set tighter limits
// where appropriate. (#5347 v3.15.7)
app.use(express.json({ limit: '128kb' }));
app.use(express.urlencoded({ extended: false, limit: '128kb' }));
// ── 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)) {
// Allow cross-origin access for images (needed for server icon pulling).
// CORP override is required because helmet defaults to 'same-origin', which
// would otherwise block cross-origin <img> loads even with ACAO set.
// Vary: Origin prevents a non-CORS cached response from being reused for a
// CORS request (which is what causes the "No 'Access-Control-Allow-Origin'
// header is present" error on a cached image).
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
res.setHeader('Vary', 'Origin');
} else if (ext === '.svg') {
// SVG (issue #5309): renderable inline via <img> tag (browsers run SVG in
// "secure static mode" — no scripts, no XHR), but direct navigation still
// gets attachment-disposition so opening the raw URL in a new tab can't
// execute the file. CSP doubles up on that — even if a future browser
// change allowed any external loads inside <img>-rendered SVG, this
// header forbids everything except inline styles (needed for fill/stroke).
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
res.setHeader('Vary', 'Origin');
res.setHeader('Content-Disposition', 'attachment');
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
} else {
res.setHeader('Content-Disposition', 'attachment');
}
}
}));
// ── 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'));
let published = [];
try {
const row = db.prepare("SELECT value FROM server_settings WHERE key = 'published_themes'").get();
if (row) published = JSON.parse(row.value);
} catch { /* DB not ready yet or parse error — default to empty */ }
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+(.+)/);
const iconM = block.match(/@icon\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();
if (iconM) meta.icon = iconM[1].trim();
}
return { file: f, ...meta, published: published.includes(f) };
});
res.json(themes);
} catch { res.json([]); }
});
// ── File uploads (DB-configurable limit, avatar max 5 MB) ──
const uploadDir = UPLOADS_DIR;
const uploadStorage = multer.diskStorage({
destination: uploadDir,
filename: (req, file, cb) => {
const ext = path.extname(file.originalname).toLowerCase();
cb(null, `${Date.now()}-${crypto.randomBytes(8).toString('hex')}${ext}`);
}
});
// Image-only upload — multer cap is generous; real limit enforced per-request from DB
const upload = multer({
storage: uploadStorage,
limits: { fileSize: 100 * 1024 * 1024 * 1024 }, // 100 GB ceiling — admin DB setting is the real limit
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: 100 * 1024 * 1024 * 1024 }, // 100 GB ceiling — admin DB setting is the real limit
});
// ── API routes ────────────────────────────────────────────
// authLimiter is applied per-route inside auth.js for credential endpoints
// (login, register, TOTP, password change). Non-credential routes like
// /validate and /user-servers are intentionally left unlimitted here so
// 50+ concurrent users joining a stream event don't trip the limiter. (#5323)
app.use('/api/auth', 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' });
}
});
// ── Per-user channel notification prefs ──────────────────
// Mirrors the localStorage `haven_muted_channels` set to the database so
// sendPushNotifications can filter out muted recipients before they hit
// FCM/web-push (#5399 follow-up — mobile users were getting pushes for
// every message regardless of channel mute state because the prefs only
// ever lived client-side).
app.get('/api/user/channel-prefs', (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');
const rows = getDb().prepare(
'SELECT channel_code FROM user_channel_prefs WHERE user_id = ? AND muted = 1'
).all(user.id);
res.json({ muted: rows.map(r => r.channel_code) });
} catch (err) {
console.error('[user/channel-prefs GET]', err);
res.status(500).json({ error: 'Internal server error' });
}
});
app.post('/api/user/channel-prefs/mute', express.json({ limit: '4kb' }), (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 { code, muted } = req.body || {};
if (typeof code !== 'string' || !code.length || code.length > 64)
return res.status(400).json({ error: 'Invalid code' });
try {
const { getDb } = require('./src/database');
getDb().prepare(`
INSERT INTO user_channel_prefs (user_id, channel_code, muted, updated_at)
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(user_id, channel_code) DO UPDATE SET
muted = excluded.muted,
updated_at = CURRENT_TIMESTAMP
`).run(user.id, code, muted ? 1 : 0);
res.json({ ok: true });
} catch (err) {
console.error('[user/channel-prefs POST]', err);
res.status(500).json({ error: 'Internal server error' });
}
});
// Bulk replace — used by the client on first sync to push the entire
// localStorage set up at once (or to converge after offline edits).
app.put('/api/user/channel-prefs/muted', express.json({ limit: '16kb' }), (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 codes = Array.isArray(req.body?.codes) ? req.body.codes : null;
if (!codes || codes.length > 500)
return res.status(400).json({ error: 'codes array required (max 500)' });
// Filter to plausible channel codes only — strings, 1..64 chars
const clean = codes.filter(c => typeof c === 'string' && c.length > 0 && c.length <= 64);
try {
const { getDb } = require('./src/database');
const db = getDb();
const tx = db.transaction((uid, list) => {
db.prepare('DELETE FROM user_channel_prefs WHERE user_id = ? AND muted = 1').run(uid);
const ins = db.prepare(`
INSERT INTO user_channel_prefs (user_id, channel_code, muted, updated_at)
VALUES (?, ?, 1, CURRENT_TIMESTAMP)
ON CONFLICT(user_id, channel_code) DO UPDATE SET
muted = 1, updated_at = CURRENT_TIMESTAMP
`);
for (const c of list) ins.run(uid, c);
});
tx(user.id, clean);
res.json({ ok: true, count: clean.length });
} catch (err) {
console.error('[user/channel-prefs PUT]', err);
res.status(500).json({ error: 'Internal server error' });
}
});
// ── ICE servers endpoint (STUN + optional TURN) ──────────
app.get('/api/ice-servers', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
const user = token ? verifyToken(token) : null;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
// STUN_URLS env var: comma-separated list of STUN URIs to override defaults.
// 3.20.2 (#5399): old defaults (stun.stunprotocol.org + stun.nextcloud.com)
// both went offline simultaneously. Mirrors the voice.js client default
// pool so any Haven server that hadn't customised STUN_URLS would have
// returned dead endpoints to its clients here too.
const stunUrls = process.env.STUN_URLS
? process.env.STUN_URLS.split(',').map(u => u.trim()).filter(Boolean)
: [
'stun:stun.cloudflare.com:3478',
'stun:stun.relay.metered.ca:80',
'stun:global.stun.twilio.com:3478',
'stun:stun.l.google.com:19302',
];
const iceServers = stunUrls.map(urls => ({ urls }));
const turnUrl = process.env.TURN_URL;
if (turnUrl) {
const turnSecret = process.env.TURN_SECRET;
const turnUser = process.env.TURN_USERNAME;
const turnPass = process.env.TURN_PASSWORD;
if (turnSecret) {
// Time-limited TURN credentials (coturn --use-auth-secret / REST API)
const ttl = 24 * 3600; // 24 hours
const expiry = Math.floor(Date.now() / 1000) + ttl;
const username = `${expiry}:${user.username}`;
const hmac = crypto.createHmac('sha1', turnSecret).update(username).digest('base64');
iceServers.push({ urls: turnUrl, username, credential: hmac });
} else if (turnUser && turnPass) {
// Static TURN credentials
iceServers.push({ urls: turnUrl, username: turnUser, credential: turnPass });
} else {
// TURN URL with no auth (uncommon but possible)
iceServers.push({ urls: turnUrl });
}
}
res.json({ iceServers });
});
// ── 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) {
fs.unlinkSync(req.file.path);
return res.status(400).json({ error: 'Avatar must be under 2 MB' });
}
// Validate file magic bytes
try {
const fd = fs.openSync(req.file.path, 'r');
const hdr = Buffer.alloc(12);
fs.readSync(fd, hdr, 0, 12, 0);
fs.closeSync(fd);
let validMagic = false;
if (req.file.mimetype === 'image/jpeg') validMagic = hdr[0] === 0xFF && hdr[1] === 0xD8 && hdr[2] === 0xFF;
else if (req.file.mimetype === 'image/png') validMagic = hdr[0] === 0x89 && hdr[1] === 0x50 && hdr[2] === 0x4E && hdr[3] === 0x47;
else if (req.file.mimetype === 'image/gif') validMagic = hdr.slice(0, 6).toString().startsWith('GIF8');
else if (req.file.mimetype === 'image/webp') validMagic = hdr.slice(0, 4).toString() === 'RIFF' && hdr.slice(8, 12).toString() === 'WEBP';
if (!validMagic) {
fs.unlinkSync(req.file.path);
return res.status(400).json({ error: 'File content does not match image type' });
}
} catch {
try { fs.unlinkSync(req.file.path); } catch {}
return res.status(400).json({ error: 'Failed to validate file' });
}
// Force safe extension
const mimeToExt = { 'image/jpeg': '.jpg', 'image/png': '.png', 'image/gif': '.gif', 'image/webp': '.webp' };
const safeExt = mimeToExt[req.file.mimetype];
if (!safeExt) {
fs.unlinkSync(req.file.path);
return res.status(400).json({ error: 'Invalid file type' });
}
const currentExt = path.extname(req.file.filename).toLowerCase();
let finalName = req.file.filename;
if (currentExt !== safeExt) {
finalName = req.file.filename.replace(/\.[^.]+$/, '') + safeExt;
const oldPath = req.file.path;
const newPath = path.join(uploadDir, finalName);
fs.renameSync(oldPath, newPath);
}
const avatarUrl = `/uploads/${finalName}`;
// Update the user's avatar in the database
try {
const db = getDb();
db.prepare('UPDATE users SET avatar = ? WHERE id = ?').run(avatarUrl, user.id);
console.log(`[Avatar] ${user.username} uploaded avatar: ${avatarUrl}`);
} catch (dbErr) {
console.error('Avatar DB update error:', dbErr);
return res.status(500).json({ error: 'Failed to save avatar' });
}
res.json({ url: avatarUrl });
});
});
// ── 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' });
}
});
// ── 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' });
// Admins or users with manage_webhooks permission can upload webhook avatars
const { getDb } = require('./src/database');
const dbUser = getDb().prepare('SELECT is_admin FROM users WHERE id = ?').get(user.id);
if (!dbUser || (!dbUser.is_admin && !userHasPermission(user.id, 'manage_webhooks'))) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
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' });
// Validate file magic bytes
try {
const fd = fs.openSync(req.file.path, 'r');
const hdr = Buffer.alloc(12);
fs.readSync(fd, hdr, 0, 12, 0);
fs.closeSync(fd);
let validMagic = false;
if (req.file.mimetype === 'image/jpeg') validMagic = hdr[0] === 0xFF && hdr[1] === 0xD8 && hdr[2] === 0xFF;
else if (req.file.mimetype === 'image/png') validMagic = hdr[0] === 0x89 && hdr[1] === 0x50 && hdr[2] === 0x4E && hdr[3] === 0x47;
else if (req.file.mimetype === 'image/gif') validMagic = hdr.slice(0, 6).toString().startsWith('GIF8');
else if (req.file.mimetype === 'image/webp') validMagic = hdr.slice(0, 4).toString() === 'RIFF' && hdr.slice(8, 12).toString() === 'WEBP';
if (!validMagic) {
fs.unlinkSync(req.file.path);
return res.status(400).json({ error: 'File content does not match image type' });
}
} catch {
try { fs.unlinkSync(req.file.path); } catch {}
return res.status(400).json({ error: 'Failed to validate file' });
}
const mimeToExt = { 'image/jpeg': '.jpg', 'image/png': '.png', 'image/gif': '.gif', 'image/webp': '.webp' };
const safeExt = mimeToExt[req.file.mimetype];
if (!safeExt) {
fs.unlinkSync(req.file.path);
return res.status(400).json({ error: 'Invalid file type' });
}
const currentExt = path.extname(req.file.filename).toLowerCase();
let finalName = req.file.filename;
if (currentExt !== safeExt) {
finalName = req.file.filename.replace(/\.[^.]+$/, '') + safeExt;
fs.renameSync(req.file.path, path.join(uploadDir, finalName));
}
const avatarUrl = `/uploads/${finalName}`;
// Update the webhook's avatar in DB
const webhookId = parseInt(req.body?.webhookId || req.query?.webhookId);
if (!isNaN(webhookId)) {
try {
getDb().prepare('UPDATE webhooks SET avatar_url = ? WHERE id = ?').run(avatarUrl, webhookId);
} catch (dbErr) {
console.error('Webhook avatar DB error:', dbErr);
}
}
res.json({ url: avatarUrl });
});
});
// ── Personas (proxy feature) (#86, #5349) ─────────────────
// CRUD + avatar upload for per-user personas. Triggered in chat with
// "PersonaName: message" (handled by send-message socket handler).
app.get('/api/personas', (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');
const rows = getDb().prepare(
'SELECT id, name, avatar, bio, created_at FROM user_personas WHERE user_id = ? ORDER BY name COLLATE NOCASE ASC'
).all(user.id);
res.json({ personas: rows });
} catch (err) {
console.error('GET /api/personas error:', err);
res.status(500).json({ error: 'Failed to load personas' });
}
});
const _validatePersonaName = (raw) => {
if (typeof raw !== 'string') return null;
const trimmed = raw.trim();
if (trimmed.length < 1 || trimmed.length > 32) return null;
// Disallow ":" and control/newline chars (the trigger uses "Name:")
if (/[\u0000-\u001F:\n\r]/.test(trimmed)) return null;
return trimmed;
};
app.post('/api/personas', 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 name = _validatePersonaName(req.body?.name);
if (!name) return res.status(400).json({ error: 'Persona name must be 1-32 chars and may not contain ":" or line breaks' });
const bio = typeof req.body?.bio === 'string' ? req.body.bio.slice(0, 190) : null;
const avatar = typeof req.body?.avatar === 'string' && req.body.avatar.startsWith('/uploads/')
? req.body.avatar : null;
try {
const { getDb } = require('./src/database');
const db = getDb();
// Cap personas per user to keep abuse / accidental spam in check.
const count = db.prepare('SELECT COUNT(*) as c FROM user_personas WHERE user_id = ?').get(user.id).c;
if (count >= 25) return res.status(400).json({ error: 'Persona limit reached (25 max)' });
// Block names that collide with real usernames to prevent impersonation.
const collision = db.prepare(
'SELECT id FROM users WHERE username = ? COLLATE NOCASE OR display_name = ? COLLATE NOCASE'
).get(name, name);
if (collision) return res.status(400).json({ error: 'That name is already taken by a real user' });
const result = db.prepare(
'INSERT INTO user_personas (user_id, name, avatar, bio) VALUES (?, ?, ?, ?)'
).run(user.id, name, avatar, bio);
const row = db.prepare(
'SELECT id, name, avatar, bio, created_at FROM user_personas WHERE id = ?'
).get(result.lastInsertRowid);
res.json({ persona: row });
} catch (err) {
if (err.code === 'SQLITE_CONSTRAINT_UNIQUE') {
return res.status(400).json({ error: 'You already have a persona with that name' });
}
console.error('POST /api/personas error:', err);
res.status(500).json({ error: 'Failed to create persona' });
}
});
app.patch('/api/personas/:id', 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 id = parseInt(req.params.id);
if (!Number.isFinite(id)) return res.status(400).json({ error: 'Bad id' });
try {
const { getDb } = require('./src/database');
const db = getDb();
const persona = db.prepare('SELECT id FROM user_personas WHERE id = ? AND user_id = ?').get(id, user.id);
if (!persona) return res.status(404).json({ error: 'Persona not found' });
const updates = [];
const vals = [];
if (req.body?.name !== undefined) {
const name = _validatePersonaName(req.body.name);
if (!name) return res.status(400).json({ error: 'Persona name must be 1-32 chars and may not contain ":" or line breaks' });
const collision = db.prepare(
'SELECT id FROM users WHERE username = ? COLLATE NOCASE OR display_name = ? COLLATE NOCASE'
).get(name, name);
if (collision) return res.status(400).json({ error: 'That name is already taken by a real user' });
updates.push('name = ?'); vals.push(name);
}
if (req.body?.avatar !== undefined) {
const avatar = req.body.avatar === null ? null
: (typeof req.body.avatar === 'string' && req.body.avatar.startsWith('/uploads/') ? req.body.avatar : null);
updates.push('avatar = ?'); vals.push(avatar);
}
if (req.body?.bio !== undefined) {
const bio = req.body.bio === null ? null
: (typeof req.body.bio === 'string' ? req.body.bio.slice(0, 190) : null);
updates.push('bio = ?'); vals.push(bio);
}
if (!updates.length) return res.status(400).json({ error: 'Nothing to update' });
vals.push(id, user.id);
db.prepare(`UPDATE user_personas SET ${updates.join(', ')} WHERE id = ? AND user_id = ?`).run(...vals);
const row = db.prepare(
'SELECT id, name, avatar, bio, created_at FROM user_personas WHERE id = ?'
).get(id);
res.json({ persona: row });
} catch (err) {
if (err.code === 'SQLITE_CONSTRAINT_UNIQUE') {
return res.status(400).json({ error: 'You already have a persona with that name' });
}
console.error('PATCH /api/personas/:id error:', err);
res.status(500).json({ error: 'Failed to update persona' });
}
});
app.delete('/api/personas/:id', (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 id = parseInt(req.params.id);
if (!Number.isFinite(id)) return res.status(400).json({ error: 'Bad id' });
try {
const { getDb } = require('./src/database');
getDb().prepare('DELETE FROM user_personas WHERE id = ? AND user_id = ?').run(id, user.id);
res.json({ ok: true });
} catch (err) {
console.error('DELETE /api/personas/:id error:', err);
res.status(500).json({ error: 'Failed to delete persona' });
}
});
// Persona avatar upload — same validation as user avatar (2 MB, magic-byte check)
app.post('/api/upload-persona-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) {
try { fs.unlinkSync(req.file.path); } catch {}
return res.status(400).json({ error: 'Avatar must be under 2 MB' });
}
try {
const fd = fs.openSync(req.file.path, 'r');
const hdr = Buffer.alloc(12);
fs.readSync(fd, hdr, 0, 12, 0);
fs.closeSync(fd);
let validMagic = false;
if (req.file.mimetype === 'image/jpeg') validMagic = hdr[0] === 0xFF && hdr[1] === 0xD8 && hdr[2] === 0xFF;
else if (req.file.mimetype === 'image/png') validMagic = hdr[0] === 0x89 && hdr[1] === 0x50 && hdr[2] === 0x4E && hdr[3] === 0x47;
else if (req.file.mimetype === 'image/gif') validMagic = hdr.slice(0, 6).toString().startsWith('GIF8');
else if (req.file.mimetype === 'image/webp') validMagic = hdr.slice(0, 4).toString() === 'RIFF' && hdr.slice(8, 12).toString() === 'WEBP';
if (!validMagic) {
fs.unlinkSync(req.file.path);
return res.status(400).json({ error: 'File content does not match image type' });
}
} catch {
try { fs.unlinkSync(req.file.path); } catch {}
return res.status(400).json({ error: 'Failed to validate file' });
}
const mimeToExt = { 'image/jpeg': '.jpg', 'image/png': '.png', 'image/gif': '.gif', 'image/webp': '.webp' };
const safeExt = mimeToExt[req.file.mimetype];
if (!safeExt) {
try { fs.unlinkSync(req.file.path); } catch {}
return res.status(400).json({ error: 'Invalid file type' });
}
const currentExt = path.extname(req.file.filename).toLowerCase();
let finalName = req.file.filename;
if (currentExt !== safeExt) {
finalName = req.file.filename.replace(/\.[^.]+$/, '') + safeExt;
fs.renameSync(req.file.path, path.join(uploadDir, finalName));
}
const avatarUrl = `/uploads/${finalName}`;
// Optional: if a personaId is supplied, persist immediately (verifying ownership).
const personaId = parseInt(req.body?.personaId || req.query?.personaId);
if (Number.isFinite(personaId)) {
try {
const persona = getDb().prepare(
'SELECT id FROM user_personas WHERE id = ? AND user_id = ?'
).get(personaId, user.id);
if (!persona) return res.status(403).json({ error: 'Not your persona' });
getDb().prepare('UPDATE user_personas SET avatar = ? WHERE id = ?').run(avatarUrl, personaId);
} catch (dbErr) {
console.error('Persona avatar DB error:', dbErr);
return res.status(500).json({ error: 'Failed to save avatar' });
}
}
res.json({ url: avatarUrl });
});
});
// ── 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' });
}
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/app', (req, res) => {
res.setHeader('Cache-Control', 'no-cache');
// Inject current version into cache-busting query strings so client
// assets are never served stale after an update (especially in Electron).
const ver = require('./package.json').version;
let html = fs.readFileSync(path.join(__dirname, 'public', 'app.html'), 'utf8');
html = html.replace(/(\?v=)[^"']*/g, `$1${ver}`);
res.type('html').send(html);
});
// ── Vanity invite link (/invite/:code) ────────────────
app.get('/invite/:vanityCode', (req, res) => {
const vanityCode = req.params.vanityCode;
if (!vanityCode || typeof vanityCode !== 'string' || !/^[a-zA-Z0-9_-]{3,32}$/.test(vanityCode)) {
return res.status(400).send('Invalid invite link');
}
const { getDb } = require('./src/database');
const row = getDb().prepare("SELECT value FROM server_settings WHERE key = 'vanity_code'").get();
if (!row || row.value !== vanityCode) {
return res.status(404).send('Invite link not found or expired');
}
// Redirect to /app with the vanity code as a query param — the frontend will auto-join
res.redirect(`/app?invite=${encodeURIComponent(vanityCode)}`);
});
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'));
// Check for magnitude-sorted order file (gitignored, optional)
const orderPath = path.join(__dirname, 'donor-order.json');
if (fs.existsSync(orderPath)) {
try {
const ordered = JSON.parse(fs.readFileSync(orderPath, 'utf-8'));
data.featuredSponsors = ordered.sponsors || [];
data.featuredDonors = ordered.donors || [];
} catch {}
}
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', '*');
res.set('Cross-Origin-Resource-Policy', 'cross-origin');
res.set('Vary', 'Origin');
let name = process.env.SERVER_NAME || 'Haven';
let icon = null;
let fingerprint = 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;
const fpRow = db.prepare("SELECT value FROM server_settings WHERE key = 'server_fingerprint'").get();
if (fpRow && fpRow.value) fingerprint = fpRow.value;
} catch {}