Skip to content
BetPlugDocs
DocsGet started
View .md twin

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#

  1. Start infrastructure & migrate — sh scripts/dev.sh up and betrailctl migrate up.
  2. Generate local .env secrets & launch services — betrail-api (:8080 / :8082 / :8083), betrail-worker, and betrail-console (:3002).
  3. Clear Valkey's 330-second post-start epoch — send one Console signup so betrail:epoch is stamped on a brand-new Valkey container, then wait 330 s once.
  4. Onboard in Console — verify email via Mailpit (http://127.0.0.1:8025), enroll Passkey or TOTP at /security?onboarding=1, bootstrap your operator & brand, and copy your one-time btr_test_<key> + signing_secret.
  5. Play or wire your casino — call POST /v1/rounds immediately, 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:8025 web inbox), then apply SQL migrations:

Shell
sh scripts/dev.sh up
BETRAIL_MIGRATE_DATABASE_URL="postgres://betrail:[email protected]:5432/betrail?sslmode=disable" \
  betrailctl migrate up

Copy .env.example to a git-ignored .env (chmod 0600 .env) and generate 32-byte random secrets (node -e 'console.log(require("node:crypto").randomBytes(32).toString("base64url"))'):

VariableLocal development valuePurpose
BETRAIL_ENVdevelopmentEnables local development mode. Unset or any value outside development / test enforces strict production startup guards.
BETRAIL_DATABASE_URLpostgres://betrail:[email protected]:5432/betrail?sslmode=disableDatabase 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_URLredis://127.0.0.1:6379/0Nonce replay store, Valkey epoch (betrail:epoch), and rate limits.
BETRAIL_SMTP_ADDR127.0.0.1:1025Sends Console sign-up, recovery, and worker credit-alert emails to Mailpit (http://127.0.0.1:8025).
BETRAIL_SEED_KEK_ID / BETRAIL_SEED_KEKdev-1 / <32 random bytes, base64url, no padding>Local key-encryption key wrapping server seeds, wallet secrets, and webhook secrets (no default).
BETRAIL_CONSOLE_SERVICE_SECRET<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_URLlocalhost / http://localhost:3002,http://127.0.0.1:3002 / http://localhost:3002WebAuthn Relying Party ID and Console origin used in verification links.
BETRAIL_SANDBOX_WALLET_ORIGINhttp://127.0.0.1:8083Points the API and worker at the built-in Sandbox Wallet listener (BETRAIL_SANDBOX_WALLET_LISTEN=127.0.0.1:8083) over plain HTTP.
BETRAIL_EGRESS_LOCAL_ALLOW127.0.0.1:3000,[::1]:3000Exact 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_SANDBOX_WALLET_ORIGIN and any non-empty BETRAIL_EGRESS_LOCAL_ALLOW refuse startup immediately in the API, worker, and Console whenever BETRAIL_ENV is anything other than development or test.

Aligned local development ports across all BetPlug web portals:

PortalLocal URLPurpose
Marketing & game showcase (web/site)http://127.0.0.1:3000Public marketing site and live interactive game showcase
Staff Admin (web/admin)http://127.0.0.1:3001Internal platform administration (private listener :8081)
Operator Console (web/console)http://localhost:3002Operator onboarding, brands, keys, wallet, webhooks, insights, billing
Developer Docs (web/docs)http://127.0.0.1:3003This documentation portal, .md twins, /llms*.txt, OpenAPI/AsyncAPI
Fairness Verifier (web/verifier)http://127.0.0.1:3004Standalone offline browser round verifier

Start the three core local processes in separate terminals with .env exported in every shell (set -a && . ./.env && set +a):

Shell
# 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-live

Confirm the API is listening:

Shell
curl -sS http://127.0.0.1:8080/healthz

2. 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:

  1. On the first nonce claim against an empty Valkey, the replay guard atomically writes SET betrail:epoch <now> NX.
  2. Every signed request with Betrail-Timestamp <= betrail:epoch + 330 is refused with 401 unauthorized:
    • On :8082 Console backend API: "Service credential timestamp predates a Valkey restart; sign a fresh request."
    • On :8080 public /v1/* routes: "This request cannot be told from one sent before a restart: sign it again in a few minutes."
  3. Local workflow: After starting a fresh Valkey container, submit one request (such as Console sign-up) so betrail:epoch is stamped, wait 330 seconds (5m30s), and retry. For the rest of that container's lifetime (sh scripts/dev.sh up keeps the container alive), signed calls succeed immediately.

3. Obtain a brand ID and sandbox key pair#

Open http://localhost:3002/signup and complete the four-step onboarding flow:

  1. Sign up (POST /console/auth/signup). Returns uniform 202 (ConsoleNoticeAck, never disclosing whether an address already exists). Open Mailpit (http://127.0.0.1:8025) and follow /verify-email?token=… (POST /console/auth/verify-email).
  2. Enroll MFA (http://localhost:3002/security?onboarding=1). After email verification, factor_required sessions redirect to /security?onboarding=1. Register a Passkey (POST /console/auth/passkey/register/begin -> POST /console/auth/passkey/register/finish, 201; http://localhost:3002 matches BETRAIL_CONSOLE_RP_ID=localhost, with passkey-only MFA enforced by default in production) or enroll a 6-digit TOTP authenticator (POST /console/auth/totp/enroll/begin -> POST /console/auth/totp/enroll/finish, 200).
  3. Bootstrap operator & brand (POST /console/onboarding/bootstrap). Supply an Idempotency-Key and { "operator_name", "brand_name", "currency"? } (default "BTC"; unknown fields fail with 400 invalid_request). Save the returned brand ID (br_…) as BETRAIL_BRAND_ID.
  4. Mint your one-time sandbox API key (POST /console/brands/{brand}/sandbox-keys). Returns api_key (btr_test_<key>) and signing_secret (>= 32 bytes) once with Cache-Control: no-store. Save them in a git-ignored 0600 .env.local:
Shell
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/session/rounds), new sandbox brands start wired to the built-in Sandbox Wallet (BETRAIL_SANDBOX_WALLET_ORIGIN): POST /console/onboarding/bootstrap 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:3000 with BETRAIL_EGRESS_LOCAL_ALLOW=127.0.0.1:3000), configure your brand in the Console UI (http://localhost:3002):

  • http://localhost:3002/wallet: Switch the sandbox wallet to your operator URL, copy the one-time wallet_secret, register an optional RFC 8032 Ed25519 answer public key (answer_public_key via PUT /console/brands/{brand}/wallet/{environment}/answer-key), run the 29-check wallet conformance tester, and save allowed_origins.
  • http://localhost:3002/webhooks: Mint or rotate the one-time 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/webhooks/deliveries/{id} and 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/go-casino, and ./examples/laravel-casino (Official SDKs).

Under the hood, /wallet and /webhooks call these Console backend API routes (api/console.yaml):

  • Seamless wallet & wallet_secret (POST /console/brands/{brand}/wallet/{environment}): Requires Idempotency-Key. Send { "target": "operator", "wallet_url": "http://127.0.0.1:3000/api/wallet/v1", "overlap_seconds": 0 } (0..86400 during secret rotation, or { "target": "sandbox_wallet" } on sandbox). Returns 201 (BrandWalletIssued) with one-time wallet_secret (BETRAIL_WALLET_SECRET; Seamless wallet protocol).
  • Allowed browser origins (PUT /console/brands/{brand}/origins/{environment}): Send { "allowed_origins": ["http://127.0.0.1:3000"] } (200, up to 64 unique bare scheme://host[:port] origins with lowercase ASCII host; explicit default ports :80 on http and :443 on https are rejected with 422 invalid_input; https:// required on live; never * or "null"). Governs POST /v1/launch return_url, /v1/session/* Origin checks (403 origin_not_allowed), iframe frame-ancestors, and betrail:v1 postMessage origin locking (Embed & launch).
  • Webhook signing_secret & endpoint (POST /console/brands/{brand}/webhooks/{environment}/secret then PUT /console/brands/{brand}/webhooks/{environment}): Mint one-time signing_secret (201 WebhookSecretIssued, Idempotency-Key + { "overlap_seconds": 0 } returning { "signing_secret", "secret_overlap_until", "rotated_at" }), then enable delivery (200) with { "url": "http://127.0.0.1:3000/api/webhooks/betrail", "enabled": true, "events": ["round.settled", "credits.low", "credits.exhausted"] } (Webhooks).
  • Launch tester (POST /console/brands/{brand}/launch-test/{environment}): Requires Idempotency-Key. Dry-runs POST /v1/launch against the brand environment's exact rules (200 LaunchTestResult). On sandbox, accepted non-live-show launches on a brand with allowed_origins also return a one-time 60-second sandbox demo (FUN) play_host_url (Cache-Control: no-store, 409 secret_already_shown on replay). On live (owner/admin + launch_tester.live passkey step-up), it runs dry-run validation only, writes zero session/ledger rows, calls no wallet, returns play_host_url: null, and notifies every Owner.

Security: Programmatic test harnesses that call 127.0.0.1:8082 directly must sign every request with betrail-v1 under BETRAIL_CONSOLE_SERVICE_SECRET and attach Cookie: betrail_console=<session_token> from /console/auth/*. The Operator Console keeps raw session tokens out of browser JavaScript inside an HttpOnly cookie.

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_KYB_REQUIRED=true), moving a brand from sandbox to live is self-serve once your production configuration passes validation: seamless wallet, allowed HTTPS origins, webhooks, live API key, active plan, and prepaid USD credits.

  1. Wallet (/wallet): Point live at your production https:// seamless wallet URL (with wallet_secret and recommended Ed25519 answer public keys) and pass the automated 29-check wallet conformance tester (Seamless wallet protocol).
  2. Allowed origins (/wallet): Save your production https:// casino origins (PUT /console/brands/{brand}/origins/live).
  3. Webhooks (/webhooks): Mint a live webhook signing_secret and enable your HTTPS receiver for round.settled, credits.low, and credits.exhausted (Webhooks).
  4. Credits (/topups): Fund prepaid USD credits for live play (live rounds pause with 402 credits_exhausted only if credits reach 0; 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 variableDefaultBehavior & fail-closed guarantees
BETRAIL_KYB_REQUIREDfalseControls 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_LIVE_KEYS_ENABLEDfalse (off outside development)Explicit production opt-in for live API key issuance outside BETRAIL_ENV=development. Set BETRAIL_LIVE_KEYS_ENABLED=true 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_SMTP_PASSWORD_FILE127.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_SMTP_PASSWORD_FILE must be owner-only (0600/0400, <= 4096 bytes, read once at startup).
BETRAIL_WORKER_ROLLUP_POOL_SIZE5 (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, and PUT /console/brands/{brand}).
  • Console insights (GET /console/insights/{environment}): Aggregated handle, payouts, GGR (exact decimal strings), and basis-point rates (bp) fed by the worker rollup pool; returns 503 stats_unavailable cleanly if a heavy query hits statement timeout.
  • Per-brand activity & player counts: GET /console/brands/{brand}/activity/{environment} and GET /console/brands/{brand}/player-counts/{environment}.
  • Webhook & wallet delivery health: GET /console/brands/{brand}/webhooks/{environment}/health and GET /console/brands/{brand}/wallet/{environment}/delivery-health surface recent success rates, latencies, and dead-letter counts.
  • Billing alert history & API usage: GET /console/billing/alerts/history tracks unified webhook + SMTP email delivery state for credits.low and credits.exhausted alerts; GET /console/request-log/{environment}/usage summarizes recent API volume.

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/operators/{operator}/statistics), incident banner history (GET /admin/incident-banner/history), and system health history (GET /admin/system/health/history).

Validating allowed origins & Console request signing#

Use this helper to pre-validate allowed_origins before calling PUT /console/brands/{brand}/origins/{environment} and sign programmatic :8082 Console calls:

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