@funfab/sdk 0.1.1 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funfab/sdk",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "Add FunFab sign-in and host safety to your game.",
6
6
  "engines": {
@@ -9,30 +9,49 @@
9
9
  "exports": {
10
10
  ".": "./index.js",
11
11
  "./server": "./server.mjs",
12
+ "./stub": "./stub.mjs",
12
13
  "./adapters/stream": "./adapters/stream.mjs",
13
14
  "./adapters/vercel": "./adapters/vercel.mjs",
14
15
  "./adapters/party": "./adapters/party.mjs",
15
16
  "./browser": "./browser.js",
17
+ "./host-panel": "./host-panel.js",
16
18
  "./host-safety": "./host-safety/index.js",
17
19
  "./schemas/host-safety": "./schemas/host-safety.schema.json"
18
20
  },
19
21
  "files": [
20
22
  "index.js",
21
23
  "server.mjs",
24
+ "hub-clients.mjs",
25
+ "stub.mjs",
26
+ "hub.openapi.json",
27
+ "gate-core.mjs",
22
28
  "adapters/stream.mjs",
23
29
  "adapters/vercel.mjs",
24
30
  "adapters/party.mjs",
25
31
  "browser.js",
32
+ "host-panel.js",
26
33
  "host-safety/index.js",
27
34
  "host-safety/name-filter.js",
28
35
  "host-safety/public-names.js",
29
36
  "schemas/host-safety.schema.json",
30
37
  "README.md"
31
38
  ],
39
+ "scripts": {
40
+ "prepack": "cp ../../docs/hub.openapi.json hub.openapi.json",
41
+ "postpack": "rm -f hub.openapi.json"
42
+ },
32
43
  "dependencies": {
33
44
  "oauth4webapi": "^3.8.8",
34
45
  "jose": "^6.2.12"
35
46
  },
47
+ "peerDependencies": {
48
+ "ajv": "8.20.0",
49
+ "ajv-formats": "3.0.1"
50
+ },
51
+ "peerDependenciesMeta": {
52
+ "ajv": { "optional": true },
53
+ "ajv-formats": { "optional": true }
54
+ },
36
55
  "publishConfig": {
37
56
  "access": "public",
38
57
  "provenance": false
package/server.mjs CHANGED
@@ -1,23 +1,42 @@
1
1
  import * as oauth from 'oauth4webapi';
2
+ import { gateError as fail, isLoopbackHost, isUuid, postPlatformJson } from './gate-core.mjs';
3
+
4
+ export { createHubClient, createHandoffClient } from './hub-clients.mjs';
2
5
 
3
6
  // Protocol bridge: the platform rename changes this one constant (#368).
4
7
  const PLATFORM_ROUTE_PREFIX = '/api/sign-in-ticket';
5
8
  export const SIGN_IN_TICKET_PREFIX = 'fst_';
6
9
  export const isSignInTicket = value => typeof value === 'string' && value.startsWith(SIGN_IN_TICKET_PREFIX) &&
7
10
  /^[A-Za-z0-9_-]{43}$/.test(value.slice(SIGN_IN_TICKET_PREFIX.length));
8
- const fail = code => Object.assign(new Error(code), { code });
9
- const uuid = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(value);
10
11
  export const ticketOperationUrl = (config, operation) => `${config.ticketApiOrigin}${PLATFORM_ROUTE_PREFIX}/${operation}`;
11
12
 
13
+ function isLoopbackOrigin(value) {
14
+ try {
15
+ const url = new URL(value);
16
+ return ['http:', 'https:'].includes(url.protocol) && url.origin === value && isLoopbackHost(url.hostname);
17
+ } catch { return false; }
18
+ }
19
+
20
+ function localBypass(env) {
21
+ if (env.FUNFAB_ACCESS_REQUIRED === '1' || env.FUNFAB_ACCESS_DISABLED_LOCAL !== '1' || env.NODE_ENV !== 'development' ||
22
+ env.FUNFAB_ENVIRONMENT || env.FUNFAB_GAME_DEPLOYMENT_HOST || env.VERCEL ||
23
+ env.VERCEL_URL || env.VERCEL_DEPLOYMENT_ID || env.VERCEL_PROJECT_PRODUCTION_URL ||
24
+ (env.VERCEL_ENV && env.VERCEL_ENV !== 'development') ||
25
+ (env.VERCEL_TARGET_ENV && env.VERCEL_TARGET_ENV !== 'development') ||
26
+ Object.keys(env).some(name => name.startsWith('RAILWAY_') && env[name])) return false;
27
+ return isLoopbackOrigin(env.FUNFAB_GAME_ORIGIN);
28
+ }
29
+
12
30
  // Shared server configuration. Runtime adapters add only their own routing/storage settings.
13
31
  export function signInTicketConfig(env = process.env) {
14
32
  if (!env.FUNFAB_GAME_ID) {
15
- if (env.FUNFAB_ACCESS_REQUIRED === '1') throw fail('invalid_gate_configuration');
33
+ if (!localBypass(env)) throw fail('invalid_gate_configuration');
34
+ console.warn('FUNFAB_ACCESS_DISABLED_LOCAL: FunFab admission disabled for local development');
16
35
  return null;
17
36
  }
18
37
  const c = { gameId: env.FUNFAB_GAME_ID, environment: env.FUNFAB_ENVIRONMENT, origin: env.FUNFAB_GAME_ORIGIN, issuer: env.FUNFAB_AUTH_ISSUER, clientId: env.FUNFAB_CLIENT_ID, accountOrigin: env.FUNFAB_ACCOUNT_ORIGIN, ticketApiOrigin: env.FUNFAB_SIGN_IN_TICKET_API_ORIGIN, credential: env.FUNFAB_SIGN_IN_TICKET_CREDENTIAL };
19
38
  try {
20
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(c.gameId || '') || !['preview','production'].includes(c.environment) || !uuid(c.clientId) || !/^fgc_[A-Za-z0-9_-]+$/.test(c.credential || '')) throw Error();
39
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(c.gameId || '') || !['preview','production'].includes(c.environment) || !isUuid(c.clientId) || !/^fgc_[A-Za-z0-9_-]+$/.test(c.credential || '')) throw Error();
21
40
  for (const key of ['origin','issuer','accountOrigin','ticketApiOrigin']) {
22
41
  const u = new URL(c[key]);
23
42
  if (u.protocol !== 'https:' || u.username || u.password || u.search || u.hash || (key !== 'issuer' && u.origin !== c[key])) throw Error();
@@ -42,7 +61,8 @@ export async function createSignInTicketClient(config, { transport = globalThis.
42
61
  async function call(operation, body) {
43
62
  let response, data;
44
63
  try {
45
- response = await transport(ticketOperationUrl(config, operation), { method:'POST', headers:{ authorization:`Bearer ${config.credential}`, 'content-type':'application/json' }, body:JSON.stringify({game:config.gameId,...body}), redirect:'error', signal:AbortSignal.timeout(8000) });
64
+ response = await postPlatformJson(transport, ticketOperationUrl(config, operation), config.credential,
65
+ JSON.stringify({game:config.gameId,...body}));
46
66
  } catch { throw fail('temporary_unavailable'); }
47
67
  if (response.status === 429 || response.status >= 500) throw fail('temporary_unavailable');
48
68
  try { data = await response.json(); } catch { throw fail('temporary_unavailable'); }
@@ -55,7 +75,10 @@ export async function createSignInTicketClient(config, { transport = globalThis.
55
75
  }
56
76
  const ticketCall = async (operation, ticket, extra = {}) => {
57
77
  // Wire names and the platform's existing opaque prefix are confined to this bridge.
58
- if (!isSignInTicket(ticket)) throw fail('authorization_required');
78
+ if (!isSignInTicket(ticket)) {
79
+ if (operation !== 'room' || typeof ticket !== 'string' || !/^stub-ticket\.[A-Za-z0-9_-]+$/.test(ticket) ||
80
+ !isLoopbackOrigin(config.ticketApiOrigin)) throw fail('authorization_required');
81
+ }
59
82
  return call(operation, {ticket,...extra});
60
83
  };
61
84
  const callback = () => {
@@ -78,7 +101,7 @@ export async function createSignInTicketClient(config, { transport = globalThis.
78
101
  const as = await discover();
79
102
  const params = oauth.validateAuthResponse(as, client, url, pending.state);
80
103
  const data = await call('exchange', {code:params.get('code'),verifier:pending.verifier,redirectUri});
81
- if (!isSignInTicket(data.ticket) || !uuid(data.accountId) || typeof data.displayState !== 'string') throw fail('temporary_unavailable');
104
+ if (!isSignInTicket(data.ticket) || !isUuid(data.accountId) || typeof data.displayState !== 'string') throw fail('temporary_unavailable');
82
105
  return {ticket:data.ticket,accountId:data.accountId,displayState:data.displayState};
83
106
  },
84
107
  status: ticket => ticketCall('status',ticket),
package/stub.mjs ADDED
@@ -0,0 +1,470 @@
1
+ import { createHash, createHmac, randomBytes, randomUUID } from 'node:crypto';
2
+ import { once } from 'node:events';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { createServer } from 'node:http';
5
+ import Ajv2020 from 'ajv/dist/2020.js';
6
+ import addFormats from 'ajv-formats';
7
+ import { isUuid } from './gate-core.mjs';
8
+
9
+ const packedSpec = new URL('./hub.openapi.json', import.meta.url);
10
+ const spec = JSON.parse(readFileSync(existsSync(packedSpec) ? packedSpec :
11
+ new URL('../../docs/hub.openapi.json', import.meta.url)));
12
+ const ajv = addFormats(new Ajv2020({ strict: false, allErrors: true }));
13
+ ajv.addSchema(spec, 'hub');
14
+ const { ShowId, HandoffId, CleanResult, Participant } = spec.components.schemas;
15
+ const cleanResultKeys = Object.keys(CleanResult.properties);
16
+ const participantKeys = Object.keys(Participant.properties);
17
+ const moments = ['leader', 'comeback', 'group', 'streamer-fooled'];
18
+ const version = { v: 1 };
19
+ const ok = { ...version, ok: true };
20
+ const minute = 60_000;
21
+ const roomPath = '/api/sign-in-ticket/room';
22
+ const digest = data => createHash('sha256').update(data).digest('base64url');
23
+ const token = () => randomBytes(24).toString('base64url');
24
+ const stamp = ms => new Date(ms).toISOString();
25
+ const pick = (data, keys) => Object.fromEntries(keys.filter(key => Object.hasOwn(data, key)).map(key => [key, data[key]]));
26
+ const subjectKey = ({ provider, user_id }) => JSON.stringify([provider, user_id]);
27
+ const subject = data => pick(data, ['provider', 'user_id']);
28
+ const source = data => pick(data, ['provider', 'channel_id', 'channel']);
29
+ const sameSource = (a, b) => a.provider === b.provider && a.channel_id === b.channel_id && a.channel === b.channel;
30
+ const sameSubject = (a, b) => subjectKey(a) === subjectKey(b);
31
+ function fail(status, error, extra) {
32
+ throw { status, body: { error, ...extra } };
33
+ }
34
+ const invalid = () => fail(400, 'accounts_request_invalid');
35
+ const unauthorized = () => fail(401, 'authorization_required');
36
+ const forbidden = () => fail(403, 'host_not_allowed');
37
+ const conflict = error => fail(409, error);
38
+ const active = show => show.view.state === 'active' && Date.parse(show.view.expires_at) > Date.now();
39
+ function readView(view, ifEtag) {
40
+ const etag = digest(JSON.stringify(view));
41
+ return ifEtag === etag ? { ...version, not_modified: true, etag } : { ...view, etag };
42
+ }
43
+
44
+ const expired = item => !item.view.closed && Date.parse(item.view.result_deadline) <= Date.now();
45
+ const closed = item => item.view.closed || expired(item);
46
+ function cleanResult(result, excluded) {
47
+ const participants = result.participants.filter(row => !excluded(row));
48
+ const moment = result.moment;
49
+ const cleaned = { ...result, participants };
50
+ if (!moment || !moments.includes(moment.kind) ||
51
+ !participants.some(row => !row.hidden && sameSubject(row, moment.subject))) delete cleaned.moment;
52
+ return cleaned;
53
+ }
54
+
55
+ function handoffView(item, ifEtag) {
56
+ const { view } = item;
57
+ return readView({ ...view, ...(expired(item) && {
58
+ state: view.state === 'returned' ? 'returned' : 'expired', on_air: false,
59
+ }) }, ifEtag);
60
+ }
61
+
62
+ function validBoard(board, roomId, title, screen) {
63
+ if (!URL.canParse(board)) return false;
64
+ const url = new URL(board);
65
+ if (url.protocol !== 'https:' || url.origin !== title.origin || url.pathname !== title.board ||
66
+ board.includes('#') || url.username || url.password) return false;
67
+ const params = [...url.searchParams];
68
+ const declared = title.board_params ?? {};
69
+ return url.searchParams.get(title.board_room_param) === roomId && url.searchParams.get('screen') === screen &&
70
+ new Set(url.searchParams.keys()).size === params.length &&
71
+ params.every(([name, value]) => Object.hasOwn(declared, name) && new RegExp(declared[name]).test(value));
72
+ }
73
+ async function readJSON(req) {
74
+ if (!/^application\/json(?:\s*;|$)/i.test(req.headers['content-type'] ?? '') ||
75
+ req.headers['content-encoding']) return invalid();
76
+ const chunks = [];
77
+ let size = 0;
78
+ for await (const chunk of req.iterator({ destroyOnReturn: false })) {
79
+ size += chunk.length;
80
+ if (size > 256 * 1024) { req.resume(); return invalid(); }
81
+ chunks.push(chunk);
82
+ }
83
+ const bytes = Buffer.concat(chunks);
84
+ try { return { body: JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)), bytes }; }
85
+ catch { return invalid(); }
86
+ }
87
+
88
+ export async function startPlatformStub({ port = 0, games, memberships, hosts }) {
89
+ const environment = 'preview';
90
+ const secret = randomBytes(32);
91
+ // Derive replayable booking replies without storing raw show references or launch codes.
92
+ const opaque = id => createHmac('sha256', secret).update(id).digest('base64url');
93
+ const shows = new Map(), handoffs = new Map(), bookedShows = new Map(), rooms = new Map();
94
+ const identities = new Map(), launchCodes = new Map(), claimedRooms = new Map();
95
+ const tickets = Object.fromEntries(Object.entries(hosts).map(([account, clients]) => [account,
96
+ Object.fromEntries(Object.entries(clients).map(([game, fixture]) => {
97
+ const ticket = `stub-ticket.${token()}`;
98
+ identities.set(digest(ticket), { account, game, fixture, playerId: randomUUID() });
99
+ return [game, ticket];
100
+ })),
101
+ ]));
102
+ const gameInEnvironment = id => Object.hasOwn(games, id) &&
103
+ (games[id].environment ?? environment) === environment ? games[id] : undefined;
104
+ const titleFor = pair => gameInEnvironment(pair.game)?.titles?.find(title => title.title === pair.title);
105
+ const approved = pair => pair.state === 'approved';
106
+ const memberList = hub => memberships.filter(pair => pair.hub === hub && approved(pair) &&
107
+ !gameInEnvironment(pair.game)?.switchedOff).map(titleFor).filter(Boolean);
108
+ function authorize({ game, ticket, show_ref }, show, allowRef) {
109
+ if (show && show.game !== game) unauthorized();
110
+ if (allowRef && show_ref !== undefined) {
111
+ if (!show || digest(show_ref) !== show.refHash) unauthorized();
112
+ return;
113
+ }
114
+ const person = typeof ticket === 'string' && identities.get(digest(ticket));
115
+ if (!person || person.game !== game) unauthorized();
116
+ return person;
117
+ }
118
+
119
+ function hostAllowed(person, show) {
120
+ if (!person.fixture.host || person.fixture.admitted === false || (show && show.host !== person.account)) forbidden();
121
+ }
122
+
123
+ const hasHostAccess = (account, game) => {
124
+ const access = hosts[account]?.[game];
125
+ return access?.host && access.admitted !== false;
126
+ };
127
+ const membershipFor = (hub, title, game) => memberships.find(pair => pair.hub === hub &&
128
+ pair.title === title && (game === undefined || game === pair.game) && approved(pair) && titleFor(pair));
129
+ const switchedOff = (hub, member) => games[hub].switchedOff || games[member].switchedOff;
130
+
131
+ function memberFor(hub, title, person) {
132
+ const pair = membershipFor(hub, title);
133
+ if (!pair) fail(403, 'not_member');
134
+ if (switchedOff(hub, pair.game)) fail(403, 'switched_off');
135
+ if (!hasHostAccess(person.account, pair.game)) forbidden();
136
+ return { pair, title: titleFor(pair) };
137
+ }
138
+
139
+ const membershipError = ({ show, view, game }) => !membershipFor(show.game, view.title, game) ? 'not_member' :
140
+ switchedOff(show.game, game) ? 'switched_off' : null;
141
+ const resultExcluded = (show, row) =>
142
+ [show.removed, games[show.game].suppressed ?? []].some(list => list.some(entry => sameSubject(entry, row)));
143
+
144
+ function requireOpenMember(item) {
145
+ if (closed(item)) conflict('handoff_closed');
146
+ if (!active(item.show)) conflict('show_not_active');
147
+ const error = membershipError(item);
148
+ if (error) fail(403, error);
149
+ }
150
+
151
+ function memberContext(item, person) {
152
+ const { view, show, game } = item;
153
+ if (game !== person.game) fail(403, 'wrong_game');
154
+ if (show.host !== person.account) fail(403, 'wrong_host');
155
+ if (!hasHostAccess(show.host, game) || !hasHostAccess(show.host, show.game)) forbidden();
156
+ requireOpenMember(item);
157
+ return { ...pick(view, ['v', 'handoff', 'show', 'title', 'result_deadline']), game,
158
+ hub: { id: show.game, origin: show.view.origin }, ...pick(show.view, ['sources', 'lang', 'screen']),
159
+ ...(item.cam !== undefined && { cam: item.cam }), minutes: item.minutes, max_ms: item.maxMs,
160
+ show_started_at: show.view.started_at, started_at: stamp(item.startedAt), room_request_id: item.roomRequestId,
161
+ return: { url: new URL('/desk', show.view.origin).href } };
162
+ }
163
+
164
+ function requireClaimedRoom(item, body) {
165
+ if (!item.claim || item.claim.room !== body.room) conflict('not_claimer');
166
+ }
167
+
168
+ function launch(item, title, show, code, issuedAt) {
169
+ const url = new URL(title.panel, title.origin);
170
+ url.searchParams.set('embed', 'launcher');
171
+ url.searchParams.set('launcher', show.view.origin);
172
+ url.hash = new URLSearchParams({ handoff: item.view.handoff, code }).toString();
173
+ return { ...version, handoff: item.view.handoff, launch_url: url.href,
174
+ code_expires_at: stamp(issuedAt + 5 * minute), max_ms: item.maxMs };
175
+ }
176
+
177
+ const operations = {
178
+ hubBookShow({ body, game, person }) {
179
+ hostAllowed(person);
180
+ if (game.switchedOff) fail(403, 'switched_off');
181
+ const { origin, sources, lang, screen, idempotency_key } = body;
182
+ if (!game.origins?.includes(origin)) fail(400, 'bad_origin');
183
+ if (sources.some(entry => game.sources && !game.sources.some(known => sameSource(known, entry)))) {
184
+ fail(400, 'bad_sources');
185
+ }
186
+ const key = JSON.stringify([body.game, person.account, idempotency_key]);
187
+ let show = bookedShows.get(key);
188
+ if (!show) {
189
+ const id = `sh_${token()}`, room = randomUUID(), now = Date.now();
190
+ const verified = sources.every(entry => person.fixture.subjects?.some(bound =>
191
+ bound.provider === entry.provider && bound.user_id === entry.channel_id));
192
+ const state = verified ? 'active' : 'pending';
193
+ const view = { ...version, show: id, origin, sources: sources.map(source), lang, screen, state,
194
+ started_at: stamp(now), expires_at: stamp(now + 24 * 60 * minute), blocks_revision: 0 };
195
+ show = { game: body.game, host: person.account, view, initialState: state, room,
196
+ refHash: digest(`sr_${opaque(id)}`), receipts: new Map(), bookings: new Map(), removed: [], hidden: [] };
197
+ bookedShows.set(key, show);
198
+ shows.set(id, show);
199
+ rooms.set(room, show);
200
+ }
201
+ return { ...pick(show.view, ['v', 'show', 'started_at', 'expires_at']), state: show.initialState,
202
+ show_ref: `sr_${opaque(show.view.show)}`, room_request_id: show.room };
203
+ },
204
+ hubEndShow({ show, body }) {
205
+ if (show.view.state !== 'ended') {
206
+ show.view.state = 'ended';
207
+ show.view.ended_at = body.ended_at ?? stamp(Date.now());
208
+ }
209
+ return ok;
210
+ },
211
+ hubReadShow({ show, body }) {
212
+ const view = show.view;
213
+ const state = view.state !== 'ended' && Date.parse(view.expires_at) <= Date.now() ? 'ended' : view.state;
214
+ return readView({ ...view, state, handoffs: [...show.bookings.values()].map(item => handoffView(item)),
215
+ receipts: [...show.receipts.values()].filter(row => !resultExcluded(show, row.subject)),
216
+ }, body.if_etag);
217
+ },
218
+ hubBookHandoff({ body, show, person }) {
219
+ if (!active(show)) conflict('show_not_active');
220
+ const { pair, title } = memberFor(show.game, body.title, person);
221
+ const { sources, lang, screen } = show.view;
222
+ if (sources.length > title.sources || sources.some(entry => !title.providers.includes(entry.provider))) {
223
+ fail(400, 'bad_sources');
224
+ }
225
+ if (!title.langs.includes(lang)) fail(400, 'bad_lang');
226
+ if (!title.screens.includes(screen)) fail(400, 'bad_screen');
227
+ const existing = show.bookings.get(body.idempotency_key);
228
+ if (existing) return launch(existing, existing.title, show, opaque(existing.view.handoff), existing.startedAt);
229
+ if (show.slot && !closed(show.slot)) conflict('handoff_open');
230
+ const id = `ho_${token()}`, startedAt = Date.now(), maxMs = (title.minutes[1] + 120) * minute, code = opaque(id);
231
+ const item = { show, title, game: pair.game, startedAt, maxMs, minutes: body.minutes ?? title.minutes[0],
232
+ cam: body.cam, seq: 0, takeBack: null, codeHash: digest(code), codeIssuedAt: startedAt, roomRequestId: randomUUID(),
233
+ view: { ...version, handoff: id, show: show.view.show, title: title.title, state: 'booked',
234
+ closed: null, on_air: false, first_on_air_at: null, result_deadline: stamp(startedAt + maxMs) } };
235
+ const reply = launch(item, title, show, code, startedAt);
236
+ handoffs.set(id, item);
237
+ rooms.set(item.roomRequestId, item);
238
+ launchCodes.set(item.codeHash, item);
239
+ show.bookings.set(body.idempotency_key, item);
240
+ show.slot = item;
241
+ return reply;
242
+ },
243
+ hubNewLaunchCode({ item, show, person }) {
244
+ if (!active(show)) conflict('show_not_active');
245
+ const { title } = memberFor(show.game, item.view.title, person);
246
+ if (closed(item)) conflict('handoff_closed');
247
+ const code = token(), now = Date.now();
248
+ const reply = launch(item, title, show, code, now);
249
+ item.codeHash = digest(code);
250
+ launchCodes.set(item.codeHash, item);
251
+ item.codeIssuedAt = now;
252
+ return reply;
253
+ },
254
+ hubSetHandoffState({ body, item }) {
255
+ const { seq, on_air, take_back, close } = body, view = item.view;
256
+ if (seq <= item.seq) return ok;
257
+ if (closed(item)) conflict('handoff_closed');
258
+ if (seq !== item.seq + 1) fail(409, 'seq_gap', { retry: true, expected_seq: item.seq + 1 });
259
+ if (close && (close === 'played') !== Boolean(view.first_on_air_at)) conflict('handoff_closed');
260
+ item.seq = seq;
261
+ if (on_air && !close) view.first_on_air_at ??= stamp(Date.now());
262
+ if (on_air !== undefined) view.on_air = on_air;
263
+ if (take_back !== undefined) item.takeBack = take_back;
264
+ if (close) { view.closed = close; view.on_air = false; }
265
+ if (close === 'unplayed') view.state = 'closed-unplayed';
266
+ return ok;
267
+ },
268
+ hubReadHandoff: ({ body, item }) => handoffView(item, body.if_etag),
269
+ hubSetBlocks({ body, show }) {
270
+ if (body.expected_revision !== show.view.blocks_revision) conflict('stale_revision');
271
+ if (show.removed.some(entry => !body.removed.some(next => sameSubject(entry, next)))) conflict('cannot_unremove');
272
+ show.hidden = body.hidden.map(subject);
273
+ show.removed = body.removed.map(subject);
274
+ for (const { view } of show.bookings.values()) {
275
+ if (view.result) view.result = cleanResult(view.result, row => resultExcluded(show, row));
276
+ }
277
+ return { ...version, blocks_revision: ++show.view.blocks_revision };
278
+ },
279
+ hubAddReceipts({ body, show, game }) {
280
+ if (!active(show)) conflict('show_not_active');
281
+ for (const row of body.receipts) {
282
+ if (show.receipts.has(row.idempotency_key)) continue;
283
+ if (row.subject.provider !== row.source.provider || !show.view.sources.some(entry => sameSource(entry, row.source))) {
284
+ fail(400, 'bad_sources');
285
+ }
286
+ if (show.removed.some(entry => sameSubject(entry, row.subject))) conflict('subject_removed');
287
+ if (game.suppressed?.some(entry => sameSubject(entry, row.subject))) conflict('subject_suppressed');
288
+ }
289
+ for (const row of body.receipts) {
290
+ if (!show.receipts.has(row.idempotency_key)) show.receipts.set(row.idempotency_key, {
291
+ show: show.view.show, game: show.game, handoff: null, subject: subject(row.subject), source: source(row.source),
292
+ ...pick(row, ['kind', 'place']),
293
+ });
294
+ }
295
+ return ok;
296
+ },
297
+ hubReportLinkEvent({ body, show }) {
298
+ const { source: where, event } = body;
299
+ if (where.provider !== 'tiktok' || !show.view.sources.some(entry => sameSource(entry, where))) fail(400, 'bad_sources');
300
+ if (Date.parse(event.sent_at) < Date.now() - minute) fail(400, 'bad_event');
301
+ const pendingHost = show.view.state === 'pending' && Date.parse(show.view.expires_at) > Date.now() &&
302
+ event.user_id === where.channel_id;
303
+ if (!active(show) && !pendingHost) conflict('show_not_active');
304
+ conflict('linking_off');
305
+ },
306
+ hubPlayerSubjects: ({ person }) => ({ ...version, subjects: (person.fixture.subjects ?? []).map(subject) }),
307
+ hubPlayerCredit: ({ person }) => ({ ...version, xp: 0, receipts: [], ...pick(person.fixture.credit ?? {}, ['xp', 'receipts']) }),
308
+ hubMembers: ({ body }) => ({ ...version, members: memberList(body.game) }),
309
+ handoffRedeem({ body, person }) {
310
+ const hash = digest(body.code), item = launchCodes.get(hash);
311
+ if (!item) fail(400, 'bad_code');
312
+ const context = memberContext(item, person);
313
+ if (hash !== item.codeHash) fail(410, 'superseded');
314
+ if (item.codeIssuedAt + 5 * minute <= Date.now()) fail(410, 'expired');
315
+ item.redeemed = true;
316
+ return context;
317
+ },
318
+ handoffContext: ({ item, person }) => memberContext(item, person),
319
+ handoffClaim({ body, game, item }) {
320
+ requireOpenMember(item);
321
+ if (game.hostedRooms && !item.hostedRoomClaimed) unauthorized();
322
+ const { room, room_id, board } = body;
323
+ const key = JSON.stringify([item.game, room_id]);
324
+ if (claimedRooms.has(key) && claimedRooms.get(key) !== item) conflict('room_booked');
325
+ if (item.claim) {
326
+ if (item.view.room_id !== room_id || item.claim.room !== room) conflict('claimed');
327
+ if (item.claim.board !== board) conflict('board_differs');
328
+ return item.claim;
329
+ }
330
+ if (!validBoard(board, room_id, item.title, item.show.view.screen)) fail(400, 'bad_board');
331
+ item.claim = { ...ok, handoff: item.view.handoff, room, board };
332
+ Object.assign(item.view, { state: 'claimed', room, room_id, board });
333
+ claimedRooms.set(key, item);
334
+ return item.claim;
335
+ },
336
+ handoffSync({ body, game, show, item }) {
337
+ requireClaimedRoom(item, body);
338
+ if (game.blocksIncomplete) fail(409, 'blocks_incomplete', { retry: true });
339
+ Object.assign(item.view, pick(body, ['phase', 'last_host_action']));
340
+ const closing = !active(show) || closed(item) || Boolean(membershipError(item));
341
+ return { ...version, blocks_revision: show.view.blocks_revision, hidden: show.hidden, removed: show.removed,
342
+ take_back: closing ? 'now' : item.takeBack, on_air: !closing && item.view.on_air };
343
+ },
344
+ handoffResult({ body, bytes, show, item }) {
345
+ requireClaimedRoom(item, body);
346
+ if (body.handoff !== item.view.handoff) fail(400, 'bad_result');
347
+ const hash = digest(bytes);
348
+ const reply = { ...ok, handoff: item.view.handoff };
349
+ if (item.resultHash) {
350
+ if (item.resultHash !== hash) conflict('result_differs');
351
+ return { ...reply, repeat: true };
352
+ }
353
+ if (item.view.closed === 'unplayed') conflict('closed_unplayed');
354
+ if (Date.parse(item.view.result_deadline) <= Date.now()) fail(410, 'deadline_passed');
355
+ if (!item.view.first_on_air_at) fail(409, 'not_on_air', { retry: true });
356
+ const sources = new Map(show.view.sources.map(entry => [entry.provider, entry]));
357
+ if (body.participants.some(row => !sources.has(row.provider)) ||
358
+ new Set(body.participants.map(subjectKey)).size !== body.participants.length ||
359
+ body.participants.some((row, i, rows) => i > 0 && (rows[i - 1].place ?? Infinity) > (row.place ?? Infinity))) {
360
+ fail(400, 'bad_result');
361
+ }
362
+ const result = cleanResult({ ...pick(body, cleanResultKeys), rounds: pick(body.rounds, ['planned', 'played']),
363
+ participants: body.participants.map(row => pick(row, participantKeys)),
364
+ ...(body.moment && { moment: { kind: body.moment.kind, subject: subject(body.moment.subject) } }),
365
+ }, row => resultExcluded(show, row));
366
+ for (const row of result.participants) {
367
+ show.receipts.set(JSON.stringify([item.view.handoff, subjectKey(row)]), {
368
+ show: show.view.show, handoff: item.view.handoff, game: item.game, subject: subject(row),
369
+ source: sources.get(row.provider), kind: row.place == null ? 'attended' : 'placed', ...pick(row, ['place']),
370
+ });
371
+ }
372
+ Object.assign(item.view, { state: 'returned', result });
373
+ item.resultHash = hash;
374
+ return reply;
375
+ },
376
+ hubOrigins: ({ body, game }) => ({ ...version, titles: (game.titles ?? []).map(({ title }) => ({
377
+ title, origins: [...new Set(memberships.filter(pair => pair.game === body.game && pair.title === title &&
378
+ approved(pair) && !gameInEnvironment(pair.hub)?.switchedOff).flatMap(pair => gameInEnvironment(pair.hub)?.origins ?? []))],
379
+ })) }),
380
+ };
381
+ const routes = Object.entries(spec.paths).flatMap(([path, { post }]) => {
382
+ const run = operations[post.operationId];
383
+ if (!run) return [];
384
+ const base = `hub#/paths/${path.replaceAll('/', '~1')}/post/requestBody/content/application~1json/schema`;
385
+ const validate = ajv.getSchema(base);
386
+ const auth = post.requestBody.content['application/json'].schema.properties ?? {};
387
+ const member = post.operationId.startsWith('handoff');
388
+ const fields = post.operationId === 'handoffClaim' ? { board: 'bad_board' } :
389
+ post.operationId === 'hubBookShow' ? { origin: 'bad_origin', sources: 'bad_sources', lang: 'bad_lang', screen: 'bad_screen' } :
390
+ post.operationId === 'hubReportLinkEvent' ? { source: 'bad_sources', event: 'bad_event' } : {};
391
+ const pattern = path.replace('{show}', `(?<show>${ShowId.pattern.slice(1, -1)})`)
392
+ .replace('{handoff}', `(?<handoff>${HandoffId.pattern.slice(1, -1)})`);
393
+ return [{ run, validate, auth, fields, match: new RegExp(`^${pattern}$`),
394
+ member, permission: member || post.operationId === 'hubOrigins' ? 'hub-launch' : 'hub' }];
395
+ });
396
+
397
+ function claimRoom(body, game) {
398
+ if (Object.keys(body).length !== 3 || !isUuid(body.roomRequestId) || typeof body.ticket !== 'string') invalid();
399
+ const binding = rooms.get(body.roomRequestId), item = binding?.show && binding;
400
+ const show = item?.show ?? binding, person = authorize(body, binding, false);
401
+ if (!game.hostedRooms || (show && person.account !== show.host) || (item && !item.redeemed)) unauthorized();
402
+ if (!hasHostAccess(person.account, body.game) || (show && !active(show)) || game.switchedOff ||
403
+ (item && (closed(item) || membershipError(item) || !hasHostAccess(person.account, show.game)))) {
404
+ fail(403, 'game_access_denied');
405
+ }
406
+ person.roomClaims ??= new Set();
407
+ const now = Date.now(), replayed = person.roomClaims.has(body.roomRequestId);
408
+ const quotaResetsAt = stamp(Date.parse(stamp(now).slice(0, 10)) + 24 * 60 * minute);
409
+ person.roomClaims.add(body.roomRequestId);
410
+ if (item) item.hostedRoomClaimed = true;
411
+ return {
412
+ status: { account_id: person.playerId, eligibility: 'eligible', cutoff_at: null, lease_expires_at: stamp(now + 5 * minute) },
413
+ gamePolicy: { game_id: body.game, environment, per_play_cost: true, daily_room_unlimited: true,
414
+ quota_day: stamp(now).slice(0, 10), quota_resets_at: quotaResetsAt },
415
+ roomClaim: { allowed: true, replayed, quota_resets_at: quotaResetsAt, request_id: body.roomRequestId },
416
+ displayState: 'eligible',
417
+ };
418
+ }
419
+ async function dispatch(req) {
420
+ const { url, headers, method } = req;
421
+ if (url.includes('?') || headers.origin !== undefined) invalid();
422
+ const route = routes.find(candidate => candidate.match.test(url));
423
+ if (!route && url !== roomPath) fail(404, 'not_found');
424
+ if (method !== 'POST') fail(405, 'method_not_allowed');
425
+ const { body, bytes } = await readJSON(req);
426
+ if (!body || typeof body !== 'object' || Array.isArray(body) || typeof body.game !== 'string') invalid();
427
+ const game = gameInEnvironment(body.game);
428
+ if (!game?.credential || headers.authorization !== `Bearer ${game.credential}` ||
429
+ !game.permissions?.includes(route?.permission ?? 'sign-in-ticket')) unauthorized();
430
+ if (game.unavailable) fail(503, 'account_unavailable');
431
+ if (!route) return claimRoom(body, game);
432
+
433
+ const { auth, validate, fields, run, member } = route;
434
+ const ids = route.match.exec(url).groups ?? {};
435
+ const item = handoffs.get(ids.handoff), show = item?.show ?? shows.get(ids.show);
436
+ const { ticket, show_ref } = body;
437
+ if ((auth.ticket || auth.show_ref) && ticket === undefined && !(auth.show_ref && show_ref !== undefined)) unauthorized();
438
+ if ((ticket !== undefined && !auth.ticket) || (show_ref !== undefined && (!auth.show_ref ||
439
+ typeof show_ref !== 'string' || ticket !== undefined))) invalid();
440
+ if ((ids.show || ids.handoff) && !show) unauthorized();
441
+ const person = (auth.ticket || auth.show_ref) ? authorize(body, member ? null : show, Boolean(auth.show_ref)) : undefined;
442
+ if (member && !person && (item?.game !== body.game || !item.redeemed)) unauthorized();
443
+ if (!member && person && show) hostAllowed(person, show);
444
+ if (!member && person?.fixture.admitted === false && !show && run !== operations.hubBookShow) unauthorized();
445
+ if (!validate(body)) {
446
+ const fieldErrors = validate.errors.map(error => error.instancePath.split('/')[1] || error.params.missingProperty);
447
+ if (fieldErrors.every(field => Object.hasOwn(fields, field))) {
448
+ const field = Object.keys(fields).find(key => fieldErrors.includes(key));
449
+ fail(400, fields[field]);
450
+ }
451
+ invalid();
452
+ }
453
+ return run({ body, bytes, game, person, show, item });
454
+ }
455
+
456
+ const server = createServer(async (req, res) => {
457
+ let status = 200, body;
458
+ try { body = await dispatch(req); }
459
+ catch (error) { ({ status, body } = error?.body ? error : { status: 503, body: { error: 'account_unavailable' } }); }
460
+ res.writeHead(status, { 'Cache-Control': 'private, no-store', 'Content-Type': 'application/json' });
461
+ res.end(JSON.stringify(body));
462
+ });
463
+ server.listen(port, '127.0.0.1');
464
+ await once(server, 'listening');
465
+ for (const [account, clients] of Object.entries(tickets)) {
466
+ for (const [game, ticket] of Object.entries(clients)) console.log('Stub ticket', account, game, ticket);
467
+ }
468
+ return { baseUrl: `http://127.0.0.1:${server.address().port}`, tickets,
469
+ close: () => new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())) };
470
+ }