# misbahan/67-royale architecture

> Architecture diagram of the GitHub repository misbahan/67-royale, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-30). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/misbahan/67-royale
- Repository: https://github.com/misbahan/67-royale

## Overview

67 Royale is a single Next.js application that contains both the browser game client and the server API layer. There is no separate backend service in the repo; instead, Next.js App Router pages render the UI, and Next.js route handlers under `src/app/api` implement the backend behavior.

Main architectural layers:

1. Client/UI layer
- Located under `frontend/src/app` and `frontend/src/components`.
- The app includes separate user flows for:
  - Solo challenge play
  - Ranked PvP matchmaking
  - Friendly 1v1 duel lobbies
  - Leaderboards and score-sharing pages
  - Tournament screens
- The `components/game` subtree holds the actual gameplay UI: camera feed, countdown, calibration overlay, game overlay, start/end screens, and mode selection.
- Shared UI elements live in `components/ui`, while leaderboard and tournament-specific panels live in their own component folders.

2. Client-side game engine / computer vision layer
- The core gameplay logic is browser-side, because it needs webcam access and low-latency per-frame tracking.
- Important code lives in `src/lib/hand-tracking.ts`, `src/lib/brainrot-detector.ts`, `src/lib/pose/movenetProvider.ts`, and hooks such as `useHandTracking` and `useGameState`.
- This layer consumes the webcam stream, detects hand landmarks, applies calibration, and counts valid alternations/reps.
- The README describes MediaPipe Hands and a custom alternation detector; the repo structure supports that as a client-side CV pipeline.
- This is intentionally local-first: raw camera processing happens in the browser to keep latency down and avoid sending video to the server for solo gameplay.

3. Real-time multiplayer layer
- PvP and friendly lobbies add a second runtime path: WebRTC-based peer-to-peer video.
- `src/hooks/useWebRTC.ts` handles client-side peer connection setup.
- Signaling and match state are mediated through Firestore-backed API routes rather than a dedicated signaling server.
- In practice:
  - The clients connect directly for media transport.
  - The app server coordinates lobby creation, join/ready/start state, and signaling metadata.
  - TURN support is optional but important for real-world connectivity.

4. Backend/API layer
- `src/app/api` contains many route groups, each representing a subsystem boundary:
  - Solo/challenge: create, session, submit, and challenge lookup routes
  - Duel: create, join, find, ready, start, submit, session, and duel lookup routes
  - Matchmaking: join, leave, status
  - Leaderboard and stats: leaderboard, PvP leaderboard, score lookup, user stats
  - Tournament: create, join, leave, list, start, cancel, match-start, and tournament lookup
  - Seed and session-related routes
  - OG image generation routes for share cards
- These route handlers are the main server-side orchestration point for validation, persistence, and state transitions.
- `src/lib/jwt.ts`, `src/lib/rate-limit.ts`, and `src/lib/profanity.ts` are cross-cutting server utilities used to enforce trust boundaries around submissions and usernames.

5. Data/storage layer
- Firebase Firestore is the primary persistent store.
- `src/lib/firebase/client.ts` and `src/lib/firebase/server.ts` separate browser SDK access from server/admin access.
- The backend uses Firebase Admin server-side for privileged operations; the client is limited to safer access patterns.
- The README defines the key collections:
  - `scores` for solo leaderboard entries
  - `duels` for private lobby sessions and WebRTC signaling subcollections
  - `duel_players` for duel participants
  - `pvp_matches` for ranked match records
  - `user_stats` for player profile, ELO, wins/losses, trophies
- `firestore.rules` and `firebase.json` define the Firestore security boundary and Firebase deployment config.

Important data flows

Solo challenge flow:
- User opens a challenge page.
- Browser acquires webcam access and runs the hand-tracking / rep-detection pipeline locally.
- When the session ends, the client submits a result to server routes such as challenge/submit or score-related endpoints.
- The server validates the request, checks rate limits and JWT/session state, and stores the result in Firestore.
- Leaderboard and score pages read back aggregated results.

PvP matchmaking flow:
- Player joins matchmaking through `matchmaking/join`.
- The backend places or pairs players and exposes status through `matchmaking/status`.
- A match record is created in Firestore, and WebRTC negotiation happens between clients.
- After the match, the result is submitted to the server, which updates `pvp_matches` and `user_stats`/ELO-related data.

