@ksaa-nlp/gamehub-sdk 3.8.0 → 4.0.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/SPEC.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # GameHub SDK — Specification
2
2
 
3
- Version: 3.1.0
3
+ Version: 4.0.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.
@@ -24,11 +24,12 @@ The SDK is not coupled to any realtime transport. When the host attaches a multi
24
24
 
25
25
  - Discover the API base URL, the active game slug, and the league/match context from the iframe environment.
26
26
  - Exchange a small set of `postMessage` envelopes with the host page (bootstrap, auth, ready, init, command).
27
- - Hold a single in-memory session token and supply it to the GameHub REST API when submitting scores.
27
+ - Hold one in-memory playthrough session at a time, retain unknown submissions for exact retry, and clear terminal sessions so the same document can run sequential rounds.
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. |
@@ -99,6 +100,7 @@ This is the only place in the package that does work on import. Module / npm con
99
100
  | `dist/src/main.d.ts` | Public type surface. |
100
101
  | `dist/src/browser-entry.js` | ESM entry that performs the same side effects as the IIFE bundle. Used by frameworks that want a tree-shakeable side-effectful import. |
101
102
  | `dist/gamehub-sdk.js` | IIFE bundle for `<script>` tag use, target ES2020, no external deps. Includes `browser-entry.ts`. Marked `sideEffects: true`. |
103
+ | `dist/gamehub-sdk.js.map` | Source map for the IIFE bundle. The app-served JS and map are refreshed together under `packages/gamehub/public/sdk/`. |
102
104
 
103
105
  `build:tsc` emits ESM with `.js` extensions in imports (NodeNext) and full `.d.ts` files. `build:bundle` runs esbuild over `src/browser-entry.ts` to produce the IIFE.
104
106
 
@@ -164,41 +166,50 @@ The full taxonomy follows. It applies to **both** transports identically.
164
166
 
165
167
  ### 6.1 Message-type taxonomy
166
168
 
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. |
169
+ | Direction | Type (after prefix) | Purpose |
170
+ | ---------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
171
+ | SDK → host | `READY` | Fired once on script load when a host transport is present (`hasHost()`). Carries `{ version }`. |
172
+ | SDK → host | `BOOTSTRAP_REQUEST` | Asks the host for bootstrap config. Carries `{ messageId }`. |
173
+ | 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`. |
174
+ | SDK → host | `AUTH_REQUEST` | Asks the host for an auth token. Carries `{ messageId }`. |
175
+ | host → SDK | `AUTH_RESPONSE` | Auth response. Carries `{ token: string \| null, leagueId?, gameId?, matchId?, messageId }`. |
176
+ | host → SDK | `SET_AUTH` | Unsolicited auth update. Carries `{ token }`. Triggers session start if not already running. |
177
+ | host → SDK | `COMMAND` | Player-visible host command. Carries `{ command: 'pause' \| 'resume' }`. Routed to optional `window.onGameHubPause/Resume`. |
178
+ | SDK → host | `INIT` | Fired after auto-init resolves. Carries `{ slug, auto: true }`. |
179
+ | SDK → host | `SESSION_STARTED` | Fired when a session token is obtained. Carries `{ token }`. |
180
+ | SDK → host | `SCORE_SUBMITTED` | Fired only when a score is accepted. Carries `{ score, sessionId, status: 'accepted', terminal: true, serverDurationMs, timeTaken, replayed? }`; score metadata is never included. |
181
+ | SDK → host | `GAME_COMPLETE` | Fired by `sdk.notifyComplete(data?)`. Carries `data` verbatim. |
182
+ | SDK → host | `REQUEST_CLOSE` | Fired by `sdk.requestClose()`. Empty payload. |
183
+ | SDK → host | `LOG_EVENT` | Fired by `sdk.logEvent(name, data?)`. Carries `{ event, data }`. |
184
+ | 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`. |
185
+ | 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. |
186
+ | SDK → host | `API_REQUEST` | Asks the host to proxy a backend HTTP call. Carries `{ messageId, endpoint, method, body }`. See §6.6. |
187
+ | host → SDK | `API_RESPONSE` | Result of a proxied call. Carries `{ messageId, ok: boolean, result?: ApiResponse, error?: string }`. See §6.6. |
188
+
189
+ The production GameHub play host uses these existing envelopes, together with
190
+ successful SDK API routes, to aggregate per-game feature observations for the
191
+ admin SDK-usage report. This is host behavior only: the SDK emits no additional
192
+ telemetry and its wire protocol/version is unchanged. The report contract and
193
+ feature-to-observation map live in
194
+ [`../../specs/sdk-usage-report.md`](../../specs/sdk-usage-report.md).
186
195
 
