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