Friendly duel flow:
- One player creates a duel lobby and receives a shareable 6-digit code.
- The second player joins through the code.
- Readiness and start state are coordinated through duel API routes.
- WebRTC signaling is stored/relayed through Firestore-backed duel state.
- Scores are submitted separately and the server records the outcome without affecting rankings.

Tournament flow:
- The tournament subsystem exists as a separate state machine for bracketed play.
- Routes under `api/tournament` handle create/join/leave/list/start/cancel and match starts.
- UI under `app/tournament` and `components/tournament` renders bracket and match state.
- This appears to be a distinct domain model from duel/PvP, but it still reuses the same auth, Firestore, and submission infrastructure.

Cross-cutting boundaries

- Camera and CV processing stay on the client.
- All authoritative score submission and match state changes go through server routes.
- Firestore is the main backend state store, but protected by server-side validation and Firestore rules.
- JWT session validation and rate limiting are used to prevent score replay and spam.
- Profanity filtering is applied to usernames before they are persisted.
- Middleware in `src/middleware.ts` likely participates in request/session gating at the edge.

Operational/deployment shape

- The app is designed for Vercel deployment.
- Firebase provides database and related backend services.
- TURN servers are an external dependency for reliable WebRTC in restrictive networks.
- MediaPipe model assets are loaded client-side, which affects first-load latency and browser compatibility.

How to think about the diagram

A good architecture diagram for this repo should show:
- A browser client containing UI, webcam capture, hand tracking, game state, and WebRTC peers.
- A Next.js server/API boundary handling sessions, matchmaking, duel/tournament orchestration, score validation, leaderboard reads, and OG image generation.
- Firestore as the central shared state store, with separate collections for scores, duels, PvP matches, user stats, and tournament-related data.
- External services for Firebase, TURN/WebRTC relay, and model/CDN assets.
- Distinct flows for solo play versus real-time multiplayer, since only the multiplayer paths require peer connections and signaling.

Main entry points: [`frontend/src/lib/firebase/server.ts`](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/lib/firebase/server.ts) (Firestore server), [`frontend/src/app/page.tsx`](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/app/page.tsx) (Game pages), [`frontend/src/app/api/challenge`](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/app/api/challenge) (Challenge API), [`frontend/src/app/api/duel`](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/app/api/duel) (Duel API)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph "Browser client"
  app_shell["App shell<br/>Next.js app<br/>[layout.tsx]"]
  home_pages["Game pages<br/>route pages<br/>[page.tsx]"]
  game_ui["Game UI<br/>components"]
  leaderboard_ui["Leaderboard UI<br/>components"]
  tournament_ui["Tournament UI<br/>components"]
  shared_ui["Shared UI<br/>components"]
  auth_context(("Auth context<br/>client state<br/>[AuthContext.tsx]"))
  game_state(("Game state<br/>hook<br/>[useGameState.ts]"))
  hand_tracking(("Hand tracking<br/>hook<br/>[useHandTracking.ts]"))
  webrtc_hook(("WebRTC hook<br/>[useWebRTC.ts]"))
  tournament_hook(("Tournament hook<br/>[useTournament.ts]"))
end

subgraph "Next.js API"
  api_challenge["Challenge API<br/>route group"]
  api_duel["Duel API<br/>route group"]
  api_matchmaking["Matchmaking API<br/>route group"]
  api_leaderboard["Leaderboard API<br/>route group"]
  api_tournament["Tournament API<br/>route group"]
  api_scores["Score API<br/>route"]
  api_session["Session API<br/>route"]
  api_og["OG images<br/>route"]
  api_stats["Stats API<br/>route"]
end

subgraph "Data layer"
  firestore_client[("Firestore client<br/>firebase sdk<br/>[client.ts]")]
  firestore_server[("Firestore server<br/>firebase admin<br/>[server.ts]")]
  db_types["DB types<br/>schema types<br/>[database.ts]"]
  firestore_rules["Rules<br/>firestore config<br/>[firestore.rules]"]
end

subgraph "Shared infra"
  jwt{{"JWT auth<br/>[jwt.ts]"}}
  rate_limit{{"Rate limit<br/>[rate-limit.ts]"}}
  profanity{{"Profanity filter<br/>[profanity.ts]"}}
  middleware{{"Middleware<br/>edge gate<br/>[middleware.ts]"}}
  webcam_models["CV models<br/>browser assets<br/>[movenetProvider.ts]"]
  ext_firebase[("Firebase<br/>external service")]
  ext_turn["TURN relay<br/>external service"]
end

