# Authentication, signing, and idempotency

Every operator-to-BetPlug REST call, BetPlug-to-wallet callback, and BetPlug-to-operator webhook uses one 6-line HMAC-SHA256 signing scheme (`betrail-v1`). Seamless wallet responses sign the companion answer-side payload (`betrail-v1-answer`) using asymmetric RFC 8032 `ed25519=` keys or `v1=` HMAC-SHA256.

## Credentials by surface

| Credential | Wire header / location | Scope & lifetime |
|---|---|---|
| Sandbox API key (`btr_test_<key>`) + signing secret | `Authorization: Bearer ...` + `Betrail-*` | Operator server -> sandbox REST (`launch:write`, `players:force_close`, `players:write`, `rounds:read`, `rounds:write`, `seeds:read`, `seeds:write`). |
| Production API key + signing secret | `Authorization: Bearer ...` + `Betrail-*` | Production server-to-server traffic only. Store exclusively in server-side secret managers; never expose to browsers, CI logs, MCP clients, or AI coding agents. |
| Launch token (43 base64url chars) | Body of `POST /v1/sessions` or `?token=` | Single-use, 60 s TTL. Exchanged once by the embedded client and stripped from URL/history immediately. |
| Session token (`bts_<token>`) | `Authorization: Bearer ...` | Embedded browser client -> `/v1/session/*`, `/v1/sessions/current/reality-check`, and `/v1/live/*` (`Bearer` only, never `Betrail-Signature`). Max 8 h (900 s idle timeout), memory-only, bound to `Origin`. |
| Live join ticket (`v1.<payload>.<mac>`) | `Sec-WebSocket-Protocol: betrail.v1, ticket.<ticket>` | Single-use, 30 s TTL, minted via `POST /v1/live/{game}/tickets`. Never logged; server echoes `betrail.v1` only. |
| Wallet Ed25519 answer keypair | `Betrail-Signature: ed25519=<86-base64url>` | Asymmetric RFC 8032 wallet answer signer (`betrail-v1-answer`). Once an Ed25519 public key is registered on the brand environment, `v1=` HMAC downgrade is strictly refused. |
| Top-up webhook (`receiveTopupEvent`) | Provider signature (`x-betrail-public: provider-signature`) | Payment provider -> `POST /v1/topup-events/{provider}` (`security: []`; authenticated by provider HMAC before reading JSON). |

## Request signing (`betrail-v1`)

Every signed HTTP request carries three headers alongside `Authorization` (for operator REST calls):

- **`Betrail-Timestamp`:** 10-digit Unix timestamp in seconds (`^[0-9]{10}$`).
- **`Betrail-Nonce`:** Unique per-attempt token (`^[A-Za-z0-9_-]{16,64}$`). Generate a fresh CSPRNG nonce on **every** HTTP attempt — including retries that reuse the same `Idempotency-Key`.
- **`Betrail-Signature`:** `v1=<64-lowercase-hex>` (or comma-separated `v1=<new>,v1=<old>` during a 24-hour secret rotation overlap).

### Signing anatomy (`betrail-v1`)

Join these exact six lines with `\n` (`0x0a`, no trailing newline):

```text
Line 1: betrail-v1                              <-- fixed request domain separator
Line 2: POST                                    <-- UPPERCASE HTTP method
Line 3: /v1/rounds?player_ref=p-1               <-- exact raw request-target (path + raw query as on wire)
Line 4: 1793232000                              <-- Betrail-Timestamp header (10 ASCII digits)
Line 5: n_01jbx7q2w3e4r5t6y7u8                  <-- Betrail-Nonce header (fresh per HTTP attempt)
Line 6: e3b0c44298fc1c149afbf4c8996fb924...     <-- lowercase hex SHA-256 of exact raw body bytes
```

### Concrete signed HTTP request (`v1=` HMAC)

```http tab=HTTP
POST /v1/rounds HTTP/1.1
Host: api.betrail.example
Authorization: Bearer btr_test_<sandbox_key>
Content-Type: application/json
Idempotency-Key: idem_round_0001
Betrail-Timestamp: 1793232000
Betrail-Nonce: n_round_attempt_0001
Betrail-Signature: v1=8f4a2e1c9d0b7a6f5e4d3c2b1a0987654321fedcba9876543210abcdef012345

{"game":"dice","brand":"br_sandbox","player_ref":"p_demo_01","currency":"BTC","stake":"0.00010000","params":{"direction":"under","chance":"47.98","payout":"1.97999"}}
```

