# Bitey Games — Player App API (v1.1)

Integration reference for the Bitey Games mobile (Flutter) player app. Every
screen the web player area offers is reachable through these endpoints. The
parity checklist at the end maps each web page to its endpoints.

- **Base URL:** `https://biteygames.com/api/v1/player`
- **Live endpoint list:** `GET https://biteygames.com/api/v1/player`
- **Format:** JSON in, JSON out. Times are ISO-8601 UTC.
- **Currencies:** `coins` (Coins) and `bites` (Bites). Bites is also the
  player's progression score (levels are reached by earning Bites). Some
  fields are still named `xp` internally — treat `xp` as Bites.

---

## 1. Authentication

Send the player's session token on every call except those marked `none`:

```
Authorization: Bearer <access_token>
```

| Auth level | Meaning |
|---|---|
| `none` | No token needed |
| `player` | Any signed-in player, **including guests** |
| `registered` | Full accounts only. Guests get `403 GUEST_NOT_ALLOWED` — show the "Create account" sheet and call `POST /me/upgrade` |

### Ways to get a token
1. **Play as guest (no sign-in)** — `POST /auth/guest`. Returns a session instantly. Use this on first launch so the player can tap **Play** straight away.
2. **Email + password** — Supabase Auth REST: `POST {SUPABASE_URL}/auth/v1/token?grant_type=password` with the project's publishable key (see section 3 of the Flutter guide), or the `supabase_flutter` SDK.
3. **Google** — `supabase_flutter` native Google sign-in.

Refresh tokens before `expires_at` with `POST /auth/refresh`. After any sign-in, call `POST /auth/login-event` once so the device appears under Connected Devices.

### Guest play flow (tap Play, no sign-in)
```text
1. App start, no stored session  -> POST /auth/guest          (store tokens securely)
2. Home / Games                   -> GET /home, GET /games
3. Player taps Play               -> GET /games/:gameId        (returns game_url)
4. Open game_url in the WebView   (pass the access_token as in the Flutter guide)
5. Scores, Coins and Bites save to the guest account automatically
6. Tournament join / purchase     -> 403 GUEST_NOT_ALLOWED -> show upgrade sheet
7. Upgrade                         -> POST /me/upgrade (keeps all progress)
```
Guests **can**: play, view everything, spin, claim daily login, missions and achievements.
Guests **cannot**: join tournaments, buy, send/answer invites, apply referral codes, change email/password.

---

## 2. Response format

```json
{ "success": true,  "data": { ... }, "request_id": "preq_..." }
{ "success": false, "error": { "code": "GUEST_NOT_ALLOWED", "message": "..." }, "request_id": "preq_..." }
```

Rate limits per minute per player: reads 240, writes 60, claims 30, auth 20.
Headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`.

Paginated lists accept `?page=1&limit=20` (limit max 100) and return `page`, `limit`, `total`.

### Common error codes
| HTTP | Code | When / what to show |
|---|---|---|
| 400 | `BAD_REQUEST`, `VALIDATION_FAILED` | Bad parameter or body |
| 401 | `UNAUTHORIZED` | Missing/expired token — refresh, else sign in again |
| 403 | `GUEST_NOT_ALLOWED` | Show "Create an account" sheet |
| 403 | `ACCOUNT_BANNED` | Account blocked |
| 404 | `NOT_FOUND` | Unknown item or endpoint |
| 405 | `METHOD_NOT_ALLOWED` | Wrong HTTP method |
| 409 | `USERNAME_TAKEN`, `ALREADY_REGISTERED` | Conflict |
| 400 | `WRONG_PASSWORD` | Current password incorrect |
| 400 | `INSUFFICIENT_FUNDS` / messages containing "insufficient" | Not enough Coins/Bites |
| 400 | `TOURNAMENT_FULL`, `TOURNAMENT_CLOSED`, `ALREADY_JOINED` | Tournament join problems |
| 429 | `RATE_LIMITED` | Slow down and retry |
| 500 | `INTERNAL` | Retry later |

---

## 3. Endpoints by screen

Notation: **[none] [player] [registered]** = auth level.

### 3.1 App start & meta
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/health` | none | Uptime check |
| GET | `/config` | none | `min_supported_version`, `maintenance`, `api_version` — force-update / maintenance screen |
| POST | `/auth/guest` | none | Creates guest session → `data.session { access_token, refresh_token, expires_at, user { id, is_anonymous } }` (201) |
| POST | `/auth/refresh` | none | Body `{ "refresh_token": "..." }` → new `session` |
| GET | `/auth/validate` | player | Confirms token; returns `user { username, account_type, is_guest }` |
| POST | `/auth/login-event` | player | Body `{ "device_id"?, "platform"? }` — records device |

```bash
curl -X POST https://biteygames.com/api/v1/player/auth/guest
```

