-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
306 lines (266 loc) · 8.5 KB
/
Copy pathserver.js
File metadata and controls
306 lines (266 loc) · 8.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
require('dotenv').config();
const express = require('express');
const { createServer } = require('http');
const { WebSocketServer } = require('ws');
const path = require('path');
const os = require('os');
const fs = require('fs');
const crypto = require('crypto');
const { generateCode, isValidCode } = require('./words');
const { generateOGImage } = require('./og');
// Get local network IP
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return 'localhost';
}
const app = express();
const server = createServer(app);
const wss = new WebSocketServer({ server });
const PORT = process.env.PORT || 3000;
const TURN_SECRET = process.env.TURN_SECRET; // Shared secret from coturn config
const TURN_HOST = process.env.TURN_HOST || '5.223.48.108'; // Your server IP
const TURN_PORT = process.env.TURN_PORT || 3478;
// Room storage: { roomCode: { sharer: ws, viewer: ws } }
const rooms = new Map();
// Generate time-limited TURN credentials using coturn's shared secret method
function getTurnCredentials(name) {
const unixTimeStamp = Math.floor(Date.now() / 1000) + 24 * 3600; // Valid for 24 hours
const username = [unixTimeStamp, name].join(':');
const hmac = crypto.createHmac('sha1', TURN_SECRET);
hmac.setEncoding('base64');
hmac.write(username);
hmac.end();
const password = hmac.read();
return {
username: username,
password: password
};
}
function getIceServers() {
// If no TURN secret is configured, fall back to STUN only
if (!TURN_SECRET) {
console.warn('TURN_SECRET not set, using STUN only');
return {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' }
]
};
}
// Generate fresh credentials
const credentials = getTurnCredentials('hyperframe');
console.log('Generated TURN credentials for relay');
return {
iceServers: [
// Public STUN servers (always available, free)
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' },
// Self-hosted TURN server (for relay when STUN fails)
{
urls: [
`turn:${TURN_HOST}:${TURN_PORT}`,
`turn:${TURN_HOST}:${TURN_PORT}?transport=tcp`
],
username: credentials.username,
credential: credentials.password
}
]
};
}
// Read viewer.html once at startup as a template for dynamic OG tags
const viewerTemplate = fs.readFileSync(path.join(__dirname, 'public', 'viewer.html'), 'utf8');
function serveViewerWithOG(res, code) {
const ogUrl = `https://hyperframe.computer/og/${code}.png`;
const html = viewerTemplate
.replace(/https:\/\/hyperframe\.computer\/images\/graph\.png/g, ogUrl);
res.type('html').send(html);
}
// Subdomain detection middleware
app.use((req, res, next) => {
const host = req.headers.host || '';
const parts = host.split('.');
console.log('[DEBUG] Middleware - Host:', host, '| Parts:', parts.length, '| Parts array:', JSON.stringify(parts));
// Check for subdomain (e.g., machine-cash.hyperframe.computer or machine-cash.localhost:3000)
// For localhost testing, handle: machine-cash.localhost:3000
if (parts.length >= 3) {
const subdomain = parts[0];
// Check if it's a valid room code (word-word format)
if (subdomain.includes('-') && isValidCode(subdomain)) {
console.log('[DEBUG] Valid room code detected:', subdomain);
req.roomCode = subdomain;
}
}
next();
});
// Route: Dynamic OG image per hyperframe code
app.get('/og/:code.png', async (req, res) => {
const code = req.params.code;
if (!isValidCode(code)) {
return res.status(404).send('Invalid code');
}
try {
const buffer = await generateOGImage(code);
res.set('Content-Type', 'image/png');
res.set('Cache-Control', 'public, max-age=86400');
res.send(buffer);
} catch (err) {
console.error('OG image generation error:', err);
res.status(500).send('Image generation failed');
}
});
// Route: Viewer page via path (for LAN access: /view/word-word)
app.get('/view/:code', (req, res) => {
const code = req.params.code;
if (isValidCode(code)) {
serveViewerWithOG(res, code);
} else {
res.status(404).send('Invalid room code');
}
});
// Route: Viewer page (when accessing via subdomain)
app.get('/', (req, res) => {
console.log('[DEBUG] GET / - req.roomCode:', req.roomCode);
if (req.roomCode) {
console.log('[DEBUG] Serving viewer.html for room:', req.roomCode);
serveViewerWithOG(res, req.roomCode);
} else {
console.log('[DEBUG] Serving index.html (sharer page)');
res.sendFile(path.join(__dirname, 'public', 'index.html'));
}
});
// API: Generate a new room code
app.get('/api/new-room', (req, res) => {
let code;
let attempts = 0;
// Generate unique code (not already in use)
do {
code = generateCode();
attempts++;
} while (rooms.has(code) && attempts < 100);
if (attempts >= 100) {
return res.status(503).json({ error: 'No available rooms' });
}
res.json({ code, lanIP: getLocalIP(), port: PORT });
});
// API: Get ICE servers with TURN credentials
app.get('/api/ice-servers', (req, res) => {
try {
const iceConfig = getIceServers();
res.json(iceConfig);
} catch (err) {
console.error('ICE servers error:', err);
res.status(500).json({ error: 'Failed to get ICE servers' });
}
});
// No caching
app.use((req, res, next) => {
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.set('Pragma', 'no-cache');
res.set('Expires', '0');
res.set('Surrogate-Control', 'no-store');
next();
});
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
// WebSocket signaling
wss.on('connection', (ws, req) => {
let currentRoom = null;
let role = null;
ws.on('message', (data) => {
try {
const message = JSON.parse(data);
switch (message.type) {
case 'join':
handleJoin(ws, message.room, message.role);
currentRoom = message.room;
role = message.role;
break;
case 'offer':
case 'answer':
case 'ice-candidate':
case 'sharing-stopped':
relayToRoom(currentRoom, role, message);
break;
default:
console.log('Unknown message type:', message.type);
}
} catch (err) {
console.error('Message parse error:', err);
}
});
ws.on('close', () => {
if (currentRoom) {
handleLeave(currentRoom, role);
}
});
ws.on('error', (err) => {
console.error('WebSocket error:', err);
});
});
function handleJoin(ws, roomCode, role) {
if (!rooms.has(roomCode)) {
rooms.set(roomCode, { sharer: null, viewer: null });
}
const room = rooms.get(roomCode);
if (role === 'sharer') {
if (room.sharer) {
ws.send(JSON.stringify({ type: 'error', message: 'Room already has a sharer' }));
return;
}
room.sharer = ws;
ws.send(JSON.stringify({ type: 'joined', role: 'sharer' }));
// Notify viewer if present
if (room.viewer) {
room.viewer.send(JSON.stringify({ type: 'sharer-joined' }));
}
} else if (role === 'viewer') {
if (room.viewer) {
ws.send(JSON.stringify({ type: 'error', message: 'Room already has a viewer' }));
return;
}
room.viewer = ws;
ws.send(JSON.stringify({ type: 'joined', role: 'viewer' }));
// Notify sharer if present
if (room.sharer) {
room.sharer.send(JSON.stringify({ type: 'viewer-joined' }));
}
}
}
function handleLeave(roomCode, role) {
const room = rooms.get(roomCode);
if (!room) return;
if (role === 'sharer') {
room.sharer = null;
if (room.viewer) {
room.viewer.send(JSON.stringify({ type: 'sharer-left' }));
}
} else if (role === 'viewer') {
room.viewer = null;
if (room.sharer) {
room.sharer.send(JSON.stringify({ type: 'viewer-left' }));
}
}
// Clean up empty rooms
if (!room.sharer && !room.viewer) {
rooms.delete(roomCode);
}
}
function relayToRoom(roomCode, senderRole, message) {
const room = rooms.get(roomCode);
if (!room) return;
const target = senderRole === 'sharer' ? room.viewer : room.sharer;
if (target && target.readyState === 1) {
target.send(JSON.stringify(message));
}
}
server.listen(PORT, '0.0.0.0', () => {
console.log(`Hyperframe server running on http://localhost:${PORT}`);
console.log(`LAN viewer URL: http://[your-ip]:${PORT}/view/[room-code]`);
});