```sh tab=cURL
curl -sS -X POST "https://api.betrail.example/v1/rounds" \
  -H "Authorization: Bearer $BETRAIL_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: idem_round_0001" \
  -H "Betrail-Timestamp: 1793232000" \
  -H "Betrail-Nonce: n_round_attempt_0001" \
  -H "Betrail-Signature: v1=8f4a2e1c9d0b7a6f5e4d3c2b1a0987654321fedcba9876543210abcdef012345" \
  -d '{"game":"dice","brand":"br_sandbox","player_ref":"p_demo_01","currency":"BTC","stake":"0.00010000","params":{"direction":"under","chance":"47.98","payout":"1.97999"}}'
```

> **Security:** Enforce these four verification checks in strict order on every incoming webhook or wallet callback:
> 1. Reject any `Content-Encoding` other than `identity` (`415`) and any body over `65,536` bytes (`413`) **before** buffering or hashing.
> 2. Hash the **exact raw request-target** (path + raw query string as received on the wire — never normalized or percent-decoded by a proxy) and exact raw UTF-8 body bytes **before** `JSON.parse`.
> 3. Reject `Betrail-Timestamp` outside `±300 s` of server time (`401`).
> 4. Compare candidate `v1=` hex digests in constant time (`timingSafeEqual`) across active secrets **before** writing `Betrail-Nonce` to your replay store (`SET NX EX 630` in Valkey) so unauthenticated traffic cannot exhaust nonce memory.

## Wallet response signing (`betrail-v1-answer` & Ed25519)

Seamless wallet responses (`200` answers and signed `4xx` refusals on verified requests) sign a 6-line `betrail-v1-answer` payload bound to the caller's `Betrail-Nonce` and `transaction_id`:

```text
Line 1: betrail-v1-answer                       <-- fixed answer domain separator (blocks request reflection)
Line 2: 200                                     <-- 3-digit HTTP response status (e.g. 200, 400, 409)
Line 3: 1793232001                              <-- answer's own Betrail-Timestamp header
Line 4: n_01jbx7q2w3e4r5t6y7u8                  <-- incoming request's Betrail-Nonce (re-signed on retries!)
Line 5: rnd_01:0:1:debit                        <-- request's transaction_id (empty "" on /balance)
Line 6: 4c9d3a1f...                             <-- lowercase hex SHA-256 of exact raw answer body bytes
```

### Concrete wallet answer wire examples (`ed25519=` vs `v1=`)

```http tab=Ed25519_200
HTTP/1.1 200 OK
Content-Type: application/json
Betrail-Timestamp: 1793232001
Betrail-Signature: ed25519=A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8S9t0U1v2W3x4Y5z6A7b8C9d0E1f2G3h4I5j6K7l8M9n0P1q2RA

{"transaction_id":"rnd_01:0:1:debit","amount":"0.00010000","currency":"BTC","operator_transaction_id":"op_tx_9001","balance":"0.04990000"}
```

```http tab=HMAC_409
HTTP/1.1 409 Conflict
Content-Type: application/json
Betrail-Timestamp: 1793232001
Betrail-Signature: v1=3a7c1e9b5d2f8a4c6e0b1d3f5a7c9e1b3d5f7a9c1e3b5d7f9a1c3e5b7d9f1a3c

{"code":"insufficient_funds","transaction_id":"rnd_01:0:1:debit"}
```

> **Warning:** Once an Ed25519 public key (43 canonical base64url chars, validated on-curve and non-8-torsion) is registered on a brand environment, BetPlug and all four [Official SDKs](/docs/sdk) enforce strict **no-downgrade pinning**: `v1=` HMAC tags alone are rejected. During migration rollout, emit `ed25519=<sig>,v1=<mac>` (`ed25519=` first). Never sign an unauthenticated `401` response.

## `Idempotency-Key` and retries

Every state-changing operator `POST` (`/v1/rounds`, `/v1/rounds/{id}/actions`, `/v1/players/{player_ref}/seeds/{game}/rotate`, `/v1/players/{player_ref}/force-close`, `/v1/launch`) and session `POST` (`/v1/sessions`, `/v1/demo/sessions`, `/v1/session/rounds`, `/v1/session/rounds/{id}/actions`, `/v1/session/seeds/rotate`, `/v1/sessions/current/reality-check`, `/v1/live/{game}/tickets`, `/v1/live/{game}/bets`, `/v1/live/meme-trade/buy-ins`) requires `Idempotency-Key` (`^[!-~]{1,128}$`).

