add WASM browser module and browser demo
This commit is contained in:
212
browser/signaling-server/server.js
Normal file
212
browser/signaling-server/server.js
Normal file
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* zig-p2p Signaling Server
|
||||
*
|
||||
* Simple WebSocket relay that routes SDP offers/answers and ICE candidates
|
||||
* between peers by peerId. No authentication — the Noise handshake over
|
||||
* the resulting WebRTC DataChannel provides mutual authentication.
|
||||
*
|
||||
* Protocol (JSON over WebSocket):
|
||||
*
|
||||
* Client → Server:
|
||||
* { "type": "register", "peerId": "abc123" }
|
||||
* { "type": "offer", "to": "xyz789", "sdp": "v=0..." }
|
||||
* { "type": "answer", "to": "abc123", "sdp": "v=0..." }
|
||||
* { "type": "candidate", "to": "xyz789", "candidate": "...", "sdpMid": "0" }
|
||||
* { "type": "ping" }
|
||||
*
|
||||
* Server → Client:
|
||||
* { "type": "registered", "peerId": "abc123" }
|
||||
* { "type": "offer", "from": "abc123", "sdp": "v=0..." }
|
||||
* { "type": "answer", "from": "xyz789", "sdp": "v=0..." }
|
||||
* { "type": "candidate", "from": "abc123", "candidate": "...", "sdpMid": "0" }
|
||||
* { "type": "error", "message": "peer not found" }
|
||||
* { "type": "pong" }
|
||||
*
|
||||
* Usage:
|
||||
* npm install
|
||||
* node server.js [--port 8080] [--host 0.0.0.0]
|
||||
*/
|
||||
|
||||
import { WebSocketServer } from 'ws';
|
||||
|
||||
// -- Configuration --
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
function getArg(name, defaultVal) {
|
||||
const idx = args.indexOf(name);
|
||||
return idx >= 0 && idx + 1 < args.length ? args[idx + 1] : defaultVal;
|
||||
}
|
||||
|
||||
const PORT = parseInt(getArg('--port', '8080'), 10);
|
||||
const HOST = getArg('--host', '0.0.0.0');
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const STALE_TIMEOUT_MS = 90_000;
|
||||
const MAX_MESSAGE_RATE = 100; // messages per second per client
|
||||
const MAX_MESSAGE_SIZE = 65536; // 64KB max message
|
||||
|
||||
// -- State --
|
||||
|
||||
/** @type {Map<string, WebSocket>} peerId → WebSocket */
|
||||
const peers = new Map();
|
||||
|
||||
/** @type {Map<WebSocket, PeerState>} */
|
||||
const state = new Map();
|
||||
|
||||
/**
|
||||
* @typedef {object} PeerState
|
||||
* @property {string} peerId
|
||||
* @property {number} lastActivity - timestamp ms
|
||||
* @property {number} messageCount - messages in current window
|
||||
* @property {number} windowStart - start of rate limit window
|
||||
*/
|
||||
|
||||
// -- Server --
|
||||
|
||||
const wss = new WebSocketServer({
|
||||
port: PORT,
|
||||
host: HOST,
|
||||
maxPayload: MAX_MESSAGE_SIZE,
|
||||
});
|
||||
|
||||
console.log(`[signaling] Listening on ws://${HOST}:${PORT}`);
|
||||
|
||||
wss.on('connection', (ws) => {
|
||||
state.set(ws, {
|
||||
peerId: null,
|
||||
lastActivity: Date.now(),
|
||||
messageCount: 0,
|
||||
windowStart: Date.now(),
|
||||
});
|
||||
|
||||
ws.on('message', (raw) => {
|
||||
const s = state.get(ws);
|
||||
if (!s) return;
|
||||
|
||||
// Rate limiting
|
||||
const now = Date.now();
|
||||
if (now - s.windowStart > 1000) {
|
||||
s.messageCount = 0;
|
||||
s.windowStart = now;
|
||||
}
|
||||
s.messageCount++;
|
||||
if (s.messageCount > MAX_MESSAGE_RATE) {
|
||||
send(ws, { type: 'error', message: 'rate limit exceeded' });
|
||||
return;
|
||||
}
|
||||
s.lastActivity = now;
|
||||
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(raw.toString());
|
||||
} catch {
|
||||
send(ws, { type: 'error', message: 'invalid JSON' });
|
||||
return;
|
||||
}
|
||||
|
||||
handleMessage(ws, s, msg);
|
||||
});
|
||||
|
||||
ws.on('close', () => {
|
||||
const s = state.get(ws);
|
||||
if (s?.peerId) {
|
||||
peers.delete(s.peerId);
|
||||
console.log(`[signaling] Peer disconnected: ${s.peerId} (${peers.size} online)`);
|
||||
}
|
||||
state.delete(ws);
|
||||
});
|
||||
|
||||
ws.on('error', () => {
|
||||
// Handled by 'close' event
|
||||
});
|
||||
});
|
||||
|
||||
// -- Message handling --
|
||||
|
||||
function handleMessage(ws, s, msg) {
|
||||
switch (msg.type) {
|
||||
case 'register': {
|
||||
const { peerId } = msg;
|
||||
if (!peerId || typeof peerId !== 'string') {
|
||||
send(ws, { type: 'error', message: 'peerId required' });
|
||||
return;
|
||||
}
|
||||
// Disconnect existing peer with same ID
|
||||
const existing = peers.get(peerId);
|
||||
if (existing && existing !== ws) {
|
||||
send(existing, { type: 'error', message: 'replaced by new connection' });
|
||||
existing.close();
|
||||
}
|
||||
s.peerId = peerId;
|
||||
peers.set(peerId, ws);
|
||||
send(ws, { type: 'registered', peerId });
|
||||
console.log(`[signaling] Peer registered: ${peerId} (${peers.size} online)`);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'offer':
|
||||
case 'answer':
|
||||
case 'candidate': {
|
||||
if (!s.peerId) {
|
||||
send(ws, { type: 'error', message: 'must register first' });
|
||||
return;
|
||||
}
|
||||
const { to } = msg;
|
||||
if (!to || typeof to !== 'string') {
|
||||
send(ws, { type: 'error', message: '"to" field required' });
|
||||
return;
|
||||
}
|
||||
const target = peers.get(to);
|
||||
if (!target) {
|
||||
send(ws, { type: 'error', message: 'peer not found' });
|
||||
return;
|
||||
}
|
||||
// Forward with "from" field added
|
||||
const forwarded = { ...msg, from: s.peerId };
|
||||
delete forwarded.to;
|
||||
send(target, forwarded);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'ping':
|
||||
send(ws, { type: 'pong' });
|
||||
break;
|
||||
|
||||
default:
|
||||
send(ws, { type: 'error', message: `unknown type: ${msg.type}` });
|
||||
}
|
||||
}
|
||||
|
||||
function send(ws, msg) {
|
||||
if (ws.readyState === ws.OPEN) {
|
||||
ws.send(JSON.stringify(msg));
|
||||
}
|
||||
}
|
||||
|
||||
// -- Heartbeat / stale cleanup --
|
||||
|
||||
const heartbeatTimer = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [ws, s] of state) {
|
||||
if (now - s.lastActivity > STALE_TIMEOUT_MS) {
|
||||
console.log(`[signaling] Dropping stale peer: ${s.peerId}`);
|
||||
ws.terminate();
|
||||
}
|
||||
}
|
||||
}, HEARTBEAT_INTERVAL_MS);
|
||||
|
||||
// -- Graceful shutdown --
|
||||
|
||||
function shutdown() {
|
||||
console.log('[signaling] Shutting down...');
|
||||
clearInterval(heartbeatTimer);
|
||||
for (const ws of state.keys()) {
|
||||
ws.close();
|
||||
}
|
||||
wss.close(() => {
|
||||
console.log('[signaling] Closed.');
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
Reference in New Issue
Block a user