187
196
  Every SDK → host envelope also includes the resolved `gameSlug` as a top-level field (except `API_REQUEST`, whose payload is the proxied request).
188
197
 
189
198
  ### 6.2 Origin handling
190
199
 
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 `'*'`.
200
+ 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
201
 
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.
202
+ 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.
203
+
204
+ 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
205
 
195
206
  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
207
 
197
208
  ### 6.3 Request/response correlation
198
209
 
199
210
  - 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.
211
+ - The host's response must echo the same `messageId`. Bootstrap, auth, and API request handlers ignore missing or mismatched IDs.
212
+ - The host may push an unsolicited `BOOTSTRAP` with no `messageId` only after a correlated response has pinned the direct parent origin.
202
213
  - 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
214
 
204
215
  ### 6.4 Bootstrap merge semantics
@@ -212,7 +223,14 @@ On the **native** transport there is no web origin: inbound `HostMessage.origin`
212
223
  - `multiplayer`:
213
224
  - Explicit `null` → `null`.
214
225
  - 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.
226
+ - Optional `roomCode`, `role`, and `connectionScope` strings are copied only
227
+ when non-empty and bounded. `connectionScope` lets a game partition its own
228
+ reconnect storage by public embed and outer-host instance; the SDK neither
229
+ stores nor interprets it.
215
230
  - Any other shape → ignored (field left as-is).
231
+ - `sessionMode` accepts only `'authenticated'`, `'embed-guest'`,
232
+ `'league-guest'`, or explicit `null`; every other value is ignored. The
233
+ trusted host, not uploaded game code, selects this authority mode.
216
234
 
217
235
  This lets the host clear fields explicitly (via `null`) without overwriting unset fields.
218
236
 
@@ -220,7 +238,7 @@ This lets the host clear fields explicitly (via `null`) without overwriting unse
220
238
 
221
239
  1. **Idle.** `state.bootstrapReceived = false`.
222
240
  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.
241
+ 3. **Response.** Host replies with `BOOTSTRAP` carrying the matching `messageId`. `state.bootstrapReceived = true`; the direct parent's non-opaque origin is pinned.
224
242
  4. **Cache.** Subsequent calls return `snapshotBootstrap()` synchronously (wrapped in a resolved promise).
225
243
  5. **Update.** Any later unsolicited `BOOTSTRAP` from the host triggers `mergeBootstrapConfig` without affecting `bootstrapReceived`. Existing callers do not get re-notified.
226
244
 
@@ -237,10 +255,17 @@ The SDK never issues a cross-origin request to the GameHub backend. When a game
237
255
 
238
256
  Protocol details:
239
257
 
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.
258
+ - `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.
259
+ - A public embed host may translate the ordinary `/sessions/start` and
260
+ `/sessions/submit` requests to its guest or authenticated embed endpoints.
261
+ That translation binds the request to host-owned embed, guest/auth session,
262
+ publisher origin, and host instance; it does not change the SDK-facing
263
+ endpoint or game integration.
241
264
  - `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`.
243
- - `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).
265
+ - The host attaches authority from **its own** context. For authenticated
266
+ external embeds this is an opaque embed credential held only in outer-host
267
+ memory; it is never added to bootstrap or an `API_REQUEST`.
268
+ - `API_RESPONSE.ok` describes the host exchange, not the backend HTTP status. Whenever the backend returned a parseable `{ success: boolean, ... }` envelope, the host sends `ok: true` and carries that envelope in `result`, including structured non-2xx errors. `ok: false` is reserved for host validation, network, or malformed-response failure and carries an `error` string. The SDK validates bounded error `code`/`message` plus `details.terminal`, `details.sessionStatus`, and `details.retryAfterMs`; score methods map those fields without inspecting message text.
244
269
  - 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
