@funfab/sdk 0.2.0 → 0.3.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
@@ -10,8 +10,8 @@ Needs Node.js 22 or newer on your server.
10
10
  ## Which part to import
11
11
  | | |
12
12
  | --- | --- |
13
- | Your game's server, on Railway | `@funfab/sdk/adapters/stream` |
14
- | Your game's server, on Vercel | `@funfab/sdk/adapters/vercel` |
13
+ | A long-running game server with rooms (for example on Railway) | `@funfab/sdk/adapters/stream` |
14
+ | Serverless request handlers (for example on Vercel) | `@funfab/sdk/adapters/vercel` |
15
15
  | Party games | `@funfab/sdk/adapters/party` |
16
16
  | Sign-in tickets, any server | `@funfab/sdk/server` |
17
17
  | Pages players see | `@funfab/sdk/browser` |
@@ -88,6 +88,60 @@ The SDK has no built-in Railway peer verification. Supply a synchronous
88
88
  transport peer as Railway ingress. Behind a verified peer, a single valid `X-Real-IP` gets 20 login
89
89
  starts per minute per IP. Otherwise, login starts share one flood limit of 200 per minute per gate instance.
90
90
 
91
+ ## Hub and hand-off clients (`hub/1`)
92
+
93
+ Use `createHubClient(gameConfig)` for a hub and `createHandoffClient(gameConfig)` for a member
94
+ game. Import both from `@funfab/sdk/server`. Hosted games pass the configuration returned by
95
+ `signInTicketConfig()`, which requires an HTTPS platform origin.
96
+
97
+ For local stub calls, pass `{ gameId, ticketApiOrigin, credential }` directly. Use the stub's
98
+ loopback origin and the seeded test credential. The game keeps its existing local sign-in
99
+ opt-out. Hub and hand-off calls accept HTTP at `localhost`, `127.0.0.1` and `[::1]`.
100
+
101
+ Pass the host's ticket as a string. On show reads, hand-off reads and link events, pass either
102
+ that ticket or `{ show_ref }` from the exact show's job payload. Receipts use `{ show_ref }`.
103
+ For `playerSubjects` and `playerCredit`, pass the viewer's own ticket. `members` and `hubOrigins`
104
+ use the game credential alone. Reads accept `{ etag }` and return `"not-modified"` when the
105
+ platform confirms the ETag still matches.
106
+
107
+ `redeem(ticket, code)` omits `v`. The member client checks that the platform returns `v: 1`,
108
+ the version `hub/1` supports, and sends that version on later hand-off requests.
109
+ Platform refusals reject with an `Error` whose
110
+ `code` is the wire error and whose `status` is the HTTP status. `seq_gap`, `not_on_air`, and
111
+ `blocks_incomplete` preserve `retry`, and `seq_gap` also preserves `expected_seq`. A transport
112
+ failure reports `account_unavailable` with the HTTP status when available.
113
+
114
+ ### Send a result
115
+
116
+ `buildResultRequest(id, result)` returns the final `Uint8Array` with `v`, `handoff` and `game`
117
+ filled in. Commit those bytes to durable game storage before the **first send** and before
118
+ emitting **`ff:ended`**. Use `sendResultRequest(id, bytes)` for the first send and every replay.
119
+ It sends the supplied bytes unchanged, including after a restart. Read them back from storage
120
+ as bytes for a replay. The game owns durable storage and decides when to retry.
121
+
122
+ ```js
123
+ const bytes = handoff.buildResultRequest(id, result);
124
+ await saveResultBytes(id, bytes);
125
+ await handoff.sendResultRequest(id, bytes);
126
+ ```
127
+
128
+ ### Run the local platform stub
129
+
130
+ To run the stub, also install `ajv@8.20.0` and `ajv-formats@3.0.1`.
131
+ Call `startPlatformStub({ port, games, memberships, hosts })` from `@funfab/sdk/stub`.
132
+ It listens on `127.0.0.1` and returns `{ baseUrl, tickets, close }`. The OS assigns the
133
+ default port. Use synthetic credentials in `games`, keyed by runtime, with each runtime's
134
+ `permissions`, `origins` or `titles`, and optional `hostedRooms` and known `sources`.
135
+ Seed `memberships` as `{ hub, game, title, state }` and `hosts` by account then runtime,
136
+ with `host: true` for hosts and optional verified `subjects` and fixture `credit`.
137
+
138
+ The stub prints `tickets[account][gameId]`. It defaults to Preview with a 24-hour show lifetime.
139
+ Seed member titles with their HTTPS board origin and path, `board_room_param`, and `board_params`
140
+ (query parameter names mapped to regex patterns). Use the member runtime's ticket for redeem
141
+ and context. For a hosted member, pass the launch context's `room_request_id` to the existing
142
+ sign-in ticket client's `room` method before claiming the hand-off. When constructing that local
143
+ client, pass the stub's loopback `baseUrl` as `ticketApiOrigin` in its config.
144
+
91
145
  ## Versions
92
146
  Trial (0.x): pin an exact version. The previous version
