@ksaa-nlp/gamehub-sdk 0.6.1 → 0.9.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,150 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.0 — 2026-05-03
4
+
5
+ Tier-2 / Tier-3 multiplayer features. The headline change is **server-enforced host-only events** (E) — a guest can no longer forge authoritative state by hand-crafting a wire frame. Also: **opt-in host migration** (G), **per-room realtime rate limits** (F), `lastSeenAt` on peers (J), and a structured `ROOM_FULL` error frame (I).
6
+
7
+ Existing games that don't enable `autoMigrateHost` keep current behaviour. Existing `multiplayer.broadcast` callers are silently upgraded — the SDK now stamps `hostOnly: true` on every broadcast, and a non-host trying to bypass `multiplayer.broadcast` and call `multiplayer.send` with `hostOnly: true` will be dropped server-side. Game code does not need to change.
8
+
9
+ ### Server-enforced `hostOnly` (E) — security
10
+
11
+ Wire frames may now carry `hostOnly: true`. The realtime server drops such a frame and replies with `{ type: 'system', eventName: 'error', payload: { code: 'HOST_ONLY', eventName } }` when the sender's role is not `host`. The SDK's `multiplayer.broadcast` and the match-API's `ctx.broadcast` / start-event paths set the flag automatically, so authoritative game state can no longer be forged by a guest. Application code does not need to set `hostOnly` directly.
12
+
13
+ ```ts
14
+ sdk.multiplayer.broadcast('cell_opened', { id: 7 });
15
+ // wire: { eventName: 'cell_opened', payload: ..., hostOnly: true }
16
+ // — server enforces; a guest sending the same frame gets HOST_ONLY back.
17
+ ```
18
+
19
+ ### Configurable per-room rate limits (F)
20
+
21
+ `RoomOptions` accepts `rateBurst` and `rateWindowMs`. Defaults remain 20 frames per 1000ms — fine for turn-based play. Real-time games (movement, drawing, fast input) raise the burst:
22
+
23
+ ```ts
24
+ sdk.multiplayer.createRoom({ rateBurst: 100, rateWindowMs: 1000 });
25
+ ```
26
+
27
+ Cached on `wsMeta` at connect time so the message hot path doesn't re-read the room doc per frame. The HTTP `/multiplayer/rooms/create` endpoint validates and persists both fields.
28
+
29
+ ### Host migration on host-disconnect (G) — opt-in
30
+
31
+ `RoomOptions.autoMigrateHost: true` flips host-disconnect from "close the room after the grace window" to "promote the earliest-joined remaining peer." Server-side flow on timer expiry:
32
+
33
+ 1. Pick the earliest-joined active peer (via `getPeers()`, now `joinedAt`-ordered — see H).
34
+ 2. Update its peer doc role to `host`, demote the previous host's peer doc to `player`, and update the room's `hostPeerId`.
35
+ 3. Flip `wsMeta.role` for the new host's live socket so its next `broadcast` passes the `hostOnly` check immediately.
36
+ 4. Publish `{ type: 'system', eventName: 'host_changed', payload: { newHostPeerId, previousHostPeerId } }` to the room.
37
+
38
+ The SDK listens for `host_changed`: if the local peer is the promotee, `state.mpRoom.role` flips to `host` and subsequent `multiplayer.isHost()` / `multiplayer.broadcast` route correctly without a reconnect. The match-API picks this up via `Multiplayer.isHost()` (already dynamic), so a mid-match migration doesn't require re-running `buildStart` — the new host just becomes responsible for `ctx.broadcast` going forward.
39
+
40
+ A new upgrade-path guard rejects WebSocket upgrades whose JWT claims `role: 'host'` when the room's current `hostPeerId` doesn't match the token's `peerId`, closing a small race where the original host's stale token could re-claim host after migration.
41
+
42
+ ```ts
43
+ // Lobby / casual co-op: keep playing if host drops.
44
+ sdk.multiplayer.createRoom({ autoMigrateHost: true });
45
+
46
+ sdk.multiplayer.on('host_changed', ({ newHostPeerId, previousHostPeerId }) => {
47
+ if (sdk.multiplayer.getMyPeerId() === newHostPeerId) {
48
+ // we are now responsible for authoritative state
49
+ }
50
+ });
51
+ ```
52
+
53
+ **Default off.** Most match-style games (link-game, quizzes) should leave it off — losing the host mid-match is correctly fatal because the host owns authoritative state. Suitable for relay / lobby / casual co-op games where any peer can keep play going.
54
+
55
+ ### `getPeers` ordered by `joinedAt` (H)
56
+
57
+ `getPeers()` now sorts by `joinedAt` ascending. This makes seat-assignment deterministic on first reference (no more lex-sort fallback by peerId), and is a prerequisite for G's "earliest-joined first" promotion. No game-visible behaviour change beyond ordering stability.
58
+
59
+ ### `ROOM_FULL` system frame (I)
60
+
61
+ Previously, a WS upgrade past `maxPlayers + overbook` was rejected with a raw `socket.destroy()` — the SDK saw a connection refused and the game showed a generic error. The server now completes the WS handshake just long enough to deliver `{ type: 'system', eventName: 'error', payload: { code: 'ROOM_FULL', maxPlayers } }` and then closes with code 4001. The HTTP `/joinRoom` path still pre-checks capacity, so this matters mainly for the WS-upgrade race when two peers try to claim the last seat simultaneously.
62
+
63
+ ### `lastSeenAt` on peers (J)
64
+
65
+ `Peer.lastSeenAt` (ms since epoch) is now populated in the `room_joined` peers list and on every `peer_joined` payload. Refreshed on every inbound frame and on the WS heartbeat. Lets games render "last seen 3s ago" badges or dim flaky peers without extra plumbing.
66
+
67
+ ```ts
68
+ const peers = sdk.multiplayer.getPeers();
69
+ peers.forEach((p) => {
70
+ const stale = Date.now() - (p.lastSeenAt ?? 0) > 5_000;
71
+ // dim avatar, show spinner, etc.
72
+ });
73
+ ```
74
+
75
+ ### Migration notes
76
+
77
+ - **Server config**: a new optional env knob `MULTIPLAYER_HOST_CLOSE_GRACE_MS` decouples the host-close timer from `RECONNECT_GRACE_MS` (production default still 30s). Used by integration tests so the migration path doesn't take 30s to fire.
78
+ - **Mongo schema**: `multiplayer_rooms` gains optional `rateBurst`, `rateWindowMs`, `autoMigrateHost` fields. All optional — existing room docs work unchanged.
79
+ - **Client semantics**: a non-host calling `multiplayer.send(name, payload, { hostOnly: true })` will now be dropped server-side with a `HOST_ONLY` error frame. This was effectively impossible before (the SDK didn't accept the option), so this is only a hazard for hand-crafted wire frames or custom clients.
80
+
81
+ ## 0.7.0 — 2026-04-30
82
+
83
+ Three Tier-1 transport features completing the multiplayer roadmap: targeted send, per-peer seq continuity across reconnect, and a server-clock helper. All three are additive — existing `multiplayer.send` / `broadcast` / `match` calls keep their current semantics.
84
+
85
+ ### Targeted send (`SendOptions.to`)
86
+
87
+ `multiplayer.send(name, payload, { to: peerId | peerId[] })` and the matching `MatchBroadcastOptions.to` route a frame to a specific subset of peers in the room instead of fanning out. Use cases: a private host→guest hint, per-player power-up effects that shouldn't leak to a spectator, host correcting one guest's view.
88
+
89
+ ```ts
90
+ sdk.multiplayer.send('private_hint', payload, { to: guestPeerId });
91
+ ctx.broadcast('reveal_for_winner', payload, { to: [winnerId] });
92
+ ```
93
+
94
+ Server-side semantics:
95
+ - The sender does NOT receive their own frame as an echo unless their id is explicitly in the `to` list.
96
+ - Unknown peerIds are silently skipped (no error frame).
97
+ - `to` and `retain` are mutually exclusive — a targeted frame is per-definition not a room-wide snapshot, so the server drops `retain` when `to` is set. The match-API mirrors this client-side and also skips the local `apply` step on targeted broadcasts (targeting means "send state to specific peers", not "this is the new authoritative state").
98
+
99
+ ### Per-peer seq continuity across reconnect
100
+
101
+ A peer's outbound `seq` counter now survives a disconnect+reconnect within `RECONNECT_GRACE_MS` (30s). Previously the counter reset to 0 on every new socket because it lived in `wsMeta` (a `WeakMap` keyed by socket); a reconnecting peer's first new message would have `seq=1`, which the SDK's `mpLastSeqByPeer` dedupe at the receiver would compare against the last value seen pre-disconnect (e.g. `seq=12`) and silently drop.
102
+
103
+ Server changes that fix this:
104
+ - The `multiplayer_peers` collection now stores `seq` per peer doc.
105
+ - `storePeer()` (called on every connect) reads the existing seq and seeds `wsMeta.state.seq` from it before any message is processed.
106
+ - The message handler captures `state.seq` into a local immediately after incrementing, then awaits `touchPeer(peerId, seq)` (persists seq + lastSeenAt) BEFORE publishing — so a crash between persist and publish leaves the DB at-least-as-recent as what receivers observed.
107
+ - The `ws.on('close')` handler no longer deletes the peer doc; it sets `lastSeenAt: 0` so `getPeers` immediately filters the peer out, but the `seq` value stays around for a reconnect to pick up.
108
+
109
+ Race fix as part of this: previously, three concurrent message handlers on the same socket could yield on `await touchPeer` interleaved, all read `state.seq` at the end, and emit identical seqs. The seq is now snapshotted into a local before any `await`.
110
+
111
+ ### Server clock helper (`multiplayer.serverNow()`)
112
+
113
+ `sdk.multiplayer.serverNow()` returns a server-anchored timestamp in milliseconds. Use it — not `Date.now()` — for any timer math compared across peers (countdowns, deadlines, replay times). Peer device clocks routinely drift seconds apart; without this, two peers running the same `maxTimeSec - (Date.now() - serverStartMs)/1000` countdown can show different remaining times.
114
+
115
+ Implementation: every incoming frame's `sentAt - Date.now()` becomes a sample. The first sample sets the offset wholesale; subsequent samples blend via a 0.85 / 0.15 EMA so a single high-latency packet doesn't yank the clock around. Retained replays are excluded from offset updates (their `sentAt` is when the host originally pinned them, not the current network).
116
+
117
+ ```ts
118
+ // Old: brittle across clock skew
119
+ const remaining = maxTimeSec - (Date.now() - serverStartMs) / 1000;
120
+
121
+ // New: stable
122
+ const remaining = maxTimeSec - (sdk.multiplayer.serverNow() - serverStartMs) / 1000;
123
+ ```
124
+
125
+ Returns `Date.now()` exactly until the first frame arrives, so games can call it during boot without special-casing.
126
+
127
+ ### Verified
128
+
129
+ - 23/23 realtime tests green (14 unit + 9 integration). New tests cover: targeted single-peer delivery, targeted multi-peer delivery, targeted-strips-retain, seq continuity across reconnect, peer-doc preserved on disconnect.
130
+ - SDK type-check + build clean.
131
+
132
+ ### Wire format
133
+
134
+ Strictly additive on the wire. Inbound (client → server):
135
+ - `to?: string | string[]` — targeted recipients.
136
+
137
+ Server → client: unchanged. The server-stamped `sentAt` was already on every frame; v0.7 just consumes it on the SDK side.
138
+
139
+ ### Unchanged
140
+
141
+ - `Sdk` interface beyond the new `multiplayer.serverNow()` method and the new `to` field on `SendOptions` / `MatchBroadcastOptions` (both optional).
142
+ - `BootstrapData`, `MpMessage`.
143
+ - All other multiplayer methods.
144
+ - The match API — adding retain/seq features here doesn't touch its semantics.
145
+
146
+ ---
147
+
3
148
  ## 0.6.1 — 2026-04-30
4
149
 
5
150
  Three small, additive fixes that surfaced while porting link-game to the `multiplayer.match` API.
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  (() => {
3
3
  // src/constants.ts
4
- var SDK_VERSION = "0.6.1";
4
+ var SDK_VERSION = "0.7.0";
5
5
  var MESSAGE_PREFIX = "GAMEHUB_SDK";
6
6
  var PARENT_REQUEST_TIMEOUT_MS = 2e3;
7
7
  var MP_MAX_RECONNECT_ATTEMPTS = 5;
@@ -52,7 +52,9 @@
52
52
  mpPeers: /* @__PURE__ */ new Map(),
53
53
  mpHandlers: /* @__PURE__ */ new Map(),
54
54
  mpLastSeqByPeer: /* @__PURE__ */ new Map(),
55
- mpViewerOverride: false
55
+ mpViewerOverride: false,
56
+ mpServerOffsetMs: 0,
57
+ mpServerOffsetSamples: 0
56
58
  };
57
59
 
58
60
  // src/utils.ts
@@ -394,6 +396,15 @@
394
396
  return;
395
397
  }
396
398
  if (!message || !message.type) return;
399
+ if (typeof message.sentAt === "number" && message.retained !== true) {
400
+ const sample = message.sentAt - Date.now();
401
+ if (state.mpServerOffsetSamples === 0) {
402
+ state.mpServerOffsetMs = sample;
403
+ } else {
404
+ state.mpServerOffsetMs = 0.85 * state.mpServerOffsetMs + 0.15 * sample;
405
+ }
406
+ state.mpServerOffsetSamples += 1;
407
+ }
397
408
  if (message.type === "system") {
398
409
  if (message.eventName === "room_joined") {
399
410
  state.mpPeers.clear();
@@ -412,6 +423,28 @@
412
423
  emit("room_left", { reason: "room_closed" });
413
424
  clearSocket();
414
425
  }
426
+ if (message.eventName === "host_changed" && message.payload?.newHostPeerId && state.mpRoom) {
427
+ const newHostPeerId = message.payload.newHostPeerId;
428
+ const previousHostPeerId = message.payload.previousHostPeerId;
429
+ if (state.mpRoom.peerId === newHostPeerId) {
430
+ state.mpRoom.role = "host";
431
+ } else if (previousHostPeerId && state.mpRoom.peerId === previousHostPeerId) {
432
+ state.mpRoom.role = "player";
433
+ }
434
+ const promoted = state.mpPeers.get(newHostPeerId);
435
+ if (promoted) {
436
+ state.mpPeers.set(newHostPeerId, { ...promoted, role: "host" });
437
+ }
438
+ if (previousHostPeerId) {
439
+ const prev = state.mpPeers.get(previousHostPeerId);
440
+ if (prev) {
441
+ state.mpPeers.set(previousHostPeerId, {
442
+ ...prev,
443
+ role: "player"
444
+ });
445
+ }
446
+ }
447
+ }
415
448
  emit(message.eventName, message.payload || {});
416
449
  return;
417
450
  }
@@ -472,7 +505,10 @@
472
505
  body: {
473
506
  gameSlug: state.gameSlug,
474
507
  maxPlayers: options.maxPlayers,
475
- passcode: options.passcode
508
+ passcode: options.passcode,
509
+ rateBurst: options.rateBurst,
510
+ rateWindowMs: options.rateWindowMs,
511
+ autoMigrateHost: options.autoMigrateHost
476
512
  }
477
513
  });