### 3.2 Home
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/home` | player | `profile`, `wallet { coins, gems, bites }`, `progress`, `daily_login`, `missions` (4 active), `offers`, `featured_games`, `continue_playing` (last 4 games played, with `last_played_at`) |
| GET | `/upcoming` | player | **Home banner.** Up to 4 items `{ id, title, description, banner_url, release_label, release_date, sort_order }` |

### 3.3 Games
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/genres` | player | All genres with counts: `items [{ genre, game_count }]` — build the genre chips from this |
| GET | `/games?genre=&q=&page=&limit=` | player | Published games. Each item: `id, name, slug, genre, description, thumbnail_url, banner_url, screenshots, is_featured, gameplay_fee` (entry cost badge), `game_url` (play link), `version` |
| GET | `/games/:gameId` | player | Game detail page (View) — same fields; `game_url` is what **Play** opens |
| GET | `/leaderboard/game/:gameId?period=daily\|weekly\|monthly\|all_time&limit=` | optional | Per-game **score** leaderboard (`entries[].score`, `my_rank`, `my_score`). Use this for game screens. |

Gameplay (normally sent by the game inside the WebView via the SDK; available if the app needs it):
| Method | Path | Auth | Body |
|---|---|---|---|
| POST | `/gameplay/session/start` | player | `{ game_id }` |
| POST | `/gameplay/session/end` | player | `{ game_id, session_id }` |
| POST | `/gameplay/score` | player | `{ game_id, score, session_id?, tournament_id?, metadata? }` |
| GET | `/gameplay/state/:gameId` | player | Cloud save |
| POST | `/gameplay/state` | player | `{ game_id, state, expected_version, schema_version? }` |

### 3.4 Tournaments
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/tournaments` | player | Filters below |
| GET | `/tournaments/recommended` | player | Up to 10 live/upcoming picks for this player |
| GET | `/tournaments/mine` | player | Tournaments I joined, with score/rank/reward |
| GET | `/tournaments/:id` | player | Detail + top 50 standings, `joined`, `can_join`, `spots_left`, `game` |
| GET | `/tournaments/:id/standings` | player | Leaderboard |
| POST | `/tournaments/:id/join` | registered | Charges the entry fee in `entry_currency`. Guests → `GUEST_NOT_ALLOWED` |

`GET /tournaments` query parameters:
| Param | Values | Default |
|---|---|---|
| `status` | `all`, `live`, `upcoming`, `joined`, `completed` | `all` (hides cancelled) |
| `stake` | `all`, `free`, `low`, `mid`, `high` | `all` |
| `sort` | `recommended`, `starting_soon`, `popular`, `top_rewards` | `recommended` |
| `q` | search text — matches tournament **and** game name | — |
| `game_id` | UUID | — |

Each item: `id, name, type, entry_fee, entry_currency, prize_pool, prize_currency, prize_breakdown [{place, percent, amount}], max_players, player_count, spots_left, avatars[] (up to 4), starts_at, ends_at, display_status (live|upcoming|completed|cancelled), joined, can_join, tags[] (HOT, FAST, TOP REWARD, POPULAR, NEW), recommended, game { id, name, thumbnail_url, banner_url }`.
Prizes are fixed by admins — entry fees never change `prize_pool`.

```bash
curl -H "Authorization: Bearer $TOKEN" \
  "https://biteygames.com/api/v1/player/tournaments?status=live&stake=low&sort=top_rewards&q=dash"
```

### 3.5 Missions
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/missions?type=daily\|weekly\|special\|event` | player | Omit `type` for all. Returns `items`, `counts` per type, `next_refresh_at` (countdown), `daily { required, claimed, complete, bonus_coins }`, `streak { current, reward_bites }` |
| POST | `/missions/claim` | player | `{ mission_id, game_id? }` → `reward_amount`, `bites_awarded`, `daily_bonus_awarded`, `streak_reward_awarded` |

Mission item: `id, title, description, category (type), mission_type, target_value, progress_value, reward_amount (Coins), reward_xp (Bites), state (not_started|in_progress|completed|claimed|expired), action_type (games|spin|tournaments|explore|game), action_target (game slug when action_type=game), available_from, available_until, required_for_daily`.
The daily bonus is paid automatically when the last required daily mission is claimed; the 7-day streak reward the same way.

### 3.6 Rewards
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/rewards` | player | Rewards center: daily reward, spin status, comeback, offers, achievements summary |
| GET | `/rewards/eligibility` | player | What can be claimed now |
| GET | `/rewards/history?type=&page=&limit=` | player | Past claims |
| GET | `/daily-login` · POST `/daily-login/claim` | player | Daily login streak |
| GET | `/spin` · POST `/spin` | player | Spin wheel segments / spin |
| GET | `/comeback` · POST `/comeback/claim` | player | Returning player reward |
| GET | `/offers` · POST `/offers/claim` | player / registered | `{ offer_key, idempotency_key }` |

### 3.7 Badges & Achievements
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/achievements/categories` | player | Tabs: `[{ category, total, claimable, claimed }]` starting with `all` |
| GET | `/achievements?category=&status=locked\|in_progress\|claimable\|claimed` | player | Item: `id, title, description, category, target_value, progress_value, reward_amount, badge_name, status` |
| POST | `/achievements/claim` | player | `{ achievement_id }` |

