c64-ready 0.6.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,67 +10,908 @@
10
10
  */
11
11
 
12
12
  import { WebSocketServer } from 'ws';
13
+ import { randomBytes } from 'crypto';
13
14
 
14
15
  /**
15
16
  * @param {Object} opts
16
- * @param {number} [opts.port=9001] - Listen port
17
- * @param {Function} opts.onInput - Called with (inputEvent: object) for each valid message
18
- * @param {boolean} [opts.verbose] - Log connections/messages to stderr
17
+ * @param {number} [opts.port=9001]
18
+ * @param {Function} opts.onInput
19
+ * @param {Function} [opts.onCommand] Called with emulator commands from the host:
20
+ * { type: 'load-crt'|'detach-crt'|'hard-reset', ... }
21
+ * @param {boolean} [opts.verbose]
22
+ * @param {number} [opts.hostTimeoutMs=300000]
23
+ * @param {Function} [opts.validateKickToken]
24
+ * @param {Function} [opts.validateAdminToken]
25
+ * @param {Function} [opts.getRuntimeStats]
26
+ * @param {Function} [opts.getWebrtcPeerSnapshot]
27
+ * @param {Function} [opts.disconnectWebrtcPeersByAddr]
28
+ * @param {Function} [opts.disconnectAllWebrtcPeers]
29
+ * @param {string} [opts.serverVersion] Package version string, e.g. '0.7.0'
30
+ * @param {string} [opts.serverGitHash] Abbreviated git commit hash, e.g. '16e86cd'
19
31
  * @returns {{ wss: WebSocketServer, close: () => Promise<void> }}
20
32
  */
