Getting started: credentials, brand configuration & local stack
This guide takes you from a fresh BetPlug checkout to a running local stack, a provisioned sandbox brand (br_…) with one-time btr_test_<key> credentials, configured seamless-wallet / origin / webhook endpoints, and production deployment readiness.
5-minute happy path#
- Start infrastructure & migrate —
sh scripts/dev.sh upandbetrailctl migrate up. - Generate local
.envsecrets & launch services —betrail-api(:8080/:8082/:8083),betrail-worker, andbetrail-console(:3002). - Clear Valkey's 330-second post-start epoch — send one Console signup so
betrail:epochis stamped on a brand-new Valkey container, then wait330 sonce. - Onboard in Console — verify email via Mailpit (
http://127.0.0.1:), enroll Passkey or TOTP at8025 /security?onboarding=, bootstrap your operator & brand, and copy your one-time1 btr_test_<key>+signing_secret. - Play or wire your casino — call
POST /v1/roundsimmediately, or configure your seamless wallet (/wallet), allowed origins (/wallet), and webhooks (/webhooks).
Part A: Local development stack#
1. Start infrastructure & apply migrations#
Start PostgreSQL (127.0.0.1:5432), Valkey (127.0.0.1:6379), and Mailpit (127.0.0.1:1025 SMTP / http://127.0.0.1: web inbox), then apply SQL migrations:
sh scripts/dev.sh up
BETRAIL_MIGRATE_DATABASE_URL="postgres://betrail:[email protected]:5432/betrail?sslmode=disable" \
betrailctl migrate upCopy .env.example to a git-ignored .env (chmod 0600 .env) and generate 32-byte random secrets (node -e 'console.):
| Variable | Local development value | Purpose |
|---|---|---|
BETRAIL_ENV | development | Enables local development mode. Unset or any value outside development / test enforces strict production startup guards. |
BETRAIL_DATABASE_URL | postgres://betrail: | Database pool for the API and worker (production separates betrail_app and betrail_worker roles; local mode logs a warning on the dev role). |
BETRAIL_VALKEY_URL | redis://127.0.0.1: | Nonce replay store, Valkey epoch (betrail:epoch), and rate limits. |
BETRAIL_SMTP_ADDR | 127.0.0.1:1025 | Sends Console sign-up, recovery, and worker credit-alert emails to Mailpit (http://127.0.0.1:). |
BETRAIL_SEED_KEK_ID / BETRAIL_SEED_KEK | dev-1 / <32 random bytes, base64url, no padding> | Local key-encryption key wrapping server seeds, wallet secrets, and webhook secrets (no default). |
BETRAIL_ | <32+ byte secret> | Shared betrail-v1 service HMAC secret between the Operator Console and the API's private 127.0.0.1:8082 listener. |
BETRAIL_CONSOLE_RP_ID / BETRAIL_CONSOLE_ORIGINS / BETRAIL_CONSOLE_URL | localhost / http://localhost: / http://localhost: | WebAuthn Relying Party ID and Console origin used in verification links. |
BETRAIL_ | http://127.0.0.1: | Points the API and worker at the built-in Sandbox Wallet listener (BETRAIL_) over plain HTTP. |
BETRAIL_ | 127.0.0.1: | Exact comma-separated address:port pairs (IP literals only, never hostnames) allowing the SSRF egress guard and Console /wallet + /webhooks validation to reach your local casino callbacks. |
Warning: Both a plain-HTTP
BETRAIL_and any non-emptySANDBOX_ WALLET_ ORIGIN BETRAIL_refuse startup immediately in the API, worker, and Console wheneverEGRESS_ LOCAL_ ALLOW BETRAIL_ENVis anything other thandevelopmentortest.
Aligned local development ports across all BetPlug web portals:
| Portal | Local URL | Purpose |
|---|---|---|
Marketing & game showcase (web/site) | http://127.0.0.1: | Public marketing site and live interactive game showcase |
Staff Admin (web/admin) | http://127.0.0.1: | Internal platform administration (private listener :8081) |
Operator Console (web/console) | http://localhost: | Operator onboarding, brands, keys, wallet, webhooks, insights, billing |
Developer Docs (web/docs) | http://127.0.0.1: | This documentation portal, .md twins, /llms*.txt, OpenAPI/AsyncAPI |
Fairness Verifier (web/verifier) | http://127.0.0.1: | Standalone offline browser round verifier |
Start the three core local processes in separate terminals with .env exported in every shell (set -a && . ./.env && set +a):
# Terminal 1: public API (:8080), private Console backend API (:8082), and Sandbox Wallet (:8083)
set -a && . ./.env && set +a && betrail-api
# Terminal 2: transactional outbox webhooks, wallet retries/sweeps, credit-alert emails, and analytics rollups
set -a && . ./.env && set +a && betrail-worker
# Terminal 3: operator Console UI on http://localhost:3002
set -a && . ./.env && set +a && BETRAIL_CONSOLE_PUBLIC_ORIGIN="http://localhost:3002" betrail-console
# Optional Terminal 4 (for live multiplayer shows & STACKOPASS tables):
# set -a && . ./.env && set +a && betrail-liveConfirm the API is listening:
curl -sS http://127.0.0.1:8080/healthz2. Valkey's 330-second post-start epoch#
Valkey runs strictly in memory with persistence disabled so lost state is always a clean empty restart. Because signed betrail-v1 requests accept Betrail-Timestamp within ±300 s plus 30 s of host-clock skew (330 seconds total), a brand-new Valkey cannot tell whether a nonce was spent immediately before restart:
- On the first nonce claim against an empty Valkey, the replay guard atomically writes
SET betrail:epoch <now> NX. - Every signed request with
Betrail-Timestamp <= betrail:epoch + 330is refused with401 unauthorized:- On
:8082Console backend API:"Service credential timestamp predates a Valkey restart; sign a fresh request." - On
:8080public/v1/*routes:"This request cannot be told from one sent before a restart: sign it again in a few minutes."
- On
- Local workflow: After starting a fresh Valkey container, submit one request (such as Console sign-up) so
betrail:epochis stamped, wait 330 seconds (5m30s), and retry. For the rest of that container's lifetime (sh scripts/dev.sh upkeeps the container alive), signed calls succeed immediately.
3. Obtain a brand ID and sandbox key pair#
Open http://localhost: and complete the four-step onboarding flow:
- Sign up (
POST /console/). Returns uniformauth/ signup 202(ConsoleNoticeAck, never disclosing whether an address already exists). Open Mailpit (http://127.0.0.1:) and follow8025 /verify-email?token=(… POST /console/).auth/ verify-email - Enroll MFA (
http://localhost:). After email verification,3002/ security?onboarding= 1 factor_requiredsessions redirect to/security?onboarding=. Register a Passkey (1 POST /console/->auth/ passkey/ register/ begin POST /console/,auth/ passkey/ register/ finish 201;http://localhost:matches3002 BETRAIL_, with passkey-only MFA enforced by default in production) or enroll a 6-digit TOTP authenticator (CONSOLE_ RP_ ID= localhost POST /console/->auth/ totp/ enroll/ begin POST /console/,auth/ totp/ enroll/ finish 200). - Bootstrap operator & brand (
POST /console/). Supply anonboarding/ bootstrap Idempotency-Keyand{ "operator_name", "brand_name", "currency"? }(default"BTC"; unknown fields fail with400 invalid_request). Save the returned brand ID (br_…) asBETRAIL_BRAND_ID. - Mint your one-time sandbox API key (
POST /console/). Returnsbrands/ {brand}/ sandbox-keys api_key(btr_test_<key>) andsigning_secret(>= 32bytes) once withCache-Control: no-store. Save them in a git-ignored0600.env.local:
BETRAIL_API_BASE_URL=http://127.0.0.1:8080
BETRAIL_BRAND_ID=br_01jbx...
BETRAIL_API_KEY=btr_test_<key>
BETRAIL_SIGNING_SECRET=<one-time-signing-secret>4. Configure brand wallet, allowed origins, webhooks & launch tester#
Headless rounds (POST /v1/rounds) settle against your own ledger and never call an external wallet. For embedded/seamless sessions (POST /v1/launch -> /v1/), new sandbox brands start wired to the built-in Sandbox Wallet (BETRAIL_): POST /console/ pre-seeds p_sandbox_demo with 1000.00000000 in the brand's default currency, and the Sandbox Wallet treats any unseen player_ref as "active" with "1000.00000000" starting balance.
When wiring your own casino server (for example on http://127.0.0.1: with BETRAIL_), configure your brand in the Console UI (http://localhost:):
http://localhost:: Switch the sandbox wallet to your operator URL, copy the one-time3002/ wallet wallet_secret, register an optional RFC 8032 Ed25519 answer public key (answer_public_keyviaPUT /console/), run the 29-check wallet conformance tester, and savebrands/ {brand}/ wallet/ {environment}/ answer-key allowed_origins.http://localhost:: Mint or rotate the one-time3002/ webhooks signing_secret, enable your receiver URL and event subscriptions (round.settled,credits.low,credits.exhausted), send a test ping, and inspect delivery logs and health (GET /console/andwebhooks/ deliveries/ {id} GET /console/).brands/ {brand}/ webhooks/ {environment}/ health - Other Console screens: Credits & Top-Ups (
/topups&/money), passkey/TOTP & MCP OAuth grants (/security), analytics (/insights), go-live status (/go-live), and team/keys (/keys,/team). Complete reference casinos live in./examples/,next-casino ./examples/, andgo-casino ./examples/(Official SDKs).laravel-casino
Under the hood, /wallet and /webhooks call these Console backend API routes (api/console.yaml):
- Seamless wallet &
wallet_secret(POST /console/): Requiresbrands/ {brand}/ wallet/ {environment} Idempotency-Key. Send{ "target": "operator", "wallet_url": "http://127.0.0.1:(3000/ api/ wallet/ v1", "overlap_seconds": 0 } 0..86400during secret rotation, or{ "target": "sandbox_wallet" }onsandbox). Returns201(BrandWalletIssued) with one-timewallet_secret(BETRAIL_WALLET_SECRET; Seamless wallet protocol). - Allowed browser origins (
PUT /console/): Sendbrands/ {brand}/ origins/ {environment} { "allowed_origins": ["http://127.0.0.1:(3000"] } 200, up to64unique barescheme://host[:port]origins with lowercase ASCII host; explicit default ports:80onhttpand:443onhttpsare rejected with422 invalid_input;https://required onlive; never*or"null"). GovernsPOST /v1/launchreturn_url,/v1/session/*Originchecks (403 origin_not_allowed), iframeframe-ancestors, andbetrail:v1postMessageorigin locking (Embed & launch). - Webhook
signing_secret& endpoint (POST /console/thenbrands/ {brand}/ webhooks/ {environment}/ secret PUT /console/): Mint one-timebrands/ {brand}/ webhooks/ {environment} signing_secret(201WebhookSecretIssued,Idempotency-Key+{ "overlap_seconds": 0 }returning{ "signing_secret", "secret_overlap_until", "rotated_at" }), then enable delivery (200) with{ "url": "http://127.0.0.1:(Webhooks).3000/ api/ webhooks/ betrail", "enabled": true, "events": ["round.settled", "credits.low", "credits. exhausted"] } - Launch tester (
POST /console/): Requiresbrands/ {brand}/ launch-test/ {environment} Idempotency-Key. Dry-runsPOST /v1/launchagainst the brand environment's exact rules (200LaunchTestResult). Onsandbox, accepted non-live-show launches on a brand withallowed_originsalso return a one-time 60-second sandboxdemo(FUN)play_host_url(Cache-Control: no-store,409 secret_already_shownon replay). Onlive(owner/admin+launch_tester.livepasskey step-up), it runs dry-run validation only, writes zero session/ledger rows, calls no wallet, returnsplay_host_url: null, and notifies every Owner.
Security: Programmatic test harnesses that call
127.0.0.1:8082directly must sign every request withbetrail-v1underBETRAIL_and attachCONSOLE_ SERVICE_ SECRET Cookie: betrail_fromconsole= <session_ token> /console/auth/*. The Operator Console keeps raw session tokens out of browser JavaScript inside anHttpOnlycookie.
Part B: Production deployment, Console operations & going live#
5. Going live#
Tip: Once operator live play and a jurisdiction allowlist are active on your account (plus operator verification approval whenever
BETRAIL_), moving a brand fromKYB_ REQUIRED= true sandboxtoliveis self-serve once your production configuration passes validation: seamless wallet, allowed HTTPS origins, webhooks, live API key, active plan, and prepaid USD credits.
- Wallet (
/wallet): Pointliveat your productionhttps://seamless wallet URL (withwallet_secretand recommended Ed25519 answer public keys) and pass the automated 29-check wallet conformance tester (Seamless wallet protocol). - Allowed origins (
/wallet): Save your productionhttps://casino origins (PUT /console/).brands/ {brand}/ origins/ live - Webhooks (
/webhooks): Mint alivewebhooksigning_secretand enable your HTTPS receiver forround.settled,credits.low, andcredits.exhausted(Webhooks). - Credits (
/topups): Fund prepaid USD credits for live play (live rounds pause with402 credits_exhaustedonly if credits reach0; open rounds settle normally and sandbox remains active).
6. Production deployment settings (betrail-api, betrail-worker)#
Self-hosted production deployments control live-key issuance, compliance gating, SMTP credit alerts, and analytics rollup capacity with explicit fail-closed environment variables:
| Environment variable | Default | Behavior & fail-closed guarantees |
|---|---|---|
BETRAIL_KYB_REQUIRED | false | Controls whether operator verification approval is required before enabling live play, issuing live API keys, or activating live brands. Defaults to false (keeping dual-control live approvals and 29-check wallet conformance gates intact); set true to enforce prior approval. Any unrecognized non-empty value fails closed by enforcing operator verification approval (Required() == true) rather than halting startup. |
BETRAIL_ | false (off outside development) | Explicit production opt-in for live API key issuance outside BETRAIL_ENV=. Set BETRAIL_ when your production deployment is ready to issue live keys; unset or false fails closed. |
BETRAIL_SMTP_ADDR, BETRAIL_SMTP_FROM, BETRAIL_SMTP_HELO, BETRAIL_SMTP_USERNAME, BETRAIL_ | 127.0.0.1:1025 (dev) | Shared SMTP relay used by betrail-api (Console onboarding & notifications) and betrail-worker (credits.low / credits.exhausted operator emails). Mandatory STARTTLS (TLS 1.2+) with certificate hostname verification whenever dialing off loopback or whenever SMTP credentials are set (loopback included). BETRAIL_ must be owner-only (0600/0400, <= 4096 bytes, read once at startup). |
BETRAIL_ | 5 (2..16) | Dedicated PostgreSQL connection pool for betrail-worker Console analytics rollups (application_name = 'betrail-worker-rollup'), isolated from the worker's main pool so backfills never starve outbox money jobs or /readyz. Adds +5 PostgreSQL connections per worker replica by default; invalid non-blank values refuse startup in every environment. |
7. Console insights, delivery health & staff admin operations#
Operators monitor live health and revenue directly in BetPlug Console (backed by private api/console.yaml routes):
- Brand management: List, create, and rename brands (
GET /console/brands,POST /console/brands, andPUT /console/).brands/ {brand} - Console insights (
GET /console/): Aggregated handle, payouts, GGR (exact decimal strings), and basis-point rates (insights/ {environment} bp) fed by the worker rollup pool; returns503 stats_unavailablecleanly if a heavy query hits statement timeout. - Per-brand activity & player counts:
GET /console/andbrands/ {brand}/ activity/ {environment} GET /console/.brands/ {brand}/ player-counts/ {environment} - Webhook & wallet delivery health:
GET /console/andbrands/ {brand}/ webhooks/ {environment}/ health GET /console/surface recent success rates, latencies, and dead-letter counts.brands/ {brand}/ wallet/ {environment}/ delivery-health - Billing alert history & API usage:
GET /console/tracks unified webhook + SMTP email delivery state forbilling/ alerts/ history credits.lowandcredits.exhaustedalerts;GET /console/summarizes recent API volume.request-log/ {environment}/ usage
For self-hosted platform operators, the private Staff Admin API (:8081, guarded by BETRAIL_ADMIN_ALLOWLIST and WebAuthn passkeys) exposes platform summary & operator statistics (GET /admin/summary, GET /admin/statistics, GET /admin/), incident banner history (GET /admin/), and system health history (GET /admin/).
Validating allowed origins & Console request signing#
Use this helper to pre-validate allowed_origins before calling PUT /console/ and sign programmatic :8082 Console calls:
import assert from "node:assert/strict";
import crypto from "node:crypto";
function isValidAllowedOrigin(raw: string, env: "sandbox" | "live"): boolean {
if (raw === "*" || raw === "null") return false;
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
return false;
}
const schemeOk = env === "live" ? parsed.protocol === "https:" : parsed.protocol === "https:" || parsed.protocol === "http:";
if (!schemeOk || parsed.origin !== raw) return false;
if (raw.endsWith(":80") || raw.endsWith(":443")) return false;
return true;
}
assert.equal(isValidAllowedOrigin("http://127.0.0.1:3000", "sandbox"), true);
assert.equal(isValidAllowedOrigin("http://127.0.0.1:3000", "live"), false);
assert.equal(isValidAllowedOrigin("https://casino.example", "live"), true);
assert.equal(isValidAllowedOrigin("https://casino.example:443", "live"), false);
assert.equal(isValidAllowedOrigin("*", "sandbox"), false);
// Sign a programmatic POST /console/onboarding/bootstrap request with betrail-v1
const body = JSON.stringify({ operator_name: "Acme Gaming", brand_name: "Acme Casino", currency: "BTC" });
const bodyHash = crypto.createHash("sha256").update(body, "utf8").digest("hex");
const canonical = ["betrail-v1", "POST", "/console/onboarding/bootstrap", "1761696000", "nonce-bootstrap-01", bodyHash].join("\n");
const sig = `v1=${crypto.createHmac("sha256", "local-console-service-secret").update(canonical, "utf8").digest("hex")}`;
assert.match(sig, /^v1=[0-9a-f]{64}$/);