@funfab/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # FunFab SDK
2
+ Add FunFab sign-in and host safety to your game.
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+ ## Install
5
+ ```sh
6
+ npm install --save-exact @funfab/sdk@0.1.0
7
+ ```
8
+ Needs Node.js 22 or newer on your server.
9
+
10
+ ## Which part to import
11
+ | | |
12
+ | --- | --- |
13
+ | Your game's server, on Railway | `@funfab/sdk/adapters/stream` |
14
+ | Your game's server, on Vercel | `@funfab/sdk/adapters/vercel` |
15
+ | Party games | `@funfab/sdk/adapters/party` |
16
+ | Sign-in tickets, any server | `@funfab/sdk/server` |
17
+ | Pages players see | `@funfab/sdk/browser` |
18
+ | Name filtering, viewer blocks | `@funfab/sdk/host-safety` |
19
+ | Host-safety result format | `@funfab/sdk/schemas/host-safety` |
20
+
21
+ ## Keep secrets on your server
22
+ Never import /server or /adapters/* in code that runs in a
23
+ browser. Your game holds its game key and players' sign-in
24
+ tickets. It never holds a player's FunFab account tokens.
25
+
26
+ ## Quick start (Vercel)
27
+ ```js
28
+ import { configuration, createGate } from "@funfab/sdk/adapters/vercel";
29
+ const gate = createGate(configuration(process.env));
30
+ const { allow, response } = await gate.handle(request);
31
+ ```
32
+
33
+ ## Versions
34
+ Trial (0.x): pin an exact version. The previous version
35
+ keeps working for 90 days after a new one. `funfab game
36
+ submit` tells you if your version is no longer supported.
@@ -0,0 +1,8 @@
1
+ import {createSignInTicketClient,signInTicketConfig} from '../server.mjs';
2
+
3
+ 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
+ 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');}
7
+ 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};}
@@ -0,0 +1,242 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { createSignInTicketClient, signInTicketConfig } from '../server.mjs';
3
+
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) {
7
+ const common = signInTicketConfig(env);
8
+ if (!common) return null; // Existing unenrolled games remain unchanged.
9
+ const c = {...common};
10
+ c.deploymentHost = env.FUNFAB_GAME_DEPLOYMENT_HOST || null;
11
+ if (c.deploymentHost && !/^[a-z0-9]+(?:-[a-z0-9]+)*\.up\.railway\.app$/.test(c.deploymentHost)) throw fail('invalid_gate_configuration');
12
+ c.callback = c.origin + '/auth/funfab/callback';
13
+ return c;
14
+ }
15
+ const json = (res, status, data, headers = {}) => res.writeHead(status, { 'content-type':'application/json', 'cache-control':'no-store', ...headers }).end(JSON.stringify(data));
16
+ const redirect = (res, location, headers = {}) => res.writeHead(303, { location, 'cache-control':'no-store', ...headers }).end();
17
+ // Public invite UUID only; never carry credentials or arbitrary return URLs.
18
+ function inviteQuery(value) {
19
+ const params = new URL(value, 'https://invite.invalid').searchParams, clean = new URLSearchParams();
20
+ const sessions = params.getAll('session'), langs = params.getAll('lang');
21
+ if (sessions.length === 1 && uuid(sessions[0])) clean.set('session', sessions[0]);
22
+ if (langs.length === 1 && ['en','pt-BR','es'].includes(langs[0])) clean.set('lang', langs[0]);
23
+ return clean.size ? `?${clean}` : '';
24
+ }
25
+ const hostPathOf = config => config.hostPath || '/dial/host.html';
26
+
27
+ // Only an operator-bound native deployment host may canonicalize an anonymous entry.
28
+ // No arbitrary Host, callback, capability, or query value is forwarded.
29
+ export function streamHostRoute(config, req, res, pathname) {
30
+ if (req.headers.host === new URL(config.origin).host) return false;
31
+ 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));
34
+ } else json(res, 403, {error:'wrong_host'});
35
+ return true;
36
+ }
37
+
38
+ // A state heartbeat is continuation only while this room already has an admitted board
39
+ // 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);
42
+
43
+ // 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 }) {
45
+ const auth = {...await createSignInTicketClient(config, {transport}), ...providedAuth};
46
+ const sessions = new Map(), pending = new Map(), live = new Map(), requests = new Map(), authStarts = new Map();
47
+ let authOpening = 0;
48
+ // 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]);
51
+ async function close(room, reason='room_closed', closedAt) {
52
+ const r = live.get(room);
53
+ if (!r || r.closed) return;
54
+ clearTimeout(r.deadlineTimer);r.closed = true;
55
+ r.terminalState = {state:reason,...(closedAt?{closed_at:closedAt}:{})};
56
+ r.terminalExpires = r.session.expires;
57
+ if(closedAt)onClose(room, reason, {closed_at:closedAt});else onClose(room, reason);
58
+ requests.delete(r.requestKey);
59
+ }
60
+ async function closeAccount(accountId, reason) { await Promise.all([...live].filter(([,r])=>r.session.accountId===accountId).map(([room])=>close(room,reason))); }
61
+ async function closeSession(session,reason) {await Promise.all([...live].filter(([,r])=>r.session===session).map(([room])=>close(room,reason)));}
62
+ async function check(session, roomRequestId) {
63
+ let accountDecision=false;
64
+ if(session.revoked)throw fail("game_access_denied");
65
+ try {
66
+ 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');
72
+ if (roomRequestId) {
73
+ const c = data.roomClaim, reset = c?.quota_resets_at;
74
+ if (!c || c.request_id !== roomRequestId || typeof c.allowed !== 'boolean' || typeof c.replayed !== 'boolean' ||
75
+ (!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
+ }
77
+ 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;
79
+ 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
+ return roomRequestId ? data.roomClaim : session;
81
+ } catch(error) {
82
+ const temporary = error.code === 'temporary_unavailable' || error.name === 'TimeoutError';
83
+ if (error.code === 'game_access_denied') accountDecision=true;
84
+ if (temporary) {
85
+ session.safe = {state:'platform_unreachable'}; session.safeAt=now();
86
+ for (const [room,r] of live) if (r.session===session && !r.closed) {
87
+ const deadline = session.lastSuccess + 1800000;
88
+ if (!session.lastSuccess || now() >= deadline) await close(room,'room_closed',new Date(deadline).toISOString());
89
+ else {if(!r.deadlineTimer)r.deadlineTimer=setTimeout(()=>{close(room,'room_closed',new Date(deadline).toISOString()).catch(()=>{});},Math.max(0,deadline-now())).unref();r.grace=true; onState(room,{state:'grace',closes_at:new Date(deadline).toISOString()});}
90
+ }
91
+ throw fail('temporary_unavailable');
92
+ }
93
+ session.revoked = true; session.safe = null;
94
+ if(accountDecision && session.accountId)await closeAccount(session.accountId,'access_ended');
95
+ else await closeSession(session,'access_ended');
96
+ throw fail('game_access_denied');
97
+ }
98
+ }
99
+ const withinGrace = r => r && !r.closed && !r.session.revoked && r.grace && r.deadlineTimer && now() < r.session.expires && now() < r.session.lastSuccess + 1800000;
100
+ async function host(req, res, { roomCreation = false } = {}) {
101
+ const session = sessionOf(req), accessUrl = `${config.accountOrigin}/account/access?game=${encodeURIComponent(config.gameId)}`;
102
+ if (!session || session.revoked) {
103
+ if (roomCreation) json(res,401,{error:'authorization_required'});
104
+ else redirect(res,'/auth/funfab/start' + inviteQuery(req.url));
105
+ return null;
106
+ }
107
+ try { return await check(session); } catch (error) {
108
+ const temporary = error.code === 'temporary_unavailable';
109
+ if (!roomCreation && temporary && [...live.values()].some(r => r.session === session && withinGrace(r))) return session;
110
+ if (roomCreation) json(res,temporary?503:403,{error:temporary?'temporary_unavailable':'game_access_denied',accessState:{state:temporary?'platform_unreachable':'access_ended'},accessUrl});
111
+ else redirect(res,accessUrl);
112
+ return null;
113
+ }
114
+ }
115
+ async function roomAccess(room, {req, hostOnly=false, end=false, boardHeartbeat=null, hostRead=false} = {}) {
116
+ const r = live.get(room);
117
+ if (!r || r.closed) throw fail('room_closed');
118
+ if(r.session.revoked)throw fail('game_access_denied');
119
+ if (hostOnly && sessionOf(req) !== r.session) {
120
+ const incoming=sessionOf(req);if(!incoming || incoming.revoked)throw fail('authorization_required');
121
+ await check(incoming);if(incoming.accountId!==r.session.accountId)throw fail('authorization_required');r.session=incoming;
122
+ }
123
+ // End show is a capability-reducing action, including while the authority is unreachable.
124
+ if (end) { await close(room); return r.session; }
125
+ try { await check(r.session); } // admissions/reconnects and host actions always need fresh authority
126
+ catch (error) {
127
+ // Only the existing board's state heartbeat may continue through the established
128
+ // grace. A refusal, closure or deadline never takes this path.
129
+ if (!(((boardHeartbeat?.() && !hostOnly) || (hostRead && hostOnly)) && error.code === 'temporary_unavailable' && live.get(room) === r && withinGrace(r))) throw error;
130
+ }
131
+ if (r.closed) throw fail('room_closed');
132
+ return r.session;
133
+ }
134
+ async function route(req,res,url) {
135
+ if(url.pathname==='/auth/games' && req.method==='GET'){redirect(res,config.accountOrigin+'/account/game.html?game='+encodeURIComponent(config.gameId));return true;}
136
+ if (url.pathname === '/auth/access-state') {
137
+ if (req.method !== 'GET') {json(res,405,{});return true;}
138
+ const origin = req.headers.origin;
139
+ if (origin && origin !== config.accountOrigin) {json(res,403,{});return true;}
140
+ const s = sessionOf(req), safe = s && !s.revoked && s.safeAt > now()-300000 ? s.safe : null;
141
+ json(res,200,safe || {state:'unavailable'}, origin ? {'access-control-allow-origin':origin,'access-control-allow-credentials':'true',vary:'Origin'} : {});return true;
142
+ }
143
+ if (url.pathname === '/auth/funfab/signout') {
144
+ if (req.method !== 'POST') {json(res,405,{});return true;}
145
+ if (req.headers.origin !== config.origin) {json(res,403,{});return true;}
146
+ const s = sessionOf(req);
147
+ if (s) {
148
+ s.revoked = true; await closeSession(s,'access_ended');
149
+ try { await auth.signout(s.ticket); }
150
+ catch (error) {
151
+ if (!['authorization_required','game_access_denied'].includes(error.code)) {json(res,503,{error:'temporary_unavailable'});return true;}
152
+ }
153
+ for (const [id, value] of sessions) if (value === s) sessions.delete(id);
154
+ }
155
+ json(res,200,{state:'signed_out'},{'set-cookie':cookie('',0)});return true;
156
+ }
157
+ if (url.pathname === '/auth/funfab/start' || url.pathname === '/auth/login') {
158
+ 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);
161
+ if (!bucket || bucket.until <= now()) {
162
+ 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);
164
+ }
165
+ if (bucket.count >= 20 || pending.size + authOpening >= 5000) {json(res,429,{error:'too_many_sign_in_requests'});return true;}
166
+ bucket.count++;
167
+ let p;authOpening++;
168
+ 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;}
170
+ finally{authOpening--;}
171
+ const id = randomBytes(32).toString('hex');
172
+ pending.set(id,{...p,invite:inviteQuery(url.href),expires:now()+600000});
173
+ redirect(res,p.url,{'set-cookie':cookie(id,600)});return true;
174
+ }
175
+ 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;}
178
+ try {
179
+ 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
+ try { await check(s); }
181
+ catch (error) {
182
+ // No admitted local session owns this ticket; end it before abandoning sign-in.
183
+ 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)}`);
186
+ return true;
187
+ }
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;
190
+ }
191
+ return false;
192
+ }
193
+ async function createRoom(session,requestId) {
194
+ if (!uuid(requestId)) throw fail('game_access_denied');
195
+ const claim = await check(session,requestId);
196
+ if (!claim.allowed) {
197
+ session.safe = {state:'daily_limit',quota_resets_at:claim.quota_resets_at};session.safeAt=now();
198
+ throw Object.assign(fail('room_quota_reached'),{accessState:session.safe});
199
+ }
200
+ const closedAttempt = () => { session.safe={state:'room_closed'};session.safeAt=now();return Object.assign(fail('room_closed'),{accessState:session.safe}); };
201
+ const key = `${session.accountId}:${requestId}`, existing = requests.get(key);
202
+ if (existing) {
203
+ const r = live.get(existing);
204
+ if (!r || r.closed) throw closedAttempt();
205
+ r.session = session;
206
+ return existing;
207
+ }
208
+ // A process restart closes the memory-owned room engine. A counted old request must
209
+ // never resurrect that room (nor reopen one ended by its host) after the restart.
210
+ if (claim.replayed) throw closedAttempt();
211
+ const room = `${config.roomPrefix || 'wwc-'}${randomBytes(8).toString('hex')}`;
212
+ requests.set(key,room); live.set(room,{session,closed:false,grace:false,requestKey:key});
213
+ return room;
214
+ }
215
+ // Fresh account authority only; discovery never makes a quota claim or creates a room.
216
+ async function findRoom(session) {
217
+ try { await check(session); }
218
+ catch (error) {
219
+ // Match host HTML reloads: only this already admitted session may reach its
220
+ // existing room during grace, including the capability-reducing End show.
221
+ if (error.code !== 'temporary_unavailable' || ![...live.values()].some(r => r.session === session && withinGrace(r))) throw error;
222
+ return [...live].reverse().find(([,r]) => r.session === session && withinGrace(r))?.[0] || null;
223
+ }
224
+ return [...live].reverse().find(([,r]) => !r.closed && !r.session.revoked && r.session.expires > now() && r.session.accountId === session.accountId)?.[0] || null;
225
+ }
226
+ async function tick() {
227
+ for(const [id,s] of sessions) if(s.expires<=now()) {sessions.delete(id);await closeSession(s,"access_ended");}
228
+ for(const [ip,bucket] of authStarts) if(bucket.until<=now()) authStarts.delete(ip);
229
+ for(const [key,p] of pending) if(p.expires<=now()) pending.delete(key);
230
+ for(const [room,r] of live) {
231
+ if(r.closed) {if(r.terminalExpires<=now())live.delete(room);continue;}
232
+ if(r.grace && now()>=r.session.lastSuccess+1800000) {await close(room,'room_closed',new Date(r.session.lastSuccess+1800000).toISOString());continue;}
233
+ if(r.session.lease<=now()) try{await check(r.session);}catch{/* check owns closure/grace */}
234
+ }
235
+ }
236
+ function accessState(room) {
237
+ const r=live.get(room);if(!r)return {state:'room_closed'};
238
+ if(r.closed)return r.terminalExpires>now()?r.terminalState:{state:'room_closed'};
239
+ return r.grace?{state:'grace',closes_at:new Date(r.session.lastSuccess+1800000).toISOString()}:{state:'active'};
240
+ }
241
+ return {route,host,roomAccess,createRoom,tick,close,sessionOf,check,accessState,findRoom};
242
+ }
@@ -0,0 +1,159 @@
1
+ // Server-only: the build copies an explicit public allowlist, never this module.
2
+ import { signInTicketConfig, createSignInTicketClient, isSignInTicket } from '../server.mjs';
3
+ import { EncryptJWT, jwtDecrypt } from 'jose';
4
+
5
+ const SESSION = '__Host-funfab-game';
6
+ const TRANSACTION = '__Host-funfab-login';
7
+ const ACCESS = '__Host-funfab-access';
8
+ const HEADERS = { 'Cache-Control': 'private, no-store', 'CDN-Cache-Control': 'no-store', 'Vercel-CDN-Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' };
9
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10
+ export function configuration(env) {
11
+ const config = signInTicketConfig(env);
12
+ if (!config) return null;
13
+ if ((env.VERCEL_ENV && env.VERCEL_ENV !== config.environment) ||
14
+ !/^[A-Za-z0-9_-]{43}$/.test(env.FUNFAB_GAME_COOKIE_KEY ?? '')) throw new Error('configuration');
15
+ return { ...config, cookieKey: Buffer.from(env.FUNFAB_GAME_COOKIE_KEY, 'base64url'), callback: `${config.origin}/auth/callback` };
16
+ }
17
+ function response(status, code) { return Response.json({ error: code }, { status, headers: HEADERS }); }
18
+ function redirect(url) { return new Response(null, { status: 303, headers: { ...HEADERS, Location: url } }); }
19
+ function cookieValue(request, name) {
20
+ const entries = (request.headers.get('cookie') ?? '').split(';').map(x => x.trim()).filter(x => x.startsWith(`${name}=`));
21
+ return entries.length === 1 ? entries[0].slice(name.length + 1) : null;
22
+ }
23
+ function putCookie(res, name, value, age) {
24
+ if (value.length > 3800) throw new Error('cookie_size');
25
+ res.headers.append('Set-Cookie', `${name}=${value}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=${Math.max(0, Math.floor(age))}`);
26
+ }
27
+ function clear(res) { putCookie(res, SESSION, '', 0); putCookie(res, TRANSACTION, '', 0); return res; }
28
+ function safePath(value) {
29
+ if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//') || /[\\\r\n]/.test(value)) return '/setup.html';
30
+ const url = new URL(value, 'https://return.invalid');
31
+ if (url.origin !== 'https://return.invalid' || url.pathname.startsWith('/auth/')) return '/setup.html';
32
+ // Do not replay arbitrary telemetry, credentials or authorization codes in return URLs.
33
+ const allowed = new URLSearchParams();
34
+ for (const name of ['channel', 'sound', 'rail', 'tower', 'words']) {
35
+ const value = url.searchParams.get(name);
36
+ if (value !== null && value.length <= 256) allowed.set(name, value);
37
+ }
38
+ const sessions = url.searchParams.getAll('session');
39
+ if (sessions.length === 1 && UUID.test(sessions[0])) allowed.set('session', sessions[0]);
40
+ return url.pathname + (allowed.size ? `?${allowed}` : '');
41
+ }
42
+ export function freshAdmission(request) {
43
+ const path = new URL(request.url).pathname;
44
+ return request.headers.get('sec-fetch-dest') === 'document' ||
45
+ (request.headers.get('accept') ?? '').includes('text/html') ||
46
+ !/\.(?:js|css|png|jpg|jpeg|webp|svg|woff2|ico)$/i.test(path);
47
+ }
48
+ export function createGate(config, dependencies = {}) {
49
+ if (!config) return { handle: async () => ({ allow: true, response: new Response(null) }) };
50
+ const now = dependencies.now ?? (() => Math.floor(Date.now() / 1000));
51
+ const client = createSignInTicketClient(config, { transport: dependencies.fetch ?? fetch });
52
+ const binding = `${config.environment}:${config.clientId}`;
53
+ async function seal(payload, kind, expires) {
54
+ return new EncryptJWT({ ...payload, kind }).setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
55
+ .setIssuer(config.origin).setAudience(binding).setIssuedAt(now()).setExpirationTime(expires).encrypt(config.cookieKey);
56
+ }
57
+ async function open(value, kind) {
58
+ const { payload } = await jwtDecrypt(value, config.cookieKey, { issuer: config.origin, audience: binding,
59
+ currentDate: new Date(now() * 1000), keyManagementAlgorithms: ['dir'], contentEncryptionAlgorithms: ['A256GCM'] });
60
+ if (payload.kind !== kind) throw new Error('cookie_kind');
61
+ return payload;
62
+ }
63
+ async function sessionFrom(request) {
64
+ const session = await open(cookieValue(request, SESSION), 'session');
65
+ // Reject the old accounts-token cookie format. There is no compatibility fallback.
66
+ if (!isSignInTicket(session.ticket) || !UUID.test(session.accountId ?? '') ||
67
+ 'token' in session || 'access_token' in session || 'refresh_token' in session ||
68
+ !Number.isFinite(session.exp) || session.exp > now() + 3600) throw new Error('session');
69
+ return session;
70
+ }
71
+ async function status(ticket, accountId, expires) {
72
+ const data = (await (await client).status(ticket)).status;
73
+ const lease = Date.parse(data?.lease_expires_at) / 1000;
74
+ const cutoff = data?.cutoff_at === null ? Infinity : Date.parse(data?.cutoff_at) / 1000;
75
+ if (data?.eligibility !== 'eligible' || data?.account_id !== accountId || !Number.isFinite(lease) ||
76
+ lease <= now() || !(cutoff > now())) throw new Error('game_access_denied');
77
+ return Math.min(lease, cutoff, now() + 300, expires);
78
+ }
79
+ async function login(returnTo) {
80
+ const pending = await (await client).begin();
81
+ const res = redirect(pending.url);
82
+ putCookie(res, TRANSACTION, await seal({ verifier: pending.verifier, state: pending.state, returnTo: safePath(returnTo) }, 'login', now() + 600), 600);
83
+ putCookie(res, SESSION, '', 0);
84
+ return res;
85
+ }
86
+ return {
87
+ // Exposed only for native protocol tests; middleware invokes handle alone.
88
+ seal, open,
89
+ async handle(request) {
90
+ const url = new URL(request.url);
91
+ if (url.origin !== config.origin) {
92
+ // Never forward an authorization code/state/token from an unregistered alias callback.
93
+ return redirect(`${config.origin}${safePath(url.pathname + (url.pathname.startsWith('/auth/') ? '' : url.search))}`);
94
+ }
95
+ if (url.pathname === '/auth/access-state') {
96
+ if (request.headers.get('origin') !== config.accountOrigin || request.method !== 'GET') return response(403, 'game_access_denied');
97
+ let state = 'unavailable';
98
+ try { const context = await open(cookieValue(request, ACCESS), 'access'); if (['offline', 'platform_unreachable'].includes(context.state)) state = context.state; } catch { /* neutral fallback */ }
99
+ return Response.json({ state }, { headers: { ...HEADERS, 'Access-Control-Allow-Origin': config.accountOrigin, 'Access-Control-Allow-Credentials': 'true', Vary: 'Origin' } });
100
+ }
101
+ if (url.pathname === '/auth/signout') {
102
+ if (request.method !== 'POST') return response(405, 'method_not_allowed');
103
+ if (request.headers.get('origin') !== config.origin) return response(403, 'game_access_denied');
104
+ let session;
105
+ try { session = await sessionFrom(request); } catch { /* Local invalidation still succeeds. */ }
106
+ let res = Response.json({ state: 'signed_out' }, { headers: HEADERS });
107
+ if (session) {
108
+ try { await (await client).signout(session.ticket); }
109
+ catch (error) {
110
+ if (!['authorization_required', 'game_access_denied'].includes(error?.code)) res = response(503, 'temporary_unavailable');
111
+ }
112
+ }
113
+ clear(res);
114
+ putCookie(res, ACCESS, '', 0);
115
+ return res;
116
+ }
117
+ if (!['GET', 'HEAD'].includes(request.method)) return response(405, 'method_not_allowed');
118
+ let issuedSession;
119
+ try {
120
+ if (url.pathname === '/auth/login') return await login(url.searchParams.get('returnTo'));
121
+ if (url.pathname === '/auth/callback') {
122
+ const transaction = await open(cookieValue(request, TRANSACTION), 'login');
123
+ const result = await (await client).complete(url, transaction);
124
+ const expires = now() + 3600;
125
+ issuedSession = { ticket: result.ticket, accountId: result.accountId, expires };
126
+ const lease = await status(result.ticket, result.accountId, expires);
127
+ const res = redirect(`${config.origin}${safePath(transaction.returnTo)}`);
128
+ putCookie(res, SESSION, await seal({ ticket: result.ticket, accountId: result.accountId, lease }, 'session', expires), expires - now());
129
+ putCookie(res, TRANSACTION, '', 0);
130
+ return res;
131
+ }
132
+ let session;
133
+ try { session = await sessionFrom(request); } catch { return await login(url.pathname + url.search); }
134
+ const shouldRefresh = freshAdmission(request) || !Number.isFinite(session.lease) || session.lease <= now();
135
+ let lease = Math.min(session.lease, session.exp);
136
+ if (shouldRefresh) {
137
+ try { lease = await status(session.ticket, session.accountId, session.exp); }
138
+ catch (error) {
139
+ if (error?.code === 'authorization_required') return await login(url.pathname + url.search);
140
+ throw error;
141
+ }
142
+ }
143
+ const res = new Response(null, { headers: HEADERS });
144
+ if (shouldRefresh) putCookie(res, SESSION, await seal({ ticket: session.ticket, accountId: session.accountId, lease }, 'session', session.exp), session.exp - now());
145
+ return { response: res, allow: true };
146
+ } catch (error) {
147
+ const state = error?.code === 'temporary_unavailable' ? 'platform_unreachable' : 'unavailable';
148
+ const res = redirect(`${config.accountOrigin}/account/access?game=${encodeURIComponent(config.gameId)}`);
149
+ if (state === 'platform_unreachable') {
150
+ // Keep the ticket and its existing deadline, without granting or extending a lease.
151
+ putCookie(res, TRANSACTION, '', 0);
152
+ if (issuedSession) putCookie(res, SESSION, await seal({ ticket: issuedSession.ticket, accountId: issuedSession.accountId, lease: 0 }, 'session', issuedSession.expires), issuedSession.expires - now());
153
+ } else clear(res);
154
+ putCookie(res, ACCESS, await seal({ state }, 'access', now() + 300), 300);
155
+ return res;
156
+ }
157
+ },
158
+ };
159
+ }
package/browser.js ADDED
@@ -0,0 +1,115 @@
1
+ // Colours reuse FunFab Colour System v4 paper.dark/ink.dark/hero.dark and account.css border.
2
+ // Shared approved S2 notices. No account details or authority are read from the URL.
3
+ export const accessCopy = {
4
+ en: {outage:"Can't reach FunFab right now.", grace:t=>`Your show keeps running and chat can still play. Host controls are paused, except End show. If we can't reconnect, this room closes at ${t}.`, end:'End show',endFailed:'Couldn’t end the show. Try again.', showEnded:'Show ended', ended:'This show has ended.', neutral:'The room is closed.', deadline:t=>`We couldn’t reach FunFab, so the room closed at ${t}. You can start a new show once we’re back.`, denied:'Your access changed, so the room closed. Questions? support@funfab.io', board:'This show has ended. Thanks for playing!', quota:t=>`Daily limit reached. You can start another show at ${t}.`, back:'Back to your games',backThisGame:'Back to this game'},
5
+ 'pt-BR': {outage:'Não foi possível conectar ao FunFab agora.',grace:t=>`Seu show continua e o chat pode continuar jogando. Os controles estão pausados, exceto Encerrar show. Se a conexão não voltar, esta sala fecha às ${t}.`,end:'Encerrar show',endFailed:'Não foi possível encerrar o show. Tente de novo.',showEnded:'Encerrou o show',ended:'Este show terminou.',neutral:'A sala foi fechada.',deadline:t=>`Não conseguimos conectar ao FunFab, então a sala foi fechada às ${t}. Você pode começar um novo show quando voltarmos.`,denied:'Seu acesso mudou, então a sala foi fechada. Dúvidas? support@funfab.io',board:'Este show terminou. Obrigado por jogar!',quota:t=>`Limite diário atingido. Você pode iniciar outro show às ${t}.`,back:'Voltar aos seus jogos',backThisGame:'Voltar a este jogo'},
6
+ es:{outage:'No podemos conectar con FunFab ahora.',grace:t=>`Tu show continúa y el chat puede seguir jugando. Los controles están pausados, excepto Finalizar show. Si no vuelve la conexión, esta sala se cierra a las ${t}.`,end:'Finalizar show',endFailed:'No se pudo finalizar el show. Inténtalo de nuevo.',showEnded:'Terminó el show',ended:'Este show ha terminado.',neutral:'La sala está cerrada.',denied:'Tu acceso cambió, por lo que la sala se cerró. ¿Preguntas? support@funfab.io',board:'Este show ha terminado. ¡Gracias por jugar!',quota:t=>`Has alcanzado el límite diario. Puedes iniciar otro show a las ${t}.`,back:'Volver a tus juegos',backThisGame:'Volver a este juego'},
7
+ };
8
+ export function mountAccess({language='en',board=false,endShow=()=>{},onClosed=()=>{},reportControls=[],closedControls=[],headerLink=null,gameAccess=false,endCard=null,liveControls=[],roomError=null}={}) {
9
+ const copy=accessCopy[language]||accessCopy.en;
10
+ const notice=document.createElement('section');notice.hidden=true;notice.setAttribute('role','status');notice.setAttribute('aria-live','polite');
11
+ notice.style.cssText='margin:12px auto;max-width:500px;width:calc(100% - 24px);padding:18px;border:1px solid #594d3c;border-radius:12px;background:#1A1613;color:#F3ECE0;font:inherit;line-height:1.55;position:relative;z-index:100';
12
+ const title=document.createElement(endCard&&!board?'h2':'strong'),detail=document.createElement('p'),end=document.createElement('button');
13
+ end.type='button';end.style.cssText='display:block;width:100%;min-height:48px;border:1px solid #F3ECE0;border-radius:9px;background:transparent;color:#F3ECE0;font:inherit;font-weight:700;cursor:pointer';end.onfocus=()=>end.style.outline='3px solid #00C1BF';end.onblur=()=>end.style.outline='';end.textContent=copy.end;end.onclick=()=>endShow();
14
+ const back=document.createElement('a');back.href='/auth/games';back.textContent=gameAccess?copy.backThisGame:copy.back;back.style.color='#00C1BF';back.hidden=true;
15
+ notice.append(title,detail,end,back);document.body.prepend(notice);
16
+ let paused=false,closed=false;
17
+ // The two host panels opt into an overlay for temporary states and their own terminal card.
18
+ // Other consumers and the board keep the existing presentation.
19
+ const panel=!board&&endCard;
20
+ let observer=null,barVisible=false,scrollPadding='',spaceHeight=0,bodyStyles=null,paddingTop=0,paddingBottom=0,minHeight=0,barScale=0,viewportWidth=0,viewportHeight=0;
21
+ function revealFocus(){
22
+ const focused=document.activeElement;
23
+ if(!barVisible||!focused||focused===document.body||notice.contains(focused))return;
24
+ const bounds=focused.getBoundingClientRect(),bottom=notice.getBoundingClientRect().bottom;
25
+ if(bounds.bottom>0&&bounds.top<bottom)window.scrollBy({top:bounds.top-bottom-8,behavior:'instant'});
26
+ }
27
+ function measureBar(){
28
+ if(!barVisible)return;
29
+ const height=Math.ceil(notice.getBoundingClientRect().height),scale=parseFloat(getComputedStyle(document.body).zoom)||1;
30
+ if(height===spaceHeight&&scale===barScale&&window.innerWidth===viewportWidth&&window.innerHeight===viewportHeight)return;
31
+ barScale=scale;viewportWidth=window.innerWidth;viewportHeight=window.innerHeight;
32
+ const scroll=window.scrollY;
33
+ document.body.style.paddingTop=`${paddingTop+height/scale}px`;
34
+ document.body.style.paddingBottom=`${paddingBottom+height/scale}px`;
35
+ document.body.style.minHeight=`${Math.max(minHeight,(window.innerHeight+2*height)/scale)}px`;
36
+ document.documentElement.style.scrollPaddingTop=`${height}px`;
37
+ window.scrollTo({top:scroll+height-spaceHeight,behavior:'instant'});spaceHeight=height;
38
+ revealFocus();
39
+ }
40
+ function stopBar(){
41
+ if(!barVisible)return;
42
+ barVisible=false;observer?.disconnect();observer=null;
43
+ window.removeEventListener('resize',measureBar);document.removeEventListener('focusin',revealFocus);
44
+ const scroll=window.scrollY;
45
+ Object.assign(document.body.style,bodyStyles);
46
+ document.documentElement.style.scrollPaddingTop=scrollPadding;
47
+ window.scrollTo({top:Math.max(0,scroll-spaceHeight),behavior:'instant'});spaceHeight=0;bodyStyles=null;
48
+ }
49
+ function showBar(){
50
+ if(!panel)return;
51
+ notice.style.cssText='position:fixed;inset:0 0 auto;z-index:100;margin:0;padding:calc(12px + env(safe-area-inset-top, 0px)) 16px 12px;background:#1A1613;color:#F3ECE0;border-bottom:1px solid #ffd36a;font:inherit;line-height:1.55';
52
+ if(!barVisible){
53
+ barVisible=true;scrollPadding=document.documentElement.style.scrollPaddingTop;
54
+ const style=document.body.style,computed=getComputedStyle(document.body);
55
+ bodyStyles={paddingTop:style.paddingTop,paddingBottom:style.paddingBottom,minHeight:style.minHeight,overflowAnchor:style.overflowAnchor};
56
+ paddingTop=parseFloat(computed.paddingTop)||0;paddingBottom=parseFloat(computed.paddingBottom)||0;minHeight=parseFloat(computed.minHeight)||0;
57
+ style.overflowAnchor='none';
58
+ observer=new ResizeObserver(measureBar);observer.observe(notice);
59
+ window.addEventListener('resize',measureBar);document.addEventListener('focusin',revealFocus);
60
+ }
61
+ measureBar();
62
+ }
63
+ // Only explicitly supplied saved-report controls bypass the live-game UI fence.
64
+ // Their existing handlers and server capabilities still decide whether a save is authorized.
65
+ const reports=board?[]:reportControls.filter(Boolean);
66
+ const afterClosed=board?[]:closedControls.filter(Boolean);
67
+ for(const name of ['click','keydown','submit','input','change']) document.addEventListener(name,event=>{
68
+ if(panel&&event.type==='keydown'&&event.key==='Tab')return;
69
+ const report=reports.some(control=>control===event.target || control.contains(event.target));
70
+ const header=!board&&gameAccess&&headerLink&&(headerLink===event.target||headerLink.contains(event.target));
71
+ const restart=closed&&afterClosed.some(control=>control===event.target || control.contains(event.target));
72
+ if((paused||closed)&&!notice.contains(event.target)&&!report&&!restart&&!header&&event.target!==back){event.preventDefault();event.stopImmediatePropagation();}
73
+ },true);
74
+ const time=value=>new Date(value).toLocaleString(language,{month:'short',day:'numeric',hour:'numeric',minute:'2-digit',timeZoneName:'short'});
75
+ const localTime=value=>new Date(value).toLocaleTimeString(language,{hour:'numeric',minute:'2-digit'}).toLowerCase();
76
+ return {
77
+ setGameAccess(value){
78
+ gameAccess=value===true;back.textContent=gameAccess?copy.backThisGame:copy.back;
79
+ if(headerLink&&!board)headerLink.hidden=!!(panel&&closed)||!gameAccess;
80
+ if(panel&&closed){back.hidden=!gameAccess;back.style.display=gameAccess?'inline-block':'none';}
81
+ },
82
+ get blocked(){return paused||closed;},
83
+ get closed(){return closed;},
84
+ update(value){
85
+ if(closed && (board || value.state!=='daily_limit'))return;
86
+ if(value.state==='active'){paused=false;notice.hidden=true;stopBar();return;}
87
+ if(value.state==='grace'){
88
+ if(board)return;paused=true;notice.hidden=false;title.textContent=copy.outage;detail.textContent=copy.grace(localTime(value.closes_at));end.hidden=false;end.style.display='block';showBar();return;
89
+ }
90
+ if(value.state==='daily_limit'){
91
+ paused=true;
92
+ if(panel&&closed){detail.textContent=copy.quota(time(value.quota_resets_at));return;}
93
+ notice.hidden=false;title.textContent=copy.quota(time(value.quota_resets_at));detail.textContent='';end.hidden=true;end.style.display='none';showBar();return;
94
+ }
95
+ if(!['room_closed','access_ended'].includes(value.state))return;
96
+ closed=true;paused=true;stopBar();onClosed(value.state);
97
+ if(board){document.body.replaceChildren(notice);notice.style.cssText='position:fixed;inset:0;display:grid;place-content:center;background:#000;color:#f3ece0;text-align:center;font:700 32px sans-serif';title.textContent=copy.board;detail.textContent='';}
98
+ else{title.textContent=copy.ended;detail.textContent=value.state==='access_ended'?copy.denied:copy.deadline && Number.isFinite(Date.parse(value.closed_at))?copy.deadline(localTime(value.closed_at)):copy.neutral;back.hidden=false;}
99
+ end.hidden=true;end.style.display='none';
100
+ if(panel){
101
+ for(const control of liveControls.filter(Boolean)){control.hidden=true;control.style.display='none';}
102
+ title.textContent=value.state==='room_closed'?copy.showEnded:copy.ended;
103
+ title.tabIndex=-1;title.style.cssText='font:inherit;font-size:24px;font-weight:800;margin:0 0 12px';
104
+ detail.style.cssText='margin:0 0 16px';
105
+ back.hidden=!gameAccess;back.style.display=gameAccess?'inline-block':'none';
106
+ back.style.color='';back.style.marginTop='14px';
107
+ if(headerLink)headerLink.hidden=true;
108
+ const primary=afterClosed[0];
109
+ if(primary)primary.hidden=value.state==='access_ended';
110
+ endCard.append(title,detail,...(primary?[primary]:[]),...(roomError?[roomError]:[]),back);
111
+ endCard.hidden=false;notice.hidden=true;title.focus();
112
+ }else{notice.hidden=false;notice.tabIndex=-1;notice.focus();}
113
+ },
114
+ };
115
+ }
@@ -0,0 +1,2 @@
1
+ export * from './name-filter.js';
2
+ export * from './public-names.js';