# KittyRec Server — Complete Flow Reference --- ## High-Level Architecture ``` Internet │ ▼ Nginx / Reverse Proxy (port 443 → 8080) │ ▼ Flask (Gunicorn / app.py) — port 8080 ├── HTTP Routes (22 blueprints) ├── WebSocket /api/notification/v2 (flask-sock) ├── Admin Panel /admin (Flask-Admin 2.x) └── SQLite Database (single file, WAL mode) Background Threads (daemons.py) ├── ban-enforcer (every 5s) ├── presence-watchdog (every 20s) ├── count-recorder (every 5min) ├── kittyrec-system (persistent, PID 23 keepalive) └── register_graceful_shutdown (SIGTERM handler) Discord Bot (separate process — /home/kittyrecbots/KittyNet-DiscordBot/) └── Calls Public API + Internal API (/api/internal/discord/*) ``` --- ## Startup Sequence (app.py) ``` 1. ProxyFix applied (x_for=1) → request.remote_addr is correct client IP 2. All 22 blueprints registered 3. Flask-Admin mounted at /admin with Bootstrap4Theme 4. SQLite DB initialized → _create_tables() runs all CREATE TABLE IF NOT EXISTS 5. Daemons started: start_ban_enforcer() start_player_count_recorder() start_presence_watchdog() register_graceful_shutdown() 6. bring_system_account_online() → PID 23 fake WS keepalive thread 7. Flask-Sock WebSocket handler registered 8. Server starts listening on 0.0.0.0:8080 ``` --- ## Every HTTP Request — Lifecycle ``` Request arrives │ ├── @limiter (flask-limiter, keyed by real IP via ProxyFix) │ Default limits set in core/limiter.py │ Route-level overrides via @limiter.limit("N per minute") │ ├── @check_auth (core/auth.py) │ Reads JWT from Authorization header │ Decodes → profile_id stored in flask.g │ Returns 401 if missing/invalid │ ├── Route handler runs │ └── Response sent ``` **Auth token flow:** ``` Login → _issue_token(pid) JWT signed with server secret Payload: { sub: pid, exp: +30days } Returned as "AuthToken" in login response All subsequent requests: Authorization: get_current_profile_id() → decodes JWT → returns pid ``` --- ## Authentication System (routes/auth.py) ### Login Flow ``` POST /api/platformlogin/v1/loginaccount │ ├── IP ban check → 403 if banned ├── Maintenance mode check → 403 if active (unless exempt) ├── Username + password verified (bcrypt) ├── Daily login reward awarded (_award_daily_login) ├── Cascade ban check (linked IP/platform accounts) ├── JWT issued (_issue_token) └── Returns full profile + token + avatar + settings ``` ### Other Auth Endpoints | Endpoint | Purpose | |---|---| | `POST /loginaccount` | Username + password login | | `POST /logincached` | Token + Platform + PlatformId (trusted re-auth) | | `POST /createaccount` | New account creation | | `POST /registeraccount` | Post-OOBE username/password registration | | `GET/POST /refreshlogin` | Extend token TTL | | `POST /logout` | Invalidate cached login | | `GET/POST /getcachedlogins` | List saved logins | | `POST /removecachedlogin` | Delete a saved login | --- ## WebSocket System (routes/ws.py) ### Connection Lifecycle ``` Client opens WS to /api/notification/v2 │ ├── JWT auth check → close if invalid ├── IP logged to ip_logins table ├── Ban check → send Id:20 (kick) + close if banned ├── Maintenance check → close if active ├── IP ban check → cascade ban if at banned IP │ ├── Receive handshake JSON from client ├── Send { SessionId: N } back │ ├── ws_registry.register(pid, ws) ├── record_heartbeat(pid) ← presence watchdog ├── Restore screen mode from DB settings │ ├── First-login Discord webhook (if first ever login) ├── Place player in dorm room session (if no session) ├── push_presence(pid, session) ← broadcasts to all online │ ├── Send Id:12 for every already-online player ├── Send Id:12 for PID 23 (system account) │ ├── Send temp password DM (if no real password set, after 10s delay) │ └── Enter receive loop ──────────────────────────────────────┐ │ heartbeat2 │ record_heartbeat(pid) │ Read SpecialGamemode from param → update session │ Send Id:4 (heartbeat response with current session) │ │ playerSubscriptions/v1/update │ For each subscribed PID → send Id:12 (presence) │ │ (anything else → logged as unhandled) │ │ ws.receive() returns None (disconnect) ─────────────────┘ ws_registry.unregister(pid, ws) session_mgr.leave_session(pid) push_presence(pid, None, online=False) session_gift_reset(pid) ``` ### WebSocket Message IDs | Id | Direction | Meaning | |---|---|---| | 2 | Server→Client | Chat/DM message push | | 4 | Server→Client | Heartbeat response (your own presence) | | 12 | Server→Client | Another player's presence update | | 20 | Server→Client | Kick / ban notification | | 22 | Server→Client | Moderation action (kick from room) | | 90 | Server→Client | Chat message push (in-room) | --- ## Session & Room System ### In-Memory State (core/state.py) **`SessionManager`** — tracks all active game sessions ``` GameSession: session_id int (auto-increment) activity_level_id GUID string (maps to a known activity or room) name display name (e.g. "Dodgeball") activity_key short key (e.g. "room", "dodgeball") private bool — hides from public session list sandbox bool creator_player_id int max_capacity int (1–40, default 20) players set[int] — PIDs currently in session photon_room_id string (e.g. "room_42") rec_room_id int | None — links to rooms DB table special_gamemode int ``` **`ConnectionRegistry`** — tracks live WebSocket connections ``` _conns: dict[pid → ws object] _screen_mode: dict[pid → bool] (True = screen mode, False = VR) ``` ### Join Flow ``` POST /api/gamesessions/v2/joinroom (or joinrandom, join, etc.) │ ├── Auth check ├── Determine target activity_level_id ├── session_mgr.join_room(pid, activity_level_id, ...) │ If private/sandbox/dorm → always new session │ Otherwise → find existing public session with space │ create new if none found ├── ws push: push_presence(pid, session) to all online └── Return GameSession dict to client (Photon room ID etc.) ``` ### Dorm Room - GUID: `76d98498-60a1-430c-ab76-b54a29b7a163` - Always private server-side (hidden from public list) - `to_dict()` returns `Private: False` so invite button works - All players placed here on WS connect if not already in a session ### Post-Game Gift Flow ``` reportjoinresult / reportgamejoinresult │ ├── XP awarded for activity ├── Level-up check → send level-up gift if leveled ├── _generate_gift_for_player(pid, activity_guid, xp) │ Picks item by rarity weighted random │ Filters: no SDK items (sdk_*), no starter items, no already-owned items │ Stores in gifts table (pending, not consumed) └── push_gift(pid, gift) via WebSocket ``` --- ## Avatar & Gift System (routes/avatar.py) ### Avatar Data Sources ``` /api/avatar/v2 ← current equipped avatar └── Reads avatars table (skin_color, hair_color, outfit parts etc.) /api/avatar/v3/items ← full item catalog └── Reads data/avatar_items.json + data/custom_items.json Merges with unlocked_items table Returns owned + unowned items /api/avatar/v*/saved ← saved outfits └── saved_outfits table (up to 3 slots) ``` ### Gift System ``` gifts table columns: profile_id, item_desc (AvatarItemDesc), context (0=Admin,1=Activity,2=Store,3=LevelUp) consumed (0=pending, 1=consumed), rarity (0/10/20/30/50) equipment_modification_guid (for equipment skins) GET /api/avatar/v2/gifts → pending unclaimed gifts POST /api/avatar/v2/gifts/consume/ → mark consumed, unlock item ``` ### Rarity Weights ``` 0 = Common (base weight: high) 10 = Uncommon 20 = Rare 30 = Epic 50 = Legendary ``` --- ## Store & Economy System (routes/storefronts.py) ### Currencies | Type | Name | |---|---| | 1 | LaserTagTickets | | 2 | RecCenterTokens | | 100 | LostSkullsGold | ### Store Rotation ``` _ROTATION_WINDOW_SECS = 86400 (24 hours) GET /api/storefronts/v*/N │ ├── Compute rotation slot = floor(time.time() / 86400) ├── Seed random with slot number → deterministic shuffle ├── Pick N items from pool for this slot └── Return store items with prices in all 3 currencies POST /admin/api/reroll_store → force rotation to next slot ``` ### Purchase Flow ``` POST /api/storefronts/v2/buy │ ├── Auth check ├── Validate item exists in current rotation ├── Check balance (currency type) ├── Deduct balance ├── Add to unlocked_items └── Return updated balance ``` ### Checklist / Weekly Challenges ``` GET /api/checklist/v1/current → active weekly challenge objectives POST /api/checklist/v1/complete → complete an objective, award tokens GET /api/challenge/v1/getCurrent → current challenge state POST /api/challenge/v2/updateProgress → update progress on challenge ``` --- ## Chat & Social System ### Direct Messages (routes/relationships.py) ``` messages table: from_player_id, to_player_id, type, content, read Types: 4=FriendRequest, 30=SystemDM, others=game notifications GET /api/messages/v2/get → inbox POST /api/messages/v2/send → send DM + push via WS (Id:2) POST /api/offlineinvite/v1/send → offline room invite ``` ### Chat Threads (routes/chat.py) ``` chat_threads: id, created_at chat_thread_players: thread_id, profile_id chat_messages: thread_id, from_player_id, content, sent_at GET /api/chat/v2/myChats → my active threads (with messages only) GET /api/chat/v2/getById → thread by ID GET /api/chat/v2/getByPlayers → find existing thread (404 if none) POST /api/chat/v1/create → create thread + optional first message POST /api/chat/v*/sendMessage → send to thread + push WS Id:90 POST /api/chat/v1/addToChat → add player to thread POST /api/chat/v1/leaveChat → leave thread ``` ### Relationships (routes/relationships.py) ``` relationships table: profile_id, target_id, relationship_type Types: 1=Following, 2=Friend, 3=FriendWithSystem, 4=Ignored Friend request flow: sendfriendrequest → creates pending request message acceptfriendrequest → upgrades to friend relationship removefriend → deletes relationship both ways ``` ### Player Social ``` GET /api/players/v1/ → profile by ID GET /api/players/v1/getByUsername → profile by username POST /api/players/v2/displayname → change display name (profanity checked) POST /api/players/v1/bio → update bio POST /api/players/v2/objective → XP + objective completion POST /api/players/v2/updateReputation → +/- reputation ``` --- ## Progression System (routes/players.py + routes/sessions.py) ### XP & Leveling ``` Level thresholds in core/database.py (_LEVEL_THRESHOLDS) XP is awarded at: - Activity completion (reportjoinresult) - Objective completion (complete_objective_v2) - Daily login reward - Admin gift On level-up: → Gift generated (context=LevelUp) → push_gift via WS ``` ### Daily Login Reward ``` _award_daily_login(pid) called on every loginaccount daily_login_rewards table tracks last claim date If new day → award tokens + XP ``` ### Objectives ``` GET /api/objectives/v1/myprogress → current objective state POST /api/objectives/v1/updateobjective → update progress POST /api/objectives/v1/completegroup → complete group + award ``` --- ## Ban System (core/ban_service.py + core/daemons.py) ### Ban Flow ``` db.ban_player(pid, reason, duration_hours, admin_name) → writes to ban_log table → sets profiles.banned = 1 cascade_kick_linked(pid) → finds all platform accounts sharing same platform_id → bans + kicks all linked accounts kick_player(pid) → ws_registry.send(pid, {Id:20}) ← ban notification → ws_registry.close_and_unregister(pid) → session_mgr.leave_session(pid) → push_presence offline ``` ### Ban Enforcer Daemon ``` Every 5 seconds: For each connected PID: if db.is_banned(pid): Send Id:20, close socket, leave session, push offline ``` ### IP Bans ``` ip_logins table: profile_id, ip_address, last_seen is_ip_banned(ip) → checks banned_ips table On login/WS connect: If IP is banned → cascade ban the account + kick ``` --- ## Presence Watchdog Daemon (core/daemons.py) ``` Every 20 seconds: For each connected PID: If last heartbeat > 90 seconds ago: close_and_unregister(pid) leave_session(pid) push_presence offline session_gift_reset(pid) remove from _last_seen record_heartbeat(pid) called: → On WS connect → On every heartbeat2 message received ``` --- ## Admin Panel (core/admin_panel.py, /admin) ### Auth ``` Cookie "Authorization" → validated against auth server at http://10.8.2.3:6820 Scopes: kittyrec.admin → full access (all actions) kittyrec.mod → limited (view, light moderation only) No auth → redirect to https://auth.tabbycluster.net Emergency login at /admin/emergency_login (env-var password) ``` ### Dashboard (/admin) ``` Shows: Online players list (username, level, room, VR/Screen badge, Dev badge) Actions: Profile, Gift, DM, Reset Password, Kick Active sessions list Recent admin actions log Stats: online count, sessions, total players, banned count ``` ### Player Management (/admin/admin_players) ``` Flask-Admin ModelView on profiles table Actions: Ban (duration select + reason) Unban Disconnect (WebSocket kick) Gift XP (1000) Gift Tokens (100) Reset Password (generates temp, sends DM) Get Temp Password (offline players) Send Notification Toggle Developer flag ``` ### Admin API Endpoints ``` POST /admin/api/ban/ → ban player POST /admin/api/unban/ → unban player POST /admin/api/disconnect/ → kick WS POST /admin/api/gift_player/ → send gift POST /admin/api/reroll_store → force store rotation POST /admin/api/send_message → broadcast system message POST /admin/api/send_dm/ → DM a player POST /admin/api/reset_password/ → temp password + DM POST /admin/api/gift_all → gift all online players POST /admin/api/toggle_dev/ → toggle developer flag GET /admin/api/stats → server stats JSON GET /admin/api/console/read → tail server log GET /admin/api/public_stats → requires admin auth (not public) ``` --- ## Web Portal & Nameserver Pages ### Web Portal (/portal) — authenticated player-facing pages ``` /portal → login page /portal/me → player dashboard (gifts, profile, photos) /portal/logout → logout POST /portal/api/consume_gift/ → consume pending gift ``` ### Nameserver Pages — in-game browser (routes/nameserver.py) ``` / → homepage /welcome → welcome / landing /dashboard → player dashboard (requires game auth) /leaderboard → top players leaderboard /account → account management (change password, pfp) /web/status → server status JSON (no auth) /web/leaderboard → public leaderboard JSON (no auth) /web/players → online players (requires auth) /web/friends → friends list (requires auth) /web/my-photos → player's photos (requires auth) /web/chats → chat list + read (requires auth) /web/notifications → notification inbox (requires auth) /web/change-password /web/upload-pfp /web/heartbeat → keep game auth session alive /web/token-balance → currency balances ``` --- ## Public API (/api/public/v1/*) No authentication required. Rate limited. | Endpoint | Limit | Returns | |---|---|---| | `GET /status` | 120/min | online count, sessions, total players, maintenance | | `GET /sessions` | 120/min | all public game sessions | | `GET /players` | 120/min | online players + room names | | `GET /leaderboard` | 60/min | top 100 by XP | | `GET /search?q=` | 20/min | player search (min 2 chars, max 20 results) | | `GET /profile/` | 60/min | public profile | | `GET /profile//photos` | 30/min | photos by player | | `GET /photos` | 30/min | recent photos | | `GET /activity` | 60/min | activities with live players | | `GET /docs` | — | this API's JSON spec | --- ## Internal API (/api/internal/discord/*) **Requires `X-Bot-Secret` header** (shared secret in config.yaml + bot config.json). Used only by the KittyNet Discord bot. ``` POST /api/internal/discord/initiate Body: { username, discord_user_id, discord_username } → Exact username match only → Checks: already linked, player exists, profile already linked, player online → Rate limit: one code per player per 60 seconds (DB checked) → Sends in-game DM with 6-char code (expires 10min) → Returns: { status: "sent"|"not_found"|"not_online"|"already_linked"|"rate_limited" } POST /api/internal/discord/confirm Body: { code, discord_user_id, discord_username } → Validates code + discord_user_id match in discord_link_codes table → Writes permanent link to discord_links table → Returns: { status: "linked"|"invalid_code"|"already_linked", profile info } ``` --- ## Discord Integration ### Webhooks (core/discord.py) Three webhook channels, all fire-and-forget (background threads): | Webhook | Events | |---|---| | `webhook_public` | First logins, player milestones, online/offline | | `webhook_admin` | Bans, server shutdown, admin actions | | `webhook_anticheat` | IP bans, suspicious activity | Throttle system prevents spam — configurable cooldown per event key. ### Discord Bot (KittyNet-DiscordBot/bot.py) Runs as a separate process (`kittynet` systemd service). **Slash commands:** | Command | Description | |---|---| | `/status` | Server status embed | | `/players` | Who's online | | `/sessions` | Active game sessions | | `/ingame` | Players grouped by room | | `/leaderboard` | Top 10 by XP | | `/profile ` | Player profile (search-based lookup) | | `/search ` | Player search, up to 10 results | | `/photos [player]` | Recent photos, optional player filter | | `/link ` | Start Discord→KittyRec account linking | | `/getkittyrec` | Request alpha access | | `/analytics growth\|activity\|channels\|voice\|users\|summary` | Admin-only analytics | **Background loops:** ``` status_loop (5min) → updates stat voice channels + status embed analytics_loop (10min) → snapshots member count, cleans old data milestone_loop (5min) → announces player count milestones ``` **DM handler:** ``` on_message (DM channel) → if message matches [ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6} → calls POST /api/internal/discord/confirm → on success: sends linked embed + assigns player_role if configured ``` **Discord linking security:** - Bot-side: 60s per-user cooldown (in-memory) - Server-side: 60s per-player cooldown (DB checked) - Code alphabet excludes ambiguous chars (0/O/1/I) - Secret comparison uses `hmac.compare_digest` --- ## KittyLoader (routes/KittyLoader.py) Used by the game launcher (KittyLoader desktop app). ``` All routes except /KittyRec/getfile require: User-Agent: KittyLoader/* Header: Branch: Valid branches: bff0c094-... → Prod fb4ce906-... → Dev f94fa96b-... → BVT GET /api/kittyloader/v1/start → Analytics event logged (branch + UA) → Returns { exit: false } GET /api/kittyloader/v1/exit → 200 OK GET /api/kittyloader/v1/KittyRec/get → Returns { FileUrl, SHA512 } for the DLL for this branch → Reads from data/KittyRecDlls.json GET /api/kittyloader/v1/KittyRec/getfile?filename= → Serves file from kittyrec_dlls/ directory → No auth, no UA check (intentional — direct download link) ``` --- ## Download System (routes/downloads.py) ``` GET /download/current → Renders current build download page (HTML) → Shows size, SHA-256, download count GET /download///

