@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.
@@ -1,21 +1,41 @@
1
1
  // Server-only: the build copies an explicit public allowlist, never this module.
2
2
  import { signInTicketConfig, createSignInTicketClient, isSignInTicket } from '../server.mjs';
3
+ import { admissionStatus, gameReturnURL, gateError as fail, isUuid, refusalCode, requireGamePath, settingError } from '../gate-core.mjs';
3
4
  import { EncryptJWT, jwtDecrypt } from 'jose';
4
5
 
5
6
  const SESSION = '__Host-funfab-game';
6
7
  const TRANSACTION = '__Host-funfab-login';
7
8
  const ACCESS = '__Host-funfab-access';
8
9
  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) {
10
+ const localOrigin = Symbol('local bypass origin');
11
+ const authParameter = /token|ticket|credential|^(?:authorization|code|state|nonce|error(?:_description|_uri)?|code_(?:verifier|challenge(?:_method)?)|session_state|iss)$/i;
12
+
13
+ function returnSettings(game) {
14
+ const returnPath = requireGamePath(game?.returnPath, 'returnPath');
15
+ const query = game?.returnQuery;
16
+ if (!query || typeof query !== 'object' || ![Object.prototype, null].includes(Object.getPrototypeOf(query))) {
17
+ throw settingError('returnQuery');
18
+ }
19
+ const entries = Object.entries(query);
20
+ for (const [name, format] of entries) {
21
+ if (!/^[a-z0-9_-]+$/i.test(name) || authParameter.test(name) || !['text', 'uuid'].includes(format)) {
22
+ throw settingError('returnQuery');
23
+ }
24
+ }
25
+ return { returnPath, returnQuery: Object.fromEntries(entries) };
26
+ }
27
+
28
+ export function configuration(env = process.env, game) {
11
29
  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` };
30
+ if (config && ((env.VERCEL_ENV && env.VERCEL_ENV !== config.environment) ||
31
+ !/^[A-Za-z0-9_-]{43}$/.test(env.FUNFAB_GAME_COOKIE_KEY ?? ''))) throw fail('invalid_gate_configuration');
32
+ const settings = returnSettings(game);
33
+ if (!config) return Object.freeze({ [localOrigin]: env.FUNFAB_GAME_ORIGIN });
34
+ return { ...config, ...settings, cookieKey: Buffer.from(env.FUNFAB_GAME_COOKIE_KEY, 'base64url'), callback: `${config.origin}/auth/callback` };
16
35
  }
17
36
  function response(status, code) { return Response.json({ error: code }, { status, headers: HEADERS }); }
18
37
  function redirect(url) { return new Response(null, { status: 303, headers: { ...HEADERS, Location: url } }); }
38
+ const handled = response => ({ allow: false, response });
19
39
  function cookieValue(request, name) {
20
40
  const entries = (request.headers.get('cookie') ?? '').split(';').map(x => x.trim()).filter(x => x.startsWith(`${name}=`));
21
41
  return entries.length === 1 ? entries[0].slice(name.length + 1) : null;
@@ -25,18 +45,20 @@ function putCookie(res, name, value, age) {
25
45
  res.headers.append('Set-Cookie', `${name}=${value}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=${Math.max(0, Math.floor(age))}`);
26
46
  }
27
47
  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';
48
+ function safePath(value, returnPath, query) {
49
+ const url = gameReturnURL(value);
50
+ if (!url) return returnPath;
32
51
  // Do not replay arbitrary telemetry, credentials or authorization codes in return URLs.
33
52
  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);
53
+ for (const [name, format] of query) {
54
+ if (format === 'uuid') {
55
+ const values = url.searchParams.getAll(name);
56
+ if (values.length === 1 && isUuid(values[0])) allowed.set(name, values[0]);
57
+ } else {
58
+ const value = url.searchParams.get(name);
59
+ if (value !== null && value.length <= 256) allowed.set(name, value);
60
+ }
37
61
  }
38
- const sessions = url.searchParams.getAll('session');
39
- if (sessions.length === 1 && UUID.test(sessions[0])) allowed.set('session', sessions[0]);
40
62
  return url.pathname + (allowed.size ? `?${allowed}` : '');
41
63
  }
42
64
  export function freshAdmission(request) {
@@ -46,7 +68,14 @@ export function freshAdmission(request) {
46
68
  !/\.(?:js|css|png|jpg|jpeg|webp|svg|woff2|ico)$/i.test(path);
47
69
  }
48
70
  export function createGate(config, dependencies = {}) {
49
- if (!config) return { handle: async () => ({ allow: true, response: new Response(null) }) };
71
+ if (config?.[localOrigin]) return {
72
+ handle: async request => new URL(request.url).origin === config[localOrigin] ?
73
+ { allow: true, response: new Response(null) } : handled(response(403, 'game_access_denied')),
74
+ };
75
+ if (!config?.gameId) throw fail('invalid_gate_configuration');
76
+ const { returnPath, returnQuery } = returnSettings(config);
77
+ const query = Object.entries(returnQuery);
78
+ const safeReturn = value => safePath(value, returnPath, query);
50
79
  const now = dependencies.now ?? (() => Math.floor(Date.now() / 1000));
51
80
  const client = createSignInTicketClient(config, { transport: dependencies.fetch ?? fetch });
52
81
  const binding = `${config.environment}:${config.clientId}`;
@@ -63,25 +92,22 @@ export function createGate(config, dependencies = {}) {
63
92
  async function sessionFrom(request) {
64
93
  const session = await open(cookieValue(request, SESSION), 'session');
65
94
  // Reject the old accounts-token cookie format. There is no compatibility fallback.
66
- if (!isSignInTicket(session.ticket) || !UUID.test(session.accountId ?? '') ||
95
+ if (!isSignInTicket(session.ticket) || !isUuid(session.accountId) ||
67
96
  'token' in session || 'access_token' in session || 'refresh_token' in session ||
68
97
  !Number.isFinite(session.exp) || session.exp > now() + 3600) throw new Error('session');
69
98
  return session;
70
99
  }
71
100
  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);
101
+ const data = await (await client).status(ticket);
102
+ const admission = admissionStatus(data, now() * 1000, { accountId, allowFutureCutoff: true });
103
+ if (admission.refusal) throw fail('game_access_denied');
104
+ return Math.min(admission.lease / 1000, admission.cutoff / 1000, now() + 300, expires);
78
105
  }
79
106
  async function login(returnTo) {
80
107
  const pending = await (await client).begin();
81
108
  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;
109
+ putCookie(res, TRANSACTION, await seal({ verifier: pending.verifier, state: pending.state, returnTo: safeReturn(returnTo) }, 'login', now() + 600), 600);
110
+ return handled(res);
85
111
  }
86
112
  return {
87
113
  // Exposed only for native protocol tests; middleware invokes handle alone.
@@ -90,69 +116,76 @@ export function createGate(config, dependencies = {}) {
90
116
  const url = new URL(request.url);
91
117
  if (url.origin !== config.origin) {
92
118
  // 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))}`);
119
+ return handled(redirect(`${config.origin}${safeReturn(url.pathname + url.search)}`));
94
120
  }