478
514
  const data = unwrapResult(result);
@@ -648,6 +684,9 @@
648
684
  if (options.to !== void 0) {
649
685
  frame.to = options.to;
650
686
  }
687
+ if (options.hostOnly === true) {
688
+ frame.hostOnly = true;
689
+ }
651
690
  socket.send(JSON.stringify(frame));
652
691
  return true;
653
692
  }
@@ -656,7 +695,7 @@
656
695
  warn("multiplayer.broadcast ignored: peer is not the host");
657
696
  return false;
658
697
  }
659
- return send(eventName, payload, options);
698
+ return send(eventName, payload, { ...options, hostOnly: true });
660
699
  }
661
700
  function getRole() {
662
701
  return state.mpRoom ? state.mpRoom.role : null;
@@ -693,6 +732,9 @@
693
732
  const s = state.mpSocket;
694
733
  return Boolean(s && s.readyState === WebSocket.OPEN);
695
734
  }
735
+ function serverNow() {
736
+ return Date.now() + state.mpServerOffsetMs;
737
+ }
696
738
 
697
739
  // src/match-context.ts
698
740
  async function fetchMatchContext() {
@@ -1258,9 +1300,12 @@
1258
1300
  }
1259
1301
  const payload = { ...payloadIn, matchId };
1260
1302
  const def = eventDefFor(String(name));
