@ksaa-nlp/gamehub-sdk 3.8.0 → 3.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.
package/README.md CHANGED
@@ -1,8 +1,15 @@
1
1
  # GameHub SDK
2
2
 
3
- The client library GameHub-hosted games use to talk to the platform: auth, sessions, score submission, questions, league matches, and the bootstrap pipeline that hands games a multiplayer reconnection token.
3
+ The client library GameHub-hosted games use to talk to the platform: auth, sessions, score submission, questions, the words bank, league matches, and the bootstrap pipeline that hands games their multiplayer seat reservation.
4
4
 
5
- Transport-agnostic — no `@colyseus/sdk` dependency. Games that need realtime open their own socket.
5
+ Works in two host environments out of the box:
6
+
7
+ - **iframe** — the classic embedding; the SDK talks to its parent window over `postMessage`.
8
+ - **native WebView** — e.g. a Flutter app; the SDK talks to an injected `window.GameHubNativeHost` bridge.
9
+
10
+ It also runs **standalone** (served from the GameHub origin or in the dev harness). Detection is automatic — your game code is identical across all three. See [Host transports](#host-transports).
11
+
12
+ Transport-agnostic for realtime — no `@colyseus/sdk` dependency. Games that need multiplayer open their own socket.
6
13
 
7
14
  For exhaustive contract details see [SPEC.md](./SPEC.md). The README below is a hands-on tour.
8
15
 
@@ -52,6 +59,20 @@ sdk.hasActiveSession(); // true if auth or league-match context is present
52
59
 
53
60
  `ready()` is idempotent; you can call it from multiple places without worrying about races.
54
61
 
62
+ ## Host transports
63
+
64
+ The SDK auto-detects how to reach its host. You never choose the transport — the same game code runs everywhere.
65
+
66
+ | Transport | When | Wire |
67
+ | ------------- | ------------------------------------------------------------ | ----------------------------------------------- |
68
+ | `postmessage` | Game runs in an `<iframe>` (`window.parent !== window`) | `window.postMessage` to the parent |
69
+ | `native` | Game is the top document in a native WebView (Flutter, etc.) | injected `window.GameHubNativeHost` bridge |
70
+ | none | Standalone — dev harness or served from the GameHub origin | direct `fetch`; host round-trips resolve `null` |
71
+
72
+ The native bridge wins over the iframe check, so a WebView host always takes precedence. The native app must inject `window.GameHubNativeHost` **before** the SDK script loads. See [SPEC.md §6.7](./SPEC.md#67-native-bridge-transport) for the bridge contract a native host must implement.
73
+
74
+ **Host-proxied HTTP.** When embedded (iframe or native), the SDK does **not** issue cross-origin requests to the GameHub backend itself — it asks the host to proxy them. The host (same-origin with the backend, and holder of the bearer token) makes the real call and returns the result. This sidesteps CORS and keeps the auth token out of the game entirely. It's transparent: `submitScore`, `getQuestions`, etc. behave identically; only the wire underneath differs. Standalone, the SDK calls the backend directly. See [SPEC.md §6.6](./SPEC.md#66-host-proxied-api-transport).
75
+
55
76
  ## Bootstrap snapshot
56
77
 
57
78
  `getBootstrap()` returns everything the host told us about this game launch:
@@ -64,12 +85,14 @@ bs.authToken; // Bearer token; null for guests
64
85
  bs.leagueId; // string | null — set inside a league context
65
86
  bs.gameId; // string | null — set inside a league context
66
87
  bs.matchId; // string | null — set inside a league match
88
+ bs.sessionMode; // 'authenticated' | 'embed-guest' | 'league-guest' | null
67
89
  bs.mode; // 'two_players_online' | 'two_players_local' | …
68
90
  bs.playerName; // free-form display name
69
91
  bs.playerCount; // free-form, e.g. '4'
70
92
  bs.teamOneName; // free-form
71
93
  bs.teamTwoName; // free-form
72
- bs.multiplayer; // { roomCode, reconnectionToken, wsEndpoint } | null
94
+ bs.profileId; // string | null — game profile chosen in the pre-start picker
95
+ bs.multiplayer; // reservation + wsEndpoint, with optional roomCode/role/connectionScope
73
96
  bs.isBootstrapped; // true after the host has replied at least once
74
97
  ```
75
98
 
@@ -77,7 +100,7 @@ All fields default to `null`. Don't assume `gameSlug` exists before `ready()` re
77
100
 
78
101
  ## Submitting scores
79
102
 
80
- ### Standalone (single-player)
103
+ ### Standalone or public embed (single-player)
81
104
 
82
105
  ```ts
83
106
  const result = await sdk.submitScore(score, {
@@ -93,7 +116,9 @@ if (result.success) {
93
116
  }
94
117
  ```
95
118
 
96
- `submitScore` opens a session automatically on first call. If the user isn't authenticated and there's no league-match context, it returns `{ success: false, error: '...' }` — it never throws.
119
+ `submitScore` opens a session automatically on first call. In a public GameHub embed, the trusted host supplies either `sessionMode: 'embed-guest'` or `sessionMode: 'authenticated'` and transparently exchanges the same `/sessions/start` and `/sessions/submit` SDK calls for the correct host-owned flow. Games never create guest IDs or receive login codes, user JWTs, or opaque embed credentials. Outside a trusted embed mode, an unauthenticated standalone game with no league-match context returns `{ success: false, error: '...' }` — it never throws.
120
+
121
+ Embed guest results are administrative play records. Authenticated embed results are normal account-attributed scores and enter the standard leaderboards.
97
122
 
98
123
  ### League match (one-score scoring)
99
124
 
@@ -141,6 +166,33 @@ questions.forEach((q) => {
141
166
 
142
167
  `limit` is clamped to 100. Any failure (bad inputs, network error, malformed response) resolves to `[]` — there's no `error` field to check.
143
168
 
169
+ Pass `profileId` to draw from a specific game **profile**. When omitted, the SDK uses the bootstrap-supplied `profileId` (set by the player's pre-start picker), and otherwise falls back to the game's default profile:
170
+
171
+ ```ts
172
+ const questions = await sdk.getQuestions({ profileId: 'beginner-pack' });
173
+ ```
174
+
175
+ ## Words (Words Bank)
176
+
177
+ For vocabulary games, `getWords` mirrors `getQuestions` but returns full nested `Word` entries (lemma, senses, word forms, relations):
178
+
179
+ ```ts
180
+ const words = await sdk.getWords({
181
+ difficulty: 'medium',
182
+ tags: ['animals', 'nature'],
183
+ limit: 20,
184
+ });
185
+
186
+ words.forEach((w) => {
187
+ console.log(w.lemma, '→', w.senses?.[0]?.definition);
188
+ });
189
+ ```
190
+
191
+ - `tags` (a `string[]`) is ANDed on top of the profile selection.
192
+ - `profileId` selects a game profile (the same profile carries both questions and words); falls back to the bootstrap `profileId`, then the default profile.
193
+ - `limit` is clamped to **50** (lower than questions' 100 because a full `Word` is heavier) and defaults to 50.
194
+ - Like `getQuestions`, any failure resolves to `[]`.
195
+
144
196
  ## Host signalling
145
197
 
146
198
  Tell the host page things:
@@ -157,9 +209,15 @@ sdk.reportQuestion({ questionId: q.id, prompt: q.prompt });
157
209
  sdk.reportQuestion({
158
210
  questions: quiz.map((q) => ({ questionId: q.id, prompt: q.prompt })),
159
211
  });
212
+
213
+ // Words Bank: report a word — same single/dropdown semantics, relabeled to lemma
214
+ sdk.reportWord({ wordId: w.id, lemma: w.lemma });
215
+ sdk.reportWord({
216
+ words: bank.map((w) => ({ wordId: w.id, lemma: w.lemma })),
217
+ });
160
218
  ```
161
219
 
162
- All of these are fire-and-forget — they just `postMessage` to the parent window. `reportQuestion` asks the host to open its report dialog (the host collects the reason + optional message, plus name/email for guests, and submits it). Pass `questions` instead of a single `questionId` to have the host render a dropdown so the player chooses which question to report.
220
+ All of these are fire-and-forget — they just signal the host (over whichever transport is active). `reportQuestion` / `reportWord` ask the host to open its report dialog (the host collects the reason + optional message, plus name/email for guests, and submits it). Pass `questions` / `words` instead of a single id to have the host render a dropdown so the player chooses which item to report.
163
221
 
164
222
  ## Pause/resume from the host
165
223
 
@@ -174,7 +232,7 @@ Both are optional. The SDK doesn't pause anything itself; it just delivers the s
174
232
 
175
233
  ## Multiplayer
176
234
 
177
- The SDK does not open a WebSocket. The host has already created a Colyseus room before the iframe boots and passes the reconnection token in the bootstrap. Open it yourself:
235
+ The SDK does not open a WebSocket. The host has already created a Colyseus room before the game boots and passes a **seat reservation** in the bootstrap. Consume it yourself:
178
236
 
179
237
  ```ts
180
238
  import { Client } from '@colyseus/sdk';
@@ -188,7 +246,9 @@ if (!multiplayer) {
188
246
  }
189
247
 
190
248
  const client = new Client(multiplayer.wsEndpoint);
191
- const room = await client.reconnect<UgcState>(multiplayer.reconnectionToken);
249
+ const room = await client.consumeSeatReservation<UgcState>(
250
+ multiplayer.reservation
251
+ );
192
252
 
193
253
  const serverNow = attachServerClock(room);
194
254
 
@@ -197,7 +257,15 @@ room.onMessage('fx:answer', (msg) => playSound(msg));
197
257
  room.send('answer:submit', { answer: 'B' });
198
258
  ```
199
259
 
200
- The returned `room` is a stock `@colyseus/sdk` `Room` — see <https://docs.colyseus.io/client/room/> for its full API. Install `@colyseus/sdk`, `@colyseus/schema`, and `@ksaa-nlp/colyseus-schemas` in your game; the SDK doesn't pull them in.
260
+ `multiplayer.reservation` is a Colyseus `SeatReservation` (the `{ room, sessionId }` envelope) — feed it straight to `consumeSeatReservation`, which performs the clean first join. No reconnection-token handoff crosses the host→game boundary; after joining, the server mints `room.reconnectionToken` for the game to keep if it wants to reconnect later.
261
+
262
+ External embeds also provide `roomCode`, `role`, and `connectionScope` when
263
+ available. If the game persists its server-issued reconnection token, include
264
+ `connectionScope` in that storage key so two publisher tabs cannot reuse each
265
+ other's reconnect state. These fields are opaque launch context; the SDK never
266
+ opens a socket or writes reconnection data.
267
+
268
+ The returned `room` is a stock `@colyseus/sdk` `Room` — see <https://docs.colyseus.io/client/room/> for its full API. Install `@colyseus/sdk`, `@colyseus/schema`, and `@ksaa-nlp/colyseus-schemas` in your game; the SDK doesn't pull them in. This works the same inside a native WebView host — the game opens its own socket from inside the WebView; the SDK never proxies realtime traffic over the native bridge.
201
269
 
202
270
  ## API summary
203
271
 
@@ -205,7 +273,7 @@ The returned `room` is a stock `@colyseus/sdk` `Room` — see <https://docs.coly
205
273
  const sdk = createSdk();
206
274
 
207
275
  // Lifecycle
208
- sdk.version; // '3.1.0'
276
+ sdk.version; // '3.8.0'
209
277
  sdk.ready(); // Promise<boolean>
210
278
  sdk.isInitialized(); // boolean
211
279
  sdk.isAuthenticated(); // boolean
@@ -221,13 +289,17 @@ sdk.submitMatchResult({ winnerId, scores }); // Promise<SubmitScoreResult>
221
289
  sdk.getMatchContext(); // Promise<MatchContext | null>
222
290
 
223
291
  // Questions
224
- sdk.getQuestions({ difficulty, category, limit }); // Promise<Question[]>
292
+ sdk.getQuestions({ difficulty, category, limit, profileId }); // Promise<Question[]>
293
+
294
+ // Words (Words Bank)
295
+ sdk.getWords({ difficulty, category, tags, limit, profileId }); // Promise<Word[]>
225
296
 
226
297
  // Host signalling
227
298
  sdk.notifyComplete(data?); // void
228
299
  sdk.requestClose(); // void
229
300
  sdk.logEvent(name, data?); // void
230
301
  sdk.reportQuestion({ questionId?, prompt?, message?, questions? }); // void
302
+ sdk.reportWord({ wordId?, lemma?, message?, words? }); // void
231
303
 
232
304
  // Context
233
305
  sdk.getGameSlug(); // string | null
@@ -249,7 +321,10 @@ import type {
249
321
  SubmitScoreResult,
250
322
  StartSessionResult,
251
323
  Question,
324
+ QuestionDifficulty,
252
325
  QuestionOptions,
326
+ ReportQuestionData,
327
+ ReportableQuestion,
253
328
  GameCompleteData,
254
329
  EventData,
255
330
  MatchContext,
@@ -258,9 +333,28 @@ import type {
258
333
  MatchResultPayload,
259
334
  ApiResponse,
260
335
  ApiRequestOptions,
336
+ // Words Bank
337
+ Word,
338
+ WordDifficulty,
339
+ WordOptions,
340
+ ReportWordData,
341
+ ReportableWord,
342
+ WordSense,
343
+ WordForm,
261
344
  } from '@ksaa-nlp/gamehub-sdk';
262
345
  ```
263
346
 
347
+ The full nested `Word` shape and its sub-interfaces (`WordSense`, `WordForm`, `Lookup`, `Synset`, `DynamicProperty`, …) are all re-exported from the package root — see [`types/word.ts`](./types/word.ts).
348
+
349
+ ## Authoring server bundles (UGC)
350
+
351
+ For games with authoritative server logic running in the Colyseus UGC sandbox, the SDK ships two extra subpaths, separate from the browser runtime:
352
+
353
+ - `@ksaa-nlp/gamehub-sdk/server` — **types only** (`GuestModule`, `Ctx`, `PeerInfo`, …) for writing the guest module.
354
+ - `@ksaa-nlp/gamehub-sdk/server/dev` — `runLocal(guest, opts)`, a pure-Node harness to unit-test a guest bundle against a simulated room without `isolated-vm`.
355
+
356
+ See [SPEC.md §21bis](./SPEC.md#21bis-ugc-server-bundle-subpath) for the full contract.
357
+
264
358
  ## Specification
265
359
 
266
360
  [SPEC.md](./SPEC.md) is the authoritative contract — postMessage taxonomy, state model, REST endpoints, error semantics, boundary rules, versioning policy. Read that before changing SDK internals or adding a new feature area.
package/SPEC.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # GameHub SDK — Specification
2
2
 
3
- Version: 3.1.0
3
+ Version: 3.11.0
4
4
  Status: Authoritative. Supersedes README/MIGRATION/CHANGELOG where they conflict.
5
5
 
6
6
  This document is the single source of truth for the GameHub SDK. Code, tests, and consumer docs follow this spec; if a behaviour is observed in code but not described here, treat it as undocumented and revisit before relying on it.
@@ -28,7 +28,8 @@ The SDK is not coupled to any realtime transport. When the host attaches a multi
28
28
  - Submit scores (`submitScore`, `submitMatchScore`) and league-match results (`submitMatchResult`).
29
29
  - Fetch questions (`getQuestions`) and words (`getWords`).
30
30
  - Request the host's report dialog for a question (`reportQuestion`) or word (`reportWord`).
31
- - Surface a bootstrap snapshot (`getBootstrap()`) including the opaque `multiplayer` block.
31
+ - Surface a bootstrap snapshot (`getBootstrap()`) including the trusted
32
+ `sessionMode` and opaque `multiplayer` block.
32
33
  - Forward player-visible host commands (`pause`, `resume`) to optional `window.onGameHubPause` / `onGameHubResume` callbacks.
33
34
  - Type definitions for authoring UGC server bundles (`./server` subpath, types-only at runtime).
34
35
  - Node-only dev harness (`./server/dev` subpath) for unit-testing a guest bundle against a simulated `ctx`.
@@ -56,7 +57,7 @@ The package is laid out flat under `src/` and `types/`. No subdirectories.
56
57
  | `src/browser-entry.ts` | The only file with side effects on import. Used by the IIFE bundle to attach `window.GameHubSDK`. |
57
58
  | `src/init.ts` | `detectEnvironment`, `autoInit`, `ensureInitialized`, `installHostMessageListener`. |
58
59
  | `src/transport.ts` | Host transport abstraction: `HostTransport` interface, `PostMessageTransport` (iframe ⇄ parent) and `NativeBridgeTransport` (`window.GameHubNativeHost`), plus `getTransport()` / `hasHost()` detection. See §6.7. |
59
- | `src/bridge.ts` | Host protocol: builds the `GAMEHUB_SDK_*` envelopes, correlates request/response by `messageId`, send helper. Transport-independent — routes through `getTransport()`. |
60
+ | `src/bridge.ts` | Host protocol: builds the `GAMEHUB_SDK_*` envelopes, correlates request/response by `messageId`, send helper. Transport-independent — routes through `getTransport()`. |
60
61
  | `src/session.ts` | `startSession`, `submitScore`, `submitMatchScore`, `submitMatchResult`, `getQuestions`, `getWords`. |
61
62
  | `src/match-context.ts` | `fetchMatchContext` (HTTP `/leagues/<id>/matches/<id>`). |
62
63
  | `src/api-client.ts` | `apiRequest`: thin `fetch` wrapper that prefixes the API base and attaches the Bearer token. |
@@ -164,41 +165,50 @@ The full taxonomy follows. It applies to **both** transports identically.
164
165
 
165
166
  ### 6.1 Message-type taxonomy
166
167
 
167
- | Direction | Type (after prefix) | Purpose |
168
- | ---------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
169
- | SDK → host | `READY` | Fired once on script load when a host transport is present (`hasHost()`). Carries `{ version }`. |
170
- | SDK → host | `BOOTSTRAP_REQUEST` | Asks the host for bootstrap config. Carries `{ messageId }`. |
171
- | host → SDK | `BOOTSTRAP` | Bootstrap config response. Carries `{ payload: BootstrapConfig, messageId? }`. Host may also push an unsolicited one any time. |
172
- | SDK → host | `AUTH_REQUEST` | Asks the host for an auth token. Carries `{ messageId }`. |
173
- | host → SDK | `AUTH_RESPONSE` | Auth response. Carries `{ token: string \| null, leagueId?, gameId?, matchId?, messageId }`. |
174
- | host → SDK | `SET_AUTH` | Unsolicited auth update. Carries `{ token }`. Triggers session start if not already running. |
175
- | host → SDK | `COMMAND` | Player-visible host command. Carries `{ command: 'pause' \| 'resume' }`. Routed to optional `window.onGameHubPause/Resume`. |
176
- | SDK → host | `INIT` | Fired after auto-init resolves. Carries `{ slug, auto: true }`. |
177
- | SDK → host | `SESSION_STARTED` | Fired when a session token is obtained. Carries `{ token }`. |
178
- | SDK → host | `SCORE_SUBMITTED` | Fired when a score is accepted. Carries `{ score, accepted, timeTaken }`. |
179
- | SDK → host | `GAME_COMPLETE` | Fired by `sdk.notifyComplete(data?)`. Carries `data` verbatim. |
180
- | SDK → host | `REQUEST_CLOSE` | Fired by `sdk.requestClose()`. Empty payload. |
181
- | SDK → host | `LOG_EVENT` | Fired by `sdk.logEvent(name, data?)`. Carries `{ event, data }`. |
182
- | SDK → host | `QUESTION_REPORT` | Fired by `sdk.reportQuestion(data)`. Carries `{ questionId?, prompt?, message?, questions? }`. With `questions` the host renders a question-picker dropdown; otherwise it reports the single `questionId`. |
183
- | SDK → host | `WORD_REPORT` | Fired by `sdk.reportWord(data)` (Words Bank feature). Carries `{ wordId?, lemma?, message?, words? }`. Same picker/single semantics as `QUESTION_REPORT`, relabeled to lemma. |
184
- | SDK → host | `API_REQUEST` | Asks the host to proxy a backend HTTP call. Carries `{ messageId, endpoint, method, body }`. See §6.6. |
185
- | host → SDK | `API_RESPONSE` | Result of a proxied call. Carries `{ messageId, ok: boolean, result?: ApiResponse, error?: string }`. See §6.6. |
168
+ | Direction | Type (after prefix) | Purpose |
169
+ | ---------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
170
+ | SDK → host | `READY` | Fired once on script load when a host transport is present (`hasHost()`). Carries `{ version }`. |
171
+ | SDK → host | `BOOTSTRAP_REQUEST` | Asks the host for bootstrap config. Carries `{ messageId }`. |
172
+ | host → SDK | `BOOTSTRAP` | Bootstrap config response. The initial response carries `{ payload: BootstrapConfig, messageId }` and must echo `BOOTSTRAP_REQUEST.messageId`. After the parent origin is pinned, the host may push an unsolicited update without `messageId`. |
173
+ | SDK → host | `AUTH_REQUEST` | Asks the host for an auth token. Carries `{ messageId }`. |
174
+ | host → SDK | `AUTH_RESPONSE` | Auth response. Carries `{ token: string \| null, leagueId?, gameId?, matchId?, messageId }`. |
175
+ | host → SDK | `SET_AUTH` | Unsolicited auth update. Carries `{ token }`. Triggers session start if not already running. |
176
+ | host → SDK | `COMMAND` | Player-visible host command. Carries `{ command: 'pause' \| 'resume' }`. Routed to optional `window.onGameHubPause/Resume`. |
177
+ | SDK → host | `INIT` | Fired after auto-init resolves. Carries `{ slug, auto: true }`. |
178
+ | SDK → host | `SESSION_STARTED` | Fired when a session token is obtained. Carries `{ token }`. |
179
+ | SDK → host | `SCORE_SUBMITTED` | Fired when a score is accepted. Carries `{ score, accepted, timeTaken }`. |
180
+ | SDK → host | `GAME_COMPLETE` | Fired by `sdk.notifyComplete(data?)`. Carries `data` verbatim. |
181
+ | SDK → host | `REQUEST_CLOSE` | Fired by `sdk.requestClose()`. Empty payload. |
182
+ | SDK → host | `LOG_EVENT` | Fired by `sdk.logEvent(name, data?)`. Carries `{ event, data }`. |
183
+ | SDK → host | `QUESTION_REPORT` | Fired by `sdk.reportQuestion(data)`. Carries `{ questionId?, prompt?, message?, questions? }`. With `questions` the host renders a question-picker dropdown; otherwise it reports the single `questionId`. |
184
+ | SDK → host | `WORD_REPORT` | Fired by `sdk.reportWord(data)` (Words Bank feature). Carries `{ wordId?, lemma?, message?, words? }`. Same picker/single semantics as `QUESTION_REPORT`, relabeled to lemma. |
185
+ | SDK → host | `API_REQUEST` | Asks the host to proxy a backend HTTP call. Carries `{ messageId, endpoint, method, body }`. See §6.6. |
186
+ | host → SDK | `API_RESPONSE` | Result of a proxied call. Carries `{ messageId, ok: boolean, result?: ApiResponse, error?: string }`. See §6.6. |
187
+
188
+ The production GameHub play host uses these existing envelopes, together with
189
+ successful SDK API routes, to aggregate per-game feature observations for the
190
+ admin SDK-usage report. This is host behavior only: the SDK emits no additional
191
+ telemetry and its wire protocol/version is unchanged. The report contract and
192
+ feature-to-observation map live in
193
+ [`../../specs/sdk-usage-report.md`](../../specs/sdk-usage-report.md).
186
194
 
187
195
  Every SDK → host envelope also includes the resolved `gameSlug` as a top-level field (except `API_REQUEST`, whose payload is the proxied request).
188
196
 
189
197
  ### 6.2 Origin handling
190
198
 
191
- Origin handling is a property of the **postMessage** transport only. The SDK fires the initial `BOOTSTRAP_REQUEST` with target origin `'*'` because it has not yet learned the parent's origin. The very first inbound reply records `event.origin` into `state.parentOrigin`. All subsequent SDK → host messages target that recorded origin. Calls before any inbound message fall back to `'*'`.
199
+ Origin handling is a property of the **postMessage** transport only. Every inbound browser message must have `event.source === window.parent`; messages from ancestors, sibling frames, popups, and unrelated windows are ignored. This direct-parent check applies before any envelope-specific handler runs.
192
200
 
193
- If `event.origin` changes mid-session (e.g. the host navigates between origins), `state.parentOrigin` is overwritten by the next inbound message. There is no origin allowlist; the SDK trusts whatever the parent reports. This is acceptable because the iframe contents are themselves served by GameHub.
201
+ The SDK fires the initial `BOOTSTRAP_REQUEST` with target origin `'*'` because it has not yet learned the parent's origin. The host must echo its `messageId`. A valid correlated `BOOTSTRAP`, `AUTH_RESPONSE`, or `API_RESPONSE` from the direct parent pins `event.origin` into `state.parentOrigin`. Empty/opaque (`'null'`) origins do not establish the browser trust boundary. All subsequent SDK → host messages target the pinned origin, and all inbound messages from a different origin are ignored.
202
+
203
+ The origin pin is immutable for the lifetime of the game document. If the host navigates to another origin, the existing SDK instance does not follow it; a fresh game document is required. Unsolicited `BOOTSTRAP`, `SET_AUTH`, and `COMMAND` messages are accepted only after the origin has been pinned and only from the same direct parent/origin.
194
204
 
195
205
  On the **native** transport there is no web origin: inbound `HostMessage.origin` is `null`, `state.parentOrigin` stays `null`, and the transport ignores it when sending (it posts through `window.GameHubNativeHost`). The trust boundary is the native app itself, which owns the WebView and injects the bridge.
196
206
 
197
207
  ### 6.3 Request/response correlation
198
208
 
199
209
  - Each SDK-initiated request includes a `messageId: string` (currently `Date.now().toString()`).
200
- - The host's response must echo the same `messageId`. The SDK's `requestBootstrapFromParent` and `getAuthTokenFromParent` ignore messages with a mismatched `messageId`.
201
- - The host may push an unsolicited `BOOTSTRAP` with no `messageId`; the SDK still merges it.
210
+ - The host's response must echo the same `messageId`. Bootstrap, auth, and API request handlers ignore missing or mismatched IDs.
211
+ - The host may push an unsolicited `BOOTSTRAP` with no `messageId` only after a correlated response has pinned the direct parent origin.
202
212
  - Each request has a `PARENT_REQUEST_TIMEOUT_MS` (2000 ms) timeout. On timeout the promise resolves to `null` (bootstrap) or `null` (auth); the SDK does not retry.
203
213
 
204
214
  ### 6.4 Bootstrap merge semantics
@@ -212,7 +222,14 @@ On the **native** transport there is no web origin: inbound `HostMessage.origin`
212
222
  - `multiplayer`:
213
223
  - Explicit `null` → `null`.
214
224
  - Object with a `reservation` object (string `name`, `sessionId`, `roomId` — the `SdkSeatReservation` shape) and a string `wsEndpoint` → only `wsEndpoint` is trimmed; the `reservation` object is stored as-is.
225
+ - Optional `roomCode`, `role`, and `connectionScope` strings are copied only
226
+ when non-empty and bounded. `connectionScope` lets a game partition its own
227
+ reconnect storage by public embed and outer-host instance; the SDK neither
228
+ stores nor interprets it.
215
229
  - Any other shape → ignored (field left as-is).
230
+ - `sessionMode` accepts only `'authenticated'`, `'embed-guest'`,
231
+ `'league-guest'`, or explicit `null`; every other value is ignored. The
232
+ trusted host, not uploaded game code, selects this authority mode.
216
233
 
217
234
  This lets the host clear fields explicitly (via `null`) without overwriting unset fields.
218
235
 
@@ -220,7 +237,7 @@ This lets the host clear fields explicitly (via `null`) without overwriting unse
220
237
 
221
238
  1. **Idle.** `state.bootstrapReceived = false`.
222
239
  2. **Request.** First call to `requestBootstrapFromParent()` posts `BOOTSTRAP_REQUEST` and starts the timeout.
223
- 3. **Response.** Host replies with `BOOTSTRAP`. `state.bootstrapReceived = true`. `parentOrigin` recorded.
240
+ 3. **Response.** Host replies with `BOOTSTRAP` carrying the matching `messageId`. `state.bootstrapReceived = true`; the direct parent's non-opaque origin is pinned.
224
241
  4. **Cache.** Subsequent calls return `snapshotBootstrap()` synchronously (wrapped in a resolved promise).
225
242
  5. **Update.** Any later unsolicited `BOOTSTRAP` from the host triggers `mergeBootstrapConfig` without affecting `bootstrapReceived`. Existing callers do not get re-notified.
226
243
 
@@ -237,9 +254,16 @@ The SDK never issues a cross-origin request to the GameHub backend. When a game
237
254
 
238
255
  Protocol details:
239
256
 
240
- - `endpoint` is the path **after** `/api` (e.g. `/sessions/start`), exactly as passed to `apiRequest`. The host prepends its own same-origin API base. The host **must reject** any `endpoint` that is not a relative path (does not start with `/`, or starts with `//`) so the iframe cannot use the host as an open proxy.
257
+ - `endpoint` is the path **after** `/api` (e.g. `/sessions/start`), exactly as passed to `apiRequest`. The host prepends its own same-origin API base. The host must use a method/path/query/body allowlist for the documented SDK REST surface (§16), bind game/league/match identifiers to trusted bootstrap context, and reject absolute/protocol-relative paths, traversal encodings, unknown queries, and unrelated GameHub APIs. A relative-path check alone is not sufficient because uploaded game code is untrusted.
258
+ - A public embed host may translate the ordinary `/sessions/start` and
259
+ `/sessions/submit` requests to its guest or authenticated embed endpoints.
260
+ That translation binds the request to host-owned embed, guest/auth session,
261
+ publisher origin, and host instance; it does not change the SDK-facing
262
+ endpoint or game integration.
241
263
  - `body` is the unserialised request body (or `null`); the host serialises it.
242
- - The host attaches authentication from **its own** auth context (it holds the same token it bootstrapped to the SDK). The SDK does not send the bearer token in `API_REQUEST`.
264
+ - The host attaches authority from **its own** context. For authenticated
265
+ external embeds this is an opaque embed credential held only in outer-host
266
+ memory; it is never added to bootstrap or an `API_REQUEST`.
243
267
  - `API_RESPONSE.ok === true` carries the parsed JSON envelope in `result`; the promise resolves with it. `ok === false` carries an `error` string; the promise rejects. The per-call `try/catch` blocks in `session.ts` / `match-context.ts` turn either outcome into the usual degraded result — public methods still never throw (§17).
244
268
  - Timeout is `HOST_API_TIMEOUT_MS` (15 000 ms), larger than the 2 s bootstrap/auth timeout because the round-trip includes the host's real network call. On timeout the promise rejects and the call degrades.
245
269
  - `messageId` is `'api_' + Date.now() + '_' + <seq>`, where `<seq>` is a monotonic counter so concurrent proxied calls (e.g. session start + questions) never collide.
@@ -295,16 +319,18 @@ If the host posts `SET_AUTH` mid-session, the new token is used for subsequent r
295
319
 
296
320
  `startSession()` picks one of three endpoints from the active context:
297
321
 
298
- | Condition | Endpoint | Body |
299
- | ----------------------------------- | ---------------------------------------------------- | -------------- |
300
- | `leagueId && gameId && matchId` | `POST /leagues/<leagueId>/matches/<matchId>/session` | `{ gameId }` |
301
- | `leagueId && gameId` (no `matchId`) | `POST /leagues/<leagueId>/sessions` | `{ gameId }` |
302
- | otherwise | `POST /sessions/start` | `{ gameSlug }` |
322
+ | Condition | Endpoint | Body |
323
+ | ----------------------------------------- | ---------------------------------------------------- | -------------- |
324
+ | `leagueId && gameId && matchId` | `POST /leagues/<leagueId>/matches/<matchId>/session` | `{ gameId }` |
325
+ | `leagueId && gameId` (no `matchId`) | `POST /leagues/<leagueId>/sessions` | `{ gameId }` |
326
+ | otherwise (including trusted embed modes) | `POST /sessions/start` | `{ gameSlug }` |
303
327
 
304
328
  ### 8.2 Preconditions
305
329
 
306
330
  - `gameSlug` must be non-null. If null, `startSession` returns `{ success: false, error: 'Game slug not set' }` synchronously.
307
- - Auth is required unless this is a league-match session (`leagueId && gameId && matchId`), which allows guest play.
331
+ - Auth is required unless this is a league-match session (`leagueId && gameId && matchId`) or the trusted bootstrap selected `sessionMode === 'embed-guest'` or `sessionMode === 'authenticated'`. In authenticated embed mode the trusted outer host, not the SDK, owns the credential.
332
+ - A game cannot opt itself into guest authority: unsupported bootstrap values
333
+ are ignored, and standalone unauthenticated behavior is unchanged.
308
334
 
309
335
  ### 8.3 Idempotency
310
336
 
@@ -314,7 +340,7 @@ Once `state.sessionToken` is non-null, subsequent `startSession()` calls short-c
314
340
 
315
341
  A session is opened by any of:
316
342
 
317
- - `autoInit()` (when auth or league-match context is present).
343
+ - `autoInit()` (when auth, a trusted authenticated/embed-guest mode, or league-match context is present).
318
344
  - The host posting `SET_AUTH` (when the slug is known and no session is already running).
319
345
  - Any score-submitting call that finds no session.
320
346
  - An explicit `sdk.startSession()` call.
@@ -398,7 +424,7 @@ The HTTP league-match surface (`getMatchContext`, `submitMatchResult`) is indepe
398
424
  ### 11.1 `getQuestions(options?)`
399
425
 
400
426
  - Awaits `ensureInitialized()`.
401
- - Identifier is `state.gameId || state.gameSlug`. Returns `[]` if both are null.
427
+ - Identifier is `state.gameSlug || state.gameId`. Returns `[]` if both are null.
402
428
  - Validates `options.difficulty` against `'easy' | 'medium' | 'hard'`. Returns `[]` on mismatch.
403
429
  - Validates `options.limit` is a positive number. Returns `[]` on mismatch.
404
430
  - GETs `/games/<identifier>/questions?limit=<n>&random=true[&gameId=…][&difficulty=…][&category=…][&profileId=…]`.
@@ -430,7 +456,7 @@ interface Question {
430
456
  ### 11bis.1 `getWords(options?)`
431
457
 
432
458
  Mirrors `getQuestions`. Awaits `ensureInitialized()`; identifier is
433
- `state.gameId || state.gameSlug` (returns `[]` if both null). Validates
459
+ `state.gameSlug || state.gameId` (returns `[]` if both null). Validates
434
460
  `options.difficulty` and `options.limit` the same way (returns `[]` on
435
461
  mismatch). GETs
436
462
  `/games/<identifier>/words?limit=<n>&random=true[&gameId=…][&difficulty=…][&category=…][&tags=a,b][&profileId=…]`.
@@ -492,6 +518,7 @@ interface SdkState {
492
518
  leagueId: string | null;
493
519
  gameId: string | null;
494
520
  matchId: string | null;
521
+ bootstrapSessionMode: BootstrapSessionMode | null;
495
522
 
496
523
  // Free-form bootstrap fields
497
524
  bootstrapMode: string | null;
@@ -616,6 +643,9 @@ interface SdkSeatReservation {
616
643
  interface BootstrapMultiplayer {
617
644
  reservation: SdkSeatReservation;
618
645
  wsEndpoint: string;
646
+ roomCode?: string;
647
+ role?: string;
648
+ connectionScope?: string;
619
649
  }
620
650
 
621
651
  interface BootstrapConfig {
@@ -624,6 +654,7 @@ interface BootstrapConfig {
624
654
  leagueId?: string | null;
625
655
  gameId?: string | null;
626
656
  matchId?: string | null;
657
+ sessionMode?: BootstrapSessionMode | null;
627
658
  mode?: string | null;
628
659
  playerName?: string | null;
629
660
  playerCount?: string | null;
@@ -639,6 +670,7 @@ interface BootstrapData {
639
670
  leagueId: string | null;
640
671
  gameId: string | null;
641
672
  matchId: string | null;
673
+ sessionMode: BootstrapSessionMode | null;
642
674
  mode: string | null;
643
675
  playerName: string | null;
644
676
  playerCount: string | null;
@@ -648,6 +680,8 @@ interface BootstrapData {
648
680
  multiplayer: BootstrapMultiplayer | null;
649
681
  isBootstrapped: boolean;
650
682
  }
683
+
684
+ type BootstrapSessionMode = 'authenticated' | 'embed-guest' | 'league-guest';
651
685
  ```
652
686
 
653
687
  ### 15.2 Session / scoring
@@ -759,14 +793,14 @@ interface ApiRequestOptions {
759
793
 
760
794
  The SDK assumes the GameHub server exposes the following endpoints. When embedded these are reached via the host proxy (§6.6); standalone they are reached directly under `state.apiBase`. Either way the SDK calls `apiRequest` with the same `endpoint` path. Any change to these contracts must be coordinated server-side and is a major-version event for the SDK.
761
795
 
762
- | Method | Path | Auth | Request body | Successful response shape |
763
- | ------ | ----------------------------------------------- | -------- | ------------------------ | ------------------------------------------------------------------ |
764
- | POST | `/sessions/start` | Bearer | `{ gameSlug }` | `{ success: true, data: { token } }` or `{ success: true, token }` |
765
- | POST | `/leagues/<leagueId>/sessions` | Bearer | `{ gameId }` | as above |
766
- | POST | `/leagues/<leagueId>/matches/<matchId>/session` | optional | `{ gameId }` | as above (guest sessions allowed) |
767
- | POST | `/sessions/submit` | optional | `{ token, score, meta }` | `{ success: true, data: { accepted, timeTaken } }` |
768
- | GET | `/games/<id-or-slug>/questions?…` | optional | n/a | `Question[]` or `{ questions: Question[] }` |
769
- | GET | `/leagues/<leagueId>/matches/<matchId>` | optional | n/a | `{ success: true, data: MatchContext }` |
796
+ | Method | Path | Auth | Request body | Successful response shape |
797
+ | ------ | ----------------------------------------------- | ---------------------------------- | ------------------------ | ------------------------------------------------------------------ |
798
+ | POST | `/sessions/start` | Bearer or trusted embed-guest host | `{ gameSlug }` | `{ success: true, data: { token } }` or `{ success: true, token }` |
799
+ | POST | `/leagues/<leagueId>/sessions` | Bearer | `{ gameId }` | as above |
800
+ | POST | `/leagues/<leagueId>/matches/<matchId>/session` | optional | `{ gameId }` | as above (guest sessions allowed) |
801
+ | POST | `/sessions/submit` | optional | `{ token, score, meta }` | `{ success: true, data: { accepted, timeTaken } }` |
802
+ | GET | `/games/<id-or-slug>/questions?…` | optional | n/a | `Question[]` or `{ questions: Question[] }` |
803
+ | GET | `/leagues/<leagueId>/matches/<matchId>` | optional | n/a | `{ success: true, data: MatchContext }` |
770
804
 
771
805
  ### 16.1 Response envelope
772
806
 
@@ -801,7 +835,9 @@ These rules exist because of a real prior regression where transport-related cle
801
835
 
802
836
  - The SDK must not import any realtime client (`@colyseus/sdk`, `ws`, `socket.io-client`, …).
803
837
  - The SDK must not open a `WebSocket`, `EventSource`, or `RTCPeerConnection`.
804
- - The `bootstrapMultiplayer` field is opaque. The SDK validates only its shape (three strings); it does not parse or interpret the values.
838
+ - The `bootstrapMultiplayer` field is opaque. The SDK validates the reservation,
839
+ endpoint, and optional bounded room/role/scope strings; it does not parse or
840
+ interpret them.
805
841
  - The server-clock helper (`attachServerClock`) belongs in `@ksaa-nlp/colyseus-schemas/clock`, not here.
806
842
 
807
843
  ### 19.2 HTTP plumbing is transport-agnostic
@@ -838,7 +874,7 @@ These rules exist because of a real prior regression where transport-related cle
838
874
 
839
875
  ### 20.3 Bundle budget
840
876
 
841
- The IIFE bundle (`dist/gamehub-sdk.js`) is expected to remain under **10 KB gzip**, the figure that matters on the wire. The raw budget was historically **25 KB**; the native-bridge transport added in 3.8.0 (a deliberate new feature area — §6.7) pushed raw to ~26 KB. Current size: ~26 KB raw / ~5.9 KB gzip. Further growth should be a deliberate decision tied to a release note, and gzip remains the hard ceiling.
877
+ The IIFE bundle (`dist/gamehub-sdk.js`) is expected to remain under **10 KB gzip**, the figure that matters on the wire. The raw budget was historically **25 KB**; the native-bridge transport added in 3.8.0 (a deliberate new feature area — §6.7) pushed raw past that historical target. Current 3.11.0 size: 27,997 bytes raw / 6,285 bytes gzip. Further growth should be a deliberate decision tied to a release note, and gzip remains the hard ceiling.
842
878
 
843
879
  ### 20.4 No runtime dependencies
844
880
 
@@ -846,7 +882,7 @@ The IIFE bundle (`dist/gamehub-sdk.js`) is expected to remain under **10 KB gzip
846
882
 
847
883
  ## 21. Testing acceptance criteria
848
884
 
849
- The SDK does not currently ship a test suite, but every change should be verifiable against this checklist:
885
+ The SDK ships focused Node tests for transport trust-boundary behavior. Every change should also be verifiable against this checklist:
850
886
 
851
887
  ### 21.1 Pure-import safety
852
888
 
@@ -857,13 +893,21 @@ The SDK does not currently ship a test suite, but every change should be verifia
857
893
 
858
894
  - `autoInit()` resolves `false` and logs the slug-not-found warning when the page is not under `/games/<slug>/`.
859
895
  - Score-submit calls in this state return `{ success: false, error }` and never throw.
896
+ - Setting `sessionMode: 'embed-guest'` through trusted bootstrap permits the
897
+ ordinary session call; an absent or invalid mode leaves anonymous
898
+ standalone calls denied.
899
+ - Setting `sessionMode: 'authenticated'` through trusted bootstrap permits
900
+ session auto-start without an SDK-visible JWT. The host must supply the
901
+ authority when proxying; standalone code cannot manufacture that authority.
860
902
 
861
903
  ### 21.3 Iframe boot
862
904
 
863
905
  - The iframe receives a `BOOTSTRAP_REQUEST` from the SDK within ~100 ms of script load.
864
- - Replying with `BOOTSTRAP { payload: { gameSlug } }` causes `getBootstrap().isBootstrapped` to flip to `true` and `getGameSlug()` to return the value.
906
+ - Replying from `window.parent` with `BOOTSTRAP { messageId, payload: { gameSlug } }`, echoing the request ID, causes `getBootstrap().isBootstrapped` to flip to `true` and `getGameSlug()` to return the value.
865
907
  - Replying with `AUTH_RESPONSE { token }` makes `isAuthenticated()` true.
866
908
  - Posting `SET_AUTH { token }` after init opens a session and fires `SESSION_STARTED`.
909
+ - A message from a window other than `window.parent` is ignored even when its envelope and `messageId` otherwise look valid.
910
+ - After the direct parent origin is pinned, a message from the same parent window with a different `event.origin` is ignored and cannot replace `state.parentOrigin`.
867
911
 
868
912
  ### 21.3b Native bridge boot
869
913
 
@@ -877,12 +921,16 @@ The SDK does not currently ship a test suite, but every change should be verifia
877
921
  - `submitScore(42, { level: 3 })` causes a POST to `/api/sessions/submit` with `{ token, score: 42, meta: { level: 3 } }` and Bearer auth. When embedded (the default), this travels as an `API_REQUEST` `{ endpoint: '/sessions/submit', method: 'POST', body: { … } }` and the **host** performs the POST with its own bearer auth (§6.6); standalone, the SDK POSTs directly.
878
922
  - Returns `{ success: true, accepted: true, timeTaken: <n> }` on a `{ success: true, data: { accepted: true, timeTaken: 1234 } }` server response.
879
923
  - Fires `SCORE_SUBMITTED { score: 42, accepted: true, timeTaken: 1234 }` to the host.
924
+ - In public embed mode, the game still emits `/sessions/start` and
925
+ `/sessions/submit`; the host binds and rewrites those requests for guest or
926
+ authenticated play. The SDK never creates or stores the embed guest ID,
927
+ authorization code, or opaque authenticated credential.
880
928
 
881
929
  ### 21.4b Host-proxied transport (embedded)
882
930
 
883
931
  - Inside an iframe, no public method issues a direct cross-origin `fetch`; each `apiRequest` posts an `API_REQUEST` and resolves on the matching `API_RESPONSE`.
884
932
  - A host that never replies leaves the call pending until `HOST_API_TIMEOUT_MS` (15 s), after which it degrades to the usual failure shape.
885
- - An `API_RESPONSE { ok: false, error }` degrades identically. The host must reject endpoints that aren't relative API paths.
933
+ - An `API_RESPONSE { ok: false, error }` degrades identically. The host must reject requests outside the documented SDK REST method/path/query/body allowlist, even when the endpoint is a relative GameHub API path.
886
934
 
887
935
  ### 21.5 League-match path
888
936
 
@@ -895,6 +943,20 @@ The SDK does not currently ship a test suite, but every change should be verifia
895
943
  - `grep -rn "@colyseus" src/ types/` returns only comment references (no import statements).
896
944
  - `npm pack --dry-run` produces a tarball whose `peerDependencies` and `dependencies` are both empty/absent.
897
945
 
946
+ ### 21.7 SDK Usage Intelligence Report synchronization
947
+
948
+ Every new public SDK method, alias, or capability must be represented in the
949
+ GameHub SDK Usage Intelligence Report in the same change. This is part of the
950
+ definition of done for a public API addition, not optional follow-up work.
951
+
952
+ The authoritative maintenance checklist is
953
+ [`../../specs/sdk-usage-report.md` §4.1](../../specs/sdk-usage-report.md#41-mandatory-synchronization-for-new-sdk-apis).
954
+ At minimum, the change must update the report inventory and labels, static
955
+ scanner registry/version, runtime-observation strategy where applicable,
956
+ admin contract/UI/CSV, automated tests, and both package specifications. A
957
+ method that cannot cross an observable host or server boundary must be
958
+ explicitly classified as static-only.
959
+
898
960
  ## 21bis. UGC server bundle subpath
899
961
 
900
962
  The `./server` and `./server/dev` subpaths are separate from the browser SDK. Importing them has **no overlap** with the iframe runtime — they target the colyseus UGC sandbox, not the browser host.