95
121
  if (url.pathname === '/auth/access-state') {
96
- if (request.headers.get('origin') !== config.accountOrigin || request.method !== 'GET') return response(403, 'game_access_denied');
122
+ if (request.headers.get('origin') !== config.accountOrigin || request.method !== 'GET') return handled(response(403, 'game_access_denied'));
97
123
  let state = 'unavailable';
98
124
  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' } });
125
+ return handled(Response.json({ state }, { headers: { ...HEADERS, 'Access-Control-Allow-Origin': config.accountOrigin, 'Access-Control-Allow-Credentials': 'true', Vary: 'Origin' } }));
100
126
  }
101
127
  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');
128
+ if (request.method !== 'POST') return handled(response(405, 'method_not_allowed'));
129
+ if (request.headers.get('origin') !== config.origin) return handled(response(403, 'game_access_denied'));
104
130
  let session;
105
131
  try { session = await sessionFrom(request); } catch { /* Local invalidation still succeeds. */ }
106
132
  let res = Response.json({ state: 'signed_out' }, { headers: HEADERS });
107
133
  if (session) {
108
134
  try { await (await client).signout(session.ticket); }
109
135
  catch (error) {
110
- if (!['authorization_required', 'game_access_denied'].includes(error?.code)) res = response(503, 'temporary_unavailable');
136
+ if (!['authorization_required', 'game_access_denied'].includes(refusalCode(error))) res = response(503, 'temporary_unavailable');
111
137
  }
112
138
  }