1261
- const me = localSelfId() ?? "";
1262
- maybeApply(String(name), def, payload, me, void 0, false);
1263
- const retain = callerOptions.retain ?? def?.retain ?? false;
1303
+ const targeted = callerOptions.to !== void 0;
1304
+ if (!targeted) {
1305
+ const me = localSelfId() ?? "";
1306
+ maybeApply(String(name), def, payload, me, void 0, false);
1307
+ }
1308
+ const retain = !targeted && (callerOptions.retain ?? def?.retain ?? false);
1264
1309
  let retainKey;
1265
1310
  if (retain) {
1266
1311
  if (callerOptions.retainKey) {
@@ -1279,11 +1324,18 @@
1279
1324
  retainKey = String(name);
1280
1325
  }
1281
1326
  }
1282
- const sendOptions = retain ? { retain: true, retainKey } : void 0;
1327
+ const sendOptions = {};
1328
+ if (retain) {
1329
+ sendOptions.retain = true;
1330
+ sendOptions.retainKey = retainKey;
1331
+ }
1332
+ if (targeted) {
1333
+ sendOptions.to = callerOptions.to;
1334
+ }
1283
1335
  return broadcast(
1284
1336
  String(name),
1285
1337
  payload,
1286
- sendOptions
1338
+ Object.keys(sendOptions).length ? sendOptions : void 0
1287
1339
  );
1288
1340
  }
1289
1341
  function refreshWaiting() {
@@ -1642,6 +1694,7 @@
1642
1694
  isHost,
1643
1695
  isViewer,
1644
1696
  selfId,
1697
+ serverNow,
1645
1698
  match: createMatch,
1646
1699
  assignSeats,
1647
1700
  waitForPeers