-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
1939 lines (1708 loc) · 62.1 KB
/
server.js
File metadata and controls
1939 lines (1708 loc) · 62.1 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
import { createServer } from 'http';
import { readFile, mkdir, writeFile, readFile as fsReadFile, stat, rename, unlink, rm } from 'fs/promises';
import { createReadStream } from 'fs';
import { execFile } from 'child_process';
import { promisify } from 'util';
import path from 'path';
import { WebSocketServer } from 'ws';
import Hyperswarm from 'hyperswarm';
import crypto from 'crypto';
import { WebSocket } from 'ws';
import os from 'os';
const execFileAsync = promisify(execFile);
const ARCHIVES_DIR = path.join(process.cwd(), 'archives');
// werift imported dynamically to handle missing native deps gracefully
let werift;
let weriftNonstandard;
try {
werift = await import('werift');
console.log('[SFU] werift loaded successfully');
// Import nonstandard module for MediaRecorder
try {
weriftNonstandard = await import('werift/nonstandard');
console.log('[SFU] werift/nonstandard loaded (MediaRecorder available)');
} catch (e) {
console.warn('[SFU] werift/nonstandard unavailable, recording disabled:', e.message);
}
} catch (e) {
console.warn('[SFU] werift unavailable, WebRTC disabled:', e.message);
}
// --- Load config file (env vars override config.json) ---
let fileConfig = {};
try {
const raw = await readFile(new URL('./config.json', import.meta.url), 'utf8');
fileConfig = JSON.parse(raw);
console.log('[oneye] Loaded config.json');
} catch {
// No config file — use env vars and defaults
}
function conf(envKey, fileKey, fallback) {
return process.env[envKey] ?? fileConfig[fileKey] ?? fallback;
}
const PORT = parseInt(conf('PORT', 'port', '3000'), 10);
const PUBLIC_URL = conf('PUBLIC_URL', 'publicUrl', null);
const TOPIC = crypto.createHash('sha256').update('oneye:live-streams:v1').digest();
const PRESENCE_TTL = 30_000; // 30s expiry for stale streams
const PING_INTERVAL = 30_000;
const RELAY_ANNOUNCE_INTERVAL = 30_000;
// --- ICE/TURN Configuration ---
// Each relay operator configures their own TURN server via env vars.
// Clients receive the ICE config on WebSocket connect.
const ICE_SERVERS = [{ urls: 'stun:stun.l.google.com:19302' }];
const _turnUrl = conf('TURN_URL', 'turnUrl', null);
if (_turnUrl) {
ICE_SERVERS.push({
urls: _turnUrl,
username: conf('TURN_USERNAME', 'turnUsername', ''),
credential: conf('TURN_CREDENTIAL', 'turnCredential', '')
});
console.log(`[ICE] TURN server configured: ${_turnUrl}`);
} else {
console.log('[ICE] No TURN server configured (STUN only). Set TURN_URL, TURN_USERNAME, TURN_CREDENTIAL for NAT traversal.');
}
// --- Security Limits ---
const MAX_WS_CONNECTIONS = parseInt(conf('MAX_WS_CONNECTIONS', 'maxConnections', '500'), 10);
const MAX_WS_MESSAGE_SIZE = 512 * 1024; // 512KB max WebSocket frame
const MAX_WS_MESSAGES_PER_SEC = 30; // rate limit per connection
const MAX_THUMBNAIL_SIZE = 500 * 1024; // 500KB for base64 thumbnails
const MAX_SDP_SIZE = 64 * 1024; // 64KB for SDP payloads
const MAX_TITLE_LENGTH = 200;
const MAX_TAG_COUNT = 10;
const MAX_TAG_LENGTH = 30;
const MAX_CHAT_MESSAGE_LENGTH = 500;
const _originsRaw = conf('ALLOWED_ORIGINS', 'allowedOrigins', null);
const ALLOWED_ORIGINS = typeof _originsRaw === 'string'
? _originsRaw.split(',').map(s => s.trim())
: (Array.isArray(_originsRaw) ? _originsRaw : null);
// Generate relay keypair for signing relay announcements
const relayKeyPair = crypto.generateKeyPairSync('ed25519');
const relayPubkeyHex = relayKeyPair.publicKey.export({ type: 'spki', format: 'der' }).subarray(12).toString('hex');
// --- State ---
const streams = new Map(); // streamId -> { presence, producers: Map<trackId, MediaStreamTrack>, consumers: Set<ws>, remote?, originRelay? }
const clients = new Map(); // ws -> { pubkey, subscribed, peerConnection, role }
const knownRelays = new Map(); // url -> { url, pubkey, lastSeen, latency }
const forwarders = new Map(); // streamId -> Set<{ ws, peerId, slots }>
const originConnections = new Map(); // streamId -> WebSocket (for cross-relay forwarding)
// --- Get public relay URL ---
function getPublicUrl() {
if (PUBLIC_URL) return PUBLIC_URL;
// Try to construct from hostname
const hostname = os.hostname();
const proto = PORT === 443 ? 'wss' : 'ws';
return `${proto}://${hostname}:${PORT}`;
}
// --- Security Helpers ---
function securityHeaders(extra = {}) {
const headers = {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=(self)',
...extra
};
if (PUBLIC_URL?.startsWith('wss://') || conf('FORCE_HSTS', 'forceHsts', null)) {
headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains';
}
return headers;
}
function corsOrigin(req) {
if (!ALLOWED_ORIGINS) return '*';
const origin = req.headers.origin;
return ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0];
}
// --- HTTP Server ---
const server = createServer(async (req, res) => {
// CORS preflight — early return before route matching
if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Access-Control-Allow-Origin': corsOrigin(req),
'Access-Control-Allow-Methods': 'GET, OPTIONS, DELETE',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '86400',
...securityHeaders()
});
res.end();
return;
}
const url = new URL(req.url, `http://${req.headers.host}`);
const pathname = url.pathname;
// Serve index.html for root or /index.html (supports subpath deployment)
if (pathname === '/' || pathname.endsWith('/index.html') || pathname.endsWith('/')) {
try {
const html = await readFile(new URL('./index.html', import.meta.url));
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Security-Policy': "default-src 'self' 'unsafe-inline' data: blob: wss: ws: https:; img-src 'self' data: blob: https:; media-src 'self' blob: https:; connect-src 'self' wss: ws: https:; object-src 'none'; base-uri 'self'",
...securityHeaders()
});
res.end(html);
} catch {
res.writeHead(500, securityHeaders());
res.end('index.html not found');
}
} else if (pathname === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json', ...securityHeaders() });
res.end(JSON.stringify({
ok: true,
streams: streams.size,
clients: clients.size,
relays: knownRelays.size,
forwarders: forwarders.size
}));
} else if (pathname === '/.well-known/oneye.json') {
// Well-known endpoint for relay discovery (Phase 5.1)
res.writeHead(200, { 'Content-Type': 'application/json', ...securityHeaders() });
res.end(JSON.stringify({
relays: [
{ url: getPublicUrl(), pubkey: relayPubkeyHex },
...Array.from(knownRelays.values()).map(r => ({ url: r.url, pubkey: r.pubkey }))
]
}));
} else if (pathname === '/relays') {
// Relay list endpoint
res.writeHead(200, { 'Content-Type': 'application/json', ...securityHeaders() });
res.end(JSON.stringify({
self: { url: getPublicUrl(), pubkey: relayPubkeyHex },
peers: Array.from(knownRelays.values())
}));
} else if (pathname === '/client-metadata.json') {
// OAuth client metadata for Bluesky AT Protocol OAuth
const proto = req.headers['x-forwarded-proto'] || (PORT === 443 ? 'https' : 'http');
const host = req.headers['x-forwarded-host'] || req.headers.host;
const baseUrl = `${proto}://${host}`;
res.writeHead(200, { 'Content-Type': 'application/json', ...securityHeaders() });
res.end(JSON.stringify({
client_id: `${baseUrl}/client-metadata.json`,
client_name: 'oneye Live Streaming',
client_uri: baseUrl,
redirect_uris: [`${baseUrl}/`],
scope: 'atproto transition:generic',
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
token_endpoint_auth_method: 'none',
application_type: 'web',
dpop_bound_access_tokens: true
}));
} else if (pathname === '/archives') {
// Serve archive index
try {
const indexPath = path.join(ARCHIVES_DIR, 'index.json');
const data = await fsReadFile(indexPath);
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': corsOrigin(req),
...securityHeaders()
});
res.end(data);
} catch {
res.writeHead(200, { 'Content-Type': 'application/json', ...securityHeaders() });
res.end(JSON.stringify({ version: 1, archives: [] }));
}
} else if (pathname.match(/^\/archives\/[^/]+\/delete$/) && req.method === 'POST') {
// Delete an archive by streamId (POST to avoid Cloudflare OPTIONS interception)
const streamId = pathname.split('/')[2];
if (!/^[a-f0-9]+$/.test(streamId)) {
res.writeHead(400, { 'Content-Type': 'application/json', ...securityHeaders() });
res.end(JSON.stringify({ error: 'Invalid archive ID' }));
return;
}
const archiveDir = path.join(ARCHIVES_DIR, streamId);
if (!archiveDir.startsWith(ARCHIVES_DIR + path.sep)) {
res.writeHead(403, securityHeaders());
res.end('Forbidden');
return;
}
try {
await rm(archiveDir, { recursive: true, force: true });
// Update index.json — remove the deleted entry
const indexPath = path.join(ARCHIVES_DIR, 'index.json');
try {
const index = JSON.parse(await fsReadFile(indexPath, 'utf8'));
index.archives = (index.archives || []).filter(a => a.id !== streamId);
index.updatedAt = Date.now();
await writeFile(indexPath, JSON.stringify(index, null, 2));
} catch {}
console.log(`[Archives] Deleted: ${streamId.slice(0, 8)}`);
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': corsOrigin(req),
...securityHeaders()
});
res.end(JSON.stringify({ ok: true, id: streamId }));
} catch (e) {
console.error(`[Archives] Delete failed: ${e.message}`);
res.writeHead(500, { 'Content-Type': 'application/json', ...securityHeaders() });
res.end(JSON.stringify({ error: 'Delete failed' }));
}
} else if (pathname.startsWith('/archives/')) {
// Serve recording files
const relativePath = pathname.slice('/archives/'.length);
const filePath = path.join(ARCHIVES_DIR, relativePath);
// Security check - prevent directory traversal
if (!filePath.startsWith(ARCHIVES_DIR + path.sep)) {
res.writeHead(403, securityHeaders());
res.end('Forbidden');
return;
}
try {
const fileStat = await stat(filePath);
const ext = path.extname(filePath).toLowerCase();
const contentTypes = {
'.webm': 'video/webm',
'.json': 'application/json',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.webp': 'image/webp'
};
res.writeHead(200, {
'Content-Type': contentTypes[ext] || 'application/octet-stream',
'Content-Length': fileStat.size,
'Access-Control-Allow-Origin': corsOrigin(req),
...securityHeaders()
});
createReadStream(filePath).pipe(res);
} catch {
res.writeHead(404, securityHeaders());
res.end('Not found');
}
} else if (pathname === '/embed' || pathname === '/embed/') {
// Embeddable player — omit X-Frame-Options so it can be iframed
const embedHeaders = securityHeaders();
delete embedHeaders['X-Frame-Options'];
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8',
'Content-Security-Policy': "default-src 'self' 'unsafe-inline' data: blob: wss: ws: https:; img-src 'self' data: blob: https:; media-src 'self' blob:; connect-src 'self' wss: ws: https:; object-src 'none'; base-uri 'self'",
...embedHeaders
});
res.end(generateEmbedHtml());
} else {
res.writeHead(404, securityHeaders());
res.end('Not found');
}
});
// --- WebSocket Server ---
const wss = new WebSocketServer({ server, maxPayload: MAX_WS_MESSAGE_SIZE });
wss.on('connection', (ws) => {
// --- Connection limit ---
if (clients.size >= MAX_WS_CONNECTIONS) {
ws.close(1013, 'Server at capacity');
return;
}
const clientState = {
pubkey: null, subscribed: false, peerConnection: null, role: null, streamId: null,
msgTokens: MAX_WS_MESSAGES_PER_SEC, msgLastRefill: Date.now()
};
clients.set(ws, clientState);
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
// Send ICE config so client uses this relay's TURN server
send(ws, { type: 'ice_servers', iceServers: ICE_SERVERS });
ws.on('message', (data) => {
// --- Rate limit ---
const state = clients.get(ws);
const now = Date.now();
if (now - state.msgLastRefill >= 1000) {
state.msgTokens = MAX_WS_MESSAGES_PER_SEC;
state.msgLastRefill = now;
}
if (state.msgTokens <= 0) {
return send(ws, { type: 'error', message: 'Rate limited' });
}
state.msgTokens--;
let msg;
try {
msg = JSON.parse(data);
} catch {
return send(ws, { type: 'error', message: 'Invalid JSON' });
}
// Reduce noise from frequent messages
if (!['candidate', 'bandwidth_report', 'ping', 'thumbnail', 'chat'].includes(msg.type)) {
console.log(`[WS] Received: ${msg.type}`);
}
handleMessage(ws, msg);
});
ws.on('close', () => {
handleDisconnect(ws);
clients.delete(ws);
broadcastRelayStats();
});
ws.on('error', () => {
handleDisconnect(ws);
clients.delete(ws);
broadcastRelayStats();
});
// Include relay list in welcome (Phase 1.3)
const streamList = getStreamList();
console.log(`[Welcome] New client, sending ${streamList.length} streams`);
const stats = getRelayStats();
send(ws, {
type: 'welcome',
streams: streamList,
relays: getRelayList(),
...stats
});
// Broadcast updated client count to all
broadcastRelayStats();
});
// Ping interval
const pingTimer = setInterval(() => {
wss.clients.forEach((ws) => {
if (!ws.isAlive) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, PING_INTERVAL);
wss.on('close', () => clearInterval(pingTimer));
// --- Message Handlers ---
function handleMessage(ws, msg) {
switch (msg.type) {
case 'subscribe':
return handleSubscribe(ws, msg);
case 'announce':
return handleAnnounce(ws, msg);
case 'unannounce':
return handleUnannounce(ws, msg);
case 'view':
return handleView(ws, msg);
case 'stop_viewing':
return handleStopViewing(ws, msg);
case 'signal_forward':
return handleSignalForward(ws, msg);
case 'answer':
return handleAnswer(ws, msg);
case 'candidate':
return handleCandidate(ws, msg);
// Phase 3.3: Bandwidth reporting for layer selection
case 'bandwidth_report':
return handleBandwidthReport(ws, msg);
// Phase 4: Mesh forwarding
case 'can_forward':
return handleCanForward(ws, msg);
case 'forward_stopped':
return handleForwardStopped(ws, msg);
case 'forward_slots':
return handleForwardSlots(ws, msg);
case 'forward_candidate':
return handleForwardCandidate(ws, msg);
case 'chat':
return handleChat(ws, msg);
case 'thumbnail':
return handleThumbnail(ws, msg);
case 'ping':
return send(ws, { type: 'pong' });
default:
return send(ws, { type: 'error', message: `Unknown type: ${msg.type}` });
}
}
function handleSubscribe(ws, msg) {
const state = clients.get(ws);
if (msg.pubkey) state.pubkey = msg.pubkey;
state.subscribed = true;
// Include relay list (Phase 1.3)
send(ws, {
type: 'subscribed',
streams: getStreamList(),
relays: getRelayList()
});
}
function handleUnannounce(ws, msg) {
const { streamId } = msg;
const state = clients.get(ws);
console.log(`[Unannounce] Stream ${streamId?.slice(0,8)} ending`);
// Verify this client owns the stream
if (state.streamId !== streamId) {
return send(ws, { type: 'error', message: 'Not your stream' });
}
const stream = streams.get(streamId);
if (stream) {
// Stop recording if active
if (stream.recording) {
stopRecording(streamId, stream);
}
// Close producer PC
if (stream.producerPC) {
try { stream.producerPC.close(); } catch {}
}
// Notify consumers
stream.consumers.forEach((viewer) => {
send(viewer, { type: 'stream_gone', streamId });
const viewerState = clients.get(viewer);
if (viewerState?.consumerPC) {
try { viewerState.consumerPC.close(); } catch {}
viewerState.consumerPC = null;
}
});
// Clean up
forwarders.delete(streamId);
streams.delete(streamId);
broadcast({ type: 'stream_gone', streamId }, ws);
console.log(`[Unannounce] Stream removed, total: ${streams.size}`);
}
// Reset client state
state.role = null;
state.streamId = null;
send(ws, { type: 'unannounced', streamId });
broadcastRelayStats();
}
async function handleAnnounce(ws, msg) {
console.log('[Announce] Processing announce request');
const { presence } = msg;
if (!presence || !presence.pubkey || !presence.signature || !presence.stream) {
console.log('[Announce] Invalid presence packet:', { presence: !!presence, pubkey: !!presence?.pubkey, sig: !!presence?.signature, stream: !!presence?.stream });
return send(ws, { type: 'error', message: 'Invalid presence packet' });
}
// Verify Ed25519 signature
const valid = await verifyPresence(presence);
if (!valid) {
console.log('[Announce] Signature verification failed');
return send(ws, { type: 'error', message: 'Invalid signature' });
}
const streamId = presence.stream.id;
// --- Input validation ---
if (typeof presence.stream.title === 'string' && presence.stream.title.length > MAX_TITLE_LENGTH) {
return send(ws, { type: 'error', message: `Title exceeds ${MAX_TITLE_LENGTH} chars` });
}
if (Array.isArray(presence.stream.tags)) {
if (presence.stream.tags.length > MAX_TAG_COUNT) {
return send(ws, { type: 'error', message: `Max ${MAX_TAG_COUNT} tags allowed` });
}
if (presence.stream.tags.some(t => typeof t !== 'string' || t.length > MAX_TAG_LENGTH)) {
return send(ws, { type: 'error', message: `Tags must be strings of max ${MAX_TAG_LENGTH} chars` });
}
}
const state = clients.get(ws);
state.pubkey = presence.pubkey;
state.role = 'broadcaster';
state.streamId = streamId;
// Check if stream already exists (created by signal_forward race condition)
const existing = streams.get(streamId);
if (existing) {
// Update presence but keep existing tracks and PC
existing.presence = presence;
existing.lastSeen = Date.now();
} else {
streams.set(streamId, {
presence,
producerPC: null,
producerTracks: [],
consumers: new Set(),
lastSeen: Date.now(),
recording: presence.stream.recording ? {
startedAt: Date.now(),
dir: path.join(ARCHIVES_DIR, streamId),
recorder: null,
pendingTracks: [],
peakViewers: 0
} : null
});
}
// Notify all subscribers
broadcast({ type: 'stream_available', presence }, ws);
// Announce to DHT
announceToSwarm(presence);
send(ws, { type: 'announced', streamId });
broadcastRelayStats();
console.log(`[Announce] Stream ${streamId.slice(0, 8)} from ${presence.pubkey.slice(0, 8)}, total streams: ${streams.size}, broadcasting to ${clients.size - 1} clients`);
}
async function handleView(ws, msg) {
const { streamId, viaForwarder } = msg;
console.log(`[View] Viewer requesting stream ${streamId?.slice(0,8)}`);
const stream = streams.get(streamId);
if (!stream) {
console.log('[View] Stream not found');
return send(ws, { type: 'error', message: 'Stream not found' });
}
console.log(`[View] Stream found, remote=${stream.remote}, tracks=${stream.producerTracks?.length}`);
const state = clients.get(ws);
// Clean up existing consumer PC if re-viewing - release tracks first
if (state.consumerPC) {
console.log('[View] Closing existing consumer PC before creating new one');
try {
// Stop all senders to release tracks before closing
const transceivers = state.consumerPC.getTransceivers?.() || [];
for (const t of transceivers) {
try {
if (t.sender?.track) {
t.sender.replaceTrack(null);
}
t.stop?.();
} catch {}
}
state.consumerPC.close();
} catch (e) {
console.log('[View] Error closing old PC:', e.message);
}
state.consumerPC = null;
}
// Also remove from consumers if already there (prevents duplicate)
stream.consumers.delete(ws);
state.role = 'viewer';
state.streamId = streamId;
stream.consumers.add(ws);
// Track peak viewers for recording
if (stream.recording) {
stream.recording.peakViewers = Math.max(
stream.recording.peakViewers,
stream.consumers.size
);
}
// Broadcast updated viewer count
broadcastViewerCount(streamId);
broadcastRelayStats();
// Phase 4: Check if we should route through a mesh forwarder
if (viaForwarder) {
const forwarder = getForwarderForStream(streamId, viaForwarder);
if (forwarder) {
return routeThroughForwarder(ws, forwarder, streamId);
}
}
// Check if stream is remote and we need to connect to origin relay (Phase 2.1)
if (stream.remote && stream.presence?.relay) {
// Check if viewer wants mesh routing
if (!viaForwarder && shouldUseMesh(streamId)) {
const forwarder = selectBestForwarder(streamId);
if (forwarder) {
return routeThroughForwarder(ws, forwarder, streamId);
}
}
return connectToOriginRelay(ws, stream);
}
// If we have a producer PC with tracks, create a consumer offer
if (stream.producerTracks.length > 0 && werift) {
await createConsumerOffer(ws, stream);
} else {
send(ws, { type: 'waiting', streamId, message: 'Waiting for broadcaster tracks' });
}
}
function handleStopViewing(ws, msg) {
const { streamId } = msg;
const state = clients.get(ws);
console.log(`[View] Viewer stopped watching stream ${streamId?.slice(0,8)}`);
// Clean up consumer PC - stop transceivers first to release tracks
if (state.consumerPC) {
try {
// Stop all senders to release tracks before closing
const transceivers = state.consumerPC.getTransceivers?.() || [];
for (const t of transceivers) {
try {
if (t.sender?.track) {
t.sender.replaceTrack(null);
}
t.stop?.();
} catch {}
}
state.consumerPC.close();
} catch (e) {
console.log('[View] Error cleaning up consumer PC:', e.message);
}
state.consumerPC = null;
}
// Remove from consumers and update count
const stream = streams.get(streamId);
if (stream && stream.consumers.has(ws)) {
stream.consumers.delete(ws);
broadcastViewerCount(streamId);
}
// Reset viewer state but keep connection open
if (state.role === 'viewer') {
state.role = null;
state.streamId = null;
broadcastRelayStats();
}
}
// --- Cross-Relay Streaming (Phase 2.1) ---
async function connectToOriginRelay(viewerWs, stream) {
const originUrl = stream.presence.relay;
const streamId = stream.presence.stream.id;
// Check if we already have a connection to this origin
let originWs = originConnections.get(streamId);
if (!originWs || originWs.readyState !== WebSocket.OPEN) {
try {
console.log(`[Cross-Relay] Connecting to origin relay: ${originUrl}`);
originWs = new WebSocket(originUrl);
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('Connection timeout')), 10000);
originWs.onopen = () => {
clearTimeout(timeout);
originConnections.set(streamId, originWs);
resolve();
};
originWs.onerror = (e) => {
clearTimeout(timeout);
reject(e);
};
});
// Set up message relay
originWs.onmessage = (e) => {
try {
const msg = JSON.parse(e.data);
handleOriginMessage(viewerWs, streamId, msg);
} catch {}
};
originWs.onclose = () => {
originConnections.delete(streamId);
// Notify viewer
send(viewerWs, { type: 'stream_gone', streamId });
};
} catch (e) {
console.error('[Cross-Relay] Failed to connect to origin:', e.message);
return send(viewerWs, { type: 'error', message: 'Origin relay unreachable' });
}
}
// Request stream from origin
originWs.send(JSON.stringify({
type: 'view',
streamId,
fromRelay: getPublicUrl()
}));
}
function handleOriginMessage(viewerWs, streamId, msg) {
// Forward signaling messages from origin relay to viewer
if (msg.type === 'signal' || msg.type === 'candidate') {
send(viewerWs, { ...msg, streamId });
} else if (msg.type === 'error') {
send(viewerWs, msg);
}
}
// --- Mesh Forwarding (Phase 4) ---
function handleCanForward(ws, msg) {
const { streamId, slots } = msg;
const state = clients.get(ws);
if (!forwarders.has(streamId)) {
forwarders.set(streamId, new Set());
}
forwarders.get(streamId).add({
ws,
peerId: state.pubkey,
slots: slots || 3
});
console.log(`[Mesh] Forwarder registered for stream ${streamId.slice(0, 8)}, slots: ${slots}`);
}
function handleForwardStopped(ws, msg) {
const { streamId } = msg;
const state = clients.get(ws);
const streamForwarders = forwarders.get(streamId);
if (streamForwarders) {
for (const f of streamForwarders) {
if (f.ws === ws || f.peerId === state.pubkey) {
streamForwarders.delete(f);
break;
}
}
if (streamForwarders.size === 0) {
forwarders.delete(streamId);
}
}
}
function handleForwardSlots(ws, msg) {
const { streamId, slots } = msg;
const state = clients.get(ws);
const streamForwarders = forwarders.get(streamId);
if (streamForwarders) {
for (const f of streamForwarders) {
if (f.ws === ws || f.peerId === state.pubkey) {
f.slots = slots;
break;
}
}
}
}
function handleForwardCandidate(ws, msg) {
const { targetPeer, candidate, streamId } = msg;
// Forward ICE candidate to the target peer in mesh network
for (const [clientWs, clientState] of clients) {
if (clientState.pubkey === targetPeer) {
send(clientWs, {
type: 'forward_candidate',
candidate,
streamId,
fromPeer: clients.get(ws)?.pubkey
});
break;
}
}
}
function shouldUseMesh(streamId) {
// Use mesh if stream has many viewers and forwarders available
const stream = streams.get(streamId);
if (!stream) return false;
const viewerCount = stream.consumers.size;
const forwarderCount = forwarders.get(streamId)?.size || 0;
// Enable mesh when > 5 viewers and forwarders available
return viewerCount > 5 && forwarderCount > 0;
}
function getForwarderForStream(streamId, targetPeerId) {
const streamForwarders = forwarders.get(streamId);
if (!streamForwarders) return null;
for (const f of streamForwarders) {
if (f.peerId === targetPeerId && f.slots > 0) {
return f;
}
}
return null;
}
function selectBestForwarder(streamId) {
const streamForwarders = forwarders.get(streamId);
if (!streamForwarders || streamForwarders.size === 0) return null;
// Select forwarder with most available slots
let best = null;
for (const f of streamForwarders) {
if (f.slots > 0 && (!best || f.slots > best.slots)) {
best = f;
}
}
return best;
}
async function routeThroughForwarder(viewerWs, forwarder, streamId) {
// Decrement forwarder slots
forwarder.slots--;
// Tell the forwarder to expect a new downstream peer
send(forwarder.ws, {
type: 'forward_request',
streamId,
viewerPubkey: clients.get(viewerWs)?.pubkey
});
// Tell viewer which forwarder to connect to
send(viewerWs, {
type: 'use_forwarder',
streamId,
forwarderPubkey: forwarder.peerId
});
}
// --- Thumbnail Handling ---
function handleThumbnail(ws, msg) {
const { streamId, data } = msg;
const state = clients.get(ws);
// Verify this is the broadcaster for this stream
if (state.role !== 'broadcaster' || state.streamId !== streamId) {
return;
}
const stream = streams.get(streamId);
if (!stream) return;
// Validate thumbnail size and format
if (typeof data !== 'string' || data.length > MAX_THUMBNAIL_SIZE) return;
if (!/^data:image\/(jpeg|png|webp);base64,[A-Za-z0-9+/=]+$/.test(data)) return;
// Store thumbnail with stream
stream.thumbnail = data;
// Broadcast to all subscribers
broadcast({ type: 'thumbnail', streamId, data }, ws);
}
// --- Chat ---
function handleChat(ws, msg) {
const { streamId, text } = msg;
const state = clients.get(ws);
if (!streamId || !streams.has(streamId)) {
return send(ws, { type: 'error', message: 'Stream not found' });
}
if (typeof text !== 'string' || text.length === 0 || text.length > MAX_CHAT_MESSAGE_LENGTH) {
return send(ws, { type: 'error', message: 'Invalid chat message' });
}
if (!state.pubkey) {
return send(ws, { type: 'error', message: 'Not subscribed' });
}
const chatMsg = { type: 'chat', streamId, text, pubkey: state.pubkey, ts: Date.now() };
// Relay to all clients subscribed to this stream
for (const [clientWs, clientState] of clients) {
if (clientWs.readyState === 1 && clientState.subscribed) {
send(clientWs, chatMsg);
}
}
}
// --- Bandwidth/Layer Selection (Phase 3.2) ---
function handleBandwidthReport(ws, msg) {
const { bandwidth } = msg;
const state = clients.get(ws);
// Store bandwidth estimate for this viewer
if (!state.bandwidth) state.bandwidth = [];
state.bandwidth.push(bandwidth);
if (state.bandwidth.length > 5) state.bandwidth.shift();
// Calculate average bandwidth
const avgBandwidth = state.bandwidth.reduce((a, b) => a + b, 0) / state.bandwidth.length;
// Select appropriate layer based on bandwidth
// h: > 2Mbps, m: > 500Kbps, l: < 500Kbps
const layer = avgBandwidth > 2000000 ? 'h' :
avgBandwidth > 500000 ? 'm' : 'l';
// Store preferred layer for this viewer
state.preferredLayer = layer;
// If using werift with simulcast, we could configure layer selection here
// (werift-specific implementation would go here)
}
function handleSignalForward(ws, msg) {
const { sdp, streamId } = msg;
console.log(`[Signal] signal_forward received, hasSdp=${!!sdp}`);
if (!sdp || typeof sdp !== 'string' || sdp.length > MAX_SDP_SIZE) return;
const state = clients.get(ws);
// Set role from message if not already set (race condition with announce)
if (!state.role && streamId) {
state.role = 'broadcaster';
state.streamId = streamId;
}
console.log(`[Signal] Client role=${state.role}, streamId=${state.streamId?.slice(0,8)}`);
if (state.role === 'broadcaster') {
handleBroadcasterOffer(ws, msg);
}
}
async function handleAnswer(ws, msg) {
const { sdp } = msg;
if (typeof sdp !== 'string' || sdp.length > MAX_SDP_SIZE) return;
const state = clients.get(ws);
if (state.role === 'viewer' && state.consumerPC) {
try {
await state.consumerPC.setRemoteDescription({ type: 'answer', sdp });
} catch (e) {
console.error('[SFU] Error setting viewer answer:', e.message);
}
}
}
async function handleCandidate(ws, msg) {
const { candidate } = msg;
if (candidate && typeof candidate.candidate === 'string' && candidate.candidate.length > 2048) return;
const state = clients.get(ws);
const pc = state.role === 'broadcaster'
? streams.get(state.streamId)?.producerPC
: state.consumerPC;
if (pc && candidate) {
try {
await pc.addIceCandidate(candidate);
} catch (e) {
// ICE candidate errors are non-fatal
}
}
}
// --- Recording Functions ---
async function startTrackRecording(stream, track) {
if (!weriftNonstandard?.MediaRecorder) {
console.warn('[Recording] MediaRecorder not available');
return;
}
await mkdir(stream.recording.dir, { recursive: true });
// Log track details for debugging
console.log(`[Recording] Track received: ${track.kind}, codec=${track.codec?.name}, payloadType=${track.codec?.payloadType}`);
// Add track to pending tracks