/

/

/get → Actual file download, increments download counter GET /api/launcher/v1/manifest → Build manifest for the launcher Admin endpoints (require admin auth): POST /admin/api/downloads/set_current/ POST /admin/api/downloads/upload (multipart, chunked) ``` --- ## Images & Photos (routes/images.py, routes/avatar.py) ``` GET /alt/ → Serves profile image by name from saved_images table → Strips dot-files early (prevents .env leakage) GET /api/images/v1/ → room image by ID GET /api/images/v3/* → named image lookup POST /api/images/v1/upload → upload room/memory image POST /web/upload-pfp → upload profile picture ``` --- ## Rate Limiting (core/limiter.py) - Uses flask-limiter, keyed by `request.remote_addr` (correct after ProxyFix) - Global defaults in `limiter.py` - Route overrides: `@limiter.limit("N per minute")` - Internal endpoints (`/api/internal/*`) protected by secret, not IP rate limit - Bot-side layer added for `/link` command (60s cooldown in-memory) --- ## Database Tables Reference ### Core | Table | Purpose | |---|---| | `profiles` | All player accounts (username, display_name, xp, level, banned, etc.) | | `avatars` | Current equipped avatar data per player | | `settings` | Key-value settings per player (screen_mode_user, OOBE, etc.) | | `platform_accounts` | Platform→Profile mapping (Steam, Oculus, etc.) | | `cached_logins` | Saved login tokens | ### Social | Table | Purpose | |---|---| | `relationships` | Friends, ignored, following (type 1/2/3/4) | | `messages` | Direct messages / notifications | | `chat_threads` | Group/DM chat threads | | `chat_thread_players` | Thread membership | | `chat_messages` | Messages within threads | ### Economy & Progression | Table | Purpose | |---|---| | `gifts` | Pending + consumed gifts (avatar items) | | `unlocked_items` | Items a player owns | | `consumable_inventory` | Consumable item counts | | `store_featured_items` | Current store rotation override | | `subscriptions` | Player subscriptions | | `saved_outfits` | Saved outfit slots (up to 3) | | `equipment_favorites` | Favorited equipment skins | | `leaderboard_scores` | Per-activity leaderboard entries | | `daily_login_rewards` | Last claim dates for daily login | | `daily_gifts` | Daily gift tracking | | `daily_cheers` | Daily cheer limit tracking | ### Objectives & Challenges | Table | Purpose | |---|---| | `player_challenge_progress` | Weekly challenge progress | | `daily_objective_completions` | Daily objective state | | `weekly_schedule` | Scheduled challenge definitions | | `player_events` | In-game events per player | ### Rooms | Table | Purpose | |---|---| | `rooms` | User-created room definitions | | `room_permissions` | Per-room permission entries | | `room_bookmarks` | Bookmarked rooms per player | | `room_cheers` | Room cheer state | | `room_visits` | Visit history | | `room_gamemode_defaults` | Default gamemode per room | | `disabled_activities` | Activities disabled server-wide | ### Security & Admin | Table | Purpose | |---|---| | `ban_log` | Full ban/unban history | | `ip_logins` | IP address history per player | | `admin_action_log` | All admin actions with timestamp | | `admin_todos` | Admin todo list | | `admin_issues` | Admin issue tracker | ### Images & Media | Table | Purpose | |---|---| | `saved_images` | Profile photos + room screenshots | | `profile_images` | Profile picture blobs | | `profile_image_history` | Profile picture history | | `memory_uploads` | MemoryStream video uploads | ### Discord & System | Table | Purpose | |---|---| | `discord_links` | Permanent Discord↔KittyRec account links | | `discord_link_codes` | Temporary link codes (10min expiry) | | `system_reply_queue` | Bot auto-reply state machine | | `amplitude_events` | Analytics events log | | `player_count_history` | Historical online count snapshots | | `dll_archive` | KittyLoader DLL version archive | --- ## System Account (PID 23) - Always appears online to all clients - Used as sender for all system DMs and notifications - Maintained by `kittyrec-system` daemon thread (fake WS keepalive) - Excluded from `connected_ids()` player count - All players auto-friended with PID 23 on account creation --- ## Core Module Map | Module | Role | |---|---| | `core/database.py` | All SQL — single `Database` class, 2000+ lines | | `core/state.py` | In-memory state: `SessionManager`, `ConnectionRegistry`, `GameSession` | | `core/auth.py` | JWT encode/decode, `@check_auth`, `get_current_profile_id()` | | `core/config.py` | Loads `data/config.yaml` → server/auth/discord/sdk sections | | `core/constants.py` | `KNOWN_ACTIVITIES`, `DORM_ROOM_GUID` | | `core/builders.py` | Response builder helpers (activity_info, profile shapes) | | `core/daemons.py` | Background threads: ban enforcer, presence watchdog, count recorder, shutdown handler | | `core/discord.py` | Webhook fire-and-forget helpers + throttle | | `core/limiter.py` | Flask-Limiter setup, IP extraction | | `core/ws_helpers.py` | `push_presence()`, `push_gift()` WS broadcast helpers | | `core/ban_service.py` | `cascade_kick_linked()`, `kick_player()` | | `core/password_crypto.py` | bcrypt helpers | | `core/profanity.py` | Profanity filter for display names | | `core/admin_auth.py` | Admin cookie auth, scope checking | | `core/admin_panel.py` | Flask-Admin views (900+ lines) | | `core/anticheat.py` | Anticheat checks | | `core/burst_detector.py` | Request burst detection | | `core/system_messages.py` | System DM helpers | | `core/models.py` | SQLAlchemy models (Flask-Admin only) |