270
  - `messageId` is `'api_' + Date.now() + '_' + <seq>`, where `<seq>` is a monotonic counter so concurrent proxied calls (e.g. session start + questions) never collide.
246
271
 
@@ -266,7 +291,7 @@ interface GameHubNativeHost {
266
291
  - The native app implements `postMessage` (typically forwarding to its WebView message channel — e.g. `flutter_inappwebview`'s `callHandler`).
267
292
  - The SDK installs `receive` when the transport is constructed. The native app calls `window.GameHubNativeHost.receive(env)` to deliver every host → SDK envelope (`BOOTSTRAP`, `AUTH_RESPONSE`, `API_RESPONSE`, `SET_AUTH`, `COMMAND`).
268
293
  - Envelope shapes, `messageId` correlation, and timeouts (§6.3) are identical to the postMessage transport. The native host must therefore echo the `messageId` on `BOOTSTRAP`/`AUTH_RESPONSE`/`API_RESPONSE` exactly as an iframe host does.
269
- - The native host is responsible for the same protocol an iframe host implements: replying to `BOOTSTRAP_REQUEST`/`AUTH_REQUEST`, proxying `API_REQUEST` (performing the real HTTPS call natively — see §6.6), and reacting to one-way signals (`REQUEST_CLOSE`, `QUESTION_REPORT`, `WORD_REPORT`, `SCORE_SUBMITTED`, `GAME_COMPLETE`, `LOG_EVENT`).
294
+ - The native host is responsible for the same protocol an iframe host implements: replying to `BOOTSTRAP_REQUEST`/`AUTH_REQUEST`, proxying `API_REQUEST` (performing the real HTTPS call natively and preserving parseable backend failure envelopes with `ok: true` — see §6.6), and reacting to one-way signals (`REQUEST_CLOSE`, `QUESTION_REPORT`, `WORD_REPORT`, accepted-only `SCORE_SUBMITTED`, `GAME_COMPLETE`, `LOG_EVENT`).
270
295
  - Multiplayer is unchanged: the host passes `bootstrap.multiplayer` `{ reservation, wsEndpoint }`, and the game opens its own Colyseus WebSocket from inside the WebView (§19.1). The SDK does not proxy realtime traffic over the bridge.
271
296
 
272
297
  ## 7. Authentication
@@ -295,26 +320,28 @@ If the host posts `SET_AUTH` mid-session, the new token is used for subsequent r
295
320
 
296
321
  `startSession()` picks one of three endpoints from the active context:
297
322
 
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 }` |
323
+ | Condition | Endpoint | Body |
324
+ | ----------------------------------------- | ---------------------------------------------------- | -------------- |
325
+ | `leagueId && gameId && matchId` | `POST /leagues/<leagueId>/matches/<matchId>/session` | `{ gameId }` |
326
+ | `leagueId && gameId` (no `matchId`) | `POST /leagues/<leagueId>/sessions` | `{ gameId }` |
327
+ | otherwise (including trusted embed modes) | `POST /sessions/start` | `{ gameSlug }` |
303
328
 
304
329
  ### 8.2 Preconditions
305
330
 
306
331
  - `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.
332
+ - 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.
333
+ - A game cannot opt itself into guest authority: unsupported bootstrap values
334
+ are ignored, and standalone unauthenticated behavior is unchanged.
308
335
 
309
336
  ### 8.3 Idempotency
310
337
 
311
- Once `state.sessionToken` is non-null, subsequent `startSession()` calls short-circuit to `{ success: true, token }`. Concurrent callers share `state.sessionStartPromise`. The SDK never starts a second session.
338
+ Once `state.sessionToken` is non-null, subsequent `startSession()` calls short-circuit to `{ success: true, token }`. Concurrent callers share `state.sessionStartPromise`. An accepted or terminally rejected submission clears the token and all start/submission state; only then may the next `startSession()` create the next playthrough.
312
339
 
313
340
  ### 8.4 Session start triggers
314
341
 
315
342
  A session is opened by any of:
316
343
 
317
- - `autoInit()` (when auth or league-match context is present).
344
+ - `autoInit()` (when auth, a trusted authenticated/embed-guest mode, or league-match context is present).
318
345
  - The host posting `SET_AUTH` (when the slug is known and no session is already running).
319
346
  - Any score-submitting call that finds no session.
320
347
  - An explicit `sdk.startSession()` call.
@@ -329,10 +356,15 @@ On success, the SDK posts `SESSION_STARTED { token }` to the host.
329
356
 
330
357
  - Awaits `ensureInitialized()`.
331
358
  - If no session, opens one (or awaits the in-flight start).
332
- - Validates: `score` must be a non-negative number; coerced to `Math.floor(score)` before submit.
359
+ - Validates: `score` must be finite and floor to an integer from 0 through 10,000,000. Metadata must match the server's 32 KiB/depth/key/string/array JSON bounds. Invalid input resolves locally before a submission is bound.
333
360
  - POSTs to `/sessions/submit` with `{ token, score, meta }`.
334
- - On success or `data.accepted`, posts `SCORE_SUBMITTED { score, accepted, timeTaken }` to the host and resolves `{ success: true, accepted, timeTaken }`.
335
- - On failure, resolves `{ success: false, error }`. Never throws.
361
+ - Snapshots the first JSON-serializable body exactly. Its canonical concurrency key is `{ floor(score), sanitized/capped attempts, clientMeta }`, with server-authoritative identity, duration, session, and source keys excluded to match the server submission hash.
362
+ - Concurrent calls with the same token and canonical payload share one in-flight request. A different payload resolves locally as a non-retriable `CONCURRENT_SUBMISSION_CONFLICT` and never races the server.
363
+ - An accepted target response resolves `{ success: true, status: 'accepted', terminal: true, sessionId, serverDurationMs, timeTaken, replayed? }`. Guest/league storage responses are normalized to this same public accepted shape.
364
+ - A structured terminal error resolves `{ success: false, status: 'rejected', terminal: true, code, error, sessionStatus? }`. Accepted and rejected terminal outcomes clear the token/start/submission/pending state after accepted host notification.
365
+ - `RATE_LIMITED` and `SUBMISSION_IN_PROGRESS` resolve the retriable variant. Server/transport failures resolve the failed variant. All non-terminal outcomes retain the active token and exact first body; an explicit same-payload call retries it and can consume `replayed: true`.
366
+ - Posts `SCORE_SUBMITTED` only for accepted outcomes. The telemetry contains lifecycle fields, never arbitrary `meta`.
367
+ - Every public score method resolves a result and never throws.
336
368
 
337
369
  ### 9.2 `submitMatchScore(score, meta?)`
338
370
 
@@ -398,7 +430,7 @@ The HTTP league-match surface (`getMatchContext`, `submitMatchResult`) is indepe
398
430
  ### 11.1 `getQuestions(options?)`
399
431
 
400
432
  - Awaits `ensureInitialized()`.
401
- - Identifier is `state.gameId || state.gameSlug`. Returns `[]` if both are null.
433
+ - Identifier is `state.gameSlug || state.gameId`. Returns `[]` if both are null.
402
434
  - Validates `options.difficulty` against `'easy' | 'medium' | 'hard'`. Returns `[]` on mismatch.
403
435
  - Validates `options.limit` is a positive number. Returns `[]` on mismatch.
404
436
  - GETs `/games/<identifier>/questions?limit=<n>&random=true[&gameId=…][&difficulty=…][&category=…][&profileId=…]`.
@@ -430,7 +462,7 @@ interface Question {
430
462
  ### 11bis.1 `getWords(options?)`
431
463
 
432
464
  Mirrors `getQuestions`. Awaits `ensureInitialized()`; identifier is
433
- `state.gameId || state.gameSlug` (returns `[]` if both null). Validates
465
+ `state.gameSlug || state.gameId` (returns `[]` if both null). Validates
434
466
  `options.difficulty` and `options.limit` the same way (returns `[]` on
435
467
  mismatch). GETs
436
468
  `/games/<identifier>/words?limit=<n>&random=true[&gameId=…][&difficulty=…][&category=…][&tags=a,b][&profileId=…]`.
@@ -492,6 +524,7 @@ interface SdkState {
492
524
  leagueId: string | null;
493
525
  gameId: string | null;
494
526
  matchId: string | null;
527
+ bootstrapSessionMode: BootstrapSessionMode | null;
495
528
 
496
529
  // Free-form bootstrap fields
497
530
  bootstrapMode: string | null;
@@ -511,6 +544,12 @@ interface SdkState {
511
544
  bootstrapRequestPromise: Promise<BootstrapConfig | null> | null;
512
545
  parentOrigin: string | null;
513
546
  sessionStartPromise: Promise<StartSessionResult> | null;
547
+ submissionPromise: Promise<SubmitScoreResult> | null;
548
+ pendingSubmission: {
549
+ token: string;
550
+ canonicalPayload: string;
551
+ body: { token: string; score: number; meta: Record<string, unknown> };
552
+ } | null;
514
553
 
515
554
  // League match (HTTP)
516
555
  matchContext: MatchContext | null;
@@ -522,7 +561,8 @@ interface SdkState {
522
561
 
523
562
  - `apiBase` is set exactly once, by `detectEnvironment()`, before any HTTP request. It is never mutated afterwards.
524
563
  - `gameSlug` may be updated by the bootstrap merge but should be considered stable after `isInitialized = true`. Changing the slug mid-session is undefined behaviour.
525
- - `sessionToken` is set at most once per page load. The SDK never invalidates or rotates it.
564
+ - At most one `sessionToken` is active. A terminal result clears it synchronously after accepted host notification; the next round receives a distinct token without reloading.
565
+ - `pendingSubmission` is bound to the active token and canonical payload. Non-terminal outcomes retain its exact body; terminal outcomes clear it together with `submissionPromise`, `sessionStartPromise`, and the token.
526
566
  - `matchContext` is set at most once. Stale match context across renavigations is the host's problem (refresh resets the SDK).
527
567
  - All `*Promise` fields are cleared when their underlying operation settles (success or failure).
528
568
 
@@ -616,6 +656,9 @@ interface SdkSeatReservation {
616
656
  interface BootstrapMultiplayer {
617
657
  reservation: SdkSeatReservation;
618
658
  wsEndpoint: string;
659
+ roomCode?: string;
660
+ role?: string;
661
+ connectionScope?: string;
619
662
  }
620
663
 
621
664
  interface BootstrapConfig {
@@ -624,6 +667,7 @@ interface BootstrapConfig {
624
667
  leagueId?: string | null;
625
668
  gameId?: string | null;
626
669
  matchId?: string | null;
670
+ sessionMode?: BootstrapSessionMode | null;
627
671
  mode?: string | null;
628
672
  playerName?: string | null;
629
673
  playerCount?: string | null;
@@ -639,6 +683,7 @@ interface BootstrapData {
639
683
  leagueId: string | null;
640
684
  gameId: string | null;
641
685
  matchId: string | null;
686
+ sessionMode: BootstrapSessionMode | null;
642
687
  mode: string | null;
643
688
  playerName: string | null;
644
689
  playerCount: string | null;
@@ -648,6 +693,8 @@ interface BootstrapData {
648
693
  multiplayer: BootstrapMultiplayer | null;
649
694
  isBootstrapped: boolean;
650
695
  }
696
+
697
+ type BootstrapSessionMode = 'authenticated' | 'embed-guest' | 'league-guest';
651
698
  ```
652
699
 
653
700
  ### 15.2 Session / scoring
@@ -666,12 +713,41 @@ interface StartSessionResult {
666
713
  error?: string;
667
714
  }
668
715
 
669
- interface SubmitScoreResult {
670
- success: boolean;
671
- accepted?: boolean;
672
- timeTaken?: number;
673
- error?: string;
674
- }
716
+ type SubmitScoreResult =
717
+ | {
718
+ success: true;
719
+ status: 'accepted';
720
+ terminal: true;
721
+ sessionId: string;
722
+ serverDurationMs: number;
723
+ timeTaken: number;
724
+ replayed?: true;
725
+ }
726
+ | {
727
+ success: false;
728
+ status: 'rejected';
729
+ terminal: true;
730
+ code: string;
731
+ error: string;
732
+ sessionStatus?: string;
733
+ }
734
+ | {
735
+ success: false;
736
+ status: 'retriable';
737
+ terminal: false;
738
+ code: 'SUBMISSION_IN_PROGRESS' | 'RATE_LIMITED';
739
+ error: string;
740
+ retryAfterMs?: number;
741
+ sessionStatus?: string;
742
+ }
743
+ | {
744
+ success: false;
745
+ status: 'failed';
746
+ terminal: false;
747
+ code: string;
748
+ error: string;
749
+ retriable: boolean;
750
+ };
675
751
 
676
752
  interface GameCompleteData {
677
753
  score?: number;
@@ -744,7 +820,15 @@ interface ApiResponse {
744
820
  success: boolean;
745
821
  data?: any;
746
822
  token?: string;
747
- error?: { message?: string };
823
+ error?: {
824
+ code?: string;
825
+ message?: string;
826
+ details?: {
827
+ terminal?: boolean;
828
+ sessionStatus?: string;
829
+ retryAfterMs?: number;
830
+ };
831
+ };
748
832
  }
749
833
 
750
834
  interface ApiRequestOptions {
@@ -759,14 +843,14 @@ interface ApiRequestOptions {
759
843
 
760
844
  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
845
 
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 }` |
846
+ | Method | Path | Auth | Request body | Successful response shape |
847
+ | ------ | ----------------------------------------------- | ---------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
848
+ | POST | `/sessions/start` | Bearer or trusted embed-guest host | `{ gameSlug }` | `{ success: true, data: { token } }` or `{ success: true, token }` |
849
+ | POST | `/leagues/<leagueId>/sessions` | Bearer | `{ gameId }` | as above |
850
+ | POST | `/leagues/<leagueId>/matches/<matchId>/session` | optional | `{ gameId }` | as above (guest sessions allowed) |
851
+ | POST | `/sessions/submit` | optional | `{ token, score, meta }` | Account target: `{ success: true, data: { status: 'accepted', terminal: true, sessionId, serverDurationMs, timeTaken, replayed? } }`; guest/league accepted responses are normalized by the SDK |
852
+ | GET | `/games/<id-or-slug>/questions?…` | optional | n/a | `Question[]` or `{ questions: Question[] }` |
853
+ | GET | `/leagues/<leagueId>/matches/<matchId>` | optional | n/a | `{ success: true, data: MatchContext }` |
770
854
 
771
855
  ### 16.1 Response envelope
772
856
 
@@ -774,14 +858,14 @@ The SDK expects (but tolerates absence of) a `{ success, data, token?, error? }`
774
858
 
775
859
  ### 16.2 Failure surface
776
860
 
777
- - Non-2xx HTTP responses are parsed as JSON and surfaced via the returned `SubmitScoreResult.error` / `null` / `[]` (depending on the call).
861
+ - Structured non-2xx HTTP envelopes are surfaced to score calls as terminal, retriable, or failed discriminated results; other calls degrade to `null` / `[]` as documented.
778
862
  - `fetch` exceptions (network failure, malformed JSON) are caught by every public method and surfaced as the same failure shape. The SDK never throws past its public surface.
779
863
  - When embedded, a host-proxy rejection (host-reported error, or `HOST_API_TIMEOUT_MS` timeout — see §6.6) surfaces identically: the call degrades to its failure shape. CORS is no longer a failure mode for embedded games, since the host (same-origin with the backend) makes the actual request.
780
864
 
781
865
  ## 17. Error handling philosophy
782
866
 
783
867
  - **Never throw to consumers.** Every public method returns either a typed success/failure result, or the degraded value (`null` / `[]`).
784
- - **No retries.** A single attempt per call. Consumers retry if they want to.
868
+ - **Explicit score retry only.** The SDK never autonomously repeats a network call. After an unknown/retriable score outcome, a consumer retries the same call; the SDK reuses the original session token and exact first request body. A different payload is refused until the session becomes terminal.
785
869
  - **No global error reporting.** Errors are logged with the `[GameHubSDK]` prefix via `console.warn` / `console.error`. The SDK does not POST to any error endpoint.
786
870
  - **No timeouts on direct HTTP.** The standalone `fetch` path inherits `fetch`'s default behaviour. The postMessage handshakes have timeouts (2 s for bootstrap/auth), and the host-proxied API transport has its own `HOST_API_TIMEOUT_MS` (15 s) cap (§6.6).
787
871
  - **Silent degradation on partial bootstrap.** Missing fields are tolerated where possible (`getQuestions` works without `gameId`, falling back to slug; `submitScore` requires auth or a league-match session but no realtime context).
@@ -801,7 +885,9 @@ These rules exist because of a real prior regression where transport-related cle
801
885
 
802
886
  - The SDK must not import any realtime client (`@colyseus/sdk`, `ws`, `socket.io-client`, …).
803
887
  - 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.
888
+ - The `bootstrapMultiplayer` field is opaque. The SDK validates the reservation,
889
+ endpoint, and optional bounded room/role/scope strings; it does not parse or
890
+ interpret them.
805
891
  - The server-clock helper (`attachServerClock`) belongs in `@ksaa-nlp/colyseus-schemas/clock`, not here.
806
892
 
807
893
  ### 19.2 HTTP plumbing is transport-agnostic
@@ -838,7 +924,7 @@ These rules exist because of a real prior regression where transport-related cle
838
924
 
839
925
  ### 20.3 Bundle budget
840
926
 
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.
927
+ The IIFE bundle (`dist/gamehub-sdk.js`) must remain under **40 KB raw** and **10 KB gzip**, the latter being the figure that matters most on the wire. The raw budget was historically 25 KB; native transport and the reliable multi-round lifecycle deliberately exceed that historical target. Current 4.0.0 size: **38,130 bytes raw / 8,570 bytes gzip**. Further growth requires a deliberate release review.
842
928
 
843
929
  ### 20.4 No runtime dependencies
844
930
 
@@ -846,7 +932,7 @@ The IIFE bundle (`dist/gamehub-sdk.js`) is expected to remain under **10 KB gzip
846
932
 
847
933
  ## 21. Testing acceptance criteria
848
934
 
849
- The SDK does not currently ship a test suite, but every change should be verifiable against this checklist:
935
+ The SDK ships focused Node tests for transport trust-boundary behavior. Every change should also be verifiable against this checklist:
850
936
 
851
937
  ### 21.1 Pure-import safety
852
938
 
@@ -857,13 +943,21 @@ The SDK does not currently ship a test suite, but every change should be verifia
857
943
 
858
944
  - `autoInit()` resolves `false` and logs the slug-not-found warning when the page is not under `/games/<slug>/`.
859
945
  - Score-submit calls in this state return `{ success: false, error }` and never throw.
946
+ - Setting `sessionMode: 'embed-guest'` through trusted bootstrap permits the
947
+ ordinary session call; an absent or invalid mode leaves anonymous
948
+ standalone calls denied.
949
+ - Setting `sessionMode: 'authenticated'` through trusted bootstrap permits
950
+ session auto-start without an SDK-visible JWT. The host must supply the
951
+ authority when proxying; standalone code cannot manufacture that authority.
860
952
 
861
953
  ### 21.3 Iframe boot
862
954
 
863
955
  - 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.
956
+ - 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
957
  - Replying with `AUTH_RESPONSE { token }` makes `isAuthenticated()` true.
866
958
  - Posting `SET_AUTH { token }` after init opens a session and fires `SESSION_STARTED`.
959
+ - A message from a window other than `window.parent` is ignored even when its envelope and `messageId` otherwise look valid.
960
+ - 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
961
 
868
962
  ### 21.3b Native bridge boot
869
963
 
@@ -875,14 +969,21 @@ The SDK does not currently ship a test suite, but every change should be verifia
875
969
  ### 21.4 Score submission
876
970
 
877
971
  - `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
- - Returns `{ success: true, accepted: true, timeTaken: <n> }` on a `{ success: true, data: { accepted: true, timeTaken: 1234 } }` server response.
879
- - Fires `SCORE_SUBMITTED { score: 42, accepted: true, timeTaken: 1234 }` to the host.
972
+ - The target account response resolves the accepted terminal variant and fires accepted-only `SCORE_SUBMITTED`; terminal rejection resolves the rejected variant and emits no score telemetry. Both immediately make `hasActiveSession()` false.
973
+ - Rate limit, live processing, `SERVER_ERROR`, host failure, and timeout retain the token and exact first body. A same-payload retry can resolve accepted with `replayed: true`.
974
+ - Two sequential accepted rounds in one document create and submit distinct session tokens.
975
+ - Concurrent canonical-identical calls issue one host request; a different concurrent payload resolves `CONCURRENT_SUBMISSION_CONFLICT` locally.
976
+ - `SCORE_SUBMITTED` contains score/session/lifecycle/duration fields only. The trusted host parser strips score/session/duration before lifecycle publication and never forwards arbitrary score metadata.
977
+ - In public embed mode, the game still emits `/sessions/start` and
978
+ `/sessions/submit`; the host binds and rewrites those requests for guest or
979
+ authenticated play. The SDK never creates or stores the embed guest ID,
980
+ authorization code, or opaque authenticated credential.
880
981
 
881
982
  ### 21.4b Host-proxied transport (embedded)
882
983
 
883
984
  - 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
985
  - 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.
986
+ - An `API_RESPONSE { ok: false, error }` degrades identically. A parseable backend failure envelope travels as `{ ok: true, result: { success: false, error: ... } }` so terminal/retriable details survive. 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
987
 
887
988
  ### 21.5 League-match path
888
989
 
@@ -895,6 +996,26 @@ The SDK does not currently ship a test suite, but every change should be verifia
895
996
  - `grep -rn "@colyseus" src/ types/` returns only comment references (no import statements).
896
997
  - `npm pack --dry-run` produces a tarball whose `peerDependencies` and `dependencies` are both empty/absent.
897
998
 
999
+ ### 21.7 SDK Usage Intelligence Report synchronization
1000
+
1001
+ Every new public SDK method, alias, or capability must be represented in the
1002
+ GameHub SDK Usage Intelligence Report in the same change. This is part of the
1003
+ definition of done for a public API addition, not optional follow-up work.
1004
+
1005
+ The authoritative maintenance checklist is
1006
+ [`../../specs/sdk-usage-report.md` §4.1](../../specs/sdk-usage-report.md#41-mandatory-synchronization-for-new-sdk-apis).
1007
+ At minimum, the change must update the report inventory and labels, static
1008
+ scanner registry/version, runtime-observation strategy where applicable,
1009
+ admin contract/UI/CSV, automated tests, and both package specifications. A
1010
+ method that cannot cross an observable host or server boundary must be
1011
+ explicitly classified as static-only.
1012
+
1013
+ Version 4.0.0 changes the lifecycle/result contract of the existing
1014
+ `startSession` and `submitScore` capabilities but adds no public method, alias,
1015
+ or capability. Their existing Usage Intelligence feature IDs and accepted-only
1016
+ server-operation observation remain authoritative; no scanner/report inventory
1017
+ version change is required for this release.
1018
+
898
1019
  ## 21bis. UGC server bundle subpath
899
1020
 
900
1021
  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.