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
6076 lines (5533 loc) · 277 KB
/
Copy pathserver.js
File metadata and controls
6076 lines (5533 loc) · 277 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, DELETED_ATTACHMENTS_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');
// ── Stale-install guard ───────────────────────────────────
// Updating by unzipping/copying a release over an existing install leaves
// behind files that newer versions deleted. That is normally harmless — until
// the deleted file is a module that was split into a folder of the same name
// (src/socketHandlers.js became src/socketHandlers/ in 2.9.8): require()
// resolves the leftover FILE before the directory, so the server silently
// runs months-old module code no matter how current every other file is, and
// eventually dies somewhere unrelated. A real self-host crashed on boot with
// "Cannot read properties of undefined (reading 'activity')" because a
// pre-2.9.8 socketHandlers.js was still shadowing the folder — after months
// of its socket layer being frozen at the old version while "fully updated".
// Catch the pattern generically and say exactly which file to delete.
{
const srcDir = path.join(__dirname, 'src');
let entries = [];
try { entries = fs.readdirSync(srcDir, { withFileTypes: true }); } catch { /* no src = other problems */ }
const dirNames = new Set(entries.filter(e => e.isDirectory()).map(e => e.name));
const stale = entries.filter(e =>
e.isFile() && e.name.endsWith('.js') && dirNames.has(e.name.slice(0, -3)) &&
fs.existsSync(path.join(srcDir, e.name.slice(0, -3), 'index.js'))
).map(e => path.join('src', e.name));
if (stale.length > 0) {
console.error('\n❌ Stale file(s) from an older Haven install detected:\n');
for (const f of stale) console.error(` ${f}`);
console.error('\n Each file above is left over from an old version and hides the');
console.error(' module folder of the same name, so this server would run with');
console.error(' outdated code and fail in confusing ways.');
console.error(' Fix: delete the file(s) listed above (the folders contain the');
console.error(' current code), or update by replacing the whole Haven folder');
console.error(' instead of copying new files over an old install. Your data is');
console.error(` safe — it lives in ${DATA_DIR}, not in the install folder.\n`);
process.exit(1);
}
}
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 });
// Also load the project root .env as an override source.
// Docker compose injects it via env_file, but when running directly on the
// host the data-directory .env may be stale (created before PUBLIC_URL was
// added), so the root .env serves as a fallback for env vars the server
// administrator has explicitly set.
//
// This must be done *after* ENV_PATH so the data-dir .env takes precedence
// for server-generated values (JWT_SECRET, VAPID keys).
const rootEnv = path.join(__dirname, '.env');
if (fs.existsSync(rootEnv)) {
require('dotenv').config({ path: rootEnv, override: false });
console.log('📄 Loaded project root .env as supplementary source');
}
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');
const diskGuard = require('./src/diskGuard');
// (#5505) Refuse uploads that would eat into the reserved disk headroom, so a
// full volume can never leave admins unable to delete the files that filled it.
const uploadDiskGuard = diskGuard.guardUploads();
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, sanitizeSoundName, sanitizeBorderTransform, toReplyContext } = require('./src/socketHandlers');
const { initFerry, stopFerry } = require('./src/ferry');
const { canAccessVoiceChannel, getAccessibleVoiceChannels } = require('./src/botVoice');
const {
BotAudioManager,
inspectAudioFile,
MAX_AUDIO_BYTES
} = require('./src/botAudio');
const { startTunnel, stopTunnel, getTunnelStatus, registerProcessCleanup } = require('./src/tunnel');
const { startDdns, getDdnsStatus, triggerDdnsNow } = require('./src/ddns');
const { initFcm, setFcmAdminEnabled } = require('./src/fcm');
const {
defaultIceServers,
hasTurn,
isTurnUrl,
parseIceServersJson,
} = require('./src/iceServers');
const app = express();
const BOT_AUDIO_DIR = path.join(UPLOADS_DIR, 'bot-audio');
fs.mkdirSync(BOT_AUDIO_DIR, { recursive: true });
let botAudioManager = null;
let socketRuntime = null;
const UPLOAD_PATH_RE = /\/uploads\/((?!(?:bot-audio|deleted-attachments|stickers)\/)(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_.-]+)/g;
const UPLOAD_URL_PATH_RE = /\/uploads\/+([-A-Za-z0-9_.~%/\\]+)/gi;
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 */ }
}
function collectUploadRelPaths(contents) {
const paths = new Set();
for (const content of contents) {
if (typeof content !== 'string' || !content) continue;
UPLOAD_URL_PATH_RE.lastIndex = 0;
let match;
while ((match = UPLOAD_URL_PATH_RE.exec(content)) !== null) {
let decoded;
try { decoded = decodeURIComponent(match[1]); } catch { continue; }
const parts = [];
let escapesRoot = false;
const segments = decoded.split(process.platform === 'win32' ? /[\\/]+/ : /\/+/);
for (const segment of segments) {
if (!segment || segment === '.') continue;
if (segment === '..') {
if (parts.length === 0) { escapesRoot = true; break; }
parts.pop();
} else {
parts.push(segment);
}
}
if (escapesRoot) continue;
const relPath = parts.join('/');
if (/^(?:bot-audio|deleted-attachments|stickers)\//i.test(relPath)) continue;
if (isSafeUploadRelPath(relPath)) paths.add(relPath);
}
}
return paths;
}
function relocateUnreferencedUploads(db, relPaths) {
const candidates = new Set(
Array.from(relPaths).filter(relPath => fs.existsSync(path.join(UPLOADS_DIR, relPath)))
);
if (candidates.size === 0) return;
const survivingMessages = db.prepare(`
SELECT content, persona_avatar, webhook_avatar
FROM messages
WHERE content LIKE '%/uploads/%'
OR persona_avatar IS NOT NULL
OR webhook_avatar IS NOT NULL
`).iterate();
for (const message of survivingMessages) {
for (const relPath of collectUploadRelPaths([
message.content,
message.persona_avatar,
message.webhook_avatar
])) {
candidates.delete(relPath);
}
if (candidates.size === 0) return;
}
const protectedUrlReferences = db.prepare(`
SELECT avatar AS reference FROM users WHERE avatar LIKE '%/uploads/%'
UNION ALL SELECT border FROM users WHERE border LIKE '%/uploads/%'
UNION ALL SELECT avatar FROM user_personas WHERE avatar LIKE '%/uploads/%'
UNION ALL SELECT avatar_url FROM webhooks WHERE avatar_url LIKE '%/uploads/%'
UNION ALL SELECT icon FROM roles WHERE icon LIKE '%/uploads/%'
UNION ALL SELECT value FROM server_settings WHERE value LIKE '%/uploads/%'
`).iterate();
for (const row of protectedUrlReferences) {
for (const relPath of collectUploadRelPaths([row.reference])) candidates.delete(relPath);
if (candidates.size === 0) return;
}
const findOwnership = db.prepare(
'SELECT user_id, scope, created_at FROM upload_ownership WHERE rel_path = ?'
);
const latestDmMessageByUser = new Map(db.prepare(`
SELECT m.user_id, MAX(COALESCE(m.edited_at, m.created_at)) AS referenced_at
FROM messages m
JOIN channels c ON c.id = m.channel_id
WHERE c.is_dm = 1 AND m.user_id IS NOT NULL
GROUP BY m.user_id
`).all().map(row => [row.user_id, row.referenced_at]));
const findProtectedFilenameReference = db.prepare(`
SELECT 1
WHERE EXISTS(SELECT 1 FROM custom_sounds WHERE filename = ?)
OR EXISTS(SELECT 1 FROM custom_emojis WHERE filename = ?)
OR EXISTS(SELECT 1 FROM stickers WHERE filename = ?)
`);
for (const relPath of candidates) {
const ownership = findOwnership.get(relPath);
// Legacy/unattributed files and private/profile uploads cannot be proven
// orphaned, so leave them in place. A channel upload is also retained if
// its owner later sent an encrypted DM that could contain a reference.
if (!ownership || ownership.scope !== 'channel') continue;
const latestDmMessage = latestDmMessageByUser.get(ownership.user_id);
if (latestDmMessage && latestDmMessage >= ownership.created_at) continue;
if (findProtectedFilenameReference.get(relPath, relPath, relPath)) continue;
moveUploadToDeleted(relPath);
}
}
// ── Per-member upload accounting (#5521) ─────────────────
// Admins could see the total size of uploads/ but never who filled it, so one
// person quietly using the server as personal cloud storage was invisible
// unless you went and read the directory yourself. DM attachments made that
// worse: the file bytes are encrypted client-side and the message that links
// them is E2E ciphertext, so nothing the server can read connects a private
// upload to the person who made it. Recording the owner at the moment of
// upload is the only place that link still exists.
function recordUploadOwnership(userId, relPath, bytes, scope = 'channel') {
if (!Number.isInteger(userId) || !isSafeUploadRelPath(relPath)) return;
try {
const { getDb } = require('./src/database');
getDb().prepare(
'INSERT OR REPLACE INTO upload_ownership (rel_path, user_id, bytes, scope) VALUES (?, ?, ?, ?)'
).run(relPath, userId, Number.isFinite(bytes) ? Math.max(0, Math.round(bytes)) : 0,
['channel', 'dm', 'profile'].includes(scope) ? scope : 'channel');
} catch (err) {
// Accounting is a reporting nicety; never fail a working upload over it.
console.warn('[uploads] ownership record failed:', err.message);
}
}
// The uploader's chosen scope only ever narrows what we already know from the
// endpoint, so a client that lies about it can shift its own bytes between the
// public and private columns of its own row. It cannot move them onto someone
// else, and the total (the number that matters here) is unaffected.
function uploadScopeFromRequest(req, fallback = 'channel') {
const raw = typeof req.body?.scope === 'string' ? req.body.scope.trim().toLowerCase() : '';
return ['channel', 'dm', 'profile'].includes(raw) ? raw : fallback;
}
// Walk the live uploads tree once and total it per owner. Reading sizes from
// disk rather than trusting the stored byte count means a deleted, purged, or
// moved-to-deleted-attachments file drops out on its own, with no delete hook to
// keep in sync, and no drift between the report and reality.
let _uploadUsageCache = null;
function getUploadUsage() {
if (_uploadUsageCache && Date.now() - _uploadUsageCache.at < 60_000) return _uploadUsageCache.data;
const sizes = new Map(); // relPath → bytes
const walk = (dir, rel) => {
let entries;
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
for (const entry of entries) {
// Deleted attachments and temporary bot audio are not live member storage.
if (!rel && ['bot-audio', 'deleted-attachments'].includes(entry.name)) continue;
const sub = rel ? `${rel}/${entry.name}` : entry.name;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) { walk(full, sub); continue; }
try { sizes.set(sub, fs.statSync(full).size); } catch { /* vanished mid-walk */ }
}
};
walk(UPLOADS_DIR, '');
const byUser = new Map(); // userId → { total, channel, dm, profile, files }
let attributedBytes = 0;
try {
const { getDb } = require('./src/database');
const rows = getDb().prepare('SELECT rel_path, user_id, scope FROM upload_ownership').all();
for (const row of rows) {
if (row.user_id === null) continue;
const bytes = sizes.get(row.rel_path);
if (bytes === undefined) continue; // gone from disk, so stop counting it
let entry = byUser.get(row.user_id);
if (!entry) { entry = { total: 0, channel: 0, dm: 0, profile: 0, files: 0 }; byUser.set(row.user_id, entry); }
entry.total += bytes;
entry[['channel', 'dm', 'profile'].includes(row.scope) ? row.scope : 'channel'] += bytes;
entry.files++;
attributedBytes += bytes;
}
} catch { /* table missing on a database that has not migrated yet */ }
let liveBytes = 0;
for (const bytes of sizes.values()) liveBytes += bytes;
// Uploads made before this shipped have no owner row, so they land here
// rather than being silently spread across members who did not make them.
const data = {
byUser,
liveBytes,
attributedBytes,
unattributedBytes: Math.max(0, liveBytes - attributedBytes),
fileCount: sizes.size
};
_uploadUsageCache = { at: Date.now(), data };
return data;
}
// 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.
// Entries are split into exact addresses (fast Set lookup, the common case)
// and CIDR ranges (linear scan, expected to stay small). Both sides are run
// through normalizeIp so a ban written as "1.2.3.4" also stops the socket
// path, which sees "::ffff:1.2.3.4" on a dual-stack listener. Before v3.42.0
// those two never compared equal and bans silently only half-applied.
const _clientIp = require('./src/clientIp');
let _ipBanCache = { set: new Set(), cidrs: [], expires: 0 };
function _refreshIpBanCache() {
try {
const { getDb } = require('./src/database');
const rows = getDb().prepare('SELECT ip FROM ip_bans').all();
const set = new Set(), cidrs = [];
for (const r of rows) {
if (!r.ip) continue;
if (r.ip.includes('/')) cidrs.push(r.ip);
else set.add(_clientIp.normalizeIp(r.ip));
}
_ipBanCache = { set, cidrs, expires: Date.now() + 30000 };
} catch { _ipBanCache = { set: new Set(), cidrs: [], expires: Date.now() + 30000 }; }
}
function invalidateIpBanCache() { _ipBanCache.expires = 0; }
function isIpBanned(ip) {
if (!ip) return false;
if (Date.now() > _ipBanCache.expires) _refreshIpBanCache();
const norm = _clientIp.normalizeIp(ip);
if (!norm) return false;
if (_ipBanCache.set.has(norm)) return true;
return _ipBanCache.cidrs.some(c => _clientIp.ipMatches(norm, c));
}
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; }
}
// ── Referrer-Policy (admin-configurable) ─────────────────
// The Referrer-Policy header is sent on every response by the security-headers
// middleware below. Admins can change it from Settings → Security; the value is
// cached in memory (loaded at boot, refreshed when it changes) so we never read
// the DB per request. Default matches the value helmet used to set.
//
// Two of the eight standard policies are deliberately NOT offered: 'unsafe-url'
// (sends the full URL to every site, always) and 'no-referrer-when-downgrade'
// (sends the full URL to any cross-origin HTTPS site). Haven puts secrets in
// the query string — invite links arrive as ?invite=CODE and deep links as
// ?channel=CODE&message=ID — and they are only scrubbed by replaceState once
// the socket connects. Under either policy, an externally hosted image in the
// channel would carry that invite code to its host in the Referer header on
// first paint. The six kept here all stop at the origin cross-origin, which is
// enough for the case this setting exists for (CDNs like X/Twitter that reject
// a cross-origin referrer on video). Anything not in this list falls back to
// the default below, so a value saved before this list was narrowed degrades
// safely instead of persisting.
// Keep in sync with the validation list in src/socketHandlers/admin.js.
const VALID_REFERRER_POLICIES = ['no-referrer', 'origin', 'origin-when-cross-origin', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin'];
// Default is 'same-origin' as of 3.41.0, up from the 'strict-origin-when-cross-origin'
// helmet used to set. Sending the origin cross-origin is enough for X's video CDN to
// return 403, so Twitter/X embeds showed a thumbnail and a dead play button on every
// Haven server out of the box. 'same-origin' sends nothing cross-origin, which fixes
// that and shares strictly less than before. Admins who need the old behaviour (a host
// that uses the referrer for hotlink protection) can pick it in Settings → Security.
const DEFAULT_REFERRER_POLICY = 'same-origin';
let currentReferrerPolicy = DEFAULT_REFERRER_POLICY;
// ── Security Headers (helmet) ────────────────────────────
// ── Do we serve TLS ourselves? ───────────────────────────
// Resolved here because the security headers below depend on the answer. On
// plain HTTP, telling a browser to upgrade every request to HTTPS breaks the
// page rather than protecting it: the CSS and JS are re-requested over https on
// a port with no TLS listener, so a remote visitor gets an unstyled page with
// dead buttons. It looks perfect to whoever is testing on localhost, which
// browsers treat as trustworthy and never upgrade. A Windows install whose SSL
// step was skipped (no OpenSSL on PATH) lands in exactly that state without
// anyone setting FORCE_HTTP.
let sslCert = process.env.SSL_CERT_PATH;
let sslKey = process.env.SSL_KEY_PATH;
// If not explicitly configured, check if the startup scripts generated certs
if (!sslCert && !sslKey) {
const autoCert = path.join(CERTS_DIR, 'cert.pem');
const autoKey = path.join(CERTS_DIR, 'key.pem');
if (fs.existsSync(autoCert) && fs.existsSync(autoKey)) {
sslCert = autoCert;
sslKey = autoKey;
}
} else {
// Resolve relative paths against the data directory
if (sslCert && !path.isAbsolute(sslCert)) sslCert = path.resolve(DATA_DIR, sslCert);
if (sslKey && !path.isAbsolute(sslKey)) sslKey = path.resolve(DATA_DIR, sslKey);
}
const forceHttp = (process.env.FORCE_HTTP || '').toLowerCase() === 'true';
const useSSL = !!(sslCert && sslKey) && !forceHttp;
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", "https://challenges.cloudflare.com"], // last host: opt-in Turnstile CAPTCHA on registration
styleSrc: ["'self'", "'unsafe-inline'"], // inline styles (fonts are self-hosted, no third-party CDN)
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'"], // self-hosted fonts only (see /public/fonts)
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", "https://challenges.cloudflare.com"], // Listen Together embeds + game iframes + Turnstile widget
baseUri: ["'self'"],
formAction: ["'self'"],
frameAncestors: ["'self'"], // allow mobile app iframe, block third-party clickjacking
...(useSSL ? {} : { upgradeInsecureRequests: null }), // helmet 8.x auto-appends upgrade-insecure-requests; it breaks every page when Haven is not serving TLS
}
},
crossOriginEmbedderPolicy: false, // needed for WebRTC
crossOriginOpenerPolicy: false, // needed for WebRTC
hsts: useSSL ? { maxAge: 31536000, includeSubDomains: false } : false, // force HTTPS for 1 year (only sent when we actually serve it)
referrerPolicy: false, // set dynamically from the admin-configurable cache in the middleware below
}));
// 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');
res.setHeader('Referrer-Policy', currentReferrerPolicy); // admin-configurable (Settings → Security)
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' }));
// ── Self-hosted fonts (long-lived cache) ─────────────────
// Fonts never change for a given filename, so let clients cache them for a
// year and skip revalidation. A ?v= bump in style.css busts the cache when a
// file is ever replaced. Mounted before the general /public handler so these
// win over its always-revalidate (maxAge:0) policy.
app.use('/fonts', express.static(path.join(__dirname, 'public', 'fonts'), {
dotfiles: 'deny',
maxAge: '1y',
immutable: true,
}));
// ── 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 internal upload folders ─────────────
// Files moved into deleted-attachments are no longer part of any message and
// must stop being reachable, which is the entire point of moving them.
//
// A 404 mounted at the prefix does not achieve that. Express matches the mount
// against the raw path while express.static decodes before it resolves, so
// three shapes walked straight past the guard and served the file:
// /uploads/deleted%2Dattachments/x, /uploads//deleted-attachments/x, and
// /uploads/deleted-attachments%2Fx. Anyone who saw an attachment before it was
// deleted knows its filename, so deletion was not actually revoking access.
//
// Decode the path, resolve it against the uploads root, and check containment,
// so it is the real target on disk being judged rather than the spelling of
// the URL. Compared case-insensitively because NTFS is.
const BLOCKED_UPLOAD_DIRS = ['deleted-attachments', 'bot-audio'].map(
dir => path.resolve(UPLOADS_DIR, dir).toLowerCase()
);
app.use('/uploads', (req, res, next) => {
let decoded;
try { decoded = decodeURIComponent(req.path); } catch { return res.status(400).end(); }
// path.resolve treats a backslash as a separator on Windows and as an
// ordinary filename character on Linux, which is exactly right in both
// cases, so the raw decoded path goes in as-is.
const target = path.resolve(UPLOADS_DIR, '.' + decoded).toLowerCase();
for (const blocked of BLOCKED_UPLOAD_DIRS) {
if (target === blocked || target.startsWith(blocked + path.sep)) return res.status(404).end();
}
return next();
});
// ── 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');
const {
compatibleThemeFiles,
createThemeFileMiddleware,
readThemeMetadataSnapshot,
validatedThemeDefault,
} = require('./src/themeMetadata');
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', createThemeFileMiddleware(THEMES_DIR));
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 {
let published = [];
try {
const row = db.prepare("SELECT value FROM server_settings WHERE key = 'published_themes'").get();
if (row) {
const stored = JSON.parse(row.value);
if (Array.isArray(stored)) published = stored;
}
} catch { /* DB not ready yet or parse error — default to empty */ }
const themes = readThemeMetadataSnapshot(THEMES_DIR)
.map(theme => ({ ...theme, published: theme.compatible && published.includes(theme.file) }));
res.json(themes);
} catch (err) {
console.error('Failed to list themes:', err.message);
res.status(500).json({ error: 'Failed to list themes' });
}
});
// ── 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
});
const botAudioUpload = multer({
storage: multer.diskStorage({
destination: BOT_AUDIO_DIR,
filename: (req, file, cb) => {
const name = `${Date.now()}-${crypto.randomBytes(8).toString('hex')}.upload`;
req.botAudioTempPath = path.join(BOT_AUDIO_DIR, name);
cb(null, name);
}
}),
limits: {
fileSize: MAX_AUDIO_BYTES,
files: 1,
fields: 1,
parts: 3,
fieldSize: 64,
fieldNestingDepth: 0,
headerPairs: 20
}
});
// ── 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);
// ── Rich presence: account linking (Steam / Spotify) ─────
// Mounted here, ahead of static + SPA handling, so /connect/* is never
// swallowed by a catch-all. The activity engine is built later inside
// setupSocketHandlers, hence the getter — see activityRef below.
const activityRef = { engine: null };
const { createConnectRoutes, baseUrl } = require('./src/connectRoutes');
app.use('/connect', createConnectRoutes(() => activityRef.engine));
// ── 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');
const db = getDb();
// An endpoint identifies one browser/device, and only one account can be
// signed into it at a time. The table is UNIQUE(user_id, endpoint), so
// signing in as someone else used to leave the previous account's row
// behind pointing at the same device. Fan-out only skips subscriptions
// whose user_id matches the sender, so that stale row kept getting pushed
// and the sender received their own messages on their own phone. Claim the
// endpoint for this user.
db.transaction(() => {
db.prepare('DELETE FROM push_subscriptions WHERE endpoint = ? AND user_id != ?').run(endpoint, user.id);
db.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' });
// Admin-configured STUN/TURN (#5399) live in server_settings and take
// precedence over env vars, which in turn override the built-in pool.
// Admins can now point at their own servers from Settings → Voice &
// Connectivity without touching env vars or redeploying.
let dbSettings = {};
try {
const { getDb } = require('./src/database');
const rows = getDb().prepare(
"SELECT key, value FROM server_settings WHERE key IN ('ice_servers_json','stun_urls','turn_url','turn_username','turn_password','voice_force_relay')"
).all();
rows.forEach(r => { dbSettings[r.key] = r.value; });
} catch { /* DB not ready — fall back to env/defaults below */ }
// New native WebRTC JSON takes precedence. If it is present but invalid,
// deliberately use the safe built-in STUN defaults rather than partially
// applying a malformed administrator configuration.
const parsedJson = parseIceServersJson(dbSettings.ice_servers_json || '');
let iceServers;
if (parsedJson.configured) {
if (parsedJson.servers) {
iceServers = parsedJson.servers;
} else {
console.warn(`[ICE] Invalid ice_servers_json; using built-in defaults: ${parsedJson.error}`);
iceServers = defaultIceServers();
}
} else {
// Legacy precedence: admin STUN/TURN → environment → built-in defaults.
const adminStun = (dbSettings.stun_urls || '').trim();
const stunUrls = adminStun
? adminStun.split(/[\n,]/).map(u => u.trim()).filter(Boolean)
: process.env.STUN_URLS
? process.env.STUN_URLS.split(',').map(u => u.trim()).filter(Boolean)
: defaultIceServers().map(s => s.urls);
iceServers = stunUrls.map(urls => ({ urls }));
// TURN precedence: admin setting (static creds) → env (supports HMAC secret).
const adminTurn = (dbSettings.turn_url || '').trim();
if (adminTurn) {
const u = (dbSettings.turn_username || '').trim();
const p = (dbSettings.turn_password || '').trim();
if (u && p) iceServers.push({ urls: adminTurn, username: u, credential: p });
else iceServers.push({ urls: adminTurn });
} else {
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) {
iceServers.push({ urls: turnUrl, username: turnUser, credential: turnPass });
} else {
iceServers.push({ urls: turnUrl });
}
}
}
}
// Chrome logs "Using five or more STUN/TURN servers slows down discovery"
// and genuinely gathers candidates more slowly past that point. A TURN relay
// on top of the built-in STUN defaults can land on five, which is
// what dragged out reconnection after a socket flap in #5444 (peers stuck on
// ice=checking). Cap the list at four, dropping STUN entries first so the
// TURN relay — the one that actually traverses strict NAT — always survives.
const MAX_ICE_SERVERS = 4;
if (!parsedJson.configured && iceServers.length > MAX_ICE_SERVERS) {
const turns = iceServers.filter(s => [].concat(s.urls || []).some(isTurnUrl));
const stuns = iceServers.filter(s => ![].concat(s.urls || []).some(isTurnUrl));
const keepStun = Math.max(0, MAX_ICE_SERVERS - turns.length);
const trimmed = [...stuns.slice(0, keepStun), ...turns];
iceServers.length = 0;
iceServers.push(...trimmed);
}
// ── Relay-only mode (v3.42.0) ───────────────────────────
// Haven voice is a peer-to-peer WebRTC mesh, so in the default configuration
// every participant in a call learns every other participant's public IP
// from the ICE candidate exchange. No click, no prompt, nothing the user
// can see. Sitting idle in a voice channel is enough to collect addresses
// from anyone who joins.
//
// iceTransportPolicy 'relay' makes the browser discard host and
// server-reflexive candidates entirely, so peers only ever see the TURN
// server's address. That costs bandwidth (all media flows through TURN) and
// hard-requires a working TURN server, which is why the settings handler
// refuses to turn this on until turn_url is set. Belt-and-braces here too:
// if TURN somehow vanished since the toggle was flipped, serve normal ICE
// rather than handing clients a config that cannot connect at all.