Embed mode, launch tokens, and message bridge
Embed BetPlug's vector-only game clients (<= 150 KB gzip combined first load, zero raster assets, self-hosted fonts, strict nonce CSP & Trusted Types) using either the <betrail-game> Web Component on your own origin (Option A) or the isolated play. iframe host (Option B).
1. Backend launch (POST /v1/launch)#
Your backend signs POST /v1/launch (launch:write scope, betrail-v1 + Idempotency-Key) and passes the single-use token (60 s TTL) or url to the browser:
curl -sS -X POST "https://api.betrail.example/v1/launch" \
-H "Authorization: Bearer $BETRAIL_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: idem_00000001" \
-H "Betrail-Timestamp: 1793232000" \
-H "Betrail-Nonce: n_launch_attempt_0001" \
-H "Betrail-Signature: v1=<64-hex-hmac-sha256>" \
-d '{"game":"dice","brand":"br_sandbox","player_ref":"p_demo_01","currency":"BTC","mode":"real","locale":"en","return_url":"https://casino.example/lobby"}'{
"token": "example_single_use_launch_token_0001",
"url": "https://play.betrail.example/dice?token=example_single_use_launch_token_0001",
"expires_at": "2026-10-29T01:46:00Z"
}How the browser completes session bootstrap:
- The client exchanges the 60-second single-use
tokenonce atPOST /v1/sessionsfor an in-memory session (bts_<token>, max 8 h, 900 s idle timeout) and strips?token=fromlocationimmediately (history.).replaceState - Subsequent
/v1/session/*and/v1/live/*requests sendAuthorization: Bearer bts_<token>and are checked against your brand'sallowed_origins(403 origin_not_allowedon mismatch;Origin: nullis always refused). - For unauthenticated previews on BetPlug's own site origins,
POST /v1/demo/sessionsopens aFUN-currency demo session for Instant, Stateful, and Slot games; live clients ask for no demo session.
Security: Never log
tokenorurlin access logs, analytics, or referrer headers, and never storebts_<token>inlocalStorage,sessionStorage, or cookies.
2. Option A: <betrail-game> Web Component#
Load the shared @betrail/runtime module and the target @betrail/ bundle from your static origin with SHA-384 Subresource Integrity (manifest.json), then mount <betrail-game>:
<script
type="module"
src="/betrail-assets/runtime/v0.1.0/betrail-runtime.js"
integrity="sha384-EXAMPLE_RUNTIME_SRI_FROM_MANIFEST_JSON_0000000000000000000000000"
></script>
<script
type="module"
src="/betrail-assets/games/dice/v0.1.0/betrail-dice.js"
integrity="sha384-EXAMPLE_DICE_SRI_FROM_MANIFEST_JSON_0000000000000000000000000"
></script>
<betrail-game
game="dice"
api-base="https://api.betrail.example"
token="EXAMPLE_launch_token_0000000000000000000000"
></betrail-game>api-base: When omitted,<betrail-game>calls the host page's own origin. Whenever your casino origin differs from the BetPlug API (for examplehttp://127.0.0.1:vs3000 http://127.0.0.1:, or8080 https://casino.vsexample https://api.), passbetrail. example api-base=(or call"https://api. betrail. example" await el.), allow that API origin in yourbootstrapLaunchToken(launchToken, apiBase) connect-src, and register your casino origin viaPUT /console/(Getting started).brands/ {brand}/ origins/ {environment} live-origin(live games only): Fortrapdoor,kombat-multiplayer,stack-o-pass,crash, andmeme-trade, also setlive-origin=(canonical"wss://live. betrail. example" wss://, or loopbackws://in local dev) and add it to your page'sconnect-src.- Host events without an iframe: Call
el.to receive the exactconnectHostBridge({ allowedOrigins: [location.origin], targetWindow: { postMessage(message) { ... } } }) betrail:v1event envelopes in-page.
3. Option B: Isolated play host iframe#
Mount url returned by POST /v1/launch inside a sandboxed <iframe>:
<iframe
id="betrail-frame"
src="https://play.betrail.example/dice?token=EXAMPLE_launch_token_0000000000000000000000"
title="BetPlug DICE"
allow="autoplay"
sandbox="allow-scripts allow-same-origin allow-top-navigation-by-user-activation"
></iframe>- Lobby navigation (
return_url): Includeallow-top-navigation-by-user-activationwhen passingreturn_urltoPOST /v1/launch; omit it if your host page renders its own lobby chrome. - Play host deployment (
BETRAIL_PLAY_ORIGIN/BETRAIL_PLAY_LISTEN):POST /v1/launchbuildsurlfromBETRAIL_PLAY_ORIGIN(defaulthttps://play.).betrail. example/ <slug>?token= … - The public API listener (
:8080) serves no HTML; enable the dedicated play host listener by settingBETRAIL_PLAY_LISTEN,BETRAIL_PLAY_ASSETS_DIR(output ofbetrail-clients build --out <dir>), andBETRAIL_PLAY_API_ORIGIN(defaulthttp://127.0.0.1:locally). Every module's SHA-384 digest is verified against8080 manifest.jsonat startup. - On each page load, the play host inspects the launch without consuming it and emits
frame-ancestorsrestricted to that brand environment'sallowed_origins. Unknown, expired, or already-exchanged tokens, mismatched routes, or brands without origins receive a plain-text refusal withframe-ancestors 'none'. - Plain
http://is refused (400, no redirect so?token=is never echoed) outside loopback local dev (BETRAIL_ENV=ordevelopment test) or proxies inBETRAIL_TRUSTED_PROXIESwith everyX-Forwarded-Protohop equal tohttps. Non-canonical paths (//dice,/x/../dice) return404with no redirect. - Valkey rate limits page loads (
BETRAIL_,PLAY_ ADDRESS_ PER_ SECOND= 50 BETRAIL_), returningPLAY_ GLOBAL_ PER_ SECOND= 5000 429+Retry-Afterbefore reading the launch. - Locally, run
BETRAIL_withPLAY_ LISTEN= 127.0.0.1: 8084 BETRAIL_PLAY_ORIGIN=, mounthttp://127.0.0.1: 8084 <betrail-game api-base=directly (Option A), or serve"http://127.0.0.1: 8080"> renderPlayHostDocumentfrom@betrail/runtimedirectly (byte-identical to the server play host, as shown in./examples/).next-casino
4. Building & hosting client bundles#
Tip: All
@betrail/client bundles are built directly from your verified repository checkout with zero external dependencies (Nodegame-<slug> >= 22.18).
betrail-clients build --out ./public/betrail-assetsThe build enforces the <= 150 KB gzipped combined first-load budget (maxGameGzipBytes: 153600) and emits versioned ES modules plus manifest.json:
/runtime/— sharedv0.1.0/ betrail-runtime. js @betrail/runtimemodule registering<betrail-game>./embed/— host-page bridge helper (v0.1.0/ betrail-embed. js createBetrailEmbed,validateBridgeEvent,validateBridgeCommand,betrail:v1constants) for Option B iframes (not loaded by game bundles)./games/— one zero-raster game plugin bundle per catalog game keyed by canonical OpenAPI<slug>/v0.1.0/ betrail-<slug>.js GameSlug(for exampledice,limbo,packs,plinko,roulette,diamonds,grimoire-of-gains,pharaoh-pump,shogun-shiba). Preserve the/runtime/v0.1.0/…and/games/relative tree so game bundles resolve<slug>/v0.1.0/ … ../../../runtime/.v0.1.0/ betrail-runtime. js manifest.json—{ version: "0.1.0", maxGameGzipBytes: 153600, runtime, embed, games }with exactpath,bytes,gzipBytes, andintegrity: "sha384-…". Read integrity hashes dynamically at render time.
5. Live demo (mode="demo") & replay (mode="replay")#
- Simulated live demo (
mode="demo"): For live clients (crash,kombat-multiplayer,meme-trade,trapdoor,stack-o-pass),<betrail-game mode="demo">needs no token: it runs a simulated show in the browser with a fakeDEMObalance under the badgeDEMO (simulated show). It opens no socket, places no bet, and creates no server record. Its verdict replays the simulated bet locally in the browser, never a server record, so both BetPlug's showcase and an operator's page may embed it. - No demo token or session on an operator's origin: Leave
tokenoff —POST /v1/launchwithmode: "demo"for a live game returns409 not_offered. The element asks for no demo session for a live client (it sends noPOST /v1/demo/sessions, which on an operator's origin would return403 origin_not_allowed), so the host bridge receives no error event. See Game catalog & live for each client's exact badge and verdict. - Settled round replay (
mode="replay"): Passmode="replay",token, andround-idto fetch one settled round's record and replay it visually without opening a live socket. A live show bet becomes readable once its show reveals its seed.
6. Typed postMessage host bridge (betrail:v1)#
Both directions share one strict envelope (@betrail/runtime). Messages with missing or extra keys, unknown channels, oversized payloads (> 8192 UTF-8 bytes, BRIDGE_), or event strings over 256 chars are dropped silently:
- Events, client -> your page:
{ channel: "betrail:v1", kind: "event", event, payload } - Commands, your page -> client:
{ channel: "betrail:v1", kind: "command", command, payload }
event | payload |
|---|---|
ready | { game: string, mode: "real" | "demo" | "replay", locale: string } |
balance | { balance: string, currency: string } |
round-start | { stake: string, currency: string } |
round-end | { roundId: string, payout: string, profit: string, win: boolean, currency: string } |
error | { code: string, message: string } |
resize | { width: number, height: number } |
command | payload |
|---|---|
setLocale | { locale: string }: one of en, es, pt-BR, de, fr, tr, ja, ko, ar, he |
setTheme | { theme: "dark" | "light" | ThemeOverride }: an override is at most 4096 bytes of JSON |
setSound | { enabled: boolean }: sound is off until you enable it |
Every amount (balance, stake, payout) is an exact decimal string; profit is signed payout - stake. Commands and resize coalesce to once per animation frame (last write wins). Breaking protocol revisions will ship on a new channel (betrail:v2); pin betrail:v1.
Origin locking with createBetrailEmbed#
Use /embed/ (loaded with manifest.) instead of raw window. boilerplate:
import { createBetrailEmbed } from "/betrail-assets/embed/v0.1.0/betrail-embed.js";
const embed = createBetrailEmbed({
frame: document.getElementById("betrail-frame") as HTMLIFrameElement,
playOrigin: "https://play.betrail.example",
onEvent(ev) {
if (ev.event === "balance") updateHeaderBalance(ev.payload.balance, ev.payload.currency);
if (ev.event === "resize") resizeFrame(ev.payload.height);
},
});
embed.send("setTheme", { theme: "dark" });
embed.send("setLocale", { locale: "pt-BR" });
// On unmount: embed.dispose();If handling message manually: verify both event.origin === "https://play. and event.source === iframe., and post commands with targetOrigin = "https://play. — never "*". When your brand has multiple configured origins, append &origin= to the iframe URL so the client locks onto your page immediately (otherwise it falls back to document.referrer or queues up to 32 events until your first command).
7. White-label theming & stored brand themes#
- Plan gating on the play host:
ThemeOverridefields (colors,radii,fontFamily, passed via?theme=orsetTheme) apply on the play host when your subscription includeswhite_label(GET /console/, Scale and Enterprise) and isbilling/ subscription activeorgrace. Otherwise the client applies mode ("dark"|"light") only and emits{ event: "error", payload: { code: "theme_not_in_plan", ... } }. Option A Web Components on your own origin accept every valid override. - Stored brand themes: Owners and Admins can save one default theme per brand across both environments via
PUT /console/(brands/ {brand}/ theme {"theme": ThemeOverride}, validated identically tosetTheme;GETreads,DELETEclears, passkey step-upbrand.theme.set/brand.theme.clear,403 forbiddenif the plan lackswhite_label). Per-session?theme=orsetThemeoverrides the stored theme for that session only.
8. CSP & Subresource Integrity checklist#
| Surface | Required CSP & security headers |
|---|---|
| Play host (Option B, automatic) | frame-ancestors <brand_origins>, connect-src <api_origin> [<live_ws_origin>], script-src 'nonce-…' 'strict-dynamic', require-trusted-types-for 'script'; trusted-types betrail, Referrer-Policy: no-referrer, Cache-Control: no-store, SHA-384 SRI on runtime & game modules. |
Casino page hosting <betrail-game> (Option A) | Load betrail-runtime.js and betrail-<slug>.js with integrity= from manifest.json; add BetPlug's API origin (and wss://live. for live games) to your connect-src; register your exact casino origin in Brand Allowed Origins. |
| Casino page framing play host (Option B) | Add https://play. to your page's frame-src; load betrail-embed.js with manifest.; never use targetOrigin: "*". |
9. Reality checks & jurisdictions#
- Jurisdiction policy (
403 jurisdiction_): Pass optional ISO 3166-1 alpha-2not_ allowed jurisdictiononPOST /v1/launch(or headlessPOST /v1/rounds). BetPlug enforces brand responsible-gaming jurisdiction blocks (sandbox&live) and operator platform live allowlists (liveonly) before consuming any nonce or calling your wallet. - Reality checks (
409 reality_check_due): When a brand enables periodic reality-check intervals in Console, wagers after the interval return409 reality_check_duewithelapsed_secondsandnet_resultin the RFC 9457Problembody. Embedded clients display the summary and callPOST /v1/(sessions/ current/ reality-check Idempotency-Keyrequired) once the player acknowledges, after which wagers resume normally.
Validating bridge messages & SRI digests (runnable sample)#
import assert from "node:assert/strict";
import crypto from "node:crypto";
const PLAY_ORIGIN = "https://play.betrail.example";
const AMOUNT_RE = /^(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$/;
const SIGNED_AMOUNT_RE = /^-?(0|[1-9][0-9]{0,29})(\.[0-9]{1,18})?$/;
type BetrailEvent =
| { event: "ready"; payload: { game: string; mode: "real" | "demo" | "replay"; locale: string } }
| { event: "balance"; payload: { balance: string; currency: string } }
| { event: "round-start"; payload: { stake: string; currency: string } }
| { event: "round-end"; payload: { roundId: string; payout: string; profit: string; win: boolean; currency: string } }
| { event: "error"; payload: { code: string; message: string } }
| { event: "resize"; payload: { width: number; height: number } };
function readBetrailEvent(ev: { origin: string; source: unknown; data: unknown }, frame: unknown): BetrailEvent | null {
if (ev.origin !== PLAY_ORIGIN || ev.source !== frame) return null;
const msg = ev.data as Record<string, unknown> | null;
if (!msg || typeof msg !== "object" || msg.channel !== "betrail:v1" || msg.kind !== "event") return null;
if (Object.keys(msg).some((k) => !["channel", "kind", "event", "payload"].includes(k))) return null;
const p = msg.payload as Record<string, unknown> | null;
if (!p || typeof p !== "object") return null;
const text = (k: string) => typeof p[k] === "string";
const amount = (k: string, re = AMOUNT_RE) => typeof p[k] === "string" && re.test(p[k] as string);
const ok =
(msg.event === "ready" && text("game") && ["real", "demo", "replay"].includes(p.mode as string) && text("locale")) ||
(msg.event === "balance" && amount("balance") && text("currency")) ||
(msg.event === "round-start" && amount("stake") && text("currency")) ||
(msg.event === "round-end" && text("roundId") && amount("payout") && amount("profit", SIGNED_AMOUNT_RE) && typeof p.win === "boolean" && text("currency")) ||
(msg.event === "error" && text("code") && text("message")) ||
(msg.event === "resize" && Number.isFinite(p.width) && Number.isFinite(p.height));
return ok ? ({ event: msg.event, payload: p } as BetrailEvent) : null;
}
const frame = { id: "betrail-frame" };
const validEnd = {
channel: "betrail:v1",
kind: "event",
event: "round-end",
payload: { roundId: "rnd_01JBX7Q2", payout: "0.00000000", profit: "-0.00100000", win: false, currency: "BTC" },
};
assert.ok(readBetrailEvent({ origin: PLAY_ORIGIN, source: frame, data: validEnd }, frame));
assert.equal(readBetrailEvent({ origin: "https://casino.example", source: frame, data: validEnd }, frame), null);
assert.equal(readBetrailEvent({ origin: PLAY_ORIGIN, source: {}, data: validEnd }, frame), null);
assert.equal(
readBetrailEvent({ origin: PLAY_ORIGIN, source: frame, data: { channel: "betrail:v1", kind: "event", event: "balance", payload: { balance: 0.1, currency: "BTC" } } }, frame),
null,
);
const sampleIntegrity = `sha384-${crypto.createHash("sha384").update("export {};\n", "utf8").digest("base64")}`;
assert.match(sampleIntegrity, /^sha384-[A-Za-z0-9+/]{64}$/);