113
139
  clear(res);
114
140
  putCookie(res, ACCESS, '', 0);
115
- return res;
141
+ return handled(res);
116
142
  }
117
- if (!['GET', 'HEAD'].includes(request.method)) return response(405, 'method_not_allowed');
118
- let issuedSession;
143
+ if (!['GET', 'HEAD'].includes(request.method)) return handled(response(405, 'method_not_allowed'));
144
+ let issuedSession, enteringLogin = false, refusedSession = false;
145
+ const startLogin = returnTo => {
146
+ enteringLogin = true;
147
+ return login(returnTo);
148
+ };
119
149
  try {
120
- if (url.pathname === '/auth/login') return await login(url.searchParams.get('returnTo'));
150
+ if (url.pathname === '/auth/login') return await startLogin(url.searchParams.get('returnTo'));
121
151
  if (url.pathname === '/auth/callback') {
122
152
  const transaction = await open(cookieValue(request, TRANSACTION), 'login');
123
153
  const result = await (await client).complete(url, transaction);
124
154
  const expires = now() + 3600;
125
155
  issuedSession = { ticket: result.ticket, accountId: result.accountId, expires };
126
156
  const lease = await status(result.ticket, result.accountId, expires);
127
- const res = redirect(`${config.origin}${safePath(transaction.returnTo)}`);
157
+ const res = redirect(`${config.origin}${safeReturn(transaction.returnTo)}`);
128
158
  putCookie(res, SESSION, await seal({ ticket: result.ticket, accountId: result.accountId, lease }, 'session', expires), expires - now());
129
159
  putCookie(res, TRANSACTION, '', 0);
130
- return res;
160
+ return handled(res);
131
161
  }
132
162
  let session;
133
- try { session = await sessionFrom(request); } catch { return await login(url.pathname + url.search); }
163
+ try { session = await sessionFrom(request); } catch { return await startLogin(url.pathname + url.search); }
134
164
  const shouldRefresh = freshAdmission(request) || !Number.isFinite(session.lease) || session.lease <= now();
135
165
  let lease = Math.min(session.lease, session.exp);
136
166
  if (shouldRefresh) {
137
167
  try { lease = await status(session.ticket, session.accountId, session.exp); }
138
168
  catch (error) {
139
- if (error?.code === 'authorization_required') return await login(url.pathname + url.search);
140
- throw error;
169
+ if (refusalCode(error) !== 'authorization_required') throw error;
170
+ refusedSession = true;
171
+ const decision = await startLogin(url.pathname + url.search);
172
+ putCookie(decision.response, SESSION, '', 0);
173
+ return decision;
141
174
  }
142
175
  }
143
176
  const res = new Response(null, { headers: HEADERS });
144
177
  if (shouldRefresh) putCookie(res, SESSION, await seal({ ticket: session.ticket, accountId: session.accountId, lease }, 'session', session.exp), session.exp - now());
145
178
  return { response: res, allow: true };
146
179
  } catch (error) {
147
- const state = error?.code === 'temporary_unavailable' ? 'platform_unreachable' : 'unavailable';
180
+ const state = refusalCode(error) === 'temporary_unavailable' ? 'platform_unreachable' : 'unavailable';
148
181
  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.
182
+ if (!refusedSession && (state === 'platform_unreachable' || enteringLogin)) {
151
183
  putCookie(res, TRANSACTION, '', 0);
184
+ // A newly exchanged ticket gets no lease until the platform confirms admission.
152
185
  if (issuedSession) putCookie(res, SESSION, await seal({ ticket: issuedSession.ticket, accountId: issuedSession.accountId, lease: 0 }, 'session', issuedSession.expires), issuedSession.expires - now());
153
186
  } else clear(res);
154
187
  putCookie(res, ACCESS, await seal({ state }, 'access', now() + 300), 300);
155
- return res;
188
+ return handled(res);
156
189
  }
157
190
  },
158
191
  };
