@funfab/sdk 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Hidden names never take a public spot (owner decision C1, 2026-10-20).
3
+ *
4
+ * A viewer whose name the name filter hides (the board shows a placeholder: "a viewer", "alguém do chat") still plays
5
+ * and scores, but on every surface viewers see (leaderboards, podiums, "FIRST!" / "Closest" / winner call-outs, recap
6
+ * lines, shout-outs, tickers) they never take a spot:
7
+ *
8
+ * - Ranked rows skip them, and the next real name moves up. The number beside a row is still that player's TRUE
9
+ * rank among everyone who played, hidden players included (standard competition ranking: 1 + how many scored
10
+ * strictly more, so ties share a rank). A hidden player alone at the top leaves "2." on the top row; a hidden
11
+ * player tied 2nd leaves "1. análise, 2. kailol". Nobody is renumbered as if the hidden player didn't exist, and
12
+ * nobody is given a place they didn't earn. A podium is ranked rows too: its places fill with the next real names,
13
+ * each labelled with their true rank where the podium shows a number.
14
+ * - A call-out whose subject is hidden (the winner, the first, the closest) names nobody: the game says its own
15
+ * "Someone got it first!" line, never the placeholder and never the next real name (they weren't first).
16
+ * - Totals still count them ("97 of 158 typed it", "+90 more").
17
+ *
18
+ * The host panel is private to the streamer and may keep showing the placeholder.
19
+ *
20
+ * Pure ESM, no imports, no DOM: each game serves its own byte-identical copy (prototypes/stream-games.json `shared`,
21
+ * written by `npm run sync:live-chat`), and prototypes/live-chat/public-names.test.js pins it down.
22
+ *
23
+ * import { isPlaceholder, rankPublic, splitPublic, shownOrNull } from "./public-names.js";
24
+ * rankPublic(rows, { hidden: (r) => r.hidden, score: (r) => r.pts, limit: 5 }) // → public rows, each with rank, tied
25
+ * splitPublic(names, { hidden: isPlaceholder, max: 3 }) // → { shown: [...], more: N }
26
+ * shownOrNull(result.first, (p) => p.hidden) // → the first, or null: name nobody
27
+ */
28
+
29
+ /** Every placeholder a board draws for a hidden name, lower-cased: the filter's English one and the boards' own
30
+ * translations (dial/lang, pop-words/lang). A real viewer can't be called this on TikTok or Twitch (no spaces in a
31
+ * handle); a nickname that is ("a viewer") is treated as hidden, which only ever keeps a name off the board. */
32
+ export const PLACEHOLDERS = ["a viewer", "alguém do chat", "alguien del chat", "alguém", "alguien"];
33
+ const SET = new Set(PLACEHOLDERS);
34
+
35
+ /** True when `name` is a placeholder the board shows for a hidden name (or empty: no name to show). */
36
+ export function isPlaceholder(name) {
37
+ const n = String(name ?? "").normalize("NFKC").trim().toLowerCase();
38
+ return !n || SET.has(n);
39
+ }
40
+
41
+ const byName = (r) => isPlaceholder(r && typeof r === "object" ? r.name : r);
42
+
43
+ /**
44
+ * Ranked rows for a public board. `rows`: every player, already in the game's order (best first, the game's own
45
+ * tie-breaks applied). Returns the rows whose name isn't hidden, at most `limit`, each copied with:
46
+ * rank: the true rank among ALL rows, hidden ones included. With `score`, ties on it share a rank (1, 2, 2, 4);
47
+ * with `score: null`, the rank is the row's position in the full list (1, 2, 3, 4).
48
+ * tied: another row (hidden or not) has the same score.
49
+ * `hidden(row)`: is this row's name hidden? Default: its `name` is a placeholder.
50
+ */
51
+ export function rankPublic(rows, { hidden = byName, score = (r) => r.pts, limit = Infinity } = {}) {
52
+ const all = Array.from(rows || []);
53
+ const out = [];
54
+ if (score === null) {
55
+ for (let i = 0; i < all.length && out.length < limit; i++) if (!hidden(all[i])) out.push({ ...all[i], rank: i + 1, tied: false });
56
+ return out;
57
+ }
58
+ const scores = all.map((r) => Number(score(r)) || 0);
59
+ const count = new Map();
60
+ for (const s of scores) count.set(s, (count.get(s) || 0) + 1);
61
+ for (let i = 0; i < all.length && out.length < limit; i++) {
62
+ if (hidden(all[i])) continue;
63
+ const s = scores[i];
64
+ let above = 0;
65
+ for (const t of scores) if (t > s) above++;
66
+ out.push({ ...all[i], rank: above + 1, tied: count.get(s) > 1 });
67
+ }
68
+ return out;
69
+ }
70
+
71
+ /**
72
+ * A list of names (or rows) for a public line: the ones that aren't hidden, at most `max`, and `more`, how many of
73
+ * the whole list weren't shown (hidden ones included), for "+N more". `shown` keeps the list's order.
74
+ */
75
+ export function splitPublic(list, { hidden = byName, max = Infinity } = {}) {
76
+ const all = Array.from(list || []);
77
+ const shown = [];
78
+ for (const x of all) { if (shown.length >= max) break; if (!hidden(x)) shown.push(x); }
79
+ return { shown, more: all.length - shown.length };
80
+ }
81
+
82
+ /** The subject of a call-out (a winner, the first, the closest), or null when there is none or their name is hidden:
83
+ * then the board names nobody personally. Never fall through to the next name: they weren't first. */
84
+ export function shownOrNull(entry, hidden = byName) {
85
+ return entry == null || hidden(entry) ? null : entry;
86
+ }
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ // Public package root. Select an explicit entry point for runtime functionality.
2
+ export {};
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@funfab/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "description": "Add FunFab sign-in and host safety to your game.",
6
+ "engines": {
7
+ "node": ">=22"
8
+ },
9
+ "exports": {
10
+ ".": "./index.js",
11
+ "./server": "./server.mjs",
12
+ "./adapters/stream": "./adapters/stream.mjs",
13
+ "./adapters/vercel": "./adapters/vercel.mjs",
14
+ "./adapters/party": "./adapters/party.mjs",
15
+ "./browser": "./browser.js",
16
+ "./host-safety": "./host-safety/index.js",
17
+ "./schemas/host-safety": "./schemas/host-safety.schema.json"
18
+ },
19
+ "files": [
20
+ "index.js",
21
+ "server.mjs",
22
+ "adapters/stream.mjs",
23
+ "adapters/vercel.mjs",
24
+ "adapters/party.mjs",
25
+ "browser.js",
26
+ "host-safety/index.js",
27
+ "host-safety/name-filter.js",
28
+ "host-safety/public-names.js",
29
+ "schemas/host-safety.schema.json",
30
+ "README.md"
31
+ ],
32
+ "dependencies": {
33
+ "oauth4webapi": "^3.8.8",
34
+ "jose": "^6.2.12"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public",
38
+ "provenance": false
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/Everyone-Loves-Beacon/funfab-website.git",
43
+ "directory": "packages/sdk"
44
+ }
45
+ }
@@ -0,0 +1,69 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://funfab.io/schemas/host-safety-result-v1.json",
4
+ "title": "Game-owned LIVE host-safety result",
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "required": [
8
+ "schemaVersion",
9
+ "gameId",
10
+ "build",
11
+ "checkVersion",
12
+ "result",
13
+ "surfaces"
14
+ ],
15
+ "properties": {
16
+ "schemaVersion": {
17
+ "const": 1
18
+ },
19
+ "gameId": {
20
+ "type": "string",
21
+ "minLength": 1,
22
+ "maxLength": 1000
23
+ },
24
+ "build": {
25
+ "type": "string",
26
+ "minLength": 1,
27
+ "maxLength": 1000
28
+ },
29
+ "checkVersion": {
30
+ "type": "string",
31
+ "minLength": 1,
32
+ "maxLength": 100
33
+ },
34
+ "result": {
35
+ "enum": [
36
+ "pass",
37
+ "fail"
38
+ ]
39
+ },
40
+ "surfaces": {
41
+ "type": "array",
42
+ "minItems": 1,
43
+ "uniqueItems": true,
44
+ "description": "Each inspected surface appears once by surface name. Passing requires both controls true on every surface.",
45
+ "items": {
46
+ "type": "object",
47
+ "additionalProperties": false,
48
+ "required": [
49
+ "surface",
50
+ "nameFiltering",
51
+ "viewerBlocks"
52
+ ],
53
+ "properties": {
54
+ "surface": {
55
+ "type": "string",
56
+ "minLength": 1,
57
+ "maxLength": 100
58
+ },
59
+ "nameFiltering": {
60
+ "type": "boolean"
61
+ },
62
+ "viewerBlocks": {
63
+ "type": "boolean"
64
+ }
65
+ }
66
+ }
67
+ }
68
+ }
69
+ }
package/server.mjs ADDED
@@ -0,0 +1,89 @@
1
+ import * as oauth from 'oauth4webapi';
2
+
3
+ // Protocol bridge: the platform rename changes this one constant (#368).
4
+ const PLATFORM_ROUTE_PREFIX = '/api/sign-in-ticket';
5
+ export const SIGN_IN_TICKET_PREFIX = 'fst_';
6
+ export const isSignInTicket = value => typeof value === 'string' && value.startsWith(SIGN_IN_TICKET_PREFIX) &&
7
+ /^[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
+ export const ticketOperationUrl = (config, operation) => `${config.ticketApiOrigin}${PLATFORM_ROUTE_PREFIX}/${operation}`;
11
+
12
+ // Shared server configuration. Runtime adapters add only their own routing/storage settings.
13
+ export function signInTicketConfig(env = process.env) {
14
+ if (!env.FUNFAB_GAME_ID) {
15
+ if (env.FUNFAB_ACCESS_REQUIRED === '1') throw fail('invalid_gate_configuration');
16
+ return null;
17
+ }
18
+ 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
+ try {
20
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(c.gameId || '') || !['preview','production'].includes(c.environment) || !uuid(c.clientId) || !/^fgc_[A-Za-z0-9_-]+$/.test(c.credential || '')) throw Error();
21
+ for (const key of ['origin','issuer','accountOrigin','ticketApiOrigin']) {
22
+ const u = new URL(c[key]);
23
+ if (u.protocol !== 'https:' || u.username || u.password || u.search || u.hash || (key !== 'issuer' && u.origin !== c[key])) throw Error();
24
+ }
25
+ } catch { throw fail('invalid_gate_configuration'); }
26
+ return Object.freeze(c);
27
+ }
28
+
29
+ export async function createSignInTicketClient(config, { transport = globalThis.fetch } = {}) {
30
+ const client = { client_id: config.clientId };
31
+ // Discovery stays lazy: a temporary discovery outage must not prevent server startup.
32
+ let metadata;
33
+ async function discover() {
34
+ if (metadata) return metadata;
35
+ const issuer = new URL(config.issuer);
36
+ try {
37
+ const response = await oauth.discoveryRequest(issuer, { [oauth.customFetch]: transport, signal: AbortSignal.timeout(8000) });
38
+ metadata = await oauth.processDiscoveryResponse(issuer, response);
39
+ return metadata;
40
+ } catch { throw fail('temporary_unavailable'); }
41
+ }
42
+ async function call(operation, body) {
43
+ let response, data;
44
+ try {
45
+ response = await transport(ticketOperationUrl(config, operation), { method:'POST', headers:{ authorization:`Bearer ${config.credential}`, 'content-type':'application/json' }, body:JSON.stringify({game:config.gameId,...body}), redirect:'error', signal:AbortSignal.timeout(8000) });
46
+ } catch { throw fail('temporary_unavailable'); }
47
+ if (response.status === 429 || response.status >= 500) throw fail('temporary_unavailable');
48
+ try { data = await response.json(); } catch { throw fail('temporary_unavailable'); }
49
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw fail('temporary_unavailable');
50
+ if (response.status === 401 && data.error === 'authorization_required') throw fail('authorization_required');
51
+ if (response.status === 403 && data.error === 'consumer_session_invalid') throw fail('authorization_required');
52
+ if (response.status === 403 && typeof data.error === 'string' && /^(?:(?:consumer|game)_[a-z_]{1,64}|account_not_eligible)$/.test(data.error)) throw fail('game_access_denied');
53
+ if (!response.ok) throw fail('temporary_unavailable');
54
+ return data;
55
+ }
56
+ const ticketCall = async (operation, ticket, extra = {}) => {
57
+ // Wire names and the platform's existing opaque prefix are confined to this bridge.
58
+ if (!isSignInTicket(ticket)) throw fail('authorization_required');
59
+ return call(operation, {ticket,...extra});
60
+ };
61
+ const callback = () => {
62
+ try {
63
+ const url = new URL(config.callback);
64
+ if (url.protocol !== 'https:' || url.origin !== config.origin || url.username || url.password || url.search || url.hash) throw Error();
65
+ return url.href;
66
+ } catch { throw fail('invalid_gate_configuration'); }
67
+ };
68
+ return Object.freeze({
69
+ async begin() {
70
+ const redirectUri = callback();
71
+ const as = await discover(), verifier = oauth.generateRandomCodeVerifier(), state = oauth.generateRandomState();
72
+ const url = new URL(as.authorization_endpoint);
73
+ url.search = new URLSearchParams({ client_id:config.clientId, redirect_uri:redirectUri, response_type:'code', scope:'openid offline_access', state, code_challenge:await oauth.calculatePKCECodeChallenge(verifier), code_challenge_method:'S256' }).toString();
74
+ return { verifier, state, url:url.href };
75
+ },
76
+ async complete(url, pending) {
77
+ const redirectUri = callback();
78
+ const as = await discover();
79
+ const params = oauth.validateAuthResponse(as, client, url, pending.state);
80
+ const data = await call('exchange', {code:params.get('code'),verifier:pending.verifier,redirectUri});
81
+ if (!isSignInTicket(data.ticket) || !uuid(data.accountId) || typeof data.displayState !== 'string') throw fail('temporary_unavailable');
82
+ return {ticket:data.ticket,accountId:data.accountId,displayState:data.displayState};
83
+ },
84
+ status: ticket => ticketCall('status',ticket),
85
+ policy: ticket => ticketCall('policy',ticket),
86
+ room: (ticket,roomRequestId) => ticketCall('room',ticket,{roomRequestId}),
87
+ signout: ticket => ticketCall('signout',ticket),
88
+ });
89
+ }