Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
193 lines (162 loc) · 6.32 KB
/
Copy pathserver.js
File metadata and controls
193 lines (162 loc) · 6.32 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
'use strict';
const express = require('express');
const { WebSocketServer } = require('ws');
const https = require('https');
const http = require('http');
const path = require('path');
const os = require('os');
const fs = require('fs');
// ── TLS certificate (auto-generated, persisted on disk) ───────────────────────
// iOS Safari requires HTTPS for getUserMedia (microphone access).
const CERT_DIR = path.join(__dirname, '.cert');
const CERT_KEY = path.join(CERT_DIR, 'key.pem');
const CERT_CRT = path.join(CERT_DIR, 'cert.pem');
let sslOptions;
if (fs.existsSync(CERT_KEY) && fs.existsSync(CERT_CRT)) {
sslOptions = { key: fs.readFileSync(CERT_KEY), cert: fs.readFileSync(CERT_CRT) };
} else {
const { execSync } = require('child_process');
fs.mkdirSync(CERT_DIR, { recursive: true });
execSync(
`openssl req -x509 -newkey rsa:2048 -days 3650 -nodes` +
` -keyout "${CERT_KEY}" -out "${CERT_CRT}"` +
` -subj "/CN=lan-voice-chat"`,
{ stdio: 'pipe' },
);
sslOptions = { key: fs.readFileSync(CERT_KEY), cert: fs.readFileSync(CERT_CRT) };
console.log('[tls] generated new self-signed certificate → .cert/');
}
// ── Servers ───────────────────────────────────────────────────────────────────
const app = express();
const server = https.createServer(sslOptions, app);
const wss = new WebSocketServer({ server });
// HTTP → HTTPS redirect (plain http://ip:3000 → https://ip:3000)
const httpRedirect = http.createServer((req, res) => {
res.writeHead(301, { Location: `https://${req.headers.host}${req.url}` });
res.end();
});
app.use(express.static(path.join(__dirname, 'public')));
// Track connected clients: id -> { ws, name, isAlive }
const clients = new Map();
let nextId = 1;
// ── Helpers ──────────────────────────────────────────────────────────────────
function broadcast(data, excludeId = null) {
const msg = JSON.stringify(data);
for (const [id, client] of clients) {
if (id !== excludeId && client.ws.readyState === 1 /* OPEN */) {
client.ws.send(msg);
}
}
}
function sendTo(targetId, data) {
const client = clients.get(targetId);
if (client && client.ws.readyState === 1) {
client.ws.send(JSON.stringify(data));
}
}
// ── WebSocket connection handling ─────────────────────────────────────────────
wss.on('connection', (ws) => {
const id = nextId++;
clients.set(id, { ws, name: `User ${id}`, isAlive: true });
// Send assigned ID and current room state
ws.send(JSON.stringify({
type: 'welcome',
id,
peers: Array.from(clients.entries())
.filter(([pid]) => pid !== id)
.map(([pid, c]) => ({ id: pid, name: c.name })),
}));
// Notify existing peers about the newcomer
broadcast({ type: 'peer-joined', id, name: clients.get(id).name }, id);
ws.on('message', (raw) => {
let msg;
try { msg = JSON.parse(raw); } catch { return; }
const client = clients.get(id);
if (!client) return;
switch (msg.type) {
case 'pong': {
client.isAlive = true;
break;
}
case 'set-name': {
if (typeof msg.name !== 'string') break;
client.name = msg.name.trim().slice(0, 32) || `User ${id}`;
broadcast({ type: 'peer-renamed', id, name: client.name }, id);
break;
}
// WebRTC signaling — relay to target peer
case 'offer':
case 'answer':
case 'ice-candidate': {
if (typeof msg.target === 'number') {
sendTo(msg.target, { ...msg, from: id });
}
break;
}
}
});
ws.on('close', () => {
clients.delete(id);
broadcast({ type: 'peer-left', id });
});
ws.on('error', (err) => {
console.error(`[ws] client ${id} error:`, err.message);
clients.delete(id);
broadcast({ type: 'peer-left', id });
});
});
// ── Heartbeat: ping every 25s, kill if no pong within 10s ────────────────────
const PING_INTERVAL = 25_000;
const PONG_TIMEOUT = 10_000;
setInterval(() => {
for (const [id, client] of clients) {
if (!client.isAlive) {
// No pong received since last ping — terminate
console.log(`[heartbeat] terminating dead client ${id}`);
client.ws.terminate();
clients.delete(id);
broadcast({ type: 'peer-left', id });
continue;
}
client.isAlive = false;
if (client.ws.readyState === 1) {
client.ws.send(JSON.stringify({ type: 'ping' }));
// Schedule pong-timeout check
setTimeout(() => {
const c = clients.get(id);
if (c && !c.isAlive) {
console.log(`[heartbeat] pong timeout for client ${id}`);
c.ws.terminate();
clients.delete(id);
broadcast({ type: 'peer-left', id });
}
}, PONG_TIMEOUT);
}
}
}, PING_INTERVAL);
// ── Start servers ─────────────────────────────────────────────────────────────
const PORT = parseInt(process.env.PORT || '3000', 10);
const HTTP_PORT = PORT + 1; // plain-HTTP redirect listener
function getLanAddresses() {
const addrs = [];
for (const iface of Object.values(os.networkInterfaces())) {
for (const addr of iface) {
if (addr.family === 'IPv4' && !addr.internal) addrs.push(addr.address);
}
}
return addrs;
}
server.listen(PORT, '0.0.0.0', () => {
const addresses = getLanAddresses();
console.log('\nLAN Voice Chat running (HTTPS)\n');
console.log(` Local: https://localhost:${PORT}`);
for (const addr of addresses) {
console.log(` Network: https://${addr}:${PORT} <-- share this`);
}
console.log('\n NOTE: browsers will show a security warning for the self-signed');
console.log(' certificate. Click "Advanced" → "Proceed" (or "Visit Website" on iOS).');
console.log('\nPress Ctrl+C to stop.\n');
});
httpRedirect.listen(HTTP_PORT, '0.0.0.0', () => {
console.log(`[redirect] http://…:${HTTP_PORT} → https://…:${PORT}`);
});