package/browser.js CHANGED
@@ -1,115 +1,27 @@
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();
1
+ // Public notice state for browser consumers that provide their own rendering.
2
+ export function createAccessState() {
3
+ let state = 'active';
4
+ let closed = false;
5
+
76
6
  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;
7
+ get blocked() { return state !== 'active'; },
8
+ get closed() { return closed; },
9
+ update(next) {
10
+ if (closed && next !== 'daily_limit') return false;
11
+ switch (next) {
12
+ case 'room_closed':
13
+ case 'access_ended':
14
+ closed = true;
15
+ break;
16
+ case 'active':
17
+ case 'grace':
18
+ case 'daily_limit':
19
+ break;
20
+ default:
21
+ return false;
94
22
  }
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();}
23
+ state = next;
24
+ return true;
113
25
  },
114
26
  };
115
27
  }
package/gate-core.mjs ADDED
@@ -0,0 +1,75 @@
1
+ export const isUuid = 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);
2
+ export const gateError = code => Object.assign(new Error(code), { code });
3
+
4
+ export const settingError = name => Object.assign(
5
+ new Error(`Missing or invalid SDK game setting: ${name}`), { code: 'invalid_gate_configuration' },
6
+ );
7
+
8
+ export const isLoopbackHost = hostname => ['localhost', '127.0.0.1', '[::1]'].includes(hostname);
9
+
10
+ export function requirePlatformGameConfig(config) {
11
+ try {
12
+ const { ticketApiOrigin, gameId, credential } = config;
13
+ const url = new URL(ticketApiOrigin);
14
+ if (url.origin === ticketApiOrigin &&
15
+ (url.protocol === 'https:' || (url.protocol === 'http:' && isLoopbackHost(url.hostname))) &&
16
+ typeof gameId === 'string' && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(gameId) &&
17
+ typeof credential === 'string' && /^fgc_[A-Za-z0-9_-]+$/.test(credential)) return;
18
+ } catch { /* Report a safe configuration error below. */ }
19
+ throw gateError('invalid_gate_configuration');
20
+ }
21
+
22
+ export function postPlatformJson(transport, url, credential, body) {
23
+ return transport(url, {
24
+ method: 'POST',
25
+ headers: { authorization: `Bearer ${credential}`, 'content-type': 'application/json' },
26
+ body,
27
+ redirect: 'error',
28
+ signal: AbortSignal.timeout(8000),
29
+ });
30
+ }
31
+
32
+ const PATH_BASE = 'https://game.invalid';
33
+ export function gameReturnURL(value) {
34
+ if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//') ||
35
+ /[\\\x00-\x1f\x7f]/.test(value)) return null;
36
+ const url = new URL(value, PATH_BASE);
37
+ if (url.origin !== PATH_BASE || url.pathname.startsWith('//') ||
38
+ url.pathname === '/auth' || url.pathname.startsWith('/auth/')) return null;
39
+ return url;
40
+ }
41
+
42
+ export function requireGamePath(value, name) {
43
+ if (typeof value !== 'string' || gameReturnURL(value)?.pathname !== value) throw settingError(name);
44
+ return value;
45
+ }
46
+
47
+ export function refusalCode(error) {
48
+ if (error?.name === 'TimeoutError') return 'temporary_unavailable';
49
+ switch (error?.code) {
50
+ case 'temporary_unavailable':
51
+ case 'authorization_required':
52
+ case 'game_access_denied':
53
+ return error.code;
54
+ default:
55
+ return null;
56
+ }
57
+ }
58
+
59
+ export function admissionStatus(body, now, { accountId, allowFutureCutoff = false, expireBeforeRefusal = false } = {}) {
60
+ const status = body?.status;
61
+ const lease = typeof status?.lease_expires_at === 'string' ? Date.parse(status.lease_expires_at) : NaN;
62
+ const cutoff = status?.cutoff_at === null ? Infinity :
63
+ typeof status?.cutoff_at === 'string' ? Date.parse(status.cutoff_at) : NaN;
64
+ if (!isUuid(status?.account_id) || typeof status.eligibility !== 'string' ||
65
+ !Number.isFinite(lease) || Number.isNaN(cutoff)) return { refusal: 'malformed' };
66
+
67
+ const expired = lease <= now;
68
+ if (expired && expireBeforeRefusal) return { refusal: 'expired' };
69
+ if (accountId && accountId !== status.account_id) return { refusal: 'identity' };
70
+ if (status.eligibility !== 'eligible' || (cutoff !== Infinity && (!allowFutureCutoff || cutoff <= now))) {
71
+ return { refusal: 'denied' };
72
+ }
73
+ if (expired) return { refusal: 'expired' };
74
+ return { accountId: status.account_id, lease, cutoff };
75
+ }
package/host-panel.js ADDED
@@ -0,0 +1,116 @@
1
+ import { createAccessState } from './browser.js';
2
+
3
+ // Colours reuse FunFab Colour System v4 paper.dark/ink.dark/hero.dark and account.css border.
4
+ // Shared approved S2 notices. No account details or authority are read from the URL.
5
+ export const accessCopy = {
6
+ 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'},
7
+ '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'},
8
+ 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'},
9
+ };
10
+ export function mountAccess({language='en',board=false,endShow=()=>{},onClosed=()=>{},reportControls=[],closedControls=[],headerLink=null,gameAccess=false,endCard=null,liveControls=[],roomError=null}={}) {
11
+ const copy=accessCopy[language]||accessCopy.en;
12
+ const notice=document.createElement('section');notice.hidden=true;notice.setAttribute('role','status');notice.setAttribute('aria-live','polite');
13
+ 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';
14
+ const title=document.createElement(endCard&&!board?'h2':'strong'),detail=document.createElement('p'),end=document.createElement('button');
15
+ 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();
16
+ const back=document.createElement('a');back.href='/auth/games';back.textContent=gameAccess?copy.backThisGame:copy.back;back.style.color='#00C1BF';back.hidden=true;
17
+ notice.append(title,detail,end,back);document.body.prepend(notice);
18
+ const access = createAccessState();
19
+ // The two host panels opt into an overlay for temporary states and their own terminal card.
20
+ // Other consumers and the board keep the existing presentation.
21
+ const panel=!board&&endCard;
22
+ let observer=null,barVisible=false,scrollPadding='',spaceHeight=0,bodyStyles=null,paddingTop=0,paddingBottom=0,minHeight=0,barScale=0,viewportWidth=0,viewportHeight=0;
23
+ function revealFocus(){
24
+ const focused=document.activeElement;
25
+ if(!barVisible||!focused||focused===document.body||notice.contains(focused))return;
26
+ const bounds=focused.getBoundingClientRect(),bottom=notice.getBoundingClientRect().bottom;
27
+ if(bounds.bottom>0&&bounds.top<bottom)window.scrollBy({top:bounds.top-bottom-8,behavior:'instant'});
28
+ }
29
+ function measureBar(){
30
+ if(!barVisible)return;
31
+ const height=Math.ceil(notice.getBoundingClientRect().height),scale=parseFloat(getComputedStyle(document.body).zoom)||1;
32
+ if(height===spaceHeight&&scale===barScale&&window.innerWidth===viewportWidth&&window.innerHeight===viewportHeight)return;
33
+ barScale=scale;viewportWidth=window.innerWidth;viewportHeight=window.innerHeight;
34
+ const scroll=window.scrollY;
35
+ document.body.style.paddingTop=`${paddingTop+height/scale}px`;
36
+ document.body.style.paddingBottom=`${paddingBottom+height/scale}px`;
37
+ document.body.style.minHeight=`${Math.max(minHeight,(window.innerHeight+2*height)/scale)}px`;
38
+ document.documentElement.style.scrollPaddingTop=`${height}px`;
39
+ window.scrollTo({top:scroll+height-spaceHeight,behavior:'instant'});spaceHeight=height;
40
+ revealFocus();
41
+ }
42
+ function stopBar(){
43
+ if(!barVisible)return;
44
+ barVisible=false;observer?.disconnect();observer=null;
45
+ window.removeEventListener('resize',measureBar);document.removeEventListener('focusin',revealFocus);
46
+ const scroll=window.scrollY;
47
+ Object.assign(document.body.style,bodyStyles);
48
+ document.documentElement.style.scrollPaddingTop=scrollPadding;
49
+ window.scrollTo({top:Math.max(0,scroll-spaceHeight),behavior:'instant'});spaceHeight=0;bodyStyles=null;
50
+ }
51
+ function showBar(){
52
+ if(!panel)return;
53
+ 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';
54
+ if(!barVisible){
55
+ barVisible=true;scrollPadding=document.documentElement.style.scrollPaddingTop;
56
+ const style=document.body.style,computed=getComputedStyle(document.body);
57
+ bodyStyles={paddingTop:style.paddingTop,paddingBottom:style.paddingBottom,minHeight:style.minHeight,overflowAnchor:style.overflowAnchor};
58
+ paddingTop=parseFloat(computed.paddingTop)||0;paddingBottom=parseFloat(computed.paddingBottom)||0;minHeight=parseFloat(computed.minHeight)||0;
59
+ style.overflowAnchor='none';
60
+ observer=new ResizeObserver(measureBar);observer.observe(notice);
61
+ window.addEventListener('resize',measureBar);document.addEventListener('focusin',revealFocus);
62
+ }
63
+ measureBar();
64
+ }
65
+ // Only explicitly supplied saved-report controls bypass the live-game UI fence.
66
+ // Their existing handlers and server capabilities still decide whether a save is authorized.
67
+ const reports=board?[]:reportControls.filter(Boolean);
68
+ const afterClosed=board?[]:closedControls.filter(Boolean);
69
+ for(const name of ['click','keydown','submit','input','change']) document.addEventListener(name,event=>{
70
+ if(panel&&event.type==='keydown'&&event.key==='Tab')return;
71
+ const report=reports.some(control=>control===event.target || control.contains(event.target));
72
+ const header=!board&&gameAccess&&headerLink&&(headerLink===event.target||headerLink.contains(event.target));
73
+ const restart=access.closed&&afterClosed.some(control=>control===event.target || control.contains(event.target));
74
+ if(access.blocked&&!notice.contains(event.target)&&!report&&!restart&&!header&&event.target!==back){event.preventDefault();event.stopImmediatePropagation();}
75
+ },true);
76
+ const time=value=>new Date(value).toLocaleString(language,{month:'short',day:'numeric',hour:'numeric',minute:'2-digit',timeZoneName:'short'});
77
+ const localTime=value=>new Date(value).toLocaleTimeString(language,{hour:'numeric',minute:'2-digit'}).toLowerCase();
78
+ return {
79
+ setGameAccess(value){
80
+ gameAccess=value===true;back.textContent=gameAccess?copy.backThisGame:copy.back;
81
+ if(headerLink&&!board)headerLink.hidden=!!(panel&&access.closed)||!gameAccess;
82
+ if(panel&&access.closed){back.hidden=!gameAccess;back.style.display=gameAccess?'inline-block':'none';}
83
+ },
84
+ get blocked(){return access.blocked;},
85
+ get closed(){return access.closed;},
86
+ update(value){
87
+ if (board && (access.closed || value.state === 'grace')) return;
88
+ if (!access.update(value.state)) return;
89
+ if(value.state==='active'){notice.hidden=true;stopBar();return;}
90
+ if(value.state==='grace'){
91
+ notice.hidden=false;title.textContent=copy.outage;detail.textContent=copy.grace(localTime(value.closes_at));end.hidden=false;end.style.display='block';showBar();return;
92
+ }
93
+ if(value.state==='daily_limit'){
94
+ if(panel&&access.closed){detail.textContent=copy.quota(time(value.quota_resets_at));return;}
95
+ notice.hidden=false;title.textContent=copy.quota(time(value.quota_resets_at));detail.textContent='';end.hidden=true;end.style.display='none';showBar();return;
96
+ }
97
+ stopBar();onClosed(value.state);
98
+ 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='';}
99
+ 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;}
100
+ end.hidden=true;end.style.display='none';
101
+ if(panel){
102
+ for(const control of liveControls.filter(Boolean)){control.hidden=true;control.style.display='none';}
103
+ title.textContent=value.state==='room_closed'?copy.showEnded:copy.ended;
104
+ title.tabIndex=-1;title.style.cssText='font:inherit;font-size:24px;font-weight:800;margin:0 0 12px';
105
+ detail.style.cssText='margin:0 0 16px';
106
+ back.hidden=!gameAccess;back.style.display=gameAccess?'inline-block':'none';
107
+ back.style.color='';back.style.marginTop='14px';
108
+ if(headerLink)headerLink.hidden=true;
109
+ const primary=afterClosed[0];
110
+ if(primary)primary.hidden=value.state==='access_ended';
111
+ endCard.append(title,detail,...(primary?[primary]:[]),...(roomError?[roomError]:[]),back);
112
+ endCard.hidden=false;notice.hidden=true;title.focus();
113
+ }else{notice.hidden=false;notice.tabIndex=-1;notice.focus();}
114
+ },
115
+ };
116
+ }