home_pages -->|"renders"| game_ui
home_pages -->|"renders"| leaderboard_ui
home_pages -->|"renders"| tournament_ui
home_pages -->|"uses"| shared_ui
home_pages -->|"consumes"| auth_context
game_ui -->|"driven by"| game_state
game_state -->|"uses"| hand_tracking
hand_tracking -->|"loads"| webcam_models
game_state -->|"submits to"| api_challenge
game_state -->|"submits to"| api_scores
webrtc_hook -->|"signals via"| api_duel
webrtc_hook -->|"pairs via"| api_matchmaking
webrtc_hook -->|"relays via"| ext_turn
tournament_hook -->|"syncs with"| api_tournament
api_challenge -->|"writes"| firestore_server
api_duel -->|"writes"| firestore_server
api_matchmaking -->|"writes"| firestore_server
api_leaderboard -->|"reads"| firestore_server
api_tournament -->|"writes"| firestore_server
api_scores -->|"reads/writes"| firestore_server
api_stats -->|"reads/writes"| firestore_server
api_session -->|"validates"| jwt
api_challenge -->|"protects"| rate_limit
api_duel -->|"protects"| rate_limit
api_scores -->|"protects"| rate_limit
api_challenge -->|"cleans"| profanity
api_duel -->|"cleans"| profanity
api_session -->|"gated by"| middleware
api_challenge -->|"constrained by"| firestore_rules
firestore_client -->|"connects to"| ext_firebase
firestore_server -->|"connects to"| ext_firebase
db_types -->|"types"| firestore_server
db_types -->|"types"| firestore_client
api_og -->|"supports"| api_duel
api_og -->|"supports"| api_scores

