@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/README.md CHANGED
@@ -3,18 +3,19 @@ Add FunFab sign-in and host safety to your game.
3
3
 
4
4
  ## Install
5
5
  ```sh
6
- npm install --save-exact @funfab/sdk@0.1.0
6
+ npm install --save-exact @funfab/sdk@0.2.0
7
7
  ```
8
8
  Needs Node.js 22 or newer on your server.
9
9
 
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` |
18
+ | Optional host-panel access notices | `@funfab/sdk/host-panel` |
18
19
  | Name filtering, viewer blocks | `@funfab/sdk/host-safety` |
19
20
  | Host-safety result format | `@funfab/sdk/schemas/host-safety` |
20
21
 
@@ -26,10 +27,121 @@ tickets. It never holds a player's FunFab account tokens.
26
27
  ## Quick start (Vercel)
27
28
  ```js
28
29
  import { configuration, createGate } from "@funfab/sdk/adapters/vercel";
29
- const gate = createGate(configuration(process.env));
30
- const { allow, response } = await gate.handle(request);
30
+ const gate = createGate(configuration(process.env, {
31
+ returnPath: "/play",
32
+ returnQuery: { level: "text", invite: "uuid" },
33
+ }));
34
+ async function middleware(request, forward) {
35
+ const { allow, response } = await gate.handle(request);
36
+ return allow ? forward(request, response.headers) : response;
37
+ }
31
38
  ```
32
39
 
40
+ Supply your app's `forward` function to continue the request and carry the gate's response headers to the browser.
41
+
42
+ Set `returnPath` to your game's fallback path. Set `returnQuery` to the game parameters a return
43
+ URL may keep, or supply `{}` to discard every parameter. A `text` value keeps up to 256 characters.
44
+ A `uuid` value must occur once and contain a valid UUID. Authentication parameters are reserved.
45
+
46
+ ### Stream configuration
47
+
48
+ ```js
49
+ import { streamConfig, createStreamGate, ongoingBoardState } from "@funfab/sdk/adapters/stream";
50
+ const config = streamConfig(process.env, {
51
+ hostPath: "/show/host.html",
52
+ roomPrefix: "show-",
53
+ getConnectionRole: connection => connection.viewerRole,
54
+ });
55
+ if (config) {
56
+ const gate = await createStreamGate({ config, onClose, onState });
57
+ const isHeartbeat = (from, message, connections) =>
58
+ ongoingBoardState(config, from, message, connections);
59
+ // Connect gate.route, gate.host and the room hooks to your server.
60
+ }
61
+ ```
62
+
63
+ Use a same-origin path without a query or fragment for `hostPath` and a nonempty room prefix
64
+ containing only letters, digits, underscores or hyphens. The same config feeds `streamHostRoute`
65
+ for the native deployment host and `ongoingBoardState` for heartbeat checks.
66
+ `getConnectionRole` reads the role from your game's connection and returns `"board"` for a board
67
+ connection. If the game has no board connections, use a reader that returns `undefined`.
68
+
69
+ ### Browser access notices
70
+
71
+ Import `mountAccess` and `accessCopy` from `@funfab/sdk/host-panel` to keep the opt-in notices,
72
+ theme, and overlay. For your own UI, `createAccessState()` from `@funfab/sdk/browser` exposes
73
+ `blocked`, `closed`, and `update(state)`. The update returns whether the public access state was
74
+ accepted. These states drive presentation. The server gate owns admission.
75
+
76
+ ### Local development
77
+
78
+ Missing `FUNFAB_GAME_ID` is a configuration error. For local Vercel or Stream development, explicitly set
79
+ `FUNFAB_ACCESS_DISABLED_LOCAL=1`, `NODE_ENV=development` and `FUNFAB_GAME_ORIGIN` to a loopback origin such
80
+ as `http://localhost:3000`. The SDK logs the opt-out. FunFab or hosting deployment markers and
81
+ `FUNFAB_ACCESS_REQUIRED=1` take precedence. Vercel limits the opt-out to requests at that origin.
82
+ Stream's `streamConfig` returns `null` for a local opt-out. Party always requires game configuration.
83
+
84
+ ### Stream login rate limit
85
+
86
+ The SDK has no built-in Railway peer verification. Supply a synchronous
87
+ `isVerifiedIngress(remoteAddress)` to `createStreamGate` if your server can verify its immediate
88
+ transport peer as Railway ingress. Behind a verified peer, a single valid `X-Real-IP` gets 20 login
89
+ starts per minute per IP. Otherwise, login starts share one flood limit of 200 per minute per gate instance.
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
+
33
145
  ## Versions