- **Network timeout / `500` / `502` / `504` / `409 idempotency_key_in_use`:** Retry with the **exact same `Idempotency-Key`** and identical JSON body, signed with a **fresh `Betrail-Timestamp` and `Betrail-Nonce`**.
- **`422 idempotency_key_reused`:** A different body was sent under an existing key. Mint a new `Idempotency-Key` for distinct logical operations.
- **`503 wallet_unavailable`:** Retry **only** when the response carries a `Retry-After` header (the wallet bulkhead rejected before changing state). Without `Retry-After`, the opening debit failed or timed out, the round voided, and replaying that `Idempotency-Key` returns the stored `503`.

> **Tip:** All four [Official SDKs](/docs/sdk) automatically mint one CSPRNG `Idempotency-Key` per logical call, reuse it on retryable statuses, and rotate `Betrail-Timestamp` + `Betrail-Nonce` on every HTTP attempt.

## Errors (`application/problem+json`) & retry matrix

Every BetPlug REST error returns RFC 9457 `application/problem+json` and includes a `Betrail-Request-Id` response header for support and log correlation.

| Field | Type | Description |
|---|---|---|
| `type` | `string` (URI) | Stable problem URI (`https://betrail.example/problems/<code>`) |
| `title` | `string` | Short human-readable summary |
| `status` | `integer` | HTTP status code |
| `detail` | `string` | Specific diagnostic explanation for this request |
| `instance` | `string` | Request path that produced the error |
| `code` | `ProblemCode` | Machine-readable error code (branch on this, never `detail`) |
| `max_stake` | `Amount` (optional) | Returned on `422 max_stake` with the largest allowed stake for the requested target and brand `max_profit` cap |
| `elapsed_seconds` / `net_result` | `integer` / `string` (optional) | Returned on `409 reality_check_due` so the client can render the responsible-gaming prompt before calling `POST /v1/sessions/current/reality-check` |

Example problem responses:

```json tab=422_max_stake
{
  "type": "https://betrail.example/problems/max_stake",
  "title": "Stake exceeds maximum allowed for target",
  "status": 422,
  "detail": "Requested stake exceeds the maximum stake permitted by the brand max_profit cap.",
  "instance": "/v1/rounds",
  "code": "max_stake",
  "max_stake": "5.00000000"
}
```

```json tab=409_reality_check_due
{
  "type": "https://betrail.example/problems/reality_check_due",
  "title": "Reality check acknowledgement required",
  "status": 409,
  "detail": "Player must acknowledge the elapsed session summary before placing another wager.",
  "instance": "/v1/session/rounds",
  "code": "reality_check_due",
  "elapsed_seconds": 3600,
  "net_result": "-0.01250000"
}
```

### Quick HTTP error retry matrix

