c64-ready 1.0.0 → 1.1.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 (40) hide show
  1. package/README.md +70 -62
  2. package/bin/headless.mjs +1 -1
  3. package/dist/assets/{CHANGELOG-CPlXKLCV.js → CHANGELOG-0a7A8Ekq.js} +113 -1
  4. package/dist/assets/index-BESofQoh.js +627 -0
  5. package/dist/games/cartridges/goat-beat.crt +0 -0
  6. package/dist/index.html +1 -1
  7. package/dist-ts/emulator/c64-emulator.d.ts +3 -0
  8. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
  9. package/dist-ts/emulator/c64-emulator.js +36 -4
  10. package/dist-ts/emulator/c64-emulator.js.map +1 -1
  11. package/dist-ts/emulator/crt-info.d.ts +61 -0
  12. package/dist-ts/emulator/crt-info.d.ts.map +1 -0
  13. package/dist-ts/emulator/crt-info.js +190 -0
  14. package/dist-ts/emulator/crt-info.js.map +1 -0
  15. package/dist-ts/emulator/input.d.ts +96 -0
  16. package/dist-ts/emulator/input.d.ts.map +1 -1
  17. package/dist-ts/emulator/input.js +549 -4
  18. package/dist-ts/emulator/input.js.map +1 -1
  19. package/dist-ts/headless/c64-headless.d.ts +1 -0
  20. package/dist-ts/headless/c64-headless.d.ts.map +1 -1
  21. package/dist-ts/headless/c64-headless.js +5 -0
  22. package/dist-ts/headless/c64-headless.js.map +1 -1
  23. package/dist-ts/types/emulator.d.ts +2 -1
  24. package/dist-ts/types/emulator.d.ts.map +1 -1
  25. package/package.json +1 -1
  26. package/public/games/cartridges/goat-beat.crt +0 -0
  27. package/src/emulator/c64-emulator.ts +37 -7
  28. package/src/emulator/crt-info.ts +35 -23
  29. package/src/emulator/input.ts +239 -19
  30. package/src/headless/c64-headless.ts +5 -0
  31. package/src/headless/headless-cli.mjs +462 -249
  32. package/src/headless/input-server.mjs +649 -278
  33. package/src/headless/webrtc-server.mjs +218 -71
  34. package/src/main.ts +30 -4
  35. package/src/player/c64-player.ts +121 -40
  36. package/src/player/input-handler.ts +8 -0
  37. package/src/player/styles/ui-controller.css +103 -21
  38. package/src/player/ui-controller.ts +186 -23
  39. package/src/types/emulator.ts +1 -1
  40. package/dist/assets/index-Ckbi7gQo.js +0 -535
@@ -17,11 +17,13 @@ import { randomBytes } from 'crypto';
17
17
  * @param {number} [opts.port=9001]
18
18
  * @param {Function} opts.onInput
19
19
  * @param {Function} [opts.onCommand] Called with emulator commands from the host:
20
- * { type: 'load-crt'|'detach-crt'|'hard-reset', ... }
20
+ * { type: 'load-crt'|'detach-crt'|'hard-reset'|'reboot', ... }
21
21
  * @param {boolean} [opts.verbose]
22
22
  * @param {number} [opts.hostTimeoutMs=300000]
23
23
  * @param {Function} [opts.validateKickToken]
24
24
  * @param {Function} [opts.validateAdminToken]
25
+ * @param {number} [opts.hostReconnectGraceMs=8000]
26
+ * @param {number} [opts.p2ReconnectGraceMs=5000]
25
27
  * @param {Function} [opts.getRuntimeStats]
26
28
  * @param {Function} [opts.getWebrtcPeerSnapshot]
27
29
  * @param {Function} [opts.disconnectWebrtcPeersByAddr]
@@ -31,17 +33,17 @@ import { randomBytes } from 'crypto';
31
33
  * @returns {{ wss: WebSocketServer, close: () => Promise<void> }}
32
34
  */
