Skip to content
BetPlugDocs
DocsIntegration
View .md twin

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.betrail.example 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
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"}'
201 Response
{
  "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:

  1. The client exchanges the 60-second single-use token once at POST /v1/sessions for an in-memory session (bts_<token>, max 8 h, 900 s idle timeout) and strips ?token= from location immediately (history.replaceState).
  2. Subsequent /v1/session/* and /v1/live/* requests send Authorization: Bearer bts_<token> and are checked against your brand's allowed_origins (403 origin_not_allowed on mismatch; Origin: null is always refused).
  3. For unauthenticated previews on BetPlug's own site origins, POST /v1/demo/sessions opens a FUN-currency demo session for Instant, Stateful, and Slot games; live clients ask for no demo session.

Security: Never log token or url in access logs, analytics, or referrer headers, and never store bts_<token> in localStorage, sessionStorage, or cookies.

2. Option A: <betrail-game> Web Component#

Load the shared @betrail/runtime module and the target @betrail/game-<slug> bundle from your static origin with SHA-384 Subresource Integrity (manifest.json), then mount <betrail-game>:

HTML
<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 example http://127.0.0.1:3000 vs http://127.0.0.1:8080, or https://casino.example vs https://api.betrail.example), pass api-base="https://api.betrail.example" (or call await el.bootstrapLaunchToken(launchToken, apiBase)), allow that API origin in your connect-src, and register your casino origin via PUT /console/brands/{brand}/origins/{environment} (Getting started).
  • live-origin (live games only): For trapdoor, kombat-multiplayer, stack-o-pass, crash, and meme-trade, also set live-origin="wss://live.betrail.example" (canonical wss://, or loopback ws:// in local dev) and add it to your page's connect-src.
  • Host events without an iframe: Call el.connectHostBridge({ allowedOrigins: [location.origin], targetWindow: { postMessage(message) { ... } } }) to receive the exact betrail:v1 event envelopes in-page.

3. Option B: Isolated play host iframe#

Mount url returned by POST /v1/launch inside a sandboxed <iframe>:

HTML
<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): Include allow-top-navigation-by-user-activation when passing return_url to POST /v1/launch; omit it if your host page renders its own lobby chrome.
  • Play host deployment (BETRAIL_PLAY_ORIGIN / BETRAIL_PLAY_LISTEN):
    • POST /v1/launch builds url from BETRAIL_PLAY_ORIGIN (default https://play.betrail.example/<slug>?token=…).
    • The public API listener (:8080) serves no HTML; enable the dedicated play host listener by setting BETRAIL_PLAY_LISTEN, BETRAIL_PLAY_ASSETS_DIR (output of betrail-clients build --out <dir>), and BETRAIL_PLAY_API_ORIGIN (default http://127.0.0.1:8080 locally). Every module's SHA-384 digest is verified against manifest.json at startup.
    • On each page load, the play host inspects the launch without consuming it and emits frame-ancestors restricted to that brand environment's allowed_origins. Unknown, expired, or already-exchanged tokens, mismatched routes, or brands without origins receive a plain-text refusal with frame-ancestors 'none'.
    • Plain http:// is refused (400, no redirect so ?token= is never echoed) outside loopback local dev (BETRAIL_ENV=development or test) or proxies in BETRAIL_TRUSTED_PROXIES with every X-Forwarded-Proto hop equal to https. Non-canonical paths (//dice, /x/../dice) return 404 with no redirect.
    • Valkey rate limits page loads (BETRAIL_PLAY_ADDRESS_PER_SECOND=50, BETRAIL_PLAY_GLOBAL_PER_SECOND=5000), returning 429 + Retry-After before reading the launch.
    • Locally, run BETRAIL_PLAY_LISTEN=127.0.0.1:8084 with BETRAIL_PLAY_ORIGIN=http://127.0.0.1:8084, mount <betrail-game api-base="http://127.0.0.1:8080"> directly (Option A), or serve renderPlayHostDocument from @betrail/runtime directly (byte-identical to the server play host, as shown in ./examples/next-casino).

4. Building & hosting client bundles#

Tip: All @betrail/game-<slug> client bundles are built directly from your verified repository checkout with zero external dependencies (Node >= 22.18).

Shell
betrail-clients build --out ./public/betrail-assets

The build enforces the <= 150 KB gzipped combined first-load budget (maxGameGzipBytes: 153600) and emits versioned ES modules plus manifest.json:

  • /runtime/v0.1.0/betrail-runtime.js — shared @betrail/runtime module registering <betrail-game>.
  • /embed/v0.1.0/betrail-embed.js — host-page bridge helper (createBetrailEmbed, validateBridgeEvent, validateBridgeCommand, betrail:v1 constants) for Option B iframes (not loaded by game bundles).
  • /games/<slug>/v0.1.0/betrail-<slug>.js — one zero-raster game plugin bundle per catalog game keyed by canonical OpenAPI GameSlug (for example dice, limbo, packs, plinko, roulette, diamonds, grimoire-of-gains, pharaoh-pump, shogun-shiba). Preserve the /runtime/v0.1.0/… and /games/<slug>/v0.1.0/… relative tree so game bundles resolve ../../../runtime/v0.1.0/betrail-runtime.js.
  • manifest.json — { version: "0.1.0", maxGameGzipBytes: 153600, runtime, embed, games } with exact path, bytes, gzipBytes, and integrity: "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 fake DEMO balance under the badge DEMO (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 token off — POST /v1/launch with mode: "demo" for a live game returns 409 not_offered. The element asks for no demo session for a live client (it sends no POST /v1/demo/sessions, which on an operator's origin would return 403 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"): Pass mode="replay", token, and round-id to 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_MAX_MESSAGE_BYTES), 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 }
eventpayload
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 }
commandpayload
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/v0.1.0/betrail-embed.js (loaded with manifest.embed.integrity) instead of raw window.addEventListener("message") boilerplate:

TypeScript
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.betrail.example" and event.source === iframe.contentWindow, and post commands with targetOrigin = "https://play.betrail.example" — never "*". When your brand has multiple configured origins, append &origin=<your_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: ThemeOverride fields (colors, radii, fontFamily, passed via ?theme= or setTheme) apply on the play host when your subscription includes white_label (GET /console/billing/subscription, Scale and Enterprise) and is active or grace. 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 to setTheme; GET reads, DELETE clears, passkey step-up brand.theme.set / brand.theme.clear, 403 forbidden if the plan lacks white_label). Per-session ?theme= or setTheme overrides the stored theme for that session only.

8. CSP & Subresource Integrity checklist#

SurfaceRequired 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="sha384-…" from manifest.json; add BetPlug's API origin (and wss://live.betrail.example 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.betrail.example to your page's frame-src; load betrail-embed.js with manifest.embed.integrity; never use targetOrigin: "*".

9. Reality checks & jurisdictions#

  • Jurisdiction policy (403 jurisdiction_not_allowed): Pass optional ISO 3166-1 alpha-2 jurisdiction on POST /v1/launch (or headless POST /v1/rounds). BetPlug enforces brand responsible-gaming jurisdiction blocks (sandbox & live) and operator platform live allowlists (live only) 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 return 409 reality_check_due with elapsed_seconds and net_result in the RFC 9457 Problem body. Embedded clients display the summary and call POST /v1/sessions/current/reality-check (Idempotency-Key required) once the player acknowledges, after which wagers resume normally.

Validating bridge messages & SRI digests (runnable sample)#

TypeScript
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}$/);
Enter to openEsc to close