93
147
  keeps working for 90 days after a new one. `funfab game
package/gate-core.mjs CHANGED
@@ -5,6 +5,30 @@ export const settingError = name => Object.assign(
5
5
  new Error(`Missing or invalid SDK game setting: ${name}`), { code: 'invalid_gate_configuration' },
6
6
  );
7
7
 
8
+ export const isLoopbackHost = hostname => ['localhost', '127.0.0.1', '[::1]'].includes(hostname);
9
+
10
+ export function requirePlatformGameConfig(config) {
11
+ try {
12
+ const { ticketApiOrigin, gameId, credential } = config;
13
+ const url = new URL(ticketApiOrigin);
14
+ if (url.origin === ticketApiOrigin &&
15
+ (url.protocol === 'https:' || (url.protocol === 'http:' && isLoopbackHost(url.hostname))) &&
16
+ typeof gameId === 'string' && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(gameId) &&
17
+ typeof credential === 'string' && /^fgc_[A-Za-z0-9_-]+$/.test(credential)) return;
18
+ } catch { /* Report a safe configuration error below. */ }
19
+ throw gateError('invalid_gate_configuration');
20
+ }
21
+
22
+ export function postPlatformJson(transport, url, credential, body) {
23
+ return transport(url, {
24
+ method: 'POST',
25
+ headers: { authorization: `Bearer ${credential}`, 'content-type': 'application/json' },
26
+ body,
27
+ redirect: 'error',
28
+ signal: AbortSignal.timeout(8000),
29
+ });
30
+ }
31
+
8
32
  const PATH_BASE = 'https://game.invalid';
9
33
  export function gameReturnURL(value) {
10
34
  if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//') ||
@@ -0,0 +1,170 @@
1
+ import { gateError, postPlatformJson, requirePlatformGameConfig } from './gate-core.mjs';
2
+
3
+ const VERSION = 1;
4
+ const prefix = '/api/hub';
5
+ const handoffId = /^ho_[A-Za-z0-9_-]{8,64}$/;
6
+ const showPath = id => resourcePath('shows', /^sh_[A-Za-z0-9_-]{8,64}$/, id);
7
+ const handoffPath = id => resourcePath('handoffs', handoffId, id);
8
+ const invalid = () => gateError('accounts_request_invalid');
9
+
10
+ const refusals = new Set([
11
+ 'accounts_request_invalid', 'authorization_required', 'method_not_allowed', 'account_unavailable',
12
+ 'bad_origin', 'bad_sources', 'bad_lang', 'bad_screen', 'host_not_allowed', 'switched_off',
13
+ 'not_member', 'handoff_open', 'show_not_active', 'handoff_closed', 'seq_gap', 'stale_revision',
14
+ 'cannot_unremove', 'subject_removed', 'subject_suppressed', 'bad_event', 'linking_off',
15
+ 'bad_code', 'wrong_game', 'wrong_host', 'expired', 'superseded', 'bad_board', 'room_booked',
16
+ 'claimed', 'board_differs', 'blocks_incomplete', 'not_claimer', 'bad_result', 'not_on_air',
17
+ 'result_differs', 'closed_unplayed', 'deadline_passed',
18
+ ]);
19
+
20
+ function resourcePath(collection, pattern, id) {
21
+ if (typeof id !== 'string' || !pattern.test(id)) throw invalid();
22
+ return `/${collection}/${id}`;
23
+ }
24
+
25
+ function person(ticket) {
26
+ // Tickets are opaque, including the stub's synthetic tickets.
27
+ if (typeof ticket !== 'string' || !ticket.length || ticket.length > 512) throw invalid();
28
+ return { ticket };
29
+ }
30
+
31
+ function job(auth) {
32
+ const ref = auth?.show_ref;
33
+ if (typeof ref !== 'string' || !/^sr_[A-Za-z0-9_-]{16,128}$/.test(ref) || 'ticket' in auth) {
34
+ throw invalid();
35
+ }
36
+ return { show_ref: ref };
37
+ }
38
+
39
+ const reader = auth => typeof auth === 'string' ? person(auth) : job(auth);
40
+
41
+ function refusal(status, reply) {
42
+ const code = refusals.has(reply?.error) ? reply.error : 'account_unavailable';
43
+ const error = Object.assign(gateError(code), { status });
44
+ if (['seq_gap', 'not_on_air', 'blocks_incomplete'].includes(code) && typeof reply.retry === 'boolean') {
45
+ error.retry = reply.retry;
46
+ }
47
+ if (code === 'seq_gap' && Number.isInteger(reply.expected_seq) && reply.expected_seq > 0) {
48
+ error.expected_seq = reply.expected_seq;
49
+ }
50
+ return error;
51
+ }
52
+
53
+ function hubTransport(config, transport) {
54
+ requirePlatformGameConfig(config);
55
+ const { ticketApiOrigin, gameId: game, credential } = config;
56
+
57
+ async function send(path, body) {
58
+ let response, reply;
59
+ try {
60
+ response = await postPlatformJson(transport, `${ticketApiOrigin}${prefix}${path}`, credential, body);
61
+ reply = await response.json();
62
+ } catch {
63
+ throw refusal(response?.status);
64
+ }
65
+ if (!response.ok || !reply || typeof reply !== 'object' || Array.isArray(reply)) {
66
+ throw refusal(response.status, reply);
67
+ }
68
+ return reply;
69
+ }
70
+
71
+ return {
72
+ game,
73
+ send,
74
+ call: (path, body) => send(path, JSON.stringify({ game, v: VERSION, ...body })),
75
+ };
76
+ }
77
+
78
+ export function createHubClient(config, { transport = globalThis.fetch } = {}) {
79
+ const { call } = hubTransport(config, transport);
80
+ async function read(path, auth, etag) {
81
+ const reply = await call(path, { ...reader(auth), if_etag: etag });
82
+ return reply.not_modified === true ? 'not-modified' : reply;
83
+ }
84
+
85
+ return Object.freeze({
86
+ async bookShow(ticket, { idempotency_key, origin, sources, lang, screen }) {
87
+ return call('/shows', { ...person(ticket), idempotency_key, origin, sources, lang, screen });
88
+ },
89
+ async endShow(ticket, show, { ended_at } = {}) {
90
+ await call(`${showPath(show)}/end`, { ...person(ticket), ended_at });
91
+ },
92
+ async readShow(auth, show, { etag } = {}) {
93
+ return read(`${showPath(show)}/read`, auth, etag);
94
+ },
95
+ async bookHandoff(ticket, show, { idempotency_key, title, minutes, cam }) {
96
+ return call(`${showPath(show)}/handoffs`, { ...person(ticket), idempotency_key, title, minutes, cam });
97
+ },
98
+ async newLaunchCode(ticket, id) {
99
+ return call(`${handoffPath(id)}/launch-code`, person(ticket));
100
+ },
101
+ async setHandoffState(ticket, id, { seq, on_air, take_back, close }) {
102
+ await call(`${handoffPath(id)}/state`, { ...person(ticket), seq, on_air, take_back, close });
103
+ },
104
+ async readHandoff(auth, id, { etag } = {}) {
105
+ return read(`${handoffPath(id)}/read`, auth, etag);
106
+ },
107
+ async setBlocks(ticket, show, { expected_revision, hidden, removed }) {
108
+ return call(`${showPath(show)}/blocks`, { ...person(ticket), expected_revision, hidden, removed });
109
+ },
110
+ async addReceipts(auth, show, receipts) {
111
+ await call(`${showPath(show)}/receipts`, { ...job(auth), receipts });
112
+ },
113
+ async reportLinkEvent(auth, show, { source, event }) {
114
+ await call(`${showPath(show)}/links`, { ...reader(auth), source, event });
115
+ },
116
+ async playerSubjects(viewerTicket) {
117
+ return (await call('/player/subjects', person(viewerTicket))).subjects;
118
+ },
119
+ async playerCredit(viewerTicket) {
120
+ return call('/player/credit', person(viewerTicket));
121
+ },
122
+ async members() {
123
+ return (await call('/members')).members;
124
+ },
125
+ });
126
+ }
127
+
128
+ export function createHandoffClient(config, { transport = globalThis.fetch } = {}) {
129
+ const { game, call, send } = hubTransport(config, transport);
130
+ function launchContext(reply, id = reply.handoff) {
131
+ // hub/1 supports exactly one version. Reject any other pin before using the context.
132
+ if (reply.v !== VERSION || typeof id !== 'string' || !handoffId.test(id) || reply.handoff !== id) {
133
+ throw refusal();
134
+ }
135
+ return reply;
136
+ }
137
+
138
+ return Object.freeze({
139
+ async redeem(ticket, code) {
140
+ const reply = await send('/handoffs/redeem', JSON.stringify({ game, ...person(ticket), code }));
141
+ return launchContext(reply);
142
+ },
143
+ async context(ticket, id) {
144
+ const reply = await call(`${handoffPath(id)}/context`, person(ticket));
145
+ return launchContext(reply, id);
146
+ },
147
+ async claim(id, { room, room_id, board }) {
148
+ return call(`${handoffPath(id)}/claim`, { room, room_id, board });
149
+ },
150
+ async sync(id, { room, phase, last_host_action }) {
151
+ return call(`${handoffPath(id)}/sync`, { room, phase, last_host_action });
152
+ },
153
+ buildResultRequest(id, {
154
+ room, blocks_revision, started_at, ended_at, ending, rounds, participants, unidentified, moment,
155
+ }) {
156
+ handoffPath(id);
157
+ return new TextEncoder().encode(JSON.stringify({
158
+ v: VERSION, handoff: id, game, room, blocks_revision, started_at, ended_at, ending,
159
+ rounds, participants, unidentified, moment,
160
+ }));
161
+ },
162
+ async sendResultRequest(id, bytes) {
163
+ if (!(bytes instanceof Uint8Array)) throw invalid();
164
+ return send(`${handoffPath(id)}/result`, bytes);
165
+ },
166
+ async hubOrigins() {
167
+ return (await call('/origins')).titles;
168
+ },
169
+ });
170
+ }