34
146
  Trial (0.x): pin an exact version. The previous version
35
147
  keeps working for 90 days after a new one. `funfab game
@@ -1,8 +1,20 @@
1
1
  import {createSignInTicketClient,signInTicketConfig} from '../server.mjs';
2
+ import {admissionStatus,refusalCode} from '../gate-core.mjs';
2
3
 
3
4
  export function origin(){const url=new URL(process.env.FUNFAB_BROWSER_ORIGIN||'http://127.0.0.1:5390');if(url.pathname!=='/'||url.search||url.hash||url.username||url.password||(url.protocol!=='https:'&&(process.env.NODE_ENV==='production'||!['localhost','127.0.0.1'].includes(url.hostname))))throw Error('BROWSER_UNAVAILABLE');return url.origin;}
4
- function uuid(value){return 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);}
5
5
  export async function ticketClient(callback=false){try{const config=signInTicketConfig(process.env);if(!config||(process.env.VERCEL_ENV&&process.env.VERCEL_ENV!==config.environment)||(callback&&config.origin!==origin()))throw Error();return await createSignInTicketClient({...config,callback:config.origin+'/api/browser-auth'});}catch{throw Error('BROWSER_UNAVAILABLE');}}
6
- export function ticketError(error){const code=error?.code;return Error(code==='temporary_unavailable'?'ACCOUNT_UNAVAILABLE':code==='authorization_required'?'SIGN_IN_EXPIRED':code==='game_access_denied'?'ACCOUNT_RESTRICTED':'OAUTH_FAILED');}
6
+ export function ticketError(error){
7
+ const code=refusalCode(error);
8
+ return Error(code==='temporary_unavailable'?'ACCOUNT_UNAVAILABLE':code==='authorization_required'?'SIGN_IN_EXPIRED':code==='game_access_denied'?'ACCOUNT_RESTRICTED':'OAUTH_FAILED');
9
+ }
7
10
  export async function signoutTicket(ticket){try{await (await ticketClient()).signout(ticket);}catch{/* Local logout must still revoke authority during a provider outage. */}}
8
- export async function centralAdmission(ticket){let body;try{body=await (await ticketClient()).status(ticket);}catch(error){if(error instanceof Error&&error.message==='BROWSER_UNAVAILABLE')throw error;throw ticketError(error);}const value=body?.status,lease=typeof value?.lease_expires_at==='string'?Date.parse(value.lease_expires_at):NaN,cutoff=value?.cutoff_at;if(!value||typeof value.eligibility!=='string'||!uuid(value.account_id)||!Number.isFinite(lease)||(cutoff!==null&&(typeof cutoff!=='string'||!Number.isFinite(Date.parse(cutoff)))))throw Error('ACCOUNT_UNAVAILABLE');if(value.eligibility!=='eligible'||cutoff!==null)throw Error('ACCOUNT_RESTRICTED');if(lease<=Date.now())throw Error('SIGN_IN_EXPIRED');return {accountId:value.account_id};}
11
+ export async function centralAdmission(ticket){
12
+ const client=await ticketClient();
13
+ let body;
14
+ try{body=await client.status(ticket);}catch(error){throw ticketError(error);}
15
+ const admission=admissionStatus(body,Date.now());
16
+ if(!admission.refusal)return {accountId:admission.accountId};
17
+ if(admission.refusal==='denied')throw Error('ACCOUNT_RESTRICTED');
18
+ if(admission.refusal==='expired')throw Error('SIGN_IN_EXPIRED');
19
+ throw Error('ACCOUNT_UNAVAILABLE');
20
+ }
@@ -1,12 +1,34 @@
1
1
  import { randomBytes } from 'node:crypto';
2
+ import { isIP } from 'node:net';
2
3
  import { createSignInTicketClient, signInTicketConfig } from '../server.mjs';
4
+ import { admissionStatus, gateError as fail, isUuid, refusalCode, requireGamePath, settingError } from '../gate-core.mjs';
3
5
 
4
- 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);
5
- const fail = code => Object.assign(Error(code), { code });
6
- export function streamConfig(env = process.env) {
6
+ const SESSION = '__Host-funfab-stream', LOGIN = '__Host-funfab-stream-login';
7
+ const UNVERIFIED_LOGIN = Symbol('unverified login');
8
+ const cookie = (name, id, age) => `${name}=${id}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=${age}`;
9
+ function cookieId(req, name) {
10
+ const values = (req.headers.cookie || '').split(';').map(value => value.trim())
11
+ .filter(value => value.startsWith(name + '='));
12
+ const id = values.length === 1 ? values[0].slice(name.length + 1) : null;
13
+ return /^[a-f0-9]{64}$/.test(id) ? id : null;
14
+ }
15
+ function connectionRoleReader(game) {
16
+ if (typeof game?.getConnectionRole !== 'function') throw settingError('getConnectionRole');
17
+ return game.getConnectionRole;
18
+ }
19
+
20
+ function streamGameSettings(game) {
21
+ const hostPath = requireGamePath(game?.hostPath, 'hostPath');
22
+ const roomPrefix = game?.roomPrefix;
23
+ if (typeof roomPrefix !== 'string' || !/^[a-z0-9_-]+$/i.test(roomPrefix)) throw settingError('roomPrefix');
24
+ return { hostPath, roomPrefix, getConnectionRole: connectionRoleReader(game) };
25
+ }
26
+
27
+ export function streamConfig(env = process.env, game) {
7
28
  const common = signInTicketConfig(env);
8
- if (!common) return null; // Existing unenrolled games remain unchanged.
9
- const c = {...common};
29
+ const settings = streamGameSettings(game);
30
+ if (!common) return null; // Explicit local development opt-out.
31
+ const c = {...common, ...settings};
10
32
  c.deploymentHost = env.FUNFAB_GAME_DEPLOYMENT_HOST || null;
11
33
  if (c.deploymentHost && !/^[a-z0-9]+(?:-[a-z0-9]+)*\.up\.railway\.app$/.test(c.deploymentHost)) throw fail('invalid_gate_configuration');
12
34
  c.callback = c.origin + '/auth/funfab/callback';
@@ -18,36 +40,49 @@ const redirect = (res, location, headers = {}) => res.writeHead(303, { location,
18
40
  function inviteQuery(value) {
19
41
  const params = new URL(value, 'https://invite.invalid').searchParams, clean = new URLSearchParams();
20
42
  const sessions = params.getAll('session'), langs = params.getAll('lang');
21
- if (sessions.length === 1 && uuid(sessions[0])) clean.set('session', sessions[0]);
43
+ if (sessions.length === 1 && isUuid(sessions[0])) clean.set('session', sessions[0]);
22
44
  if (langs.length === 1 && ['en','pt-BR','es'].includes(langs[0])) clean.set('lang', langs[0]);
23
45
  return clean.size ? `?${clean}` : '';
24
46
  }
25
- const hostPathOf = config => config.hostPath || '/dial/host.html';
26
-
27
47
  // Only an operator-bound native deployment host may canonicalize an anonymous entry.
28
48
  // No arbitrary Host, callback, capability, or query value is forwarded.
29
49
  export function streamHostRoute(config, req, res, pathname) {
50
+ const hostPath = requireGamePath(config?.hostPath, 'hostPath');
30
51
  if (req.headers.host === new URL(config.origin).host) return false;
52
+ const directory = hostPath.slice(0, hostPath.lastIndexOf('/') + 1);
31
53
  if (config.deploymentHost && req.headers.host === config.deploymentHost &&
32
- ['GET', 'HEAD'].includes(req.method) && ['/', hostPathOf(config).replace(/\/host\.html$/, ''), hostPathOf(config).replace(/host\.html$/, ''), hostPathOf(config)].includes(pathname)) {
33
- redirect(res, config.origin + hostPathOf(config) + inviteQuery(req.url));
54
+ ['GET', 'HEAD'].includes(req.method) && ['/', directory.slice(0, -1), directory, hostPath].includes(pathname)) {
55
+ redirect(res, config.origin + hostPath + inviteQuery(req.url));
34
56
  } else json(res, 403, {error:'wrong_host'});
35
57
  return true;
36
58
  }
37
59
 
38
60
  // A state heartbeat is continuation only while this room already has an admitted board
39
61
  // stream. Callers still validate the room's board capability before using this predicate.
40
- export const ongoingBoardState = (from, message, connections) => from === 'board' &&
41
- message.t === 'state' && [...(connections || [])].some(response => response.wwcRole === 'board' && !response.destroyed && !response.writableEnded);
62
+ export function ongoingBoardState(config, from, message, connections) {
63
+ const getConnectionRole = connectionRoleReader(config);
64
+ return from === 'board' && message.t === 'state' && [...(connections || [])]
65
+ .some(response => !response.destroyed && !response.writableEnded && getConnectionRole(response) === 'board');
66
+ }
42
67
 
43
68
  // Shared stream-game gate. Game capability checks remain with the existing room engine.
44
- export async function createStreamGate({ config, onClose, onState, auth: providedAuth, transport = fetch, now = Date.now }) {
69
+ export async function createStreamGate({ config, onClose, onState, auth: providedAuth, transport = fetch, now = Date.now, isVerifiedIngress } = {}) {
70
+ if (!config?.gameId) throw fail('invalid_gate_configuration');
71
+ const { hostPath, roomPrefix } = streamGameSettings(config);
45
72
  const auth = {...await createSignInTicketClient(config, {transport}), ...providedAuth};
46
73
  const sessions = new Map(), pending = new Map(), live = new Map(), requests = new Map(), authStarts = new Map();
47
74
  let authOpening = 0;
48
75
  // Existing one-hour cookie/session retention; central calls own ticket validity.
49
- const cookie = (id, age=3600) => `__Host-funfab-stream=${id}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=${age}`;
50
- const sessionOf = req => sessions.get(/(?:^|;\s*)__Host-funfab-stream=([a-f0-9]{64})(?:;|$)/.exec(req.headers.cookie || '')?.[1]);
76
+ const sessionOf = req => sessions.get(cookieId(req, SESSION));
77
+ function loginBucket(req) {
78
+ const peer = req.socket?.remoteAddress, ip = req.headers['x-real-ip'];
79
+ if (typeof ip === 'string' && isIP(ip) && typeof peer === 'string' && isIP(peer)) {
80
+ try {
81
+ if (isVerifiedIngress?.(peer) === true) return ip;
82
+ } catch { /* Unverified peers use the shared bucket. */ }
83
+ }
84
+ return UNVERIFIED_LOGIN;
85
+ }
51
86
  async function close(room, reason='room_closed', closedAt) {
52
87
  const r = live.get(room);
53
88
  if (!r || r.closed) return;
@@ -60,28 +95,26 @@ export async function createStreamGate({ config, onClose, onState, auth: provide
60
95
  async function closeAccount(accountId, reason) { await Promise.all([...live].filter(([,r])=>r.session.accountId===accountId).map(([room])=>close(room,reason))); }
61
96
  async function closeSession(session,reason) {await Promise.all([...live].filter(([,r])=>r.session===session).map(([room])=>close(room,reason)));}
62
97
  async function check(session, roomRequestId) {
63
- let accountDecision=false;
64
98
  if(session.revoked)throw fail("game_access_denied");
65
99
  try {
66
100
  const data = roomRequestId ? await auth.room(session.ticket,roomRequestId) : await auth.policy(session.ticket);
67
- const s = data?.status, p = data?.gamePolicy;
68
- const lease = Date.parse(s?.lease_expires_at);
69
- if (!uuid(s?.account_id) || typeof s.eligibility !== 'string' || (s.cutoff_at !== null && !Number.isFinite(Date.parse(s.cutoff_at))) || !Number.isFinite(lease) || lease <= now() || !p || p.game_id !== config.gameId || p.environment !== config.environment) throw fail('temporary_unavailable');
70
- if (session.accountId && session.accountId !== s.account_id) throw fail('authorization_required');
71
- if (s.eligibility !== 'eligible' || s.cutoff_at !== null) throw fail('game_access_denied');
101
+ const p = data?.gamePolicy;
102
+ const admission = admissionStatus(data, now(), { accountId:session.accountId, expireBeforeRefusal:true });
103
+ if (['malformed','expired'].includes(admission.refusal) || p?.game_id !== config.gameId || p.environment !== config.environment) throw fail('temporary_unavailable');
104
+ if (admission.refusal === 'identity') throw fail('authorization_required');
105
+ if (admission.refusal === 'denied') throw fail('game_access_denied');
72
106
  if (roomRequestId) {
73
107
  const c = data.roomClaim, reset = c?.quota_resets_at;
74
108
  if (!c || c.request_id !== roomRequestId || typeof c.allowed !== 'boolean' || typeof c.replayed !== 'boolean' ||
75
109
  (!c.allowed && c.replayed) || typeof reset !== 'string' || !/^\d{4}-\d{2}-\d{2}T00:00:00(?:\.0{1,6})?(?:Z|\+00:00)$/.test(reset) || !Number.isFinite(Date.parse(reset)) || Date.parse(reset) <= now()) throw fail('temporary_unavailable');
76
110
  }
77
111
  if(session.revoked)throw fail("authorization_required");
78
- session.accountId = s.account_id; session.policy = p; session.lastSuccess = now(); session.lease = Math.min(lease,now()+299000); session.safe = null;
112
+ session.accountId = admission.accountId; session.policy = p; session.lastSuccess = now(); session.lease = Math.min(admission.lease,now()+299000); session.safe = null;
79
113
  for (const [room,r] of live) if (r.session===session && !r.closed) { clearTimeout(r.deadlineTimer);r.deadlineTimer=null;r.grace = false; onState(room,{state:'active'}); }
80
114
  return roomRequestId ? data.roomClaim : session;
81
115
  } catch(error) {
82
- const temporary = error.code === 'temporary_unavailable' || error.name === 'TimeoutError';
83
- if (error.code === 'game_access_denied') accountDecision=true;
84
- if (temporary) {
116
+ const code = refusalCode(error);
117
+ if (code === 'temporary_unavailable') {
85
118
  session.safe = {state:'platform_unreachable'}; session.safeAt=now();
86
119
  for (const [room,r] of live) if (r.session===session && !r.closed) {
87
120
  const deadline = session.lastSuccess + 1800000;
@@ -91,7 +124,7 @@ export async function createStreamGate({ config, onClose, onState, auth: provide
91
124
  throw fail('temporary_unavailable');
92
125
  }
93
126
  session.revoked = true; session.safe = null;
94
- if(accountDecision && session.accountId)await closeAccount(session.accountId,'access_ended');
127
+ if(code === 'game_access_denied' && session.accountId)await closeAccount(session.accountId,'access_ended');
95
128
  else await closeSession(session,'access_ended');
96
129
  throw fail('game_access_denied');
97
130
  }
@@ -143,55 +176,67 @@ export async function createStreamGate({ config, onClose, onState, auth: provide
143
176
  if (url.pathname === '/auth/funfab/signout') {
144
177
  if (req.method !== 'POST') {json(res,405,{});return true;}
145
178
  if (req.headers.origin !== config.origin) {json(res,403,{});return true;}
179
+ const pendingId = cookieId(req, LOGIN);
180
+ if (pendingId) pending.delete(pendingId);
181
+ const loginClear = cookie(LOGIN, '', 0);
146
182
  const s = sessionOf(req);
147
183
  if (s) {
148
184
  s.revoked = true; await closeSession(s,'access_ended');
149
185
  try { await auth.signout(s.ticket); }
150
186
  catch (error) {
151
- if (!['authorization_required','game_access_denied'].includes(error.code)) {json(res,503,{error:'temporary_unavailable'});return true;}
187
+ if (!['authorization_required','game_access_denied'].includes(refusalCode(error))) {
188
+ json(res,503,{error:'temporary_unavailable'},pendingId ? {'set-cookie':loginClear} : {});return true;
189
+ }
152
190
  }
153
191
  for (const [id, value] of sessions) if (value === s) sessions.delete(id);
154
192
  }
155
- json(res,200,{state:'signed_out'},{'set-cookie':cookie('',0)});return true;
193
+ const sessionClear = cookie(SESSION, '', 0);
194
+ json(res,200,{state:'signed_out'},{'set-cookie':pendingId ? [sessionClear, loginClear] : sessionClear});return true;
156
195
  }
157
196
  if (url.pathname === '/auth/funfab/start' || url.pathname === '/auth/login') {
158
197
  if (req.method !== 'GET') {json(res,405,{});return true;}
159
- const ip = String(req.headers['x-real-ip'] || req.socket?.remoteAddress || '?');
160
- let bucket = authStarts.get(ip);
198
+ const key = loginBucket(req);
199
+ const limit = key === UNVERIFIED_LOGIN ? 200 : 20;
200
+ let bucket = authStarts.get(key);
161
201
  if (!bucket || bucket.until <= now()) {
162
202
  if (!bucket && authStarts.size >= 5000) {json(res,429,{error:'too_many_sign_in_requests'});return true;}
163
- bucket = {count:0,until:now()+60000};authStarts.set(ip,bucket);
203
+ bucket = {count:0,until:now()+60000};authStarts.set(key,bucket);
164
204
  }
165
- if (bucket.count >= 20 || pending.size + authOpening >= 5000) {json(res,429,{error:'too_many_sign_in_requests'});return true;}
205
+ if (bucket.count >= limit || pending.size + authOpening >= 5000) {json(res,429,{error:'too_many_sign_in_requests'});return true;}
166
206
  bucket.count++;
167
207
  let p;authOpening++;
168
208
  try {p=await auth.begin();}
169
- catch (error) {json(res,error.code === 'temporary_unavailable'?503:403,{error:error.code === 'temporary_unavailable'?'temporary_unavailable':'game_access_denied'});return true;}
209
+ catch (error) {const temporary = refusalCode(error) === 'temporary_unavailable';json(res,temporary?503:403,{error:temporary?'temporary_unavailable':'game_access_denied'});return true;}
170
210
  finally{authOpening--;}
171
211
  const id = randomBytes(32).toString('hex');
172
212
  pending.set(id,{...p,invite:inviteQuery(url.href),expires:now()+600000});
173
- redirect(res,p.url,{'set-cookie':cookie(id,600)});return true;
213
+ redirect(res,p.url,{'set-cookie':cookie(LOGIN,id,600)});return true;
174
214
  }
175
215
  if (url.pathname === '/auth/funfab/callback') {
176
- const id = /(?:^|;\s*)__Host-funfab-stream=([a-f0-9]{64})(?:;|$)/.exec(req.headers.cookie || '')?.[1], p = pending.get(id); pending.delete(id);
177
- if (!p || p.expires <= now() || req.method !== 'GET') {json(res,403,{error:'authorization_required'});return true;}
216
+ if (req.method !== 'GET') {json(res,403,{error:'authorization_required'});return true;}
217
+ const id = cookieId(req, LOGIN), p = pending.get(id);
218
+ pending.delete(id);
219
+ const loginClear = cookie(LOGIN, '', 0), cleared = {'set-cookie':loginClear};
220
+ if (!p || p.expires <= now()) {json(res,403,{error:'authorization_required'},cleared);return true;}
178
221
  try {
179
222
  const identity = await auth.complete(new URL(req.url,config.origin),p), s={ticket:identity.ticket,accountId:identity.accountId,lastSuccess:0,lease:0,expires:now()+3600000};
180
223
  try { await check(s); }
181
224
  catch (error) {
182
225
  // No admitted local session owns this ticket; end it before abandoning sign-in.
183
226
  try { await auth.signout(s.ticket); } catch { /* Best effort if the authority is unreachable. */ }
184
- if (error.code === 'temporary_unavailable') json(res,503,{error:'temporary_unavailable'});
185
- else redirect(res,`${config.accountOrigin}/account/access?game=${encodeURIComponent(config.gameId)}`);
227
+ if (error.code === 'temporary_unavailable') json(res,503,{error:'temporary_unavailable'},cleared);
228
+ else redirect(res,`${config.accountOrigin}/account/access?game=${encodeURIComponent(config.gameId)}`,cleared);
186
229
  return true;
187
230
  }
188
- const sid=randomBytes(32).toString('hex'); sessions.set(sid,s); redirect(res,hostPathOf(config)+inviteQuery(p.invite || ''),{'set-cookie':cookie(sid)});
189
- } catch (error) {json(res,error.code === 'temporary_unavailable'?503:403,{error:error.code === 'temporary_unavailable'?'temporary_unavailable':'game_access_denied'});} return true;
231
+ const sid=randomBytes(32).toString('hex'); sessions.set(sid,s);
232
+ redirect(res,hostPath+inviteQuery(p.invite || ''),{'set-cookie':[cookie(SESSION,sid,3600),loginClear]});
233
+ } catch (error) {const temporary = refusalCode(error) === 'temporary_unavailable';json(res,temporary?503:403,{error:temporary?'temporary_unavailable':'game_access_denied'},cleared);}
234
+ return true;
190
235
  }
191
236
  return false;
192
237
  }
193
238
  async function createRoom(session,requestId) {
194
- if (!uuid(requestId)) throw fail('game_access_denied');
239
+ if (!isUuid(requestId)) throw fail('game_access_denied');
195
240
  const claim = await check(session,requestId);
196
241
  if (!claim.allowed) {
197
242
  session.safe = {state:'daily_limit',quota_resets_at:claim.quota_resets_at};session.safeAt=now();
@@ -208,7 +253,7 @@ export async function createStreamGate({ config, onClose, onState, auth: provide
208
253
  // A process restart closes the memory-owned room engine. A counted old request must
209
254
  // never resurrect that room (nor reopen one ended by its host) after the restart.
210
255
  if (claim.replayed) throw closedAttempt();
211
- const room = `${config.roomPrefix || 'wwc-'}${randomBytes(8).toString('hex')}`;
256
+ const room = `${roomPrefix}${randomBytes(8).toString('hex')}`;
212
257
  requests.set(key,room); live.set(room,{session,closed:false,grace:false,requestKey:key});
213
258
  return room;
214
259
  }