21
33
  export function createInputServer(opts = {}) {
22
- const port = opts.port ?? 9001;
23
- const onInput = opts.onInput;
24
- const verbose = opts.verbose ?? false;
34
+ const port = opts.port ?? 9001;
35
+ const onInput = opts.onInput;
36
+ const onCommand = opts.onCommand ?? (() => {});
37
+ const verbose = opts.verbose ?? false;
38
+ const logEvents = opts.logEvents ?? false;
39
+ const HOST_TIMEOUT = opts.hostTimeoutMs ?? 10 * 60 * 1000;
40
+ const validateKickToken = opts.validateKickToken ?? (() => null);
41
+ const validateAdminToken = opts.validateAdminToken ?? (() => false);
42
+ const serverVersion = opts.serverVersion ?? null;
43
+ const serverGitHash = opts.serverGitHash ?? null;
44
+ const getRuntimeStats = opts.getRuntimeStats ?? (() => null);
45
+ const getWebrtcPeerSnapshot = opts.getWebrtcPeerSnapshot ?? (() => null);
46
+ const disconnectWebrtcPeersByAddr = opts.disconnectWebrtcPeersByAddr ?? (() => 0);
47
+ const disconnectAllWebrtcPeers = opts.disconnectAllWebrtcPeers ?? (() => 0);
48
+
49
+ // ── Input flood instrumentation ───────────────────────────────────────────────
50
+ const _inputStats = {
51
+ host: { joystick: 0, key: 0, lastMsgTime: 0 },
52
+ p2: { joystick: 0, key: 0, lastMsgTime: 0 },
53
+ };
54
+ // ── Input latency tracking ─────────────────────────────────────────────────
55
+ const LATENCY_SPIKE_MS = 200;
56
+ const _latencyCount = { host: 0, p2: 0 };
57
+ const _avgLatency = { host: 0, p2: 0 };
58
+ let _latencyLogTimer = null;
59
+ let _inputLogTimer = null;
60
+ let _networkStatsTimer = null;
61
+ const _networkStats = {
62
+ host: { avgLatency: null, lastLatency: null, lastSpikeLatency: null, lastSpikeAt: null },
63
+ p2: { avgLatency: null, lastLatency: null, lastSpikeLatency: null, lastSpikeAt: null },
64
+ };
65
+
66
+ function broadcastNetworkStats() {
67
+ if (!hostClient && !p2Client) return;
68
+ const runtime = getRuntimeStats?.() ?? null;
69
+ const payload = JSON.stringify({
70
+ type: 'network-stats',
71
+ serverTime: Date.now(),
72
+ host: { ..._networkStats.host },
73
+ p2: { ..._networkStats.p2 },
74
+ ...(runtime ? { server: runtime } : {}),
75
+ });
76
+ if (hostClient && hostClient.readyState === hostClient.OPEN) {
77
+ try { hostClient.send(payload); } catch (_) {}
78
+ }
79
+ if (p2Client && p2Client.readyState === p2Client.OPEN) {
80
+ try { p2Client.send(payload); } catch (_) {}
81
+ }
82
+ }
83
+ const INPUT_LOG_INTERVAL_MS = 5000; // every 5 seconds
84
+
85
+ function _startInputLog() {
86
+ if (_inputLogTimer) return;
87
+ _inputLogTimer = setInterval(() => {
88
+ const now = Date.now();
89
+ // Only log if there's been recent activity (within last 10s)
90
+ const h = _inputStats.host.lastMsgTime && (now - _inputStats.host.lastMsgTime < 10000);
91
+ const p = _inputStats.p2.lastMsgTime && (now - _inputStats.p2.lastMsgTime < 10000);
92
+ if ((h || p) && (logEvents || verbose)) {
93
+ console.error(`[event] input-flood host-joystick=${_inputStats.host.joystick} host-key=${_inputStats.host.key} p2-joystick=${_inputStats.p2.joystick} p2-key=${_inputStats.p2.key}`);
94
+ }
95
+ // Reset counters after reporting
96
+ _inputStats.host.joystick = 0;
97
+ _inputStats.host.key = 0;
98
+ _inputStats.p2.joystick = 0;
99
+ _inputStats.p2.key = 0;
100
+ }, INPUT_LOG_INTERVAL_MS);
101
+ }
102
+
103
+ function _startNetworkStatsTicker() {
104
+ if (_networkStatsTimer) return;
105
+ _networkStatsTimer = setInterval(() => {
106
+ broadcastNetworkStats();
107
+ }, 5000);
108
+ }
109
+
110
+ /** Emit a structured event log line — only when --log-events is active.
111
+ * Format: [event] <tag> key=value ...
112
+ * Never called per-frame; only on meaningful state transitions. */
113
+ function logEv(tag, fields = {}) {
114
+ if (!logEvents) return;
115
+ const ts = new Date().toISOString();
116
+ const pairs = Object.entries(fields).map(([k, v]) => `${k}=${v}`).join(' ');
117
+ console.error(`[event] ${ts} ${tag}${pairs ? ' ' + pairs : ''}`);
118
+ }
25
119
 
26
120
  const wss = new WebSocketServer({ port });
121
+ const HOST_RECONNECT_GRACE = opts.hostReconnectGraceMs ?? 8_000;
122
+
123
+ // ── Room state ────────────────────────────────────────────────────────────
124
+ let hostClient = null;
125
+ let hostUsername = null;
126
+
127
+ let p2Client = null;
128
+ let p2Username = null;
129
+ let inviteToken = null;
130
+
131
+ // Joystick port swap — when true, host uses port 1, P2 uses port 2
132
+ let portsSwapped = false;
133
+
134
+ // ── Host reconnect grace period ───────────────────────────────────────────
135
+ // When the host disconnects we hold off on promoting P2 for up to
136
+ // HOST_RECONNECT_GRACE ms, giving the host a chance to refresh and reclaim.
137
+ let graceTimer = null;
138
+ let pendingHostUsername = null; // username of the disconnected host
139
+ // Currently loaded cartridge filename (for hello message to late joiners).
140
+ // Seeded from opts.initialCartFilename when a default game is pre-loaded.
141
+ let currentCartFilename = opts.initialCartFilename ?? null;
142
+
143
+ function hostPort() { return portsSwapped ? 1 : 2; }
144
+ function p2Port() { return portsSwapped ? 2 : 1; }
145
+
146
+ // ── Host inactivity timeout ───────────────────────────────────────────────
147
+ let hostTimeoutTimer = null;
148
+
149
+ function resetHostTimeout() {
150
+ if (!hostClient) return;
151
+ if (hostTimeoutTimer) clearTimeout(hostTimeoutTimer);
152
+ hostTimeoutTimer = setTimeout(() => kickHostForInactivity(), HOST_TIMEOUT);
153
+ }
154
+
155
+ function clearHostTimeout() {
156
+ if (hostTimeoutTimer) { clearTimeout(hostTimeoutTimer); hostTimeoutTimer = null; }
157
+ }
158
+
159
+ // ── P2 inactivity timeout ─────────────────────────────────────────────────
160
+ let p2TimeoutTimer = null;
161
+
162
+ function resetP2Timeout() {
163
+ if (!p2Client) return;
164
+ if (p2TimeoutTimer) clearTimeout(p2TimeoutTimer);
165
+ p2TimeoutTimer = setTimeout(() => kickP2ForInactivity(), HOST_TIMEOUT);
166
+ }
167
+
168
+ function clearP2Timeout() {
169
+ if (p2TimeoutTimer) { clearTimeout(p2TimeoutTimer); p2TimeoutTimer = null; }
170
+ }
171
+
172
+ function kickP2ForInactivity() {
173
+ if (!p2Client) return;
174
+ if (verbose) console.error(`[input-server] p2 ${p2Username} timed out due to inactivity`);
175
+ logEv('p2-timeout', { username: p2Username });
176
+ if (p2Client.readyState === p2Client.OPEN) {
177
+ p2Client.send(JSON.stringify({ type: 'p2-timeout-kick', username: p2Username }));
178
+ }
179
+ const leaving = p2Username;
180
+ setWsIdentity(p2Client, 'spectator', null);
181
+ p2Client = null;
182
+ p2Username = null;
183
+ clearP2Timeout();
184
+ broadcastAll({ type: 'player2-left', username: leaving, reason: 'timeout' });
185
+ broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
186
+ }
187
+
188
+ // ── Host reconnect grace period helpers ───────────────────────────────────
189
+ function clearGrace() {
190
+ if (graceTimer) { clearTimeout(graceTimer); graceTimer = null; }
191
+ pendingHostUsername = null;
192
+ }
193
+
194
+ // Called when grace expires without the host reconnecting.
195
+ function expireGrace() {
196
+ graceTimer = null;
197
+ const leaving = pendingHostUsername;
198
+ pendingHostUsername = null;
199
+ if (verbose) console.error(`[input-server] host grace expired for ${leaving}`);
200
+ logEv('host-grace-expired', { username: leaving });
201
+ broadcastAll({ type: 'host-left', username: leaving, reason: 'disconnect' });
202
+ broadcastAll({ type: 'p2-slot-status', open: false });
203
+ }
204
+
205
+ // Called on host WS close — starts grace period, notifies clients.
206
+ function onHostDisconnect(leaving) {
207
+ clearGrace();
208
+ pendingHostUsername = leaving;
209
+ if (verbose) console.error(`[input-server] host ${leaving} disconnected — grace ${HOST_RECONNECT_GRACE}ms`);
210
+ logEv('host-disconnected', { username: leaving, graceMs: HOST_RECONNECT_GRACE });
211
+ // Tell everyone the host is temporarily gone; P2 should wait before acting.
212
+ broadcastAll({ type: 'host-disconnected', username: leaving, graceMs: HOST_RECONNECT_GRACE });
213
+ graceTimer = setTimeout(expireGrace, HOST_RECONNECT_GRACE);
214
+ }
215
+
216
+ function kickHostForInactivity() {
217
+ if (!hostClient) return;
218
+ if (verbose) console.error(`[input-server] host ${hostUsername} timed out due to inactivity`);
219
+ logEv('host-timeout', { username: hostUsername });
220
+ // Notify the host client they are being kicked
221
+ if (hostClient.readyState === hostClient.OPEN) {
222
+ hostClient.send(JSON.stringify({ type: 'host-timeout-kick', username: hostUsername }));
223
+ }
224
+ const leaving = hostUsername;
225
+ setWsIdentity(hostClient, 'spectator', null);
226
+ hostClient = null;
227
+ hostUsername = null;
228
+ inviteToken = null;
229
+ clearHostTimeout();
230
+ clearGrace();
231
+ // Broadcast host-left with reason so clients can show a contextual notice
232
+ broadcastAll({ type: 'host-left', username: leaving, reason: 'timeout' });
233
+ broadcastAll({ type: 'p2-slot-status', open: false });
234
+ }
235
+
236
+ function kickHostByReason(reason = 'admin-kick') {
237
+ if (!hostClient) return { kicked: false, username: null, addr: null };
238
+ const targetWs = hostClient;
239
+ const targetMeta = clientMeta.get(targetWs);
240
+ const addr = targetMeta?.addr ?? null;
241
+ const leaving = hostUsername;
242
+ clearHostTimeout();
243
+ clearGrace();
244
+ if (targetWs.readyState === targetWs.OPEN) {
245
+ try { targetWs.send(JSON.stringify({ type: 'host-kicked', reason })); } catch (_) {}
246
+ }
247
+ hostClient = null;
248
+ hostUsername = null;
249
+ inviteToken = null;
250
+ portsSwapped = false;
251
+ setWsIdentity(targetWs, 'spectator', null);
252
+ broadcastAll({ type: 'host-left', username: leaving, reason });
253
+ broadcastAll({ type: 'p2-slot-status', open: false });
254
+ if (addr) disconnectWebrtcPeersByAddr(addr, reason);
255
+ return { kicked: true, username: leaving, addr };
256
+ }
257
+
258
+ function kickP2ByReason(reason = 'admin-kick') {
259
+ if (!p2Client) return { kicked: false, username: null, addr: null };
260
+ const targetWs = p2Client;
261
+ const targetMeta = clientMeta.get(targetWs);
262
+ const addr = targetMeta?.addr ?? null;
263
+ const leaving = p2Username;
264
+ if (targetWs.readyState === targetWs.OPEN) {
265
+ try { targetWs.send(JSON.stringify({ type: 'kicked', reason })); } catch (_) {}
266
+ }
267
+ clearP2Timeout();
268
+ p2Client = null;
269
+ p2Username = null;
270
+ setWsIdentity(targetWs, 'spectator', null);
271
+ broadcastAll({ type: 'player2-left', username: leaving, reason });
272
+ broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
273
+ if (addr) disconnectWebrtcPeersByAddr(addr, reason);
274
+ return { kicked: true, username: leaving, addr };
275
+ }
276
+
277
+
278
+ function broadcastExcept(excludeWs, msg) {
279
+ const raw = JSON.stringify(msg);
280
+ wss.clients.forEach((c) => {
281
+ if (c !== excludeWs && c.readyState === c.OPEN) c.send(raw);
282
+ });
283
+ }
284
+
285
+ function broadcastAll(msg) {
286
+ const raw = JSON.stringify(msg);
287
+ wss.clients.forEach((c) => { if (c.readyState === c.OPEN) c.send(raw); });
288
+ }
289
+
290
+ // True when the P2 slot is available for open joining
291
+ function isP2SlotOpen() {
292
+ return !!(hostClient && hostClient.readyState === hostClient.OPEN)
293
+ && !(p2Client && p2Client.readyState === p2Client.OPEN);
294
+ }
295
+
27
296
  let clientCount = 0;
297
+ const clientMeta = new Map(); // Map<WebSocket, { addr: string, role: string, username: string|null }>
298
+
299
+ function normalizeAddr(addr) {
300
+ if (!addr) return '';
301
+ return String(addr).replace(/^::ffff:/, '');
302
+ }
303
+
304
+ function setWsIdentity(ws, role, username = null) {
305
+ const meta = clientMeta.get(ws);
306
+ if (!meta) return;
307
+ meta.role = role;
308
+ meta.username = username;
309
+ }
310
+
311
+ function getWebrtcPeerCountByAddr() {
312
+ const snapshot = getWebrtcPeerSnapshot?.() ?? null;
313
+ const peers = Array.isArray(snapshot?.peers) ? snapshot.peers : [];
314
+ const byAddr = new Map();
315
+ for (const p of peers) {
316
+ const addr = normalizeAddr(p?.addr);
317
+ if (!addr) continue;
318
+ byAddr.set(addr, (byAddr.get(addr) ?? 0) + 1);
319
+ }
320
+ return { snapshot, byAddr };
321
+ }
322
+
323
+ function buildAdminStatus() {
324
+ const hostMeta = hostClient ? clientMeta.get(hostClient) : null;
325
+ const p2Meta = p2Client ? clientMeta.get(p2Client) : null;
326
+ const spectators = [];
327
+ const { snapshot: webrtcSnapshot, byAddr: webrtcByAddr } = getWebrtcPeerCountByAddr();
328
+ const mappedAddrSet = new Set();
329
+ if (hostMeta?.addr) mappedAddrSet.add(hostMeta.addr);
330
+ if (p2Meta?.addr) mappedAddrSet.add(p2Meta.addr);
331
+ for (const [ws, meta] of clientMeta.entries()) {
332
+ if (ws === hostClient || ws === p2Client) continue;
333
+ if (ws.readyState !== ws.OPEN) continue;
334
+ if (meta.role === 'admin') continue;
335
+ if (meta.addr) mappedAddrSet.add(meta.addr);
336
+ spectators.push({
337
+ addr: meta.addr,
338
+ role: meta.role ?? 'spectator',
339
+ username: meta.username ?? null,
340
+ webrtcPeers: webrtcByAddr.get(meta.addr) ?? 0,
341
+ });
342
+ }
343
+
344
+ let mappedWebrtcPeers = 0;
345
+ for (const addr of mappedAddrSet) {
346
+ mappedWebrtcPeers += webrtcByAddr.get(addr) ?? 0;
347
+ }
348
+ const webrtcTotal = Number.isFinite(webrtcSnapshot?.total) ? webrtcSnapshot.total : 0;
349
+ const anonymousWebrtcPeers = Math.max(0, webrtcTotal - mappedWebrtcPeers);
350
+
351
+ return {
352
+ host: hostClient ? {
353
+ connected: hostClient.readyState === hostClient.OPEN,
354
+ username: hostUsername,
355
+ addr: hostMeta?.addr ?? null,
356
+ webrtcPeers: hostMeta?.addr ? (webrtcByAddr.get(hostMeta.addr) ?? 0) : 0,
357
+ } : null,
358
+ p2: p2Client ? {
359
+ connected: p2Client.readyState === p2Client.OPEN,
360
+ username: p2Username,
361
+ addr: p2Meta?.addr ?? null,
362
+ webrtcPeers: p2Meta?.addr ? (webrtcByAddr.get(p2Meta.addr) ?? 0) : 0,
363
+ } : null,
364
+ spectators,
365
+ counts: {
366
+ inputClients: clientCount,
367
+ spectators: spectators.length,
368
+ webrtcActive: Number.isFinite(webrtcSnapshot?.active) ? webrtcSnapshot.active : 0,
369
+ webrtcPending: Number.isFinite(webrtcSnapshot?.pending) ? webrtcSnapshot.pending : 0,
370
+ webrtcTotal,
371
+ anonymousWebrtcPeers,
372
+ },
373
+ webrtc: webrtcSnapshot,
374
+ runtime: getRuntimeStats?.() ?? null,
375
+ sampledAt: Date.now(),
376
+ };
377
+ }
28
378
 
29
379
  wss.on('listening', () => {
30
380
  console.error(`[input-server] WebSocket listening on ws://0.0.0.0:${port}`);
381
+ logEv('server-listening', { port });
382
+ // Start input flood logging
383
+ _startInputLog();
384
+ _startNetworkStatsTicker();
31
385
  });
32
386
 
33
387
  wss.on('connection', (ws, req) => {
34
388
  clientCount++;
35
389
  const addr = req.socket.remoteAddress;
390
+ clientMeta.set(ws, { addr: normalizeAddr(addr), role: 'spectator', username: null });
36
391
  if (verbose) console.error(`[input-server] client connected from ${addr} (${clientCount} total)`);
392
+ logEv('client-connected', { addr, total: clientCount });
37
393
 
38
394
  ws.on('message', (data) => {
395
+ let msg;
39
396
  try {
40
- const msg = JSON.parse(typeof data === 'string' ? data : data.toString('utf8'));
41
- if (verbose) console.error(`[input-server] rx:`, JSON.stringify(msg));
42
- if (onInput) onInput(msg);
397
+ msg = JSON.parse(typeof data === 'string' ? data : data.toString('utf8'));
43
398
  } catch (err) {
44
399
  if (verbose) console.error(`[input-server] bad message:`, err.message);
400
+ logEv('error', { kind: 'bad-message', err: err.message });
401
+ return;
402
+ }
403
+ // Avoid re-serialising load-crt messages for logging — the base64 data
404
+ // field can be 100KB+ and JSON.stringify-ing it synchronously on the
405
+ // main thread causes a noticeable pause proportional to file size.
406
+ if (verbose) {
407
+ if (msg.type === 'load-crt') {
408
+ console.error(`[input-server] rx: load-crt filename=${msg.filename ?? '?'} dataLen=${(msg.data ?? '').length}`);
409
+ } else {
410
+ console.error(`[input-server] rx:`, JSON.stringify(msg));
411
+ }
412
+ }
413
+
414
+ // ── Host claim ────────────────────────────────────────────────────────
415
+ if (msg.type === 'host') {
416
+ if (hostClient && hostClient.readyState === hostClient.OPEN) {
417
+ // force:true lets a new connection take over from a stale/ghost host
418
+ // (e.g. page reload, WebRTC reconnect, or lost tab). Without this
419
+ // the new browser tab gets host-taken and detach/reset silently fail.
420
+ if (!msg.force) {
421
+ ws.send(JSON.stringify({ type: 'host-taken' }));
422
+ logEv('host-claim-rejected', { reason: 'slot-taken', username: msg.username ?? 'player' });
423
+ return;
424
+ }
425
+ // Forcibly evict the existing host before granting the new claim.
426
+ if (verbose) console.error(`[input-server] force host claim — evicting ${hostUsername}`);
427
+ logEv('host-force-evicted', { evicted: hostUsername, by: msg.username ?? 'player' });
428
+ clearHostTimeout();
429
+ clearGrace();
430
+ try { hostClient.send(JSON.stringify({ type: 'host-evicted', reason: 'force-claim' })); } catch (_) {}
431
+ try { hostClient.close(); } catch (_) {}
432
+ setWsIdentity(hostClient, 'spectator', null);
433
+ hostClient = null;
434
+ hostUsername = null;
435
+ inviteToken = null;
436
+ }
437
+ const isRejoin = graceTimer && pendingHostUsername === (msg.username ?? 'player');
438
+ if (graceTimer) clearGrace(); // cancel grace regardless of who's claiming
439
+ hostClient = ws;
440
+ hostUsername = msg.username ?? 'player';
441
+ setWsIdentity(ws, 'host', hostUsername);
442
+ ws.send(JSON.stringify({
443
+ type: 'host-confirmed', username: hostUsername, joystickPort: hostPort(),
444
+ player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
445
+ }));
446
+ if (isRejoin) {
447
+ broadcastExcept(ws, { type: 'host-rejoined', username: hostUsername, joystickPort: hostPort() });
448
+ } else {
449
+ broadcastExcept(ws, { type: 'host-joined', username: hostUsername, joystickPort: hostPort() });
450
+ }
451
+ if (verbose) console.error(`[input-server] host ${isRejoin ? 're' : ''}claimed by ${hostUsername}`);
452
+ logEv(isRejoin ? 'host-rejoined' : 'host-joined', { username: hostUsername, joystickPort: hostPort() });
453
+ resetHostTimeout();
454
+ // P2 slot just opened (host present, no P2)
455
+ broadcastExcept(ws, { type: 'p2-slot-status', open: isP2SlotOpen() });
456
+ return;
457
+ }
458
+
459
+ // ── Swap joystick ports ───────────────────────────────────────────────
460
+ if (msg.type === 'swap-ports') {
461
+ if (ws !== hostClient) return;
462
+ portsSwapped = !portsSwapped;
463
+ if (verbose) console.error(`[input-server] ports swapped: host=${hostPort()} p2=${p2Port()}`);
464
+ logEv('ports-swapped', { hostPort: hostPort(), p2Port: p2Port() });
465
+ broadcastAll({
466
+ type: 'ports-swapped',
467
+ swapped: portsSwapped,
468
+ hostPort: hostPort(),
469
+ p2Port: p2Port(),
470
+ });
471
+ return;
472
+ }
473
+ // ── Voluntary player 2 leave ──────────────────────────────────────────
474
+ if (msg.type === 'p2-leave') {
475
+ if (ws === p2Client) {
476
+ clearP2Timeout();
477
+ p2Client = null;
478
+ const leaving = p2Username;
479
+ p2Username = null;
480
+ setWsIdentity(ws, 'spectator', null);
481
+ if (verbose) console.error(`[input-server] player2 ${leaving} voluntarily left`);
482
+ logEv('p2-left', { username: leaving, reason: 'voluntary' });
483
+ ws.send(JSON.stringify({ type: 'player2-left', username: leaving, voluntary: true }));
484
+ broadcastExcept(ws, { type: 'player2-left', username: leaving, voluntary: true });
485
+ broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
486
+ }
487
+ return;
488
+ }
489
+
490
+ // ── Voluntary host leave ──────────────────────────────────────────────
491
+ if (msg.type === 'host-leave') {
492
+ if (ws === hostClient) {
493
+ clearHostTimeout();
494
+ clearGrace();
495
+ hostClient = null;
496
+ const leaving = hostUsername;
497
+ hostUsername = null;
498
+ inviteToken = null;
499
+ portsSwapped = false;
500
+ setWsIdentity(ws, 'spectator', null);
501
+ if (verbose) console.error(`[input-server] host ${leaving} voluntarily left`);
502
+ logEv('host-left', { username: leaving, reason: 'voluntary' });
503
+ ws.send(JSON.stringify({ type: 'host-left', username: leaving, voluntary: true }));
504
+ broadcastExcept(ws, { type: 'host-left', username: leaving, voluntary: true });
505
+ broadcastAll({ type: 'p2-slot-status', open: false });
506
+ }
507
+ return;
508
+ }
509
+
510
+ // ── Host issues a player-2 invite ─────────────────────────────────────
511
+ if (msg.type === 'invite-p2') {
512
+ if (ws !== hostClient) return;
513
+ if (p2Client && p2Client.readyState === p2Client.OPEN) {
514
+ ws.send(JSON.stringify({ type: 'invite-p2-error', reason: 'slot-taken' }));
515
+ logEv('invite-p2-rejected', { reason: 'slot-taken' });
516
+ return;
517
+ }
518
+ inviteToken = randomBytes(6).toString('hex');
519
+ ws.send(JSON.stringify({ type: 'invite-token', token: inviteToken }));
520
+ if (verbose) console.error(`[input-server] invite token issued: ${inviteToken}`);
521
+ logEv('invite-p2-issued', { host: hostUsername });
522
+ return;
523
+ }
524
+
525
+ // ── Player 2 open join (no token) ────────────────────────────────────
526
+ if (msg.type === 'join-p2-open') {
527
+ if (!hostClient || hostClient.readyState !== hostClient.OPEN) {
528
+ ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'no-host' }));
529
+ logEv('p2-join-rejected', { reason: 'no-host', username: msg.username ?? 'player2' });
530
+ return;
531
+ }
532
+ if (p2Client && p2Client.readyState === p2Client.OPEN) {
533
+ ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'slot-taken' }));
534
+ logEv('p2-join-rejected', { reason: 'slot-taken', username: msg.username ?? 'player2' });
535
+ return;
536
+ }
537
+ if (ws === hostClient) {
538
+ ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'already-host' }));
539
+ return;
540
+ }
541
+ p2Client = ws;
542
+ p2Username = msg.username ?? 'player2';
543
+ inviteToken = null;
544
+ setWsIdentity(ws, 'p2', p2Username);
545
+ ws.send(JSON.stringify({
546
+ type: 'join-p2-confirmed', username: p2Username, joystickPort: p2Port(),
547
+ }));
548
+ broadcastExcept(ws, { type: 'player2-joined', username: p2Username, joystickPort: p2Port() });
549
+ // Notify all clients that the slot is now taken
550
+ broadcastAll({ type: 'p2-slot-status', open: false });
551
+ if (verbose) console.error(`[input-server] player2 open-joined: ${p2Username}`);
552
+ logEv('p2-joined', { username: p2Username, joystickPort: p2Port(), method: 'open' });
553
+ resetP2Timeout();
554
+ return;
555
+ }
556
+
557
+ // ── Player 2 join (invite token) ──────────────────────────────────────
558
+ if (msg.type === 'join-p2') {
559
+ if (!inviteToken || msg.token !== inviteToken) {
560
+ ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'invalid-token' }));
561
+ logEv('p2-join-rejected', { reason: 'invalid-token', username: msg.username ?? 'player2' });
562
+ return;
563
+ }
564
+ if (p2Client && p2Client.readyState === p2Client.OPEN) {
565
+ ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'slot-taken' }));
566
+ return;
567
+ }
568
+ p2Client = ws;
569
+ p2Username = msg.username ?? 'player2';
570
+ inviteToken = null;
571
+ setWsIdentity(ws, 'p2', p2Username);
572
+ ws.send(JSON.stringify({
573
+ type: 'join-p2-confirmed', username: p2Username, joystickPort: p2Port(),
574
+ }));
575
+ broadcastExcept(ws, { type: 'player2-joined', username: p2Username, joystickPort: p2Port() });
576
+ broadcastAll({ type: 'p2-slot-status', open: false });
577
+ if (verbose) console.error(`[input-server] player2 joined: ${p2Username}`);
578
+ logEv('p2-joined', { username: p2Username, joystickPort: p2Port(), method: 'token' });
579
+ resetP2Timeout();
580
+ return;
581
+ }
582
+
583
+ // ── Host revokes the invite / kicks p2 ───────────────────────────────
584
+ if (msg.type === 'revoke-p2') {
585
+ if (ws !== hostClient) return;
586
+ inviteToken = null;
587
+ if (p2Client && p2Client.readyState === p2Client.OPEN) {
588
+ p2Client.send(JSON.stringify({ type: 'kicked' }));
589
+ }
590
+ const leaving = p2Username;
591
+ clearP2Timeout();
592
+ p2Client = null;
593
+ p2Username = null;
594
+ setWsIdentity(ws, 'spectator', null);
595
+ if (leaving) broadcastAll({ type: 'player2-left', username: leaving });
596
+ broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
597
+ if (verbose) console.error(`[input-server] p2 revoked by host`);
598
+ logEv('p2-kicked', { username: leaving ?? '?', by: 'host' });
599
+ return;
600
+ }
601
+
602
+ // ── Admin CLI commands (token-authenticated) ─────────────────────────
603
+ if (msg.type === 'admin-status') {
604
+ const valid = validateAdminToken(msg.token ?? '');
605
+ if (!valid) {
606
+ ws.send(JSON.stringify({ type: 'admin-error', command: 'status', reason: 'invalid-token' }));
607
+ return;
608
+ }
609
+ setWsIdentity(ws, 'admin', null);
610
+ ws.send(JSON.stringify({
611
+ type: 'admin-status-ok',
612
+ status: buildAdminStatus(),
613
+ }));
614
+ return;
615
+ }
616
+
617
+ if (msg.type === 'admin-kick-player') {
618
+ const valid = validateAdminToken(msg.token ?? '');
619
+ if (!valid) {
620
+ ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'invalid-token' }));
621
+ return;
622
+ }
623
+ setWsIdentity(ws, 'admin', null);
624
+ const target = msg.target === 'p2' ? 'p2' : (msg.target === 'host' ? 'host' : null);
625
+ if (!target) {
626
+ ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'invalid-target' }));
627
+ return;
628
+ }
629
+ const result = target === 'host'
630
+ ? kickHostByReason('admin-kick')
631
+ : kickP2ByReason('admin-kick');
632
+ if (!result.kicked) {
633
+ ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'target-not-present', target }));
634
+ return;
635
+ }
636
+ logEv(target === 'host' ? 'host-kicked' : 'p2-kicked', { username: result.username ?? '-', by: 'admin-cli' });
637
+ ws.send(JSON.stringify({
638
+ type: 'admin-kick-player-ok',
639
+ target,
640
+ username: result.username,
641
+ addr: result.addr,
642
+ status: buildAdminStatus(),
643
+ }));
644
+ return;
645
+ }
646
+
647
+ if (msg.type === 'admin-kick-all') {
648
+ const valid = validateAdminToken(msg.token ?? '');
649
+ if (!valid) {
650
+ ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-all', reason: 'invalid-token' }));
651
+ return;
652
+ }
653
+ setWsIdentity(ws, 'admin', null);
654
+ const kicked = { host: null, p2: null, spectators: 0, webrtcPeers: 0 };
655
+ const previousHostWs = hostClient;
656
+ const previousP2Ws = p2Client;
657
+ const hostResult = kickHostByReason('admin-kick-all');
658
+ if (hostResult.kicked) kicked.host = hostResult.username;
659
+ const p2Result = kickP2ByReason('admin-kick-all');
660
+ if (p2Result.kicked) kicked.p2 = p2Result.username;
661
+
662
+ for (const c of wss.clients) {
663
+ if (c === ws) continue;
664
+ if (c === previousHostWs || c === previousP2Ws) continue;
665
+ const meta = clientMeta.get(c);
666
+ if (meta?.role === 'admin') continue;
667
+ try {
668
+ if (c.readyState === c.OPEN) c.send(JSON.stringify({ type: 'kicked', reason: 'admin-kick-all' }));
669
+ c.close();
670
+ kicked.spectators++;
671
+ } catch (_) {}
672
+ }
673
+ kicked.webrtcPeers = disconnectAllWebrtcPeers('admin-kick-all');
674
+ logEv('admin-kick-all', { spectators: kicked.spectators, webrtcPeers: kicked.webrtcPeers });
675
+ ws.send(JSON.stringify({
676
+ type: 'admin-kick-all-ok',
677
+ kicked,
678
+ status: buildAdminStatus(),
679
+ }));
680
+ return;
681
+ }
682
+
683
+ // ── Admin kick (legacy one-time token flow) ───────────────────────────
684
+ if (msg.type === 'admin-kick') {
685
+ const valid = validateKickToken(msg.token ?? '');
686
+ if (!valid) {
687
+ ws.send(JSON.stringify({ type: 'admin-kick-error', reason: 'invalid-token' }));
688
+ if (verbose) console.error('[input-server] admin-kick rejected: invalid token');
689
+ logEv('error', { kind: 'admin-kick-invalid-token' });
690
+ return;
691
+ }
692
+ const target = valid.target;
693
+ if (target === 'host' && hostClient) {
694
+ if (verbose) console.error(`[input-server] admin kicked host ${hostUsername}`);
695
+ const result = kickHostByReason('admin-kick');
696
+ logEv('host-kicked', { username: result.username ?? '-', by: 'admin' });
697
+ } else if (target === 'p2' && p2Client) {
698
+ if (verbose) console.error(`[input-server] admin kicked player2 ${p2Username}`);
699
+ const result = kickP2ByReason('admin-kick');
700
+ logEv('p2-kicked', { username: result.username ?? '-', by: 'admin' });
701
+ } else {
702
+ ws.send(JSON.stringify({ type: 'admin-kick-error', reason: 'target-not-present' }));
703
+ logEv('error', { kind: 'admin-kick-target-missing', target });
704
+ }
705
+ return;
706
+ }
707
+
708
+ // ── Emulator commands (host only) ─────────────────────────────────────
709
+ if (msg.type === 'load-crt') {
710
+ if (ws !== hostClient) return;
711
+ if (verbose) console.error(`[input-server] load-crt: ${msg.filename ?? '?'}`);
712
+ logEv('cmd-load-crt', { filename: msg.filename ?? '?', dataLen: (msg.data ?? '').length });
713
+ const loadFilename = msg.filename ?? '';
714
+ broadcastAll({ type: 'cart-loading', filename: loadFilename });
715
+ Promise.resolve()
716
+ .then(() => onCommand({ type: 'load-crt', filename: loadFilename, data: msg.data ?? '' }))
717
+ .then(() => {
718
+ currentCartFilename = loadFilename || null;
719
+ broadcastAll({ type: 'cart-loaded', filename: loadFilename });
720
+ })
721
+ .catch((e) => {
722
+ broadcastAll({ type: 'cart-load-error', reason: String(e?.message ?? e) });
723
+ if (verbose) console.error('[input-server] load-crt error:', e);
724
+ logEv('error', { kind: 'load-crt-failed', filename: loadFilename, err: String(e?.message ?? e) });
725
+ });
726
+ return;
727
+ }
728
+
729
+ if (msg.type === 'detach-crt') {
730
+ if (ws !== hostClient) return;
731
+ if (verbose) console.error('[input-server] detach-crt');
732
+ logEv('cmd-detach-crt', {});
733
+ Promise.resolve()
734
+ .then(() => onCommand({ type: 'detach-crt' }))
735
+ .then(() => {
736
+ currentCartFilename = null;
737
+ broadcastAll({ type: 'cart-detached' });
738
+ })
739
+ .catch((e) => {
740
+ if (verbose) console.error('[input-server] detach-crt error:', e);
741
+ logEv('error', { kind: 'detach-crt-failed', err: String(e?.message ?? e) });
742
+ });
743
+ return;
744
+ }
745
+
746
+ if (msg.type === 'hard-reset') {
747
+ if (ws !== hostClient) return;
748
+ if (verbose) console.error('[input-server] hard-reset');
749
+ logEv('cmd-hard-reset', { host: hostUsername });
750
+ Promise.resolve()
751
+ .then(() => onCommand({ type: 'hard-reset' }))
752
+ .then(() => {
753
+ broadcastAll({ type: 'machine-reset' });
754
+ })
755
+ .catch((e) => {
756
+ if (verbose) console.error('[input-server] hard-reset error:', e);
757
+ logEv('error', { kind: 'hard-reset-failed', err: String(e?.message ?? e) });
758
+ });
759
+ return;
760
+ }
761
+
762
+ // ── Input events ─────────────────────────────────────────────────────
763
+ if (msg.type === 'joystick' || msg.type === 'key') {
764
+ if (ws !== hostClient && ws !== p2Client) return;
765
+ if (ws === hostClient) resetHostTimeout();
766
+ if (ws === p2Client) resetP2Timeout();
767
+ // Track input counts for flood investigation
768
+ const role = ws === hostClient ? 'host' : 'p2';
769
+ const stats = role === 'host' ? _inputStats.host : _inputStats.p2;
770
+ if (msg.type === 'joystick') stats.joystick++;
771
+ else stats.key++;
772
+ stats.lastMsgTime = Date.now();
773
+
774
+ // ── Input latency profiling ───────────────────────────────────────
775
+ if (msg.clientTime) {
776
+ const now = Date.now();
777
+ const latency = now - msg.clientTime;
778
+ const bucket = _networkStats[role];
779
+ if (bucket) {
780
+ bucket.lastLatency = latency;
781
+ }
782
+ // Log latency periodically (every 5s) to avoid spam
783
+ if (!_latencyLogTimer) {
784
+ _latencyLogTimer = setInterval(() => {
785
+ const hostActive = _latencyCount.host > 0;
786
+ const p2Active = _latencyCount.p2 > 0;
787
+ if (hostActive || p2Active) {
788
+ const hostAvg = hostActive ? Number(_avgLatency.host.toFixed(0)) : null;
789
+ const p2Avg = p2Active ? Number(_avgLatency.p2.toFixed(0)) : null;
790
+ const hostLabel = hostAvg != null ? `${hostAvg}` : '--';
791
+ const p2Label = p2Avg != null ? `${p2Avg}` : '--';
792
+ if (logEvents || verbose) {
793
+ console.error(`[event] input-latency host-avg=${hostLabel}ms p2-avg=${p2Label}ms`);
794
+ }
795
+ _networkStats.host.avgLatency = hostAvg;
796
+ _networkStats.p2.avgLatency = p2Avg;
797
+ broadcastNetworkStats();
798
+ }
799
+ // Reset averages
800
+ _avgLatency.host = 0; _avgLatency.p2 = 0;
801
+ _latencyCount.host = 0; _latencyCount.p2 = 0;
802
+ }, 5000);
803
+ }
804
+ // Accumulate for averaging
805
+ _latencyCount[role]++;
806
+ _avgLatency[role] = ((_avgLatency[role] * (_latencyCount[role] - 1)) + latency) / _latencyCount[role];
807
+ if (latency > LATENCY_SPIKE_MS) {
808
+ if (bucket) {
809
+ bucket.lastSpikeLatency = latency;
810
+ bucket.lastSpikeAt = now;
811
+ }
812
+ if (logEvents || verbose) {
813
+ console.error(`[event] input-latency-spike role=${role} latency=${latency}ms type=${msg.type} action=${msg.action ?? '-'} ` +
814
+ `dir=${msg.direction ?? '-'} fire=${msg.fire ? 1 : 0}`);
815
+ }
816
+ }
817
+ }
818
+
819
+ // Tag with role so onInput can include it in logEvents output
820
+ // without input-server needing to know about logEvents details.
821
+ msg._role = role;
822
+ if (onInput) onInput(msg);
823
+ if (Number.isFinite(msg.inputId) && ws.readyState === ws.OPEN) {
824
+ try {
825
+ ws.send(JSON.stringify({ type: 'input-ack', inputId: msg.inputId }));
826
+ } catch (_) {}
827
+ }
828
+ return;
829
+ }
830
+
831
+ if (msg.type === 'ping') {
832
+ const role = ws === hostClient ? 'host' : (ws === p2Client ? 'p2' : 'spectator');
833
+ const now = Date.now();
834
+ const payload = {
835
+ type: 'pong',
836
+ pingId: msg.pingId ?? null,
837
+ serverTime: now,
838
+ clientTime: msg.clientTime ?? null,
839
+ };
840
+ try { ws.send(JSON.stringify(payload)); } catch (_) {}
841
+ if (verbose) console.error(`[ping] role=${role} pong pingId=${msg.pingId ?? '-'} `);
842
+ return;
45
843
  }