| HTTP | Common `code` values | Retry? | Action |
|---|---|---|---|
| `400` | `invalid_request` | No | Fix malformed JSON, missing headers, or extra fields (`additionalProperties: false`). |
| `401` | `unauthorized`, `session_expired` | Conditional | Check clock skew (`±300 s`), Valkey post-start epoch (`330 s`), and fresh `Betrail-Nonce`; re-launch expired `bts_` sessions. |
| `402` | `credits_exhausted`, `plan_inactive` | After top-up | Top up prepaid live USD credits in Console `/topups` (sandbox stays unaffected). |
| `403` | `forbidden`, `origin_not_allowed`, `player_blocked`, `jurisdiction_not_allowed` | No | Verify API key scopes, allowed origins, player status, or brand/operator jurisdiction policy. |
| `404` | `not_found`, `unknown_game`, `unknown_version` | No | Confirm ID belongs to this operator/environment and slug matches [`GameSlug`](/docs/api-reference#gameslug). |
| `409` | `idempotency_key_in_use`, `pending` | **Yes** | Retry with the **same** `Idempotency-Key` + body and a **fresh** `Betrail-Nonce`. |
| `409` | `odds_changed`, `reality_check_due`, `round_open`, `seed_not_revealed`, `insufficient_funds`, `limit_exceeded`, `not_offered`, `closed`, `max_exposure` | No (resolve state) | Re-quote multiplier (`odds_changed`), acknowledge reality check, finish open round, or rotate seeds first. |
| `413` / `415` | `body_too_large`, `unsupported_encoding` | No | Keep body `<= 64 KB` and send uncompressed `identity` JSON. |
| `422` | `invalid_input`, `invalid_action`, `stake_out_of_range`, `max_stake`, `idempotency_key_reused` | No | Fix parameters (cap to `max_stake`) or mint a new `Idempotency-Key`. |
| `429` | `rate_limited` | **Yes** | Honor `Retry-After` seconds; reuse `Idempotency-Key` with a fresh `Betrail-Nonce`. |
| `500` | `internal`, `no_acceptable_draw` | **Yes** | Retry same `Idempotency-Key` + body with a fresh `Betrail-Timestamp` and `Betrail-Nonce`. |
| `503` | `wallet_unavailable` | **Only with `Retry-After`** | With `Retry-After`: bulkhead rejected before state change (safe to retry). Without `Retry-After`: round voided (do not retry same key). |

For the full table of every `ProblemCode`, see [Shared HTTP errors & retry matrix](/docs/api-reference#shared-http-errors--retry-matrix).

## Verifying official signing vectors (`api/testdata/signing-vectors.json`)

This runnable TypeScript sample verifies every official `betrail-v1` request vector (including 24-hour dual-secret rotation) and `betrail-v1-answer` wallet response vector (including reflected-request rejection and retry re-signing):

```ts
import assert from "node:assert/strict";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";

interface SigningVector {
  name: string;
  first_line?: string;
  must_not_verify?: string;
  hmac_with: string;
  previous_hmac_with?: string;
  method?: string;
  target?: string;
  status?: string;
  timestamp: string;
  nonce: string;
  transaction_id?: string;
  body: string;
  body_sha256: string;
  canonical: string;
  signature_header: string;
  stale_signature_header?: string;
}

const sha256Hex = (text: string) => crypto.createHash("sha256").update(text, "utf8").digest("hex");
const hmacHex = (secret: string, canonical: string) =>
  crypto.createHmac("sha256", Buffer.from(secret, "utf8")).update(canonical, "utf8").digest("hex");

function verifyHeaderConstantTime(header: string, secrets: string[], canonical: string): boolean {
  let matched = false;
  for (const part of header.split(",")) {
    if (!/^v1=[0-9a-f]{64}$/.test(part)) return false;
    const given = Buffer.from(part.slice(3), "hex");
    for (const secret of secrets) {
      const expected = Buffer.from(hmacHex(secret, canonical), "hex");
      if (given.length === expected.length && crypto.timingSafeEqual(given, expected)) matched = true;
    }
  }
  return matched;
}

const repoRoot = process.env.BETRAIL_REPO_ROOT ?? process.cwd();
const { vectors } = JSON.parse(
  fs.readFileSync(path.join(repoRoot, "api", "testdata", "signing-vectors.json"), "utf8"),
) as { vectors: SigningVector[] };

assert.equal(vectors.length, 9);
for (const v of vectors) {
  assert.equal(sha256Hex(v.body), v.body_sha256, v.name);
  if (v.first_line === "betrail-v1-answer") {
    const canonical = ["betrail-v1-answer", v.status ?? "", v.timestamp, v.nonce, v.transaction_id ?? "", v.body_sha256].join("\n");
    assert.equal(canonical, v.canonical, v.name);
    assert.equal(verifyHeaderConstantTime(v.signature_header, [v.hmac_with], canonical), v.must_not_verify !== "true", v.name);
    if (v.stale_signature_header) {
      assert.equal(verifyHeaderConstantTime(v.stale_signature_header, [v.hmac_with], canonical), false, v.name);
    }
  } else {
    const canonical = ["betrail-v1", v.method ?? "", v.target ?? "", v.timestamp, v.nonce, v.body_sha256].join("\n");
    assert.equal(canonical, v.canonical, v.name);
    const secrets = v.previous_hmac_with ? [v.hmac_with, v.previous_hmac_with] : [v.hmac_with];
    assert.equal(secrets.map((s) => `v1=${hmacHex(s, canonical)}`).join(","), v.signature_header, v.name);
    for (const s of secrets) assert.equal(verifyHeaderConstantTime(v.signature_header, [s], canonical), true, v.name);
  }
}
```