33
35
  export function createInputServer(opts = {}) {
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;
36
+ const port = opts.port ?? 9001;
37
+ const onInput = opts.onInput;
38
+ const onCommand = opts.onCommand ?? (() => {});
39
+ const verbose = opts.verbose ?? false;
40
+ const logEvents = opts.logEvents ?? false;
41
+ const HOST_TIMEOUT = opts.hostTimeoutMs ?? 10 * 60 * 1000;
40
42
  const validateKickToken = opts.validateKickToken ?? (() => null);
41
43
  const validateAdminToken = opts.validateAdminToken ?? (() => false);
42
- const serverVersion = opts.serverVersion ?? null;
43
- const serverGitHash = opts.serverGitHash ?? null;
44
- const getRuntimeStats = opts.getRuntimeStats ?? (() => null);
44
+ const serverVersion = opts.serverVersion ?? null;
45
+ const serverGitHash = opts.serverGitHash ?? null;
46
+ const getRuntimeStats = opts.getRuntimeStats ?? (() => null);
45
47
  const getWebrtcPeerSnapshot = opts.getWebrtcPeerSnapshot ?? (() => null);
46
48
  const disconnectWebrtcPeersByAddr = opts.disconnectWebrtcPeersByAddr ?? (() => 0);
47
49
  const disconnectAllWebrtcPeers = opts.disconnectAllWebrtcPeers ?? (() => 0);
@@ -49,7 +51,7 @@ export function createInputServer(opts = {}) {
49
51
  // ── Input flood instrumentation ───────────────────────────────────────────────
50
52
  const _inputStats = {
51
53
  host: { joystick: 0, key: 0, lastMsgTime: 0 },
52
- p2: { joystick: 0, key: 0, lastMsgTime: 0 },
54
+ p2: { joystick: 0, key: 0, lastMsgTime: 0 },
53
55
  };
54
56
  // ── Input latency tracking ─────────────────────────────────────────────────
55
57
  const LATENCY_SPIKE_MS = 200;
@@ -60,7 +62,7 @@ export function createInputServer(opts = {}) {
60
62
  let _networkStatsTimer = null;
61
63
  const _networkStats = {
62
64
  host: { avgLatency: null, lastLatency: null, lastSpikeLatency: null, lastSpikeAt: null },
63
- p2: { avgLatency: null, lastLatency: null, lastSpikeLatency: null, lastSpikeAt: null },
65
+ p2: { avgLatency: null, lastLatency: null, lastSpikeLatency: null, lastSpikeAt: null },
64
66
  };
65
67
 
66
68
  function broadcastNetworkStats() {
@@ -70,14 +72,18 @@ export function createInputServer(opts = {}) {
70
72
  type: 'network-stats',
71
73
  serverTime: Date.now(),
72
74
  host: { ..._networkStats.host },
73
- p2: { ..._networkStats.p2 },
75
+ p2: { ..._networkStats.p2 },
74
76
  ...(runtime ? { server: runtime } : {}),
75
77
  });
76
78
  if (hostClient && hostClient.readyState === hostClient.OPEN) {
77
- try { hostClient.send(payload); } catch (_) {}
79
+ try {
80
+ hostClient.send(payload);
81
+ } catch (_) {}
78
82
  }
79
83
  if (p2Client && p2Client.readyState === p2Client.OPEN) {
80
- try { p2Client.send(payload); } catch (_) {}
84
+ try {
85
+ p2Client.send(payload);
86
+ } catch (_) {}
81
87
  }
82
88
  }
83
89
  const INPUT_LOG_INTERVAL_MS = 5000; // every 5 seconds
@@ -87,10 +93,12 @@ export function createInputServer(opts = {}) {
87
93
  _inputLogTimer = setInterval(() => {
88
94
  const now = Date.now();
89
95
  // 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);
96
+ const h = _inputStats.host.lastMsgTime && now - _inputStats.host.lastMsgTime < 10000;
97
+ const p = _inputStats.p2.lastMsgTime && now - _inputStats.p2.lastMsgTime < 10000;
92
98
  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}`);
99
+ console.error(
100
+ `[event] input-flood host-joystick=${_inputStats.host.joystick} host-key=${_inputStats.host.key} p2-joystick=${_inputStats.p2.joystick} p2-key=${_inputStats.p2.key}`,
101
+ );
94
102
  }
95
103
  // Reset counters after reporting
96
104
  _inputStats.host.joystick = 0;
@@ -113,7 +121,9 @@ export function createInputServer(opts = {}) {
113
121
  function logEv(tag, fields = {}) {
114
122
  if (!logEvents) return;
115
123
  const ts = new Date().toISOString();
116
- const pairs = Object.entries(fields).map(([k, v]) => `${k}=${v}`).join(' ');
124
+ const pairs = Object.entries(fields)
125
+ .map(([k, v]) => `${k}=${v}`)
126
+ .join(' ');
117
127
  console.error(`[event] ${ts} ${tag}${pairs ? ' ' + pairs : ''}`);
118
128
  }
119
129
 
@@ -122,15 +132,15 @@ export function createInputServer(opts = {}) {
122
132
  const P2_RECONNECT_GRACE = opts.p2ReconnectGraceMs ?? HOST_RECONNECT_GRACE;
123
133
 
124
134
  // ── Room state ────────────────────────────────────────────────────────────
125
- let hostClient = null;
126
- let hostUsername = null;
135
+ let hostClient = null;
136
+ let hostUsername = null;
127
137
 
128
- let p2Client = null;
129
- let p2Username = null;
130
- let inviteToken = null;
138
+ let p2Client = null;
139
+ let p2Username = null;
140
+ let inviteToken = null;
131
141
 
132
142
  // Joystick port swap — when true, host uses port 1, P2 uses port 2
133
- let portsSwapped = false;
143
+ let portsSwapped = false;
134
144
  // Optional host-defined override for independent per-role joystick ports.
135
145
  let portOverrideEnabled = false;
136
146
  let overrideHostPort = 2;
@@ -139,19 +149,19 @@ export function createInputServer(opts = {}) {
139
149
  // ── Host reconnect grace period ───────────────────────────────────────────
140
150
  // When the host disconnects we hold off on promoting P2 for up to
141
151
  // HOST_RECONNECT_GRACE ms, giving the host a chance to refresh and reclaim.
142
- let graceTimer = null;
143
- let pendingHostUsername = null; // username of the disconnected host
144
- let p2GraceTimer = null;
145
- let pendingP2Username = null;
152
+ let graceTimer = null;
153
+ let pendingHostUsername = null; // username of the disconnected host
154
+ let p2GraceTimer = null;
155
+ let pendingP2Username = null;
146
156
  // Currently loaded cartridge filename (for hello message to late joiners).
147
157
  // Seeded from opts.initialCartFilename when a default game is pre-loaded.
148
158
  let currentCartFilename = opts.initialCartFilename ?? null;
149
159
 
150
160
  function hostPort() {
151
- return portOverrideEnabled ? overrideHostPort : (portsSwapped ? 1 : 2);
161
+ return portOverrideEnabled ? overrideHostPort : portsSwapped ? 1 : 2;
152
162
  }
153
163
  function p2Port() {
154
- return portOverrideEnabled ? overrideP2Port : (portsSwapped ? 2 : 1);
164
+ return portOverrideEnabled ? overrideP2Port : portsSwapped ? 2 : 1;
155
165
  }
156
166
 
157
167
  // ── Host inactivity timeout ───────────────────────────────────────────────
@@ -164,7 +174,10 @@ export function createInputServer(opts = {}) {
164
174
  }
165
175
 
166
176
  function clearHostTimeout() {
167
- if (hostTimeoutTimer) { clearTimeout(hostTimeoutTimer); hostTimeoutTimer = null; }
177
+ if (hostTimeoutTimer) {
178
+ clearTimeout(hostTimeoutTimer);
179
+ hostTimeoutTimer = null;
180
+ }
168
181
  }
169
182
 
170
183
  // ── P2 inactivity timeout ─────────────────────────────────────────────────
@@ -177,7 +190,10 @@ export function createInputServer(opts = {}) {
177
190
  }
178
191
 
179
192
  function clearP2Timeout() {
180
- if (p2TimeoutTimer) { clearTimeout(p2TimeoutTimer); p2TimeoutTimer = null; }
193
+ if (p2TimeoutTimer) {
194
+ clearTimeout(p2TimeoutTimer);
195
+ p2TimeoutTimer = null;
196
+ }
181
197
  }
182
198
 
183
199
  function kickP2ForInactivity() {
@@ -189,8 +205,8 @@ export function createInputServer(opts = {}) {
189
205
  }
190
206
  const leaving = p2Username;
191
207
  setWsIdentity(p2Client, 'spectator', null);
192
- p2Client = null;
193
- p2Username = null;
208
+ p2Client = null;
209
+ p2Username = null;
194
210
  clearP2Grace();
195
211
  clearP2Timeout();
196
212
  broadcastAll({ type: 'player2-left', username: leaving, reason: 'timeout' });
@@ -199,19 +215,25 @@ export function createInputServer(opts = {}) {
199
215
 
200
216
  // ── Host reconnect grace period helpers ───────────────────────────────────
201
217
  function clearGrace() {
202
- if (graceTimer) { clearTimeout(graceTimer); graceTimer = null; }
218
+ if (graceTimer) {
219
+ clearTimeout(graceTimer);
220
+ graceTimer = null;
221
+ }
203
222
  pendingHostUsername = null;
204
223
  }
205
224
 
206
225
  function clearP2Grace() {
207
- if (p2GraceTimer) { clearTimeout(p2GraceTimer); p2GraceTimer = null; }
226
+ if (p2GraceTimer) {
227
+ clearTimeout(p2GraceTimer);
228
+ p2GraceTimer = null;
229
+ }
208
230
  pendingP2Username = null;
209
231
  }
210
232
 
211
233
  // Called when grace expires without the host reconnecting.
212
234
  function expireGrace() {
213
- graceTimer = null;
214
- const leaving = pendingHostUsername;
235
+ graceTimer = null;
236
+ const leaving = pendingHostUsername;
215
237
  pendingHostUsername = null;
216
238
  if (verbose) console.error(`[input-server] host grace expired for ${leaving}`);
217
239
  logEv('host-grace-expired', { username: leaving });
@@ -223,7 +245,10 @@ export function createInputServer(opts = {}) {
223
245
  function onHostDisconnect(leaving) {
224
246
  clearGrace();
225
247
  pendingHostUsername = leaving;
226
- if (verbose) console.error(`[input-server] host ${leaving} disconnected — grace ${HOST_RECONNECT_GRACE}ms`);
248
+ if (verbose)
249
+ console.error(
250
+ `[input-server] host ${leaving} disconnected — grace ${HOST_RECONNECT_GRACE}ms`,
251
+ );
227
252
  logEv('host-disconnected', { username: leaving, graceMs: HOST_RECONNECT_GRACE });
228
253
  // Tell everyone the host is temporarily gone; P2 should wait before acting.
229
254
  broadcastAll({ type: 'host-disconnected', username: leaving, graceMs: HOST_RECONNECT_GRACE });
@@ -231,8 +256,8 @@ export function createInputServer(opts = {}) {
231
256
  }
232
257
 
233
258
  function expireP2Grace() {
234
- p2GraceTimer = null;
235
- const leaving = pendingP2Username;
259
+ p2GraceTimer = null;
260
+ const leaving = pendingP2Username;
236
261
  pendingP2Username = null;
237
262
  if (verbose) console.error(`[input-server] p2 grace expired for ${leaving}`);
238
263
  logEv('p2-grace-expired', { username: leaving });
@@ -243,7 +268,10 @@ export function createInputServer(opts = {}) {
243
268
  function onP2Disconnect(leaving) {
244
269
  clearP2Grace();
245
270
  pendingP2Username = leaving;
246
- if (verbose) console.error(`[input-server] player2 ${leaving} disconnected — grace ${P2_RECONNECT_GRACE}ms`);
271
+ if (verbose)
272
+ console.error(
273
+ `[input-server] player2 ${leaving} disconnected — grace ${P2_RECONNECT_GRACE}ms`,
274
+ );
247
275
  logEv('p2-disconnected', { username: leaving, graceMs: P2_RECONNECT_GRACE });
248
276
  p2GraceTimer = setTimeout(expireP2Grace, P2_RECONNECT_GRACE);
249
277
  }
@@ -258,9 +286,9 @@ export function createInputServer(opts = {}) {
258
286
  }
259
287
  const leaving = hostUsername;
260
288
  setWsIdentity(hostClient, 'spectator', null);
261
- hostClient = null;
262
- hostUsername = null;
263
- inviteToken = null;
289
+ hostClient = null;
290
+ hostUsername = null;
291
+ inviteToken = null;
264
292
  portOverrideEnabled = false;
265
293
  overrideHostPort = 2;
266
294
  overrideP2Port = 1;
@@ -280,7 +308,9 @@ export function createInputServer(opts = {}) {
280
308
  clearHostTimeout();
281
309
  clearGrace();
282
310
  if (targetWs.readyState === targetWs.OPEN) {
283
- try { targetWs.send(JSON.stringify({ type: 'host-kicked', reason })); } catch (_) {}
311
+ try {
312
+ targetWs.send(JSON.stringify({ type: 'host-kicked', reason }));
313
+ } catch (_) {}
284
314
  }
285
315
  hostClient = null;
286
316
  hostUsername = null;
@@ -303,7 +333,9 @@ export function createInputServer(opts = {}) {
303
333
  const addr = targetMeta?.addr ?? null;
304
334
  const leaving = p2Username;
305
335
  if (targetWs.readyState === targetWs.OPEN) {
306
- try { targetWs.send(JSON.stringify({ type: 'kicked', reason })); } catch (_) {}
336
+ try {
337
+ targetWs.send(JSON.stringify({ type: 'kicked', reason }));
338
+ } catch (_) {}
307
339
  }
308
340
  clearP2Timeout();
309
341
  clearP2Grace();
@@ -316,7 +348,6 @@ export function createInputServer(opts = {}) {
316
348
  return { kicked: true, username: leaving, addr };
317
349
  }
318
350
 
319
-
320
351
  function broadcastExcept(excludeWs, msg) {
321
352
  const raw = JSON.stringify(msg);
322
353
  wss.clients.forEach((c) => {
@@ -326,18 +357,32 @@ export function createInputServer(opts = {}) {
326
357
 
327
358
  function broadcastAll(msg) {
328
359
  const raw = JSON.stringify(msg);
329
- wss.clients.forEach((c) => { if (c.readyState === c.OPEN) c.send(raw); });
360
+ wss.clients.forEach((c) => {
361
+ if (c.readyState === c.OPEN) c.send(raw);
362
+ });
330
363
  }
331
364
 
332
365
  // True when the P2 slot is available for open joining
333
366
  function isP2SlotOpen() {
334
- return !!(hostClient && hostClient.readyState === hostClient.OPEN)
335
- && !(p2Client && p2Client.readyState === p2Client.OPEN)
336
- && !p2GraceTimer;
367
+ return (
368
+ !!(hostClient && hostClient.readyState === hostClient.OPEN) &&
369
+ !(p2Client && p2Client.readyState === p2Client.OPEN) &&
370
+ !p2GraceTimer
371
+ );
337
372
  }
338
373
 
339
374
  let clientCount = 0;
340
- const clientMeta = new Map(); // Map<WebSocket, { addr: string, role: string, username: string|null }>
375
+ const clientMeta = new Map(); // Map<WebSocket, { addr: string, role: string, username: string|null, sessionId: string|null }>
376
+
377
+ function normalizeSessionId(value) {
378
+ const raw = String(value ?? '').trim();
379
+ return raw || null;
380
+ }
381
+
382
+ function normalizeUsername(value) {
383
+ const username = String(value ?? '').trim().toLowerCase();
384
+ return username || null;
385
+ }
341
386
 
342
387
  function normalizeAddr(addr) {
343
388
  if (!addr) return '';
@@ -351,59 +396,229 @@ export function createInputServer(opts = {}) {
351
396
  meta.username = username;
352
397
  }
353
398
 
399
+ function getRoleByPeer({ addr = null, sessionId = null } = {}) {
400
+ const normalizedSessionId = normalizeSessionId(sessionId);
401
+ const hostMeta = hostClient ? clientMeta.get(hostClient) : null;
402
+ const p2Meta = p2Client ? clientMeta.get(p2Client) : null;
403
+
404
+ if (normalizedSessionId) {
405
+ if (hostMeta?.sessionId && hostMeta.sessionId === normalizedSessionId) {
406
+ return { role: 'host', username: hostUsername, ws: hostClient };
407
+ }
408
+ if (p2Meta?.sessionId && p2Meta.sessionId === normalizedSessionId) {
409
+ return { role: 'p2', username: p2Username, ws: p2Client };
410
+ }
411
+ return null;
412
+ }
413
+
414
+ const normalizedAddr = normalizeAddr(addr);
415
+ if (!normalizedAddr) return null;
416
+ const hostMatches = !!(hostMeta?.addr && hostMeta.addr === normalizedAddr);
417
+ const p2Matches = !!(p2Meta?.addr && p2Meta.addr === normalizedAddr);
418
+ if (hostMatches && !p2Matches) return { role: 'host', username: hostUsername, ws: hostClient };
419
+ if (p2Matches && !hostMatches) return { role: 'p2', username: p2Username, ws: p2Client };
420
+ return null;
421
+ }
422
+
423
+ function handleInputTransportMessage({ msg, role, respond = null } = {}) {
424
+ if (!msg || (msg.type !== 'joystick' && msg.type !== 'key' && msg.type !== 'ping')) return false;
425
+
426
+ if (msg.type === 'ping') {
427
+ const now = Date.now();
428
+ const payload = {
429
+ type: 'pong',
430
+ pingId: msg.pingId ?? null,
431
+ serverTime: now,
432
+ clientTime: msg.clientTime ?? null,
433
+ };
434
+ try {
435
+ respond?.(payload);
436
+ } catch (_) {}
437
+ if (verbose) console.error(`[ping] role=${role} pong pingId=${msg.pingId ?? '-'} `);
438
+ return true;
439
+ }
440
+
441
+ if (role === 'host') resetHostTimeout();
442
+ if (role === 'p2') resetP2Timeout();
443
+
444
+ const stats = role === 'host' ? _inputStats.host : _inputStats.p2;
445
+ if (msg.type === 'joystick') stats.joystick++;
446
+ else stats.key++;
447
+ stats.lastMsgTime = Date.now();
448
+
449
+ if (msg.clientTime) {
450
+ const now = Date.now();
451
+ const latency = now - msg.clientTime;
452
+ const bucket = _networkStats[role];
453
+ if (bucket) {
454
+ bucket.lastLatency = latency;
455
+ }
456
+ if (!_latencyLogTimer) {
457
+ _latencyLogTimer = setInterval(() => {
458
+ const hostActive = _latencyCount.host > 0;
459
+ const p2Active = _latencyCount.p2 > 0;
460
+ if (hostActive || p2Active) {
461
+ const hostAvg = hostActive ? Number(_avgLatency.host.toFixed(0)) : null;
462
+ const p2Avg = p2Active ? Number(_avgLatency.p2.toFixed(0)) : null;
463
+ const hostLabel = hostAvg != null ? `${hostAvg}` : '--';
464
+ const p2Label = p2Avg != null ? `${p2Avg}` : '--';
465
+ if (logEvents || verbose) {
466
+ console.error(
467
+ `[event] input-latency host-avg=${hostLabel}ms p2-avg=${p2Label}ms`,
468
+ );
469
+ }
470
+ _networkStats.host.avgLatency = hostAvg;
471
+ _networkStats.p2.avgLatency = p2Avg;
472
+ broadcastNetworkStats();
473
+ }
474
+ _avgLatency.host = 0;
475
+ _avgLatency.p2 = 0;
476
+ _latencyCount.host = 0;
477
+ _latencyCount.p2 = 0;
478
+ }, 5000);
479
+ }
480
+ _latencyCount[role]++;
481
+ _avgLatency[role] =
482
+ (_avgLatency[role] * (_latencyCount[role] - 1) + latency) / _latencyCount[role];
483
+ if (latency > LATENCY_SPIKE_MS) {
484
+ if (bucket) {
485
+ bucket.lastSpikeLatency = latency;
486
+ bucket.lastSpikeAt = now;
487
+ }
488
+ if (logEvents || verbose) {
489
+ console.error(
490
+ `[event] input-latency-spike role=${role} latency=${latency}ms type=${msg.type} action=${msg.action ?? '-'} ` +
491
+ `dir=${msg.direction ?? '-'} fire=${msg.fire ? 1 : 0}`,
492
+ );
493
+ }
494
+ }
495
+ }
496
+
497
+ msg._role = role;
498
+ if (msg.type === 'joystick') {
499
+ msg.joystickPort = role === 'host' ? hostPort() : p2Port();
500
+ }
501
+ if (onInput) onInput(msg);
502
+ if (Number.isFinite(msg.inputId)) {
503
+ try {
504
+ respond?.({ type: 'input-ack', inputId: msg.inputId });
505
+ } catch (_) {}
506
+ }
507
+ return true;
508
+ }
509
+
510
+ function resetRoleActivity(role, source = 'unknown') {
511
+ if (role === 'host') resetHostTimeout();
512
+ else if (role === 'p2') resetP2Timeout();
513
+ else return false;
514
+ if (verbose) console.error(`[input-server] activity role=${role} source=${source}`);
515
+ logEv('activity', { role, source });
516
+ return true;
517
+ }
518
+
519
+ function handlePeerDataMessage({ addr = null, sessionId = null, msg, send = null } = {}) {
520
+ const identity = getRoleByPeer({ addr, sessionId });
521
+ if (!identity || (identity.role !== 'host' && identity.role !== 'p2')) return false;
522
+ return handleInputTransportMessage({ msg, role: identity.role, respond: send, isWebSocket: false, ws: identity.ws });
523
+ }
524
+
354
525
  function getWebrtcPeerCountByAddr() {
355
526
  const snapshot = getWebrtcPeerSnapshot?.() ?? null;
356
527
  const peers = Array.isArray(snapshot?.peers) ? snapshot.peers : [];
357
528
  const byAddr = new Map();
529
+ const bySession = new Map();
358
530
  for (const p of peers) {
359
531
  const addr = normalizeAddr(p?.addr);
532
+ const session = normalizeSessionId(p?.session);
360
533
  if (!addr) continue;
361
534
  byAddr.set(addr, (byAddr.get(addr) ?? 0) + 1);
535
+ if (session) bySession.set(session, (bySession.get(session) ?? 0) + 1);
362
536
  }
363
- return { snapshot, byAddr };
537
+ return { snapshot, byAddr, bySession };
538
+ }
539
+
540
+ function getSpectatorIdentity(meta, ws) {
541
+ const sessionId = normalizeSessionId(meta?.sessionId);
542
+ if (sessionId) return `session:${sessionId}`;
543
+ const username = normalizeUsername(meta?.username);
544
+ if (username) return `user:${username}`;
545
+ return `socket:${String(meta?.addr ?? 'unknown')}:${ws._socket?._handle?.fd ?? 'na'}`;
364
546
  }
365
547
 
366
548
  function buildAdminStatus() {
367
549
  const hostMeta = hostClient ? clientMeta.get(hostClient) : null;
368
550
  const p2Meta = p2Client ? clientMeta.get(p2Client) : null;
369
551
  const spectators = [];
370
- const { snapshot: webrtcSnapshot, byAddr: webrtcByAddr } = getWebrtcPeerCountByAddr();
371
- const mappedAddrSet = new Set();
372
- if (hostMeta?.addr) mappedAddrSet.add(hostMeta.addr);
373
- if (p2Meta?.addr) mappedAddrSet.add(p2Meta.addr);
552
+ const { snapshot: webrtcSnapshot, byAddr: webrtcByAddr, bySession: webrtcBySession } = getWebrtcPeerCountByAddr();
553
+ const matchedPeerSlots = new Set();
554
+ const webrtcPeers = Array.isArray(webrtcSnapshot?.peers) ? webrtcSnapshot.peers : [];
555
+
556
+ function matchWebrtcPeers(meta) {
557
+ const sessionId = normalizeSessionId(meta?.sessionId);
558
+ if (sessionId && webrtcBySession.has(sessionId)) {
559
+ let matched = 0;
560
+ webrtcPeers.forEach((peer, index) => {
561
+ if (normalizeSessionId(peer?.session) !== sessionId) return;
562
+ matchedPeerSlots.add(index);
563
+ matched++;
564
+ });
565
+ return matched;
566
+ }
567
+
568
+ const addr = normalizeAddr(meta?.addr);
569
+ if (!addr || !webrtcByAddr.has(addr)) return 0;
570
+ let matched = 0;
571
+ webrtcPeers.forEach((peer, index) => {
572
+ if (normalizeAddr(peer?.addr) !== addr) return;
573
+ matchedPeerSlots.add(index);
574
+ matched++;
575
+ });
576
+ return matched;
577
+ }
578
+
579
+ const spectatorByIdentity = new Map();
580
+ const hostWebrtcPeers = matchWebrtcPeers(hostMeta);
581
+ const p2WebrtcPeers = matchWebrtcPeers(p2Meta);
374
582
  for (const [ws, meta] of clientMeta.entries()) {
375
583
  if (ws === hostClient || ws === p2Client) continue;
376
584
  if (ws.readyState !== ws.OPEN) continue;
377
585
  if (meta.role === 'admin') continue;
378
- if (meta.addr) mappedAddrSet.add(meta.addr);
379
- spectators.push({
586
+ const identity = getSpectatorIdentity(meta, ws);
587
+ const existing = spectatorByIdentity.get(identity);
588
+ const spectator = existing ?? {
380
589
  addr: meta.addr,
381
590
  role: meta.role ?? 'spectator',
382
591
  username: meta.username ?? null,
383
- webrtcPeers: webrtcByAddr.get(meta.addr) ?? 0,
384
- });
592
+ webrtcPeers: 0,
593
+ };
594
+ spectator.addr = spectator.addr ?? meta.addr;
595
+ spectator.username = spectator.username ?? meta.username ?? null;
596
+ spectator.webrtcPeers = Math.max(spectator.webrtcPeers, matchWebrtcPeers(meta));
597
+ spectatorByIdentity.set(identity, spectator);
385
598
  }
386
599
 
387
- let mappedWebrtcPeers = 0;
388
- for (const addr of mappedAddrSet) {
389
- mappedWebrtcPeers += webrtcByAddr.get(addr) ?? 0;
390
- }
600
+ spectators.push(...spectatorByIdentity.values());
601
+
391
602
  const webrtcTotal = Number.isFinite(webrtcSnapshot?.total) ? webrtcSnapshot.total : 0;
392
- const anonymousWebrtcPeers = Math.max(0, webrtcTotal - mappedWebrtcPeers);
603
+ const anonymousWebrtcPeers = Math.max(0, webrtcTotal - matchedPeerSlots.size);
393
604
 
394
605
  return {
395
- host: hostClient ? {
396
- connected: hostClient.readyState === hostClient.OPEN,
397
- username: hostUsername,
398
- addr: hostMeta?.addr ?? null,
399
- webrtcPeers: hostMeta?.addr ? (webrtcByAddr.get(hostMeta.addr) ?? 0) : 0,
400
- } : null,
401
- p2: p2Client ? {
402
- connected: p2Client.readyState === p2Client.OPEN,
403
- username: p2Username,
404
- addr: p2Meta?.addr ?? null,
405
- webrtcPeers: p2Meta?.addr ? (webrtcByAddr.get(p2Meta.addr) ?? 0) : 0,
406
- } : null,
606
+ host: hostClient
607
+ ? {
608
+ connected: hostClient.readyState === hostClient.OPEN,
609
+ username: hostUsername,
610
+ addr: hostMeta?.addr ?? null,
611
+ webrtcPeers: hostWebrtcPeers,
612
+ }
613
+ : null,
614
+ p2: p2Client
615
+ ? {
616
+ connected: p2Client.readyState === p2Client.OPEN,
617
+ username: p2Username,
618
+ addr: p2Meta?.addr ?? null,
619
+ webrtcPeers: p2WebrtcPeers,
620
+ }
621
+ : null,
407
622
  spectators,
408
623
  counts: {
409
624
  inputClients: clientCount,
@@ -430,8 +645,11 @@ export function createInputServer(opts = {}) {
430
645
  wss.on('connection', (ws, req) => {
431
646
  clientCount++;
432
647
  const addr = req.socket.remoteAddress;
433
- clientMeta.set(ws, { addr: normalizeAddr(addr), role: 'spectator', username: null });
434
- if (verbose) console.error(`[input-server] client connected from ${addr} (${clientCount} total)`);
648
+ const reqUrl = new URL(req.url || '/', 'http://localhost');
649
+ const sessionId = normalizeSessionId(reqUrl.searchParams.get('sid'));
650
+ clientMeta.set(ws, { addr: normalizeAddr(addr), role: 'spectator', username: null, sessionId });
651
+ if (verbose)
652
+ console.error(`[input-server] client connected from ${addr} (${clientCount} total)`);
435
653
  logEv('client-connected', { addr, total: clientCount });
436
654
 
437
655
  ws.on('message', (data) => {
@@ -448,7 +666,9 @@ export function createInputServer(opts = {}) {
448
666
  // main thread causes a noticeable pause proportional to file size.
449
667
  if (verbose) {
450
668
  if (msg.type === 'load-crt') {
451
- console.error(`[input-server] rx: load-crt filename=${msg.filename ?? '?'} dataLen=${(msg.data ?? '').length}`);
669
+ console.error(
670
+ `[input-server] rx: load-crt filename=${msg.filename ?? '?'} dataLen=${(msg.data ?? '').length}`,
671
+ );
452
672
  } else {
453
673
  console.error(`[input-server] rx:`, JSON.stringify(msg));
454
674
  }
@@ -462,7 +682,10 @@ export function createInputServer(opts = {}) {
462
682
  // the new browser tab gets host-taken and detach/reset silently fail.
463
683
  if (!msg.force) {
464
684
  ws.send(JSON.stringify({ type: 'host-taken' }));
465
- logEv('host-claim-rejected', { reason: 'slot-taken', username: msg.username ?? 'player' });
685
+ logEv('host-claim-rejected', {
686
+ reason: 'slot-taken',
687
+ username: msg.username ?? 'player',
688
+ });
466
689
  return;
467
690
  }
468
691
  // Forcibly evict the existing host before granting the new claim.
@@ -470,29 +693,49 @@ export function createInputServer(opts = {}) {
470
693
  logEv('host-force-evicted', { evicted: hostUsername, by: msg.username ?? 'player' });
471
694
  clearHostTimeout();
472
695
  clearGrace();
473
- try { hostClient.send(JSON.stringify({ type: 'host-evicted', reason: 'force-claim' })); } catch (_) {}
474
- try { hostClient.close(); } catch (_) {}
696
+ try {
697
+ hostClient.send(JSON.stringify({ type: 'host-evicted', reason: 'force-claim' }));
698
+ } catch (_) {}
699
+ try {
700
+ hostClient.close();
701
+ } catch (_) {}
475
702
  setWsIdentity(hostClient, 'spectator', null);
476
- hostClient = null;
703
+ hostClient = null;
477
704
  hostUsername = null;
478
- inviteToken = null;
705
+ inviteToken = null;
479
706
  }
480
707
  const isRejoin = graceTimer && pendingHostUsername === (msg.username ?? 'player');
481
708
  if (graceTimer) clearGrace(); // cancel grace regardless of who's claiming
482
- hostClient = ws;
709
+ hostClient = ws;
483
710
  hostUsername = msg.username ?? 'player';
484
711
  setWsIdentity(ws, 'host', hostUsername);
485
- ws.send(JSON.stringify({
486
- type: 'host-confirmed', username: hostUsername, joystickPort: hostPort(),
487
- player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
488
- }));
712
+ ws.send(
713
+ JSON.stringify({
714
+ type: 'host-confirmed',
715
+ username: hostUsername,
716
+ joystickPort: hostPort(),
717
+ player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
718
+ }),
719
+ );
489
720
  if (isRejoin) {
490
- broadcastExcept(ws, { type: 'host-rejoined', username: hostUsername, joystickPort: hostPort() });
721
+ broadcastExcept(ws, {
722
+ type: 'host-rejoined',
723
+ username: hostUsername,
724
+ joystickPort: hostPort(),
725
+ });
491
726
  } else {
492
- broadcastExcept(ws, { type: 'host-joined', username: hostUsername, joystickPort: hostPort() });
727
+ broadcastExcept(ws, {
728
+ type: 'host-joined',
729
+ username: hostUsername,
730
+ joystickPort: hostPort(),
731
+ });
493
732
  }
494
- if (verbose) console.error(`[input-server] host ${isRejoin ? 're' : ''}claimed by ${hostUsername}`);
495
- logEv(isRejoin ? 'host-rejoined' : 'host-joined', { username: hostUsername, joystickPort: hostPort() });
733
+ if (verbose)
734
+ console.error(`[input-server] host ${isRejoin ? 're' : ''}claimed by ${hostUsername}`);
735
+ logEv(isRejoin ? 'host-rejoined' : 'host-joined', {
736
+ username: hostUsername,
737
+ joystickPort: hostPort(),
738
+ });
496
739
  resetHostTimeout();
497
740
  // P2 slot just opened (host present, no P2)
498
741
  broadcastExcept(ws, { type: 'p2-slot-status', open: isP2SlotOpen() });
@@ -503,13 +746,14 @@ export function createInputServer(opts = {}) {
503
746
  if (msg.type === 'swap-ports') {
504
747
  if (ws !== hostClient) return;
505
748
  portsSwapped = !portsSwapped;
506
- if (verbose) console.error(`[input-server] ports swapped: host=${hostPort()} p2=${p2Port()}`);
749
+ if (verbose)
750
+ console.error(`[input-server] ports swapped: host=${hostPort()} p2=${p2Port()}`);
507
751
  logEv('ports-swapped', { hostPort: hostPort(), p2Port: p2Port() });
508
752
  broadcastAll({
509
- type: 'ports-swapped',
510
- swapped: portsSwapped,
511
- hostPort: hostPort(),
512
- p2Port: p2Port(),
753
+ type: 'ports-swapped',
754
+ swapped: portsSwapped,
755
+ hostPort: hostPort(),
756
+ p2Port: p2Port(),
513
757
  });
514
758
  return;
515
759
  }
@@ -520,9 +764,18 @@ export function createInputServer(opts = {}) {
520
764
  const enabled = !!msg.enabled;
521
765
  const hp = Number(msg.hostPort);
522
766
  const pp = Number(msg.p2Port);
523
- if (!Number.isFinite(hp) || !Number.isFinite(pp) || (hp !== 1 && hp !== 2) || (pp !== 1 && pp !== 2)) {
767
+ if (
768
+ !Number.isFinite(hp) ||
769
+ !Number.isFinite(pp) ||
770
+ (hp !== 1 && hp !== 2) ||
771
+ (pp !== 1 && pp !== 2)
772
+ ) {
524
773
  if (verbose) console.error('[input-server] invalid set-port-override payload');
525
- logEv('error', { kind: 'set-port-override-invalid', hostPort: msg.hostPort, p2Port: msg.p2Port });
774
+ logEv('error', {
775
+ kind: 'set-port-override-invalid',
776
+ hostPort: msg.hostPort,
777
+ p2Port: msg.p2Port,
778
+ });
526
779
  return;
527
780
  }
528
781
  portOverrideEnabled = enabled;
@@ -549,9 +802,9 @@ export function createInputServer(opts = {}) {
549
802
  if (msg.type === 'p2-leave') {
550
803
  if (ws === p2Client) {
551
804
  clearP2Timeout();
552
- p2Client = null;
553
- const leaving = p2Username;
554
- p2Username = null;
805
+ p2Client = null;
806
+ const leaving = p2Username;
807
+ p2Username = null;
555
808
  setWsIdentity(ws, 'spectator', null);
556
809
  if (verbose) console.error(`[input-server] player2 ${leaving} voluntarily left`);
557
810
  logEv('p2-left', { username: leaving, reason: 'voluntary' });
@@ -567,11 +820,11 @@ export function createInputServer(opts = {}) {
567
820
  if (ws === hostClient) {
568
821
  clearHostTimeout();
569
822
  clearGrace();
570
- hostClient = null;
571
- const leaving = hostUsername;
572
- hostUsername = null;
573
- inviteToken = null;
574
- portsSwapped = false;
823
+ hostClient = null;
824
+ const leaving = hostUsername;
825
+ hostUsername = null;
826
+ inviteToken = null;
827
+ portsSwapped = false;
575
828
  portOverrideEnabled = false;
576
829
  overrideHostPort = 2;
577
830
  overrideP2Port = 1;
@@ -628,18 +881,28 @@ export function createInputServer(opts = {}) {
628
881
  ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'already-host' }));
629
882
  return;
630
883
  }
631
- p2Client = ws;
632
- p2Username = requestedUsername;
884
+ p2Client = ws;
885
+ p2Username = requestedUsername;
633
886
  inviteToken = null;
634
887
  setWsIdentity(ws, 'p2', p2Username);
635
- ws.send(JSON.stringify({
636
- type: 'join-p2-confirmed', username: p2Username, joystickPort: p2Port(),
637
- }));
638
- broadcastExcept(ws, { type: 'player2-joined', username: p2Username, joystickPort: p2Port() });
888
+ ws.send(
889
+ JSON.stringify({
890
+ type: 'join-p2-confirmed',
891
+ username: p2Username,
892
+ joystickPort: p2Port(),
893
+ }),
894
+ );
895
+ broadcastExcept(ws, {
896
+ type: 'player2-joined',
897
+ username: p2Username,
898
+ joystickPort: p2Port(),
899
+ });
639
900
  // Notify all clients that the slot is now taken
640
901
  broadcastAll({ type: 'p2-slot-status', open: false });
641
902
  if (verbose) {
642
- console.error(`[input-server] player2 ${isRejoin ? 're' : ''}joined (open): ${p2Username}`);
903
+ console.error(
904
+ `[input-server] player2 ${isRejoin ? 're' : ''}joined (open): ${p2Username}`,
905
+ );
643
906
  }
644
907
  logEv(isRejoin ? 'p2-rejoined' : 'p2-joined', {
645
908
  username: p2Username,
@@ -654,7 +917,10 @@ export function createInputServer(opts = {}) {
654
917
  if (msg.type === 'join-p2') {
655
918
  if (!inviteToken || msg.token !== inviteToken) {
656
919
  ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'invalid-token' }));
657
- logEv('p2-join-rejected', { reason: 'invalid-token', username: msg.username ?? 'player2' });
920
+ logEv('p2-join-rejected', {
921
+ reason: 'invalid-token',
922
+ username: msg.username ?? 'player2',
923
+ });
658
924
  return;
659
925
  }
660
926
  if (p2Client && p2Client.readyState === p2Client.OPEN) {
@@ -673,17 +939,27 @@ export function createInputServer(opts = {}) {
673
939
  return;
674
940
  }
675
941
  if (isRejoin) clearP2Grace();
676
- p2Client = ws;
677
- p2Username = requestedUsername;
942
+ p2Client = ws;
943
+ p2Username = requestedUsername;
678
944
  inviteToken = null;
679
945
  setWsIdentity(ws, 'p2', p2Username);
680
- ws.send(JSON.stringify({
681
- type: 'join-p2-confirmed', username: p2Username, joystickPort: p2Port(),
682
- }));
683
- broadcastExcept(ws, { type: 'player2-joined', username: p2Username, joystickPort: p2Port() });
946
+ ws.send(
947
+ JSON.stringify({
948
+ type: 'join-p2-confirmed',
949
+ username: p2Username,
950
+ joystickPort: p2Port(),
951
+ }),
952
+ );
953
+ broadcastExcept(ws, {
954
+ type: 'player2-joined',
955
+ username: p2Username,
956
+ joystickPort: p2Port(),
957
+ });
684
958
  broadcastAll({ type: 'p2-slot-status', open: false });
685
959
  if (verbose) {
686
- console.error(`[input-server] player2 ${isRejoin ? 're' : ''}joined (token): ${p2Username}`);
960
+ console.error(
961
+ `[input-server] player2 ${isRejoin ? 're' : ''}joined (token): ${p2Username}`,
962
+ );
687
963
  }
688
964
  logEv(isRejoin ? 'p2-rejoined' : 'p2-joined', {
689
965
  username: p2Username,
@@ -705,11 +981,15 @@ export function createInputServer(opts = {}) {
705
981
  const pendingLeaving = pendingP2Username;
706
982
  clearP2Timeout();
707
983
  clearP2Grace();
708
- p2Client = null;
709
- p2Username = null;
984
+ p2Client = null;
985
+ p2Username = null;
710
986
  setWsIdentity(ws, 'spectator', null);
711
987
  if (leaving || pendingLeaving) {
712
- broadcastAll({ type: 'player2-left', username: leaving ?? pendingLeaving, reason: 'revoked' });
988
+ broadcastAll({
989
+ type: 'player2-left',
990
+ username: leaving ?? pendingLeaving,
991
+ reason: 'revoked',
992
+ });
713
993
  }
714
994
  broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
715
995
  if (verbose) console.error(`[input-server] p2 revoked by host`);
@@ -721,51 +1001,114 @@ export function createInputServer(opts = {}) {
721
1001
  if (msg.type === 'admin-status') {
722
1002
  const valid = validateAdminToken(msg.token ?? '');
723
1003
  if (!valid) {
724
- ws.send(JSON.stringify({ type: 'admin-error', command: 'status', reason: 'invalid-token' }));
1004
+ ws.send(
1005
+ JSON.stringify({ type: 'admin-error', command: 'status', reason: 'invalid-token' }),
1006
+ );
725
1007
  return;
726
1008
  }
727
1009
  setWsIdentity(ws, 'admin', null);
728
- ws.send(JSON.stringify({
729
- type: 'admin-status-ok',
730
- status: buildAdminStatus(),
731
- }));
1010
+ ws.send(
1011
+ JSON.stringify({
1012
+ type: 'admin-status-ok',
1013
+ status: buildAdminStatus(),
1014
+ }),
1015
+ );
732
1016
  return;
733
1017
  }
734
1018
 
735
1019
  if (msg.type === 'admin-kick-player') {
736
1020
  const valid = validateAdminToken(msg.token ?? '');
737
1021
  if (!valid) {
738
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'invalid-token' }));
1022
+ ws.send(
1023
+ JSON.stringify({
1024
+ type: 'admin-error',
1025
+ command: 'kick-player',
1026
+ reason: 'invalid-token',
1027
+ }),
1028
+ );
739
1029
  return;
740
1030
  }
741
1031
  setWsIdentity(ws, 'admin', null);
742
- const target = msg.target === 'p2' ? 'p2' : (msg.target === 'host' ? 'host' : null);
1032
+ const target = msg.target === 'p2' ? 'p2' : msg.target === 'host' ? 'host' : null;
743
1033
  if (!target) {
744
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'invalid-target' }));
1034
+ ws.send(
1035
+ JSON.stringify({
1036
+ type: 'admin-error',
1037
+ command: 'kick-player',
1038
+ reason: 'invalid-target',
1039
+ }),
1040
+ );
745
1041
  return;
746
1042
  }
747
- const result = target === 'host'
748
- ? kickHostByReason('admin-kick')
749
- : kickP2ByReason('admin-kick');
1043
+ const result =
1044
+ target === 'host' ? kickHostByReason('admin-kick') : kickP2ByReason('admin-kick');
750
1045
  if (!result.kicked) {
751
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-player', reason: 'target-not-present', target }));
1046
+ ws.send(
1047
+ JSON.stringify({
1048
+ type: 'admin-error',
1049
+ command: 'kick-player',
1050
+ reason: 'target-not-present',
1051
+ target,
1052
+ }),
1053
+ );
1054
+ return;
1055
+ }
1056
+ logEv(target === 'host' ? 'host-kicked' : 'p2-kicked', {
1057
+ username: result.username ?? '-',
1058
+ by: 'admin-cli',
1059
+ });
1060
+ ws.send(
1061
+ JSON.stringify({
1062
+ type: 'admin-kick-player-ok',
1063
+ target,
1064
+ username: result.username,
1065
+ addr: result.addr,
1066
+ status: buildAdminStatus(),
1067
+ }),
1068
+ );
1069
+ return;
1070
+ }
1071
+
1072
+ if (msg.type === 'admin-activity') {
1073
+ const valid = validateAdminToken(msg.token ?? '');
1074
+ if (!valid) {
1075
+ ws.send(
1076
+ JSON.stringify({ type: 'admin-error', command: 'activity', reason: 'invalid-token' }),
1077
+ );
1078
+ return;
1079
+ }
1080
+ setWsIdentity(ws, 'admin', null);
1081
+ const role = msg.role === 'p2' ? 'p2' : msg.role === 'host' ? 'host' : null;
1082
+ if (!role) {
1083
+ ws.send(
1084
+ JSON.stringify({ type: 'admin-error', command: 'activity', reason: 'invalid-role' }),
1085
+ );
752
1086
  return;
753
1087
  }
754
- logEv(target === 'host' ? 'host-kicked' : 'p2-kicked', { username: result.username ?? '-', by: 'admin-cli' });
755
- ws.send(JSON.stringify({
756
- type: 'admin-kick-player-ok',
757
- target,
758
- username: result.username,
759
- addr: result.addr,
760
- status: buildAdminStatus(),
761
- }));
1088
+ const active = role === 'host' ? !!hostClient : !!p2Client;
1089
+ if (!active) {
1090
+ ws.send(
1091
+ JSON.stringify({ type: 'admin-error', command: 'activity', reason: 'role-not-present' }),
1092
+ );
1093
+ return;
1094
+ }
1095
+ resetRoleActivity(role, msg.source ?? 'admin');
1096
+ ws.send(
1097
+ JSON.stringify({
1098
+ type: 'admin-activity-ok',
1099
+ role,
1100
+ source: msg.source ?? 'admin',
1101
+ }),
1102
+ );
762
1103
  return;
763
1104
  }
764
1105
 
765
1106
  if (msg.type === 'admin-kick-all') {
766
1107
  const valid = validateAdminToken(msg.token ?? '');
767
1108
  if (!valid) {
768
- ws.send(JSON.stringify({ type: 'admin-error', command: 'kick-all', reason: 'invalid-token' }));
1109
+ ws.send(
1110
+ JSON.stringify({ type: 'admin-error', command: 'kick-all', reason: 'invalid-token' }),
1111
+ );
769
1112
  return;
770
1113
  }
771
1114
  setWsIdentity(ws, 'admin', null);
@@ -783,18 +1126,21 @@ export function createInputServer(opts = {}) {
783
1126
  const meta = clientMeta.get(c);
784
1127
  if (meta?.role === 'admin') continue;
785
1128
  try {
786
- if (c.readyState === c.OPEN) c.send(JSON.stringify({ type: 'kicked', reason: 'admin-kick-all' }));
1129
+ if (c.readyState === c.OPEN)
1130
+ c.send(JSON.stringify({ type: 'kicked', reason: 'admin-kick-all' }));
787
1131
  c.close();
788
1132
  kicked.spectators++;
789
1133
  } catch (_) {}
790
1134
  }
791
1135
  kicked.webrtcPeers = disconnectAllWebrtcPeers('admin-kick-all');
792
1136
  logEv('admin-kick-all', { spectators: kicked.spectators, webrtcPeers: kicked.webrtcPeers });
793
- ws.send(JSON.stringify({
794
- type: 'admin-kick-all-ok',
795
- kicked,
796
- status: buildAdminStatus(),
797
- }));
1137
+ ws.send(
1138
+ JSON.stringify({
1139
+ type: 'admin-kick-all-ok',
1140
+ kicked,
1141
+ status: buildAdminStatus(),
1142
+ }),
1143
+ );
798
1144
  return;
799
1145
  }
800
1146
 
@@ -828,7 +1174,8 @@ export function createInputServer(opts = {}) {
828
1174
  if (ws !== hostClient) return;
829
1175
  const loadFilename = msg.filename ?? '';
830
1176
  const fileType = msg.fileType ?? 'crt';
831
- if (verbose) console.error(`[input-server] load-file: ${loadFilename || '?'} (${fileType})`);
1177
+ if (verbose)
1178
+ console.error(`[input-server] load-file: ${loadFilename || '?'} (${fileType})`);
832
1179
  logEv('cmd-load-file', {
833
1180
  filename: loadFilename || '?',
834
1181
  fileType,
@@ -836,7 +1183,14 @@ export function createInputServer(opts = {}) {
836
1183
  });
837
1184
  broadcastAll({ type: 'cart-loading', filename: loadFilename });
838
1185
  Promise.resolve()
839
- .then(() => onCommand({ type: 'load-file', filename: loadFilename, fileType, data: msg.data ?? '' }))
1186
+ .then(() =>
1187
+ onCommand({
1188
+ type: 'load-file',
1189
+ filename: loadFilename,
1190
+ fileType,
1191
+ data: msg.data ?? '',
1192
+ }),
1193
+ )
840
1194
  .then(() => {
841
1195
  currentCartFilename = loadFilename || null;
842
1196
  broadcastAll({ type: 'cart-loaded', filename: loadFilename });
@@ -861,7 +1215,14 @@ export function createInputServer(opts = {}) {
861
1215
  const loadFilename = msg.filename ?? '';
862
1216
  broadcastAll({ type: 'cart-loading', filename: loadFilename });
863
1217
  Promise.resolve()
864
- .then(() => onCommand({ type: 'load-file', filename: loadFilename, fileType: 'crt', data: msg.data ?? '' }))
1218
+ .then(() =>
1219
+ onCommand({
1220
+ type: 'load-file',
1221
+ filename: loadFilename,
1222
+ fileType: 'crt',
1223
+ data: msg.data ?? '',
1224
+ }),
1225
+ )
865
1226
  .then(() => {
866
1227
  currentCartFilename = loadFilename || null;
867
1228
  broadcastAll({ type: 'cart-loaded', filename: loadFilename });
@@ -869,7 +1230,11 @@ export function createInputServer(opts = {}) {
869
1230
  .catch((e) => {
870
1231
  broadcastAll({ type: 'cart-load-error', reason: String(e?.message ?? e) });
871
1232
  if (verbose) console.error('[input-server] load-crt error:', e);
872
- logEv('error', { kind: 'load-crt-failed', filename: loadFilename, err: String(e?.message ?? e) });
1233
+ logEv('error', {
1234
+ kind: 'load-crt-failed',
1235
+ filename: loadFilename,
1236
+ err: String(e?.message ?? e),
1237
+ });
873
1238
  });
874
1239
  return;
875
1240
  }
@@ -907,89 +1272,74 @@ export function createInputServer(opts = {}) {
907
1272
  return;
908
1273
  }
909
1274
 
1275
+ if (msg.type === 'reboot') {
1276
+ if (ws !== hostClient) return;
1277
+ if (verbose) console.error('[input-server] reboot');
1278
+ logEv('cmd-reboot', { host: hostUsername });
1279
+ Promise.resolve()
1280
+ .then(() => onCommand({ type: 'reboot' }))
1281
+ .then(() => {
1282
+ currentCartFilename = null;
1283
+ broadcastAll({ type: 'machine-rebooted' });
1284
+ })
1285
+ .catch((e) => {
1286
+ if (verbose) console.error('[input-server] reboot error:', e);
1287
+ logEv('error', { kind: 'reboot-failed', err: String(e?.message ?? e) });
1288
+ });
1289
+ return;
1290
+ }
1291
+
1292
+ if (msg.type === 'save-snapshot') {
1293
+ if (ws !== hostClient) return;
1294
+ if (verbose) console.error('[input-server] save-snapshot');
1295
+ logEv('cmd-save-snapshot', { host: hostUsername });
1296
+ Promise.resolve()
1297
+ .then(() => onCommand({ type: 'save-snapshot' }))
1298
+ .then((result) => {
1299
+ if (!result || ws.readyState !== ws.OPEN) return;
1300
+ ws.send(
1301
+ JSON.stringify({
1302
+ type: 'snapshot-data',
1303
+ filename: result.filename ?? 'snapshot.c64',
1304
+ data: result.data ?? '',
1305
+ }),
1306
+ );
1307
+ })
1308
+ .catch((e) => {
1309
+ if (ws.readyState === ws.OPEN) {
1310
+ ws.send(JSON.stringify({ type: 'snapshot-save-error', reason: String(e?.message ?? e) }));
1311
+ }
1312
+ if (verbose) console.error('[input-server] save-snapshot error:', e);
1313
+ logEv('error', { kind: 'save-snapshot-failed', err: String(e?.message ?? e) });
1314
+ });
1315
+ return;
1316
+ }
1317
+
910
1318
  // ── Input events ─────────────────────────────────────────────────────
911
1319
  if (msg.type === 'joystick' || msg.type === 'key') {
912
1320
  if (ws !== hostClient && ws !== p2Client) return;
913
- if (ws === hostClient) resetHostTimeout();
914
- if (ws === p2Client) resetP2Timeout();
915
- // Track input counts for flood investigation
916
1321
  const role = ws === hostClient ? 'host' : 'p2';
917
- const stats = role === 'host' ? _inputStats.host : _inputStats.p2;
918
- if (msg.type === 'joystick') stats.joystick++;
919
- else stats.key++;
920
- stats.lastMsgTime = Date.now();
921
-
922
- // ── Input latency profiling ───────────────────────────────────────
923
- if (msg.clientTime) {
924
- const now = Date.now();
925
- const latency = now - msg.clientTime;
926
- const bucket = _networkStats[role];
927
- if (bucket) {
928
- bucket.lastLatency = latency;
929
- }
930
- // Log latency periodically (every 5s) to avoid spam
931
- if (!_latencyLogTimer) {
932
- _latencyLogTimer = setInterval(() => {
933
- const hostActive = _latencyCount.host > 0;
934
- const p2Active = _latencyCount.p2 > 0;
935
- if (hostActive || p2Active) {
936
- const hostAvg = hostActive ? Number(_avgLatency.host.toFixed(0)) : null;
937
- const p2Avg = p2Active ? Number(_avgLatency.p2.toFixed(0)) : null;
938
- const hostLabel = hostAvg != null ? `${hostAvg}` : '--';
939
- const p2Label = p2Avg != null ? `${p2Avg}` : '--';
940
- if (logEvents || verbose) {
941
- console.error(`[event] input-latency host-avg=${hostLabel}ms p2-avg=${p2Label}ms`);
942
- }
943
- _networkStats.host.avgLatency = hostAvg;
944
- _networkStats.p2.avgLatency = p2Avg;
945
- broadcastNetworkStats();
946
- }
947
- // Reset averages
948
- _avgLatency.host = 0; _avgLatency.p2 = 0;
949
- _latencyCount.host = 0; _latencyCount.p2 = 0;
950
- }, 5000);
951
- }
952
- // Accumulate for averaging
953
- _latencyCount[role]++;
954
- _avgLatency[role] = ((_avgLatency[role] * (_latencyCount[role] - 1)) + latency) / _latencyCount[role];
955
- if (latency > LATENCY_SPIKE_MS) {
956
- if (bucket) {
957
- bucket.lastSpikeLatency = latency;
958
- bucket.lastSpikeAt = now;
959
- }
960
- if (logEvents || verbose) {
961
- console.error(`[event] input-latency-spike role=${role} latency=${latency}ms type=${msg.type} action=${msg.action ?? '-'} ` +
962
- `dir=${msg.direction ?? '-'} fire=${msg.fire ? 1 : 0}`);
963
- }
964
- }
965
- }
966
-
967
- // Tag with role so onInput can include it in logEvents output
968
- // without input-server needing to know about logEvents details.
969
- msg._role = role;
970
- if (msg.type === 'joystick') {
971
- msg.joystickPort = role === 'host' ? hostPort() : p2Port();
972
- }
973
- if (onInput) onInput(msg);
974
- if (Number.isFinite(msg.inputId) && ws.readyState === ws.OPEN) {
975
- try {
976
- ws.send(JSON.stringify({ type: 'input-ack', inputId: msg.inputId }));
977
- } catch (_) {}
978
- }
1322
+ handleInputTransportMessage({
1323
+ msg,
1324
+ role,
1325
+ respond: (payload) => {
1326
+ if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(payload));
1327
+ },
1328
+ });
979
1329
  return;
980
1330
  }
981
1331
 
982
1332
  if (msg.type === 'ping') {
983
- const role = ws === hostClient ? 'host' : (ws === p2Client ? 'p2' : 'spectator');
984
- const now = Date.now();
985
- const payload = {
986
- type: 'pong',
987
- pingId: msg.pingId ?? null,
988
- serverTime: now,
989
- clientTime: msg.clientTime ?? null,
990
- };
991
- try { ws.send(JSON.stringify(payload)); } catch (_) {}
992
- if (verbose) console.error(`[ping] role=${role} pong pingId=${msg.pingId ?? '-'} `);
1333
+ const role = ws === hostClient ? 'host' : ws === p2Client ? 'p2' : 'spectator';
1334
+ handleInputTransportMessage({
1335
+ msg,
1336
+ role,
1337
+ respond: (payload) => {
1338
+ try {
1339
+ ws.send(JSON.stringify(payload));
1340
+ } catch (_) {}
1341
+ },
1342
+ });
993
1343
  return;
994
1344
  }
995
1345
  });
@@ -1001,11 +1351,11 @@ export function createInputServer(opts = {}) {
1001
1351
 
1002
1352
  if (ws === hostClient) {
1003
1353
  clearHostTimeout();
1004
- hostClient = null;
1354
+ hostClient = null;
1005
1355
  const leaving = hostUsername;
1006
- hostUsername = null;
1007
- inviteToken = null;
1008
- portsSwapped = false;
1356
+ hostUsername = null;
1357
+ inviteToken = null;
1358
+ portsSwapped = false;
1009
1359
  portOverrideEnabled = false;
1010
1360
  overrideHostPort = 2;
1011
1361
  overrideP2Port = 1;
@@ -1014,9 +1364,9 @@ export function createInputServer(opts = {}) {
1014
1364
 
1015
1365
  if (ws === p2Client) {
1016
1366
  clearP2Timeout();
1017
- p2Client = null;
1367
+ p2Client = null;
1018
1368
  const leaving = p2Username;
1019
- p2Username = null;
1369
+ p2Username = null;
1020
1370
  onP2Disconnect(leaving);
1021
1371
  }
1022
1372
  clientMeta.delete(ws);
@@ -1030,31 +1380,39 @@ export function createInputServer(opts = {}) {
1030
1380
  // ── Hello handshake ───────────────────────────────────────────────────
1031
1381
  const hostActive = !!(hostClient && hostClient.readyState === hostClient.OPEN);
1032
1382
  const serverTime = Date.now();
1033
- ws.send(JSON.stringify({
1034
- type: 'hello',
1035
- protocol: 'c64-input',
1036
- version: 1,
1037
- serverTime, // Unix ms for client clock sync
1038
- // During grace period: treat slot as free so the original host can reclaim it.
1039
- // hostPendingRejoin tells P2 (and spectators) to hold off.
1040
- hostTaken: hostActive,
1041
- hostPendingRejoin: !hostActive && !!graceTimer ? { username: pendingHostUsername, graceMs: HOST_RECONNECT_GRACE } : null,
1042
- host: hostActive ? { username: hostUsername, joystickPort: hostPort() } : null,
1043
- p2PendingRejoin: !p2Client && !!p2GraceTimer ? { username: pendingP2Username, graceMs: P2_RECONNECT_GRACE } : null,
1044
- player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
1045
- p2SlotOpen: isP2SlotOpen(),
1046
- portOverride: {
1047
- enabled: portOverrideEnabled,
1048
- hostPort: overrideHostPort,
1049
- p2Port: overrideP2Port,
1050
- effectiveHostPort: hostPort(),
1051
- effectiveP2Port: p2Port(),
1052
- },
1053
- ...(currentCartFilename ? { cartFilename: currentCartFilename } : {}),
1054
- joystickBitmask: { up: 0x1, down: 0x2, left: 0x4, right: 0x8, fire: 0x10 },
1055
- ...(serverVersion ? { serverVersion } : {}),
1056
- ...(serverGitHash ? { serverGitHash } : {}),
1057
- }));
1383
+ ws.send(
1384
+ JSON.stringify({
1385
+ type: 'hello',
1386
+ protocol: 'c64-input',
1387
+ version: 1,
1388
+ serverTime, // Unix ms for client clock sync
1389
+ // During grace period: treat slot as free so the original host can reclaim it.
1390
+ // hostPendingRejoin tells P2 (and spectators) to hold off.
1391
+ hostTaken: hostActive,
1392
+ hostPendingRejoin:
1393
+ !hostActive && !!graceTimer
1394
+ ? { username: pendingHostUsername, graceMs: HOST_RECONNECT_GRACE }
1395
+ : null,
1396
+ host: hostActive ? { username: hostUsername, joystickPort: hostPort() } : null,
1397
+ p2PendingRejoin:
1398
+ !p2Client && !!p2GraceTimer
1399
+ ? { username: pendingP2Username, graceMs: P2_RECONNECT_GRACE }
1400
+ : null,
1401
+ player2: p2Username ? { username: p2Username, joystickPort: p2Port() } : null,
1402
+ p2SlotOpen: isP2SlotOpen(),
1403
+ portOverride: {
1404
+ enabled: portOverrideEnabled,
1405
+ hostPort: overrideHostPort,
1406
+ p2Port: overrideP2Port,
1407
+ effectiveHostPort: hostPort(),
1408
+ effectiveP2Port: p2Port(),
1409
+ },
1410
+ ...(currentCartFilename ? { cartFilename: currentCartFilename } : {}),
1411
+ joystickBitmask: { up: 0x1, down: 0x2, left: 0x4, right: 0x8, fire: 0x10 },
1412
+ ...(serverVersion ? { serverVersion } : {}),
1413
+ ...(serverGitHash ? { serverGitHash } : {}),
1414
+ }),
1415
+ );
1058
1416
  });
1059
1417
 
1060
1418
  wss.on('error', (err) => {
@@ -1062,16 +1420,29 @@ export function createInputServer(opts = {}) {
1062
1420
  logEv('error', { kind: 'server-error', err: err.message });
1063
1421
  });
1064
1422
 
1065
- const close = () => new Promise((resolve) => {
1066
- clearHostTimeout();
1067
- clearP2Timeout();
1068
- clearGrace();
1069
- clearP2Grace();
1070
- if (_inputLogTimer) { clearInterval(_inputLogTimer); _inputLogTimer = null; }
1071
- if (_latencyLogTimer) { clearInterval(_latencyLogTimer); _latencyLogTimer = null; }
1072
- if (_networkStatsTimer) { clearInterval(_networkStatsTimer); _networkStatsTimer = null; }
1073
- wss.close(() => resolve());
1074
- });
1423
+ const close = () =>
1424
+ new Promise((resolve) => {
1425
+ clearHostTimeout();
1426
+ clearP2Timeout();
1427
+ clearGrace();
1428
+ clearP2Grace();
1429
+ if (_inputLogTimer) {
1430
+ clearInterval(_inputLogTimer);
1431
+ _inputLogTimer = null;
1432
+ }
1433
+ if (_latencyLogTimer) {
1434
+ clearInterval(_latencyLogTimer);
1435
+ _latencyLogTimer = null;
1436
+ }
1437
+ if (_networkStatsTimer) {
1438
+ clearInterval(_networkStatsTimer);
1439
+ _networkStatsTimer = null;
1440
+ }
1441
+ for (const client of wss.clients) {
1442
+ try { client.terminate(); } catch (_) {}
1443
+ }
1444
+ wss.close(() => resolve());
1445
+ });
1075
1446
 
1076
- return { wss, close };
1447
+ return { wss, close, handlePeerDataMessage };
1077
1448
  }