46
844
  });
47
845
 
48
846
  ws.on('close', () => {
49
847
  clientCount--;
50
848
  if (verbose) console.error(`[input-server] client disconnected (${clientCount} remaining)`);
849
+ logEv('client-disconnected', { total: clientCount });
850
+
851
+ if (ws === hostClient) {
852
+ clearHostTimeout();
853
+ hostClient = null;
854
+ const leaving = hostUsername;
855
+ hostUsername = null;
856
+ inviteToken = null;
857
+ portsSwapped = false;
858
+ onHostDisconnect(leaving);
859
+ }
860
+
861
+ if (ws === p2Client) {
862
+ clearP2Timeout();
863
+ p2Client = null;
864
+ const leaving = p2Username;
865
+ p2Username = null;
866
+ if (verbose) console.error(`[input-server] player2 ${leaving} disconnected`);
867
+ logEv('p2-disconnected', { username: leaving, total: clientCount });
868
+ broadcastExcept(ws, { type: 'player2-left', username: leaving });
869
+ broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
870
+ }
871
+ clientMeta.delete(ws);
51
872
  });
52
873
 
53
874
  ws.on('error', (err) => {
54
875
  console.error(`[input-server] ws error:`, err.message);
876
+ logEv('error', { kind: 'ws-error', err: err.message });
55
877
  });
