@funfab/sdk 0.1.1 → 0.2.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 +61 -3
- package/adapters/party.mjs +15 -3
- package/adapters/stream.mjs +87 -42
- package/adapters/vercel.mjs +78 -45
- package/browser.js +22 -110
- package/gate-core.mjs +51 -0
- package/host-panel.js +116 -0
- package/package.json +4 -1
- package/server.mjs +19 -5
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@ 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.
|
|
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
|
|
|
@@ -15,6 +15,7 @@ Needs Node.js 22 or newer on your server.
|
|
|
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,67 @@ 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
|
-
|
|
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
|
+
|
|
33
91
|
## Versions
|
|
34
92
|
Trial (0.x): pin an exact version. The previous version
|
|
35
93
|
keeps working for 90 days after a new one. `funfab game
|
package/adapters/party.mjs
CHANGED
|
@@ -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){
|
|
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){
|
|
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
|
+
}
|
package/adapters/stream.mjs
CHANGED
|
@@ -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
|
|
5
|
-
const
|
|
6
|
-
|
|
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
|
-
|
|
9
|
-
|
|
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 &&
|
|
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) && ['/',
|
|
33
|
-
redirect(res, config.origin +
|
|
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
|
|
41
|
-
|
|
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
|
|
50
|
-
|
|
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
|
|
68
|
-
const
|
|
69
|
-
if (
|
|
70
|
-
if (
|
|
71
|
-
if (
|
|
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 =
|
|
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
|
|
83
|
-
if (
|
|
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(
|
|
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
|
|
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
|
-
|
|
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
|
|
160
|
-
|
|
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(
|
|
203
|
+
bucket = {count:0,until:now()+60000};authStarts.set(key,bucket);
|
|
164
204
|
}
|
|
165
|
-
if (bucket.count >=
|
|
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) {
|
|
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
|
-
|
|
177
|
-
|
|
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);
|
|
189
|
-
|
|
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 (!
|
|
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 = `${
|
|
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
|
}
|
package/adapters/vercel.mjs
CHANGED
|
@@ -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
|
|
10
|
-
|
|
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 (
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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
|
-
|
|
30
|
-
|
|
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
|
|
35
|
-
|
|
36
|
-
|
|
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 (
|
|
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) || !
|
|
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 =
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
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:
|
|
83
|
-
|
|
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}${
|
|
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
|
|
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
|
|
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}${
|
|
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
|
|
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
|
|
140
|
-
|
|
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
|
|
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
|
-
//
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
if(
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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
|
-
|
|
96
|
-
|
|
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,51 @@
|
|
|
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
|
+
const PATH_BASE = 'https://game.invalid';
|
|
9
|
+
export function gameReturnURL(value) {
|
|
10
|
+
if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//') ||
|
|
11
|
+
/[\\\x00-\x1f\x7f]/.test(value)) return null;
|
|
12
|
+
const url = new URL(value, PATH_BASE);
|
|
13
|
+
if (url.origin !== PATH_BASE || url.pathname.startsWith('//') ||
|
|
14
|
+
url.pathname === '/auth' || url.pathname.startsWith('/auth/')) return null;
|
|
15
|
+
return url;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function requireGamePath(value, name) {
|
|
19
|
+
if (typeof value !== 'string' || gameReturnURL(value)?.pathname !== value) throw settingError(name);
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function refusalCode(error) {
|
|
24
|
+
if (error?.name === 'TimeoutError') return 'temporary_unavailable';
|
|
25
|
+
switch (error?.code) {
|
|
26
|
+
case 'temporary_unavailable':
|
|
27
|
+
case 'authorization_required':
|
|
28
|
+
case 'game_access_denied':
|
|
29
|
+
return error.code;
|
|
30
|
+
default:
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function admissionStatus(body, now, { accountId, allowFutureCutoff = false, expireBeforeRefusal = false } = {}) {
|
|
36
|
+
const status = body?.status;
|
|
37
|
+
const lease = typeof status?.lease_expires_at === 'string' ? Date.parse(status.lease_expires_at) : NaN;
|
|
38
|
+
const cutoff = status?.cutoff_at === null ? Infinity :
|
|
39
|
+
typeof status?.cutoff_at === 'string' ? Date.parse(status.cutoff_at) : NaN;
|
|
40
|
+
if (!isUuid(status?.account_id) || typeof status.eligibility !== 'string' ||
|
|
41
|
+
!Number.isFinite(lease) || Number.isNaN(cutoff)) return { refusal: 'malformed' };
|
|
42
|
+
|
|
43
|
+
const expired = lease <= now;
|
|
44
|
+
if (expired && expireBeforeRefusal) return { refusal: 'expired' };
|
|
45
|
+
if (accountId && accountId !== status.account_id) return { refusal: 'identity' };
|
|
46
|
+
if (status.eligibility !== 'eligible' || (cutoff !== Infinity && (!allowFutureCutoff || cutoff <= now))) {
|
|
47
|
+
return { refusal: 'denied' };
|
|
48
|
+
}
|
|
49
|
+
if (expired) return { refusal: 'expired' };
|
|
50
|
+
return { accountId: status.account_id, lease, cutoff };
|
|
51
|
+
}
|
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
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@funfab/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Add FunFab sign-in and host safety to your game.",
|
|
6
6
|
"engines": {
|
|
@@ -13,16 +13,19 @@
|
|
|
13
13
|
"./adapters/vercel": "./adapters/vercel.mjs",
|
|
14
14
|
"./adapters/party": "./adapters/party.mjs",
|
|
15
15
|
"./browser": "./browser.js",
|
|
16
|
+
"./host-panel": "./host-panel.js",
|
|
16
17
|
"./host-safety": "./host-safety/index.js",
|
|
17
18
|
"./schemas/host-safety": "./schemas/host-safety.schema.json"
|
|
18
19
|
},
|
|
19
20
|
"files": [
|
|
20
21
|
"index.js",
|
|
21
22
|
"server.mjs",
|
|
23
|
+
"gate-core.mjs",
|
|
22
24
|
"adapters/stream.mjs",
|
|
23
25
|
"adapters/vercel.mjs",
|
|
24
26
|
"adapters/party.mjs",
|
|
25
27
|
"browser.js",
|
|
28
|
+
"host-panel.js",
|
|
26
29
|
"host-safety/index.js",
|
|
27
30
|
"host-safety/name-filter.js",
|
|
28
31
|
"host-safety/public-names.js",
|
package/server.mjs
CHANGED
|
@@ -1,23 +1,37 @@
|
|
|
1
1
|
import * as oauth from 'oauth4webapi';
|
|
2
|
+
import { gateError as fail, isUuid } from './gate-core.mjs';
|
|
2
3
|
|
|
3
4
|
// Protocol bridge: the platform rename changes this one constant (#368).
|
|
4
5
|
const PLATFORM_ROUTE_PREFIX = '/api/sign-in-ticket';
|
|
5
6
|
export const SIGN_IN_TICKET_PREFIX = 'fst_';
|
|
6
7
|
export const isSignInTicket = value => typeof value === 'string' && value.startsWith(SIGN_IN_TICKET_PREFIX) &&
|
|
7
8
|
/^[A-Za-z0-9_-]{43}$/.test(value.slice(SIGN_IN_TICKET_PREFIX.length));
|
|
8
|
-
const fail = code => Object.assign(new Error(code), { code });
|
|
9
|
-
const uuid = value => typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(value);
|
|
10
9
|
export const ticketOperationUrl = (config, operation) => `${config.ticketApiOrigin}${PLATFORM_ROUTE_PREFIX}/${operation}`;
|
|
11
10
|
|
|
11
|
+
function localBypass(env) {
|
|
12
|
+
if (env.FUNFAB_ACCESS_REQUIRED === '1' || env.FUNFAB_ACCESS_DISABLED_LOCAL !== '1' || env.NODE_ENV !== 'development' ||
|
|
13
|
+
env.FUNFAB_ENVIRONMENT || env.FUNFAB_GAME_DEPLOYMENT_HOST || env.VERCEL ||
|
|
14
|
+
env.VERCEL_URL || env.VERCEL_DEPLOYMENT_ID || env.VERCEL_PROJECT_PRODUCTION_URL ||
|
|
15
|
+
(env.VERCEL_ENV && env.VERCEL_ENV !== 'development') ||
|
|
16
|
+
(env.VERCEL_TARGET_ENV && env.VERCEL_TARGET_ENV !== 'development') ||
|
|
17
|
+
Object.keys(env).some(name => name.startsWith('RAILWAY_') && env[name])) return false;
|
|
18
|
+
try {
|
|
19
|
+
const url = new URL(env.FUNFAB_GAME_ORIGIN);
|
|
20
|
+
return ['http:', 'https:'].includes(url.protocol) && url.origin === env.FUNFAB_GAME_ORIGIN &&
|
|
21
|
+
['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
22
|
+
} catch { return false; }
|
|
23
|
+
}
|
|
24
|
+
|
|
12
25
|
// Shared server configuration. Runtime adapters add only their own routing/storage settings.
|
|
13
26
|
export function signInTicketConfig(env = process.env) {
|
|
14
27
|
if (!env.FUNFAB_GAME_ID) {
|
|
15
|
-
if (env
|
|
28
|
+
if (!localBypass(env)) throw fail('invalid_gate_configuration');
|
|
29
|
+
console.warn('FUNFAB_ACCESS_DISABLED_LOCAL: FunFab admission disabled for local development');
|
|
16
30
|
return null;
|
|
17
31
|
}
|
|
18
32
|
const c = { gameId: env.FUNFAB_GAME_ID, environment: env.FUNFAB_ENVIRONMENT, origin: env.FUNFAB_GAME_ORIGIN, issuer: env.FUNFAB_AUTH_ISSUER, clientId: env.FUNFAB_CLIENT_ID, accountOrigin: env.FUNFAB_ACCOUNT_ORIGIN, ticketApiOrigin: env.FUNFAB_SIGN_IN_TICKET_API_ORIGIN, credential: env.FUNFAB_SIGN_IN_TICKET_CREDENTIAL };
|
|
19
33
|
try {
|
|
20
|
-
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(c.gameId || '') || !['preview','production'].includes(c.environment) || !
|
|
34
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(c.gameId || '') || !['preview','production'].includes(c.environment) || !isUuid(c.clientId) || !/^fgc_[A-Za-z0-9_-]+$/.test(c.credential || '')) throw Error();
|
|
21
35
|
for (const key of ['origin','issuer','accountOrigin','ticketApiOrigin']) {
|
|
22
36
|
const u = new URL(c[key]);
|
|
23
37
|
if (u.protocol !== 'https:' || u.username || u.password || u.search || u.hash || (key !== 'issuer' && u.origin !== c[key])) throw Error();
|
|
@@ -78,7 +92,7 @@ export async function createSignInTicketClient(config, { transport = globalThis.
|
|
|
78
92
|
const as = await discover();
|
|
79
93
|
const params = oauth.validateAuthResponse(as, client, url, pending.state);
|
|
80
94
|
const data = await call('exchange', {code:params.get('code'),verifier:pending.verifier,redirectUri});
|
|
81
|
-
if (!isSignInTicket(data.ticket) || !
|
|
95
|
+
if (!isSignInTicket(data.ticket) || !isUuid(data.accountId) || typeof data.displayState !== 'string') throw fail('temporary_unavailable');
|
|
82
96
|
return {ticket:data.ticket,accountId:data.accountId,displayState:data.displayState};
|
|
83
97
|
},
|
|
84
98
|
status: ticket => ticketCall('status',ticket),
|