### 3.8 Wallet
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/wallet` | player | `coins { balance, total_credited, total_debited }`, `bites { bites_balance, ... }` |
| GET | `/wallet/history?currency=all\|coins\|bites&type=all\|credit\|debit&page=&limit=` | player | Rows: `amount, currency, currency_label (Coins/Bites), direction (in/out), label, balance_after, created_at` — use `currency` for the icon |

### 3.9 Progression (Bites & levels)
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/progression` | player | `level, title, total_xp (Bites), bites_to_next, progress_to_next, rank, recent_activity, upcoming_rewards` |
| GET | `/progression/level-rewards` | player | Upcoming level rewards: `[{ level, bites_required, bites_remaining, reward_amount, title_unlock }]` |
| GET | `/progression/activity` | player | Recent Bites activity: `[{ label, bites, game_name, created_at }]` |
| GET | `/progression/how-to-earn` | player | How to earn Bites: `platform[]`, `per_game[]` (`display_label, xp_amount, game_name`) |
| GET | `/leaderboard/xp?period=daily\|weekly\|monthly\|all_time&limit=` | player | Global Bites leaderboard + `my_rank` |

### 3.10 Invite friends · Earn coins
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/referral` | player | `referral_code, share_url, total_referrals, recent[], base_bonus_per_referral, milestone_bonus_every_5, next_milestone_in` — share `share_url` with the native share sheet |
| POST | `/referral/apply` | registered | `{ code }` |
| POST | `/players/search` | player | `{ query }` (min 2 chars) |
| GET | `/invites` | player | Tournament invites received/sent |
| POST | `/invites` | registered | `{ tournament_id, invitee_user_id }` |
| POST | `/invites/:id/respond` | registered | `{ accept: true\|false }` |

### 3.11 Profile & Account
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/me` | player | Profile, roles, wallet, progress, subscription, `is_guest` |
| GET | `/me/stats` | player | Games played, wins, streaks, achievements summary |
| PATCH | `/me` | player | Update name/avatar: `{ username?, avatar_url? }` (username 3-24 chars, letters, numbers, `_ - .`) |
| GET | `/me/username-available?username=` | player | `{ available, valid, unchanged }` — call while typing |
| POST | `/me/email` | registered | `{ email }` — confirmation emails sent to old and new address |
| POST | `/me/password` | registered | `{ current_password, new_password }` (min 8). Google-only accounts get `NO_PASSWORD_ACCOUNT` |
| POST | `/me/upgrade` | player (guest) | `{ email, password, username? }` — turns the guest into a full account keeping Coins, Bites and progress. Ask the player to confirm their email, then sign in with email+password to get a full-account token |
| GET | `/me/devices` | player | Connected devices `items[]` + `recent_activity[]` (sign-ins) |
| DELETE | `/me` | player | **Delete account permanently.** Body `{ confirm: "DELETE", password? }` (password required for email/password accounts; Google and guest accounts omit it). Returns `{ deleted: true }`; discard stored tokens and return to the welcome screen. Errors: `PASSWORD_REQUIRED`, `WRONG_PASSWORD` (400), `IN_LIVE_TOURNAMENT` (409). Required by the App Store / Google Play — expose it under Account settings. Players can also email support@biteygames.com (see https://biteygames.com/support) |
| DELETE | `/me/devices/:deviceId` | player | Sign a device out |
| POST / DELETE | `/me/push-token` | player | `{ token, platform: ios\|android, device_id? }` |

### 3.12 Notifications
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/notifications?limit=` | player | Reward/activity notifications |
| POST | `/notifications/read` | player | `{ ids: [uuid] }` |
| POST | `/analytics/event` | player | `{ event_name, game_id?, properties? }` |

### 3.13 Store
| Method | Path | Auth | Notes |
|---|---|---|---|
| GET | `/store` | player | Products and bundles |
| POST | `/store/purchase` | registered | Buy with Coins/Bites: `{ product_id, idempotency_key }` |
| POST | `/store/free-claim` | player | `{ product_id }` |
| POST | `/payments/order` | registered | `{ product_id, provider }` |
| POST | `/payments/verify` | registered | `{ order_id, provider_payment_id, signature }` |
| GET | `/subscriptions` | player | Active subscription |

---

## 4. Web-to-app parity checklist

| Web page / feature | App endpoints |
|---|---|
| Home / Games list, genres, search | `/home`, `/genres`, `/games`, `/upcoming` |
| Game detail (View) and Play | `/games/:gameId` → `game_url` in WebView |
| Play as guest without sign-in | `/auth/guest` |
| Dashboard overview, Continue playing | `/home`, `/me/stats` |
| Tournaments (status, stake, sort, search), detail, join | `/tournaments`, `/tournaments/recommended`, `/tournaments/:id`, `/join`, `/standings`, `/mine` |
| Missions (Daily / Weekly / Special / Event, streak, daily bonus) | `/missions?type=`, `/missions/claim` |
| Rewards, Spin, Daily login, Comeback, Offers | `/rewards`, `/spin`, `/daily-login`, `/comeback`, `/offers` |
| Badges & Achievements (tabs) | `/achievements/categories`, `/achievements`, `/achievements/claim` |
| Wallet (Coins / Bites history) | `/wallet`, `/wallet/history` |
| Progression, Upcoming level rewards, Recent Bites activity, How to earn Bites | `/progression`, `/progression/level-rewards`, `/progression/activity`, `/progression/how-to-earn` |
| Leaderboard | `/leaderboard/xp`, `/leaderboard/game/:gameId` |
| Invite friends · Earn coins | `/referral`, `/referral/apply`, `/players/search`, `/invites` |
| Account: name, email, password, devices, guest upgrade, delete account | `PATCH /me`, `/me/username-available`, `/me/email`, `/me/password`, `/me/devices`, `/me/upgrade`, `DELETE /me` |
| Notifications | `/notifications`, `/notifications/read` |
| Store | `/store`, `/store/purchase`, `/store/free-claim`, `/payments/*`, `/subscriptions` |

---

## 5. Changelog

- v1.3: New `POST /games/:id/launch`; games now recognise the player inside the Flutter WebView with no game changes (replaces the old Option A/B workaround).
- v1.2: New `DELETE /me` (account deletion). Game-scoped `GET /tournaments?game_id=` now returns only live and upcoming tournaments unless `status=completed` is passed.

**v1.1 (Oct 2026)**
- Fixed: `GET /upcoming` (home banner) failed — now returns banner items.
- New: `/auth/guest`, `/auth/refresh`, `/genres`, `/tournaments/recommended`, `/progression/level-rewards`, `/progression/activity`, `/progression/how-to-earn`, `/achievements/categories`, `/me/username-available`, `/me/email`, `/me/password`, `/me/upgrade`.
- Upgraded: `/tournaments` (status/stake/sort/search, tags, avatars, prize breakdown, joined), `/missions` (type filter, refresh countdown, daily bonus, streak), `/achievements` (category/status filters), `/wallet/history` (Coins/Bites filter and labels), `/games` (entry cost `gameplay_fee`, pagination), `/home` (Bites balance, continue playing), `/referral` (`share_url`), `/me/devices` (recent sign-in activity), `PATCH /me` (available to guests, username checks).
- Tournament prizes are fixed; entry fees no longer change prize pools.

**v1.0 (Aug 2026)** — initial player API.

---

## Flutter Integration Guide

This section covers everything a Flutter developer needs to ship the Bitey
Games player app to production: how games are rendered, how the SDK
handshake works inside a WebView, where credentials come from, security
best practices, and a production checklist.

### Architecture overview

The Flutter app is a thin shell. It does two jobs:

1. **Player-facing screens** (home, wallet, rewards, tournaments, profile,
   store) are built natively in Flutter and talk to the Player REST API
   (`/api/v1/player/*`) using the player's Supabase session JWT.
2. **Gameplay** is rendered inside a native `WebView` that loads the same
   web game build the platform already serves. The game communicates with
   the platform through the embedded `@biteygames/sdk` inside the WebView,
   which calls the SDK Gateway (`/api/v1/sdk/rpc`).

```text
┌─────────────────────────────────────────────────────┐
│  Flutter App                                         │
│                                                     │
│  ┌───────────────┐     ┌─────────────────────────┐  │
│  │  Native UI    │     │  WebView (InAppWebView)  │  │
│  │  (Dart)       │     │  ┌─────────────────────┐ │  │
│  │               │     │  │  Web Game Build    │ │  │
│  │  REST calls   │     │  │  + @biteygames/sdk  │ │  │
│  │  /api/v1/player│    │  │       │            │ │  │
│  │       │       │     │  │  /api/v1/sdk/rpc    │ │  │
│  └───────┼───────┘     │  └─────────┼──────────┘ │  │
│          │             └────────────┼────────────┘  │
│          │  (Supabase JWT bearer)   │ (game-key+JWT)│
└──────────┼─────────────────────────┼───────────────┘
           ▼                         ▼
     Player REST API            SDK Gateway RPC
```

Two separate API surfaces, one shared user session token.

### 1. How gameplay works in the Flutter app

Games on Bitey Games are HTML5/Canvas/WebGL web builds — the exact same
builds that run in the platform's iframe on the web. The Flutter app does
not reimplement or port game logic. It renders the game inside a native
`WebView` (use `flutter_inappwebview` or `webview_flutter`).

**Flow:**

1. Flutter fetches the game's `game_url` from `GET /games/:gameId`.
2. Flutter opens a full-screen `WebView` pointing at that URL.
3. The web game initializes `@biteygames/sdk` and calls
   `BiteyGames.connect()`, which starts the handshake (see below).
4. Once connected, the game SDK handles its own session lifecycle:
   `session.start()`, `wallet.credit()`, `scores.submit()`,
   `state.save()`, `session.end()` — all through `/api/v1/sdk/rpc`.
5. Flutter does **not** need to call gameplay endpoints for the embedded
   game. The Player REST API's gameplay endpoints
   (`/gameplay/session/start`, `/gameplay/score`, etc.) exist for
   edge cases where the Flutter app itself needs to record a score or
   manage cloud save outside the WebView.

**WebView configuration:**

```dart
final settings = InAppWebViewSettings(
  // The game build needs same-origin and scripts to function.
  allowFileAccess: true,
  allowContentAccess: true,
  // Hardware acceleration for WebGL/Canvas games.
  hardwareAcceleration: true,
  // Allow media autoplay for games with audio.
  mediaPlaybackRequiresUserGesture: false,
  // Include app version in the user-agent for server-side gating.
  userAgent: 'BiteyGames/1.0.0 (Flutter; Android)',
);
```

**Banner ads:** On the web platform, banner ads are shown inside the
iframe container. In Flutter you can either let the web game handle its
own ads, or overlay a native ad widget at the bottom of the WebView and
fire `POST /analytics/event` to keep ad metrics unified.

### 2. Opening a game so it knows the player (v1.3)

On the website, the play page tells the game who the player is with a
`gv:auth` message. A Flutter WebView has no page around the game, so the app
passes the same details directly. **Game developers change nothing** — the
Bitey Games kit (HTML5 `/sdk`, npm package, Unity WebGL template) reads them
automatically.

**Step 1 — ask the API for a launch.** Works for guests and signed-in players.

```bash
curl -X POST https://biteygames.com/api/v1/player/games/GAME_ID/launch \
  -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: application/json" \
  -d '{"tournament_id": null}'
```

```json
{ "success": true, "data": {
  "game": { "id": "…", "name": "Road Rush 2" },
  "play_url": "https://…/index.html",
  "launch_url": "https://biteygames.com/embed/play#bitey_auth=%7B…%7D",
  "auth": { "type": "gv:auth", "token": "…", "session_id": "…", "game_id": "…",
            "tournament_id": null, "api_base": "https://biteygames.com",
            "user": { "id": "…", "username": "…", "avatar_url": null, "level": 3, "xp": 420 } }
} }
```

Errors: `NOT_FOUND` (404, no playable build), `NOT_JOINED` (403, tournament
not joined — call `/tournaments/:id/join` first).

> **Update (Nov 2026): one way to open every game in the app.** `launch_url` now points at
> `https://biteygames.com/embed/play#bitey_auth=…`, a small Bitey Games player page that loads the game
> and hands it the player the same way the website does. This works for **every** game — old copied-in
> kits, the hosted `/sdk`, and Unity — with no game changes. Always open `launch_url` (never `play_url` or
> your own injection) and listen for `bitey` events (`gv:exit`, `gv:wallet`, `gv:session_started`, …) from
> the WebView. Check: open a game → the game's console shows `SDK connected (via platform handshake)` →
> coins change in the wallet after a run.

**Step 2 — open the WebView.** Either load `launch_url` as-is (simplest), or
load `play_url` and inject `auth` before the page's scripts run:

```dart
final launch = (await api.post('/games/$gameId/launch', {'tournament_id': tid}))['data'];

InAppWebView(
  initialUrlRequest: URLRequest(url: WebUri(launch['launch_url'])),
  // Alternative to launch_url: inject before load
  initialUserScripts: UnmodifiableListView([
    UserScript(
      source: 'window.__BITEY_AUTH__ = ${jsonEncode(launch['auth'])};',
      injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START,
    ),
  ]),
  onWebViewCreated: (c) {
    // Step 3 — game events come back here
    c.addJavaScriptHandler(handlerName: 'bitey', callback: (args) {
      final msg = args.first as Map;
      switch (msg['type']) {
        case 'gv:session_started':
        case 'gv:session_end':
          refreshWallet(); break;
        case 'gv:exit':
          refreshWallet(); Navigator.pop(context); break;
      }
    });
  },
);
```

Using `webview_flutter` instead? Add a JavaScript channel named
`BiteyBridge`; the kit posts each event as a JSON string to it.

**Step 3 — refresh.** After `gv:session_end` / `gv:exit`, re-fetch
`/wallet`, `/progression` and `/missions`. Scores, Coins and Bites are
already saved on the server against the player (guest or full account).

**How to check it works**
- [ ] Guest taps Play → game opens without a sign-in screen.
- [ ] After a round, `/wallet/history` and `/progression/activity` show the new entries.
- [ ] Exit inside the game closes the WebView.
- [ ] Tournament play: launch with `tournament_id` and the score appears in `/tournaments/:id/standings`.

Tokens expire after about an hour: call `/auth/refresh`, then `/launch` again
for the next game.


### 3. Where keys and access tokens come from

The Flutter app needs credentials from three sources. Understanding which
credential goes where is critical — they are not interchangeable.

#### 3.1 Supabase project URL + publishable (anon) key

These are needed by the Supabase Flutter SDK (`supabase_flutter`) to
authenticate the player and obtain the JWT used for all Player REST API
calls. They are **public, publishable** values — safe to embed in the app
binary. They are not secret.

| Credential | Value / Where to get it | Used by |
|---|---|---|
| Supabase Project URL | `https://<project-ref>.supabase.co` — obtain the project ref from the platform admin / backend configuration; it is the host segment of your Supabase URL | `supabase_flutter` client init |
| Supabase publishable key | `sb_publishable_2NqY5bcxxF5eO9yeUkwKVQ_w01MDFXg` (already configured on the platform — safe to embed in the app binary) | `supabase_flutter` client init |

```dart
await Supabase.initialize(
  // Replace <project-ref> with your Supabase project ref from the platform admin.
  url: 'https://<project-ref>.supabase.co',
  anonKey: 'sb_publishable_2NqY5bcxxF5eO9yeUkwKVQ_w01MDFXg',
);
```

#### 3.2 Player session JWT (the actual auth token)

This is the only token the Player REST API accepts. It is obtained after
the player signs in via Supabase Auth (email/password or Google OAuth).
It expires (typically 1 hour) and must be refreshed with the Supabase
refresh token.

```dart
// Sign in
final response = await Supabase.instance.client.auth.signInWithPassword(
  email: email,
  password: password,
);
final accessToken = response.session!.accessToken;

// Use it for Player REST API calls
final res = await dio.get(
  'https://biteygames.com/api/v1/player/me',
  options: Options(headers: {'Authorization': 'Bearer $accessToken'}),
);
```

The `supabase_flutter` SDK handles token storage and refresh
automatically. Access the current token via
`Supabase.instance.client.auth.currentSession?.accessToken`.

#### 3.3 Game key (`gk_...`) — for the embedded game only

A public per-game identifier from the **Developer Dashboard — your game —
API Keys** tab. It is safe to ship in the app. It is used **only** by the
`@biteygames/sdk` inside the WebView (as the `x-game-key` header to
`/api/v1/sdk/rpc`), not by Flutter's own REST calls to `/api/v1/player/*`.

#### 3.4 Dev token (`bdt_...`) — local testing only

An 8-hour sandbox token minted in **Developer Dashboard — your game —
Local Development**. It authenticates as an auto-created sandbox player
with a separate wallet and isolated stats. Sandbox activity is excluded
from public leaderboards and analytics. **Never ship a dev token in a
production build.**

### Summary of credential usage

```text
┌─────────────────────┬────────────────────┬──────────────────┐
│ Credential          │ Used by            │ Sent to          │
├─────────────────────┼────────────────────┼──────────────────┤
│ Supabase URL+anon   │ supabase_flutter   │ Supabase Auth     │
│ Player JWT          │ Flutter REST calls │ /api/v1/player/* │
│ Player JWT (inject) │ SDK in WebView     │ /api/v1/sdk/rpc   │
│ Game key (gk_...)   │ SDK in WebView     │ /api/v1/sdk/rpc   │
│ Dev token (bdt_...) │ SDK on localhost   │ /api/v1/sdk/rpc   │
└─────────────────────┴────────────────────┴──────────────────┘
```

> The publishable anon key value (`sb_publishable_...`) is provided in
> section 3.1. The Supabase project ref for the URL is obtained from the
> platform admin / backend configuration.

### 4. Security best practices for production

#### 4.1 Secure token storage

Never store the Supabase session (access token + refresh token) in plain
`SharedPreferences` — it is readable by any process on a rooted Android
device. Use platform-secure storage:

```dart
// Use flutter_secure_storage for the Supabase session
// supabase_flutter supports this via a custom LocalStorage implementation:

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class SecureLocalStorage extends LocalStorage {
  final _storage = const FlutterSecureStorage();

  @override
  Future<String?> get(String key) async => await _storage.read(key: key);

  @override
  Future<void> set(String key, String value) async =>
      await _storage.write(key: key, value: value);

  @override
  Future<void> remove(String key) async => await _storage.delete(key: key);
}

await Supabase.initialize(
  // Replace <project-ref> with your Supabase project ref from the platform admin.
  url: 'https://<project-ref>.supabase.co',
  anonKey: 'sb_publishable_2NqY5bcxxF5eO9yeUkwKVQ_w01MDFXg',
  localStorage: SecureLocalStorage(),
);
```

On iOS this uses the Keychain; on Android it uses
EncryptedSharedPreferences + Keystore.

#### 4.2 JWT expiry and refresh

Supabase access tokens expire (default 1 hour). The `supabase_flutter` SDK
auto-refreshes, but you must handle the case where a REST call gets a
`401`:

```dart
Future<Response> playerGet(String path) async {
  final token = Supabase.instance.client.auth.currentSession?.accessToken;
  try {
    return await dio.get(
      'https://biteygames.com/api/v1/player$path',
      options: Options(headers: {'Authorization': 'Bearer $token'}),
    );
  } on DioException catch (e) {
    if (e.response?.statusCode == 401) {
      // Token expired — force refresh and retry once
      await Supabase.instance.client.auth.refreshSession();
      final newToken =
          Supabase.instance.client.auth.currentSession?.accessToken;
      return await dio.get(
        'https://biteygames.com/api/v1/player$path',
        options: Options(headers: {'Authorization': 'Bearer $newToken'}),
      );
    }
    rethrow;
  }
}
```

#### 4.3 Never embed secrets in the app binary

- The Supabase **publishable/anon key** and the **game key** (`gk_...`)
  are public — safe to embed.
- The Supabase **service role key** must **never** be in the app. It
  bypasses RLS and grants full database access.
- **Dev tokens** (`bdt_...`) must never ship in production builds.
- Payment provider keys (Stripe, Razorpay) — only use the publishable
  key client-side; secret keys are server-only.

#### 4.4 HTTPS everywhere

All API calls must go over `https://`. Never disable certificate
validation. Never use `http://` in production, even for testing.
Configure `dio` to enforce TLS:

```dart
final dio = Dio(BaseOptions(
  baseUrl: 'https://biteygames.com',
  connectTimeout: const Duration(seconds: 10),
  receiveTimeout: const Duration(seconds: 15),
));
```

#### 4.5 Input validation

The API validates all input server-side with Zod schemas, but the Flutter
app should still validate before sending (e.g., email format, password
length, username character restrictions). Never send unvalidated user
input to any endpoint. Always URL-encode query parameters.

#### 4.6 WebView security

- Only load game URLs from `biteygames.com` or whitelisted CDN origins.
  Never load arbitrary URLs in the game WebView.
- Do not enable `allowFileAccessFromFileURLs` or
  `allowUniversalAccessFromFileURLs` — these create XSS vectors.
- The game build runs in a sandboxed context; do not inject platform
  secrets beyond the player's session token.

#### 4.7 Push token security

Register FCM/APNS tokens via `POST /me/push-token` immediately after
sign-in. Delete them on sign-out (`DELETE /me/push-token?token=...`) so
notifications don't reach a device after the user logs out.

```dart
// On sign-in
final fcmToken = await FirebaseMessaging.instance.getToken();
if (fcmToken != null) {
  await playerPost('/me/push-token', {'token': fcmToken, 'platform': 'android'});
}

// On sign-out
final fcmToken = await FirebaseMessaging.instance.getToken();
if (fcmToken != null) {
  await playerDelete('/me/push-token?token=$fcmToken');
}
await Supabase.instance.client.auth.signOut();
```

#### 4.8 Error handling and information leakage

Always check the `success` field in the response envelope. Map
`error.code` to user-facing messages. Never log full response bodies or
tokens to the console or crash reporting — they may contain sensitive
data. Filter crash reports to strip authorization headers.

#### 4.9 Guest account handling

Guest sessions (anonymous sign-in) can read data and claim casual
rewards, but cannot spend, purchase, join tournaments, or apply referral
codes. These endpoints return `403 GUEST_NOT_ALLOWED`. The Flutter app
should intercept this and prompt the user to create a full account:

```dart
if (errorResponse.statusCode == 403 &&
    errorResponse.data['error']?['code'] == 'GUEST_NOT_ALLOWED') {
  // Show upgrade-to-account prompt
  _showUpgradeDialog();
  return;
}
```

### 5. Production checklist

- [ ] **Supabase init** — configure `supabase_flutter` with project URL
      and publishable key.
- [ ] **Secure storage** — use `flutter_secure_storage` for the session,
      not `SharedPreferences`.
- [ ] **Auth flow** — email/password and Google sign-in; handle refresh.
- [ ] **401 retry** — intercept `401`, refresh the session, retry once.
- [ ] **Game WebView** — configure `flutter_inappwebview` with hardware
      acceleration, scripts enabled, no file access from URLs.
- [ ] **Token injection** — inject the JWT into the WebView before the
      game loads (section 2 above: `POST /games/:id/launch`).
- [ ] **Token refresh in WebView** — re-inject on `TOKEN_REFRESHED`.
- [ ] **Game key** — embed the public `gk_...` key; never ship API
      secrets or dev tokens.
- [ ] **Push tokens** — register FCM/APNS on login; delete on logout.
- [ ] **App version gating** — call `GET /config` at launch; honor
      `maintenance` and `min_supported_version`.
- [ ] **Rate limit handling** — respect `X-RateLimit-Remaining`; back off
      on `429`.
- [ ] **Error handling** — check `success`; map `error.code` to UI
      messages; handle `GUEST_NOT_ALLOWED`.
- [ ] **Offline support** — queue gameplay scores and analytics events
      locally; replay when online (scores are idempotent per session).
- [ ] **HTTPS only** — never use `http://` in production; never disable
      cert validation.
- [ ] **Crash reporting** — strip authorization headers and tokens from
      crash reports.
- [ ] **No secrets in binary** — publishable key and game key only;
      no service role key, no dev tokens, no payment secret keys.

## Update (Oct 2026): tournament scores
Open tournament games through POST /api/v1/player/games/:id/launch with the tournament_id. Scores from the game are credited to the player's live tournament automatically; refresh the tournament details screen to show standings.

## Update (Oct 30 2026): browsing without sign-in + "game not connected" checklist

### Public browse endpoints (no token needed)
These now work with **no** `Authorization` header, so the app can show content before sign-in:
`GET /home`, `/games`, `/games/:gameId`, `/genres`, `/upcoming`, `/tournaments`, `/tournaments/recommended`, `/tournaments/:id`, `/tournaments/:id/standings`.
If a token is sent, personal fields (wallet, missions, joined, recommendations) are filled in. Without one, `/home` returns `signed_in: false` with featured games, and tournaments return `is_guest: true`, `joined: false`.
Everything else (launch, play, wallet, missions, rewards, join, profile) still needs a token. To let users play straight away, the app can call `POST /auth/guest` silently on first launch.

### `:id` in `POST /games/:id/launch`
`:id` is the game's `id` from `GET /games` (e.g. Galactic Dash = `99c352b1-b6e3-4ae1-a3bf-364f4f808a70`).

### Game not spending/earning coins or losing purchases — check these
1. **The game must call the kit.** Spending: `await gv.wallet.debit(amount, "warship")`. Earning: `await gv.wallet.credit(amount, "run_reward")`. Keeping items: `gv.state.set({ ships: [...] })` then `await gv.state.save()` (load it back with `await gv.state.load()` on start). Items held only in game memory are lost on exit.
2. **The app must open `launch_url`**, not `play_url`. `launch_url` carries the player identity.
3. **Use the current kit.** Load it from `https://biteygames.com/sdk` or rebuild a bundled copy with the latest version.
4. **On Exit:** `await gv.shutdown()` (it saves state and ends the session) — and wait for it before the app closes the WebView. The app should close on the `gv:exit` message, not immediately on tap.
5. **Look at the browser console.** `[BiteyGames] NOT CONNECTED` means no identity reached the game (see item 2/3).

Quick test: play once in the app, buy something and finish a run, then check the player's wallet history — it should show one spend and one reward line for the game.
Quick test: play once in the app, buy something and finish a run, then check the player's wallet history — it should show one spend and one reward line for the game.

### Troubleshooting: "session.start() failed — Load failed" (iOS)
If Safari Web Inspector shows `Fetch API cannot load http://biteygames.com/api/v1/sdk/rpc due to access control checks`, the game was given an `http://` server address. Since Nov 2026 the launch response always returns `https://` and the player page upgrades old links. Log `data.auth.api_base` from the launch response — it must start with `https://`.

## Update (Nov 9 2026): game leaderboards, fitting the screen, iOS full screen

### Game leaderboard: show score, not XP
`GET /leaderboard/xp` is the **overall Bites (XP) ranking**. It is not a game leaderboard. For a game's leaderboard screen, use:

```
GET /api/v1/player/leaderboard/game/:gameId?period=daily|weekly|monthly|all_time&limit=50
```

Sign-in is optional. With a token you also get `my_rank` and `my_score`.

```json
{
  "period": "weekly",
  "game_id": "99c352b1-...",
  "total": 42,
  "entries": [
    { "rank": 1, "user_id": "0f59...", "username": "A_H", "avatar_url": "https://...", "score": 18450 }
  ],
  "my_rank": 7,
  "my_score": 9120
}
```

Show `score` in the list. `period` defaults to `weekly`.

### Game wider than the screen (for example Stax in portrait)
The player page at `launch_url` now locks itself to the device width (`viewport-fit=cover`, no zoom) and clips anything that overflows. If a game still spills off the side, the game is drawing at a fixed width:
- HTML5: size the canvas from `window.innerWidth/innerHeight` and listen for `resize`; never hard-code 1280 px or similar.
- Unity WebGL: use the Bitey Games template, a Canvas Scaler set to "Scale With Screen Size", and match width in portrait.

### Full screen on iOS
iPhone Safari and WKWebView don't let a web page go full screen by itself, so the Flutter game screen must do it:

```dart
// When the game screen opens
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);

// When it closes
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);

Scaffold(
  extendBody: true,
  extendBodyBehindAppBar: true,
  appBar: null,                 // no AppBar on the game screen
  body: WebViewWidget(controller: controller), // NOT wrapped in SafeArea
);
```

With `webview_flutter_wkwebview`, allow inline media playback (`allowsInlineMediaPlayback: true` in `WebKitWebViewControllerCreationParams`), and in `Info.plist` set `UIViewControllerBasedStatusBarAppearance` = `NO` / `UIStatusBarHidden` = `YES` for the game screen if needed. Keep your own Exit button inside the safe area (use `MediaQuery.of(context).padding`).