56
878
 
57
- // Send a welcome/handshake so the client knows the protocol version
879
+ // ── Hello handshake ───────────────────────────────────────────────────
880
+ const hostActive = !!(hostClient && hostClient.readyState === hostClient.OPEN);
881
+ const serverTime = Date.now();
58
882
  ws.send(JSON.stringify({
59
- type: 'hello',
60
- protocol: 'c64-input',
61
- version: 1,
883
+ type: 'hello',
884
+ protocol: 'c64-input',
885
+ version: 1,
886
+ serverTime, // Unix ms for client clock sync
887
+ // During grace period: treat slot as free so the original host can reclaim it.
888
+ // hostPendingRejoin tells P2 (and spectators) to hold off.
889
+ hostTaken: hostActive,
890
+ hostPendingRejoin: !hostActive && !!graceTimer ? { username: pendingHostUsername, graceMs: HOST_RECONNECT_GRACE } : null,
891
+ host: hostActive ? { username: hostUsername, joystickPort: hostPort() } : null,
892
+ player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
893
+ p2SlotOpen: isP2SlotOpen(),
894
+ ...(currentCartFilename ? { cartFilename: currentCartFilename } : {}),
62
895
  joystickBitmask: { up: 0x1, down: 0x2, left: 0x4, right: 0x8, fire: 0x10 },
896
+ ...(serverVersion ? { serverVersion } : {}),
897
+ ...(serverGitHash ? { serverGitHash } : {}),
63
898
  }));
64
899
  });
65
900
 
66
901
  wss.on('error', (err) => {
67
902
  console.error(`[input-server] server error:`, err.message);
903
+ logEv('error', { kind: 'server-error', err: err.message });
68
904
  });
69
905
 
70
906
  const close = () => new Promise((resolve) => {
907
+ clearHostTimeout();
908
+ clearP2Timeout();
909
+ clearGrace();
910
+ if (_inputLogTimer) { clearInterval(_inputLogTimer); _inputLogTimer = null; }
911
+ if (_latencyLogTimer) { clearInterval(_latencyLogTimer); _latencyLogTimer = null; }
912
+ if (_networkStatsTimer) { clearInterval(_networkStatsTimer); _networkStatsTimer = null; }
71
913
  wss.close(() => resolve());
72
914
  });
73
915
 
74
916
  return { wss, close };
75
917
  }
76
-