click app_shell "https://github.com/misbahan/67-royale/blob/main/frontend/src/app/layout.tsx"
click home_pages "https://github.com/misbahan/67-royale/blob/main/frontend/src/app/page.tsx"
click game_ui "https://github.com/misbahan/67-royale/tree/main/frontend/src/components/game"
click leaderboard_ui "https://github.com/misbahan/67-royale/tree/main/frontend/src/components/leaderboard"
click tournament_ui "https://github.com/misbahan/67-royale/tree/main/frontend/src/components/tournament"
click shared_ui "https://github.com/misbahan/67-royale/tree/main/frontend/src/components/ui"
click auth_context "https://github.com/misbahan/67-royale/blob/main/frontend/src/contexts/AuthContext.tsx"
click game_state "https://github.com/misbahan/67-royale/blob/main/frontend/src/hooks/useGameState.ts"
click hand_tracking "https://github.com/misbahan/67-royale/blob/main/frontend/src/hooks/useHandTracking.ts"
click webrtc_hook "https://github.com/misbahan/67-royale/blob/main/frontend/src/hooks/useWebRTC.ts"
click tournament_hook "https://github.com/misbahan/67-royale/blob/main/frontend/src/hooks/useTournament.ts"
click api_challenge "https://github.com/misbahan/67-royale/tree/main/frontend/src/app/api/challenge"
click api_duel "https://github.com/misbahan/67-royale/tree/main/frontend/src/app/api/duel"
click api_matchmaking "https://github.com/misbahan/67-royale/tree/main/frontend/src/app/api/matchmaking"
click api_leaderboard "https://github.com/misbahan/67-royale/tree/main/frontend/src/app/api/leaderboard"
click api_tournament "https://github.com/misbahan/67-royale/tree/main/frontend/src/app/api/tournament"
click api_scores "https://github.com/misbahan/67-royale/tree/main/frontend/src/app/api/score"
click api_session "https://github.com/misbahan/67-royale/tree/main/frontend/src/app/api/session"
click api_og "https://github.com/misbahan/67-royale/tree/main/frontend/src/app/api/og"
click api_stats "https://github.com/misbahan/67-royale/tree/main/frontend/src/app/api/stats"
click firestore_client "https://github.com/misbahan/67-royale/blob/main/frontend/src/lib/firebase/client.ts"
click firestore_server "https://github.com/misbahan/67-royale/blob/main/frontend/src/lib/firebase/server.ts"
click db_types "https://github.com/misbahan/67-royale/blob/main/frontend/src/types/database.ts"
click firestore_rules "https://github.com/misbahan/67-royale/blob/main/firestore.rules"
click jwt "https://github.com/misbahan/67-royale/blob/main/frontend/src/lib/jwt.ts"
click rate_limit "https://github.com/misbahan/67-royale/blob/main/frontend/src/lib/rate-limit.ts"
click profanity "https://github.com/misbahan/67-royale/blob/main/frontend/src/lib/profanity.ts"
click middleware "https://github.com/misbahan/67-royale/blob/main/frontend/src/middleware.ts"
click webcam_models "https://github.com/misbahan/67-royale/blob/main/frontend/src/lib/pose/movenetProvider.ts"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class app_shell,home_pages,game_ui,leaderboard_ui,tournament_ui,shared_ui,auth_context,game_state,hand_tracking,webrtc_hook,tournament_hook toneBlue
class api_challenge,api_duel,api_matchmaking,api_leaderboard,api_tournament,api_scores,api_session,api_og,api_stats toneAmber
class firestore_client,firestore_server,db_types,firestore_rules toneMint
class jwt,rate_limit,profanity,middleware,webcam_models,ext_firebase,ext_turn toneRose
```

## Components

### Browser client

Next.js App Router UI plus browser-side game/CV/runtime logic.

- [App shell](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/app/layout.tsx): Next.js app · Root layout, global styles, and top-level pages for the web app. · `frontend/src/app/layout.tsx`
- [Game pages](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/app/page.tsx): route pages · Entry pages for solo challenge, duel, PvP, leaderboard, score, and tournament flows. · `frontend/src/app/page.tsx`
- [Game UI](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/components/game): components · Gameplay screens and overlays for camera, calibration, countdown, start/end states, and mode selection. · `frontend/src/components/game`
- [Leaderboard UI](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/components/leaderboard): components · Leaderboard presentation panel used by score and ranking screens. · `frontend/src/components/leaderboard`
- [Tournament UI](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/components/tournament): components · Bracket, match, and tournament cards for tournament views. · `frontend/src/components/tournament`
- [Shared UI](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/components/ui): components · Common header, footer, icons, and legal modal elements. · `frontend/src/components/ui`
- [Auth context](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/contexts/AuthContext.tsx): client state · Client-side session/user context used across pages and hooks. · `frontend/src/contexts/AuthContext.tsx`
- [Game state](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/hooks/useGameState.ts): hook · Coordinates client gameplay state transitions and result flow. · `frontend/src/hooks/useGameState.ts`
- [Hand tracking](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/hooks/useHandTracking.ts): hook · Browser webcam pipeline for landmark tracking and rep detection. · `frontend/src/hooks/useHandTracking.ts`
- [WebRTC hook](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/hooks/useWebRTC.ts): hook · Sets up peer connections for friendly duel and PvP media transport. · `frontend/src/hooks/useWebRTC.ts`
- [Tournament hook](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/hooks/useTournament.ts): hook · Client-side tournament state and refresh logic. · `frontend/src/hooks/useTournament.ts`

### Next.js API

Route handlers that validate, orchestrate, and persist game state.

- [Challenge API](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/app/api/challenge): route group · Create, session, lookup, and submit endpoints for solo challenge runs. · `frontend/src/app/api/challenge`
- [Duel API](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/app/api/duel): route group · Lobby creation, join/start/readiness, session, submit, and duel lookup routes. · `frontend/src/app/api/duel`
- [Matchmaking API](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/app/api/matchmaking): route group · Join, leave, and status endpoints for ranked pairing. · `frontend/src/app/api/matchmaking`
- [Leaderboard API](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/app/api/leaderboard): route group · Aggregated leaderboard endpoints for solo and PvP rankings. · `frontend/src/app/api/leaderboard`
- [Tournament API](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/app/api/tournament): route group · Tournament lifecycle and match-start orchestration endpoints. · `frontend/src/app/api/tournament`
- [Score API](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/app/api/score): route · Score lookup and submission endpoints used by share pages and result views. · `frontend/src/app/api/score`
- [Session API](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/app/api/session): route · Session and user-state endpoint for request gating. · `frontend/src/app/api/session`
- [OG images](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/app/api/og): route · Open Graph image generation for share cards. · `frontend/src/app/api/og`
- [Stats API](https://github.com/misbahan/67-royale/tree/HEAD/frontend/src/app/api/stats): route · User stats and profile endpoint used for player progress. · `frontend/src/app/api/stats`

### Data layer

Firestore access, rules, and typed storage models.

- [Firestore client](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/lib/firebase/client.ts): firebase sdk · Browser Firebase access for safe client reads and auth-aware usage. · `frontend/src/lib/firebase/client.ts`
- [Firestore server](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/lib/firebase/server.ts): firebase admin · Privileged server-side Firestore access for authoritative writes and orchestration. · `frontend/src/lib/firebase/server.ts`
- [DB types](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/types/database.ts): schema types · Typed Firestore/database and game model definitions. · `frontend/src/types/database.ts`
- [Rules](https://github.com/misbahan/67-royale/blob/HEAD/firestore.rules): firestore config · Security boundary for direct Firebase data access. · `firestore.rules`

### Shared infra

Cross-cutting auth, limits, filtering, middleware, and external dependencies.

- [JWT auth](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/lib/jwt.ts): utility · Token validation for trusted submissions and gated actions. · `frontend/src/lib/jwt.ts`
- [Rate limit](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/lib/rate-limit.ts): utility · Server-side abuse control for score and action submissions. · `frontend/src/lib/rate-limit.ts`
- [Profanity filter](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/lib/profanity.ts): utility · Username moderation before persistence. · `frontend/src/lib/profanity.ts`
- [Middleware](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/middleware.ts): edge gate · Edge request/session gating before routes execute. · `frontend/src/middleware.ts`
- [CV models](https://github.com/misbahan/67-royale/blob/HEAD/frontend/src/lib/pose/movenetProvider.ts): browser assets · MediaPipe and MoveNet model assets consumed client-side for low-latency tracking. · `frontend/src/lib/pose/movenetProvider.ts`
- **Firebase**: external service · Managed database and backend platform backing Firestore usage.
- **TURN relay**: external service · Optional relay service for reliable WebRTC connectivity.

## Connections

- Game pages → Game UI: renders · Pages compose the gameplay UI.
- Game pages → Leaderboard UI: renders · Leaderboard pages use shared panels.
- Game pages → Tournament UI: renders · Tournament pages use bracket and card components.
- Game pages → Shared UI: uses · All screens share common chrome and legal UI.
- Game pages → Auth context: consumes · Pages read auth/session context.
- Game UI → Game state: driven by · Gameplay screens react to client game state.
- Game state → Hand tracking: uses · Game state depends on browser CV input.
- Hand tracking → CV models: loads · Tracking pipeline uses client-side pose/model assets.
- Game state → Challenge API: submits to · Solo results are posted to challenge routes.
- Game state → Score API: submits to · Some result flows use score endpoints.
- WebRTC hook → Duel API: signals via · Duel lobby and signaling metadata are coordinated by routes.
- WebRTC hook → Matchmaking API: pairs via · Ranked pairing state is coordinated through matchmaking routes.
- WebRTC hook → TURN relay: relays via · TURN improves peer connectivity when direct P2P fails.
- Tournament hook → Tournament API: syncs with · Tournament state is coordinated through tournament routes.
- Challenge API → Firestore server: writes · Authoritative solo results and sessions are persisted server-side.
- Duel API → Firestore server: writes · Lobby state, signaling, and duel outcomes are stored server-side.
- Matchmaking API → Firestore server: writes · Matchmaking state and match records are persisted server-side.
- Leaderboard API → Firestore server: reads · Leaderboard endpoints aggregate stored results.
- Tournament API → Firestore server: writes · Tournament lifecycle and bracket state are stored server-side.
- Score API → Firestore server: reads/writes · Score lookup and submission touch authoritative storage.
- Stats API → Firestore server: reads/writes · User profile and ELO-like stats are maintained in storage.
- Session API → JWT auth: validates · Session and request trust are checked with JWT helpers.
- Challenge API → Rate limit: protects · Submission endpoints are rate-limited.
- Duel API → Rate limit: protects · Lobby and submit endpoints are rate-limited.
- Score API → Rate limit: protects · Score submission endpoints are rate-limited.
- Challenge API → Profanity filter: cleans · Submitted names are filtered before persistence.
- Duel API → Profanity filter: cleans · Lobby/player names are filtered before persistence.
- Session API → Middleware: gated by · Edge middleware participates in request/session gating.
- Challenge API → Rules: constrained by · Direct client access remains bounded by Firestore rules.
- Firestore client → Firebase: connects to · Browser SDK talks to Firebase services.
- Firestore server → Firebase: connects to · Admin SDK talks to Firebase services.
- DB types → Firestore server: types · Server storage code follows shared database models.
- DB types → Firestore client: types · Client data access follows shared database models.
- OG images → Duel API: supports · Share-card images are generated for duel flows.
- OG images → Score API: supports · Share-card images are generated for score pages.
