Skip to content

About

An online server-authoritative seed-based puzzle game with user auth, daily seeds, friend system and Brevo mail integration

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Critical Region

A competitive online puzzle game built with Python, FastAPI, and real-time WebSocket support. Players compete in seed-based leaderboards where everyone plays the same daily puzzle, with social features including friends lists and online presence.

How it plays

Critical Region is a falling-block puzzle played with the 12 pentominoes on a 12×24 board. Lines don't clear. Instead, filling a solid 5×5 square triggers a clear that spreads out along its rows and up its columns until it hits a hole, so a carefully built board can set off big cascades. Everyone gets the same piece sequence each day (a UTC daily seed), and scores go on that day's leaderboard.

The full rules are in Critical_Region.md.

Critical Region mid-game: the pentomino board, next-piece queue, controls and daily leaderboard

Architecture

Engine Layer (engine/)

  • Pure Python game logic, decoupled from server and UI
  • Modular game modes
  • Core components: Board, Piece, GameState
  • No external dependencies on server or client

Server API Layer (server/)

  • FastAPI-based REST API and WebSocket support
  • Secure user authentication (JWT tokens, bcrypt password hashing)
  • SQLite database with parameterized queries
  • Server-side validation of all game actions
  • Social features (friends list, friend requests)

Client Layer (client/)

  • Minimal JavaScript for canvas rendering only
  • HTML/CSS interface
  • All game logic executed server-side

Key Features

  • Seed-Based Competition: Daily puzzle challenges where all players compete on the same game seed
  • Leaderboards: Compare scores and times with other players globally and among friends
  • User Authentication: JWT-based auth with email verification via Brevo
  • Social System: Friends list, friend requests, online presence tracking
  • Real-time Updates: WebSocket-based presence and leaderboard updates
  • Rate Limiting: Comprehensive rate limits on all sensitive endpoints
  • Account Security: Login attempt tracking, account lockouts, password strength requirements
  • Token Management: Token blacklist for secure logout and revocation
  • Admin Controls: Admin API for user management and system monitoring

Security Features

  • Authentication: JWT tokens with bcrypt password hashing and token blacklist
  • Email Verification: Brevo-powered email verification with timed codes
  • Input Validation: Comprehensive server-side validation and sanitization
  • SQL Injection Prevention: Parameterized queries with aiosqlite
  • XSS Prevention: HTML escaping and Content-Security-Policy headers
  • Password Requirements: Enforced strong password policy (8+ chars, uppercase, lowercase, digit, special)
  • CORS Protection: Configurable allowed origins with strict defaults
  • Rate Limiting: SlowAPI-based rate limiting on auth, registration, API, and game endpoints
  • Login Protection: Failed login tracking with progressive lockouts
  • Trusted Hosts: Middleware to prevent host header attacks

Quick Start

Local Development

  1. Clone and setup environment:
git clone https://github.com/gage-marshall/CriticalRegion.git
cd CriticalRegion
python -m venv .venv
source .venv/bin/activate  # Windows: .venv\Scripts\activate
  1. Install dependencies:
pip install -r requirements.txt      # Production dependencies
pip install -r requirements-dev.txt  # Development tools (optional)
  1. Configure environment:
cp .env.example .env
# Edit .env with your configuration:
# - Generate SECRET_KEY: python -c "import secrets; print(secrets.token_urlsafe(32))"
# - Set up Brevo API key for email verification (optional for local dev)
# - Configure CORS_ORIGINS and ALLOWED_HOSTS
  1. Run the server:
# Using uvicorn (development)
uvicorn server.api.main:app --reload --host 0.0.0.0 --port 8000

# Or use the convenience scripts:
# Windows: start_local.bat
# Linux/Mac: ./start_local.sh
  1. Access the application:

Production Deployment (Render)

See DEPLOYMENT.md and RENDER_DEPLOYMENT.md for detailed deployment instructions.

The application is configured for Render deployment via render.yaml with:

  • Gunicorn production server (configured in gunicorn.conf.py)
  • Environment variables for secrets management
  • SQLite database (can be upgraded to PostgreSQL)
  • Rate limiting and security hardening

API Endpoints

Authentication (/api/auth)

  • POST /register - Register new user with email verification
  • POST /verify-email - Verify email with verification code
  • POST /resend-verification - Resend verification code
  • POST /token - Login and get JWT access token
  • GET /me - Get current authenticated user info
  • POST /logout - Logout and blacklist current token
  • POST /change-password - Change user password

Public Game (/public)

  • POST /game/start - Start anonymous game session
  • POST /game/{game_id}/action - Perform game action
  • GET /game/{game_id} - Get game state

Game (/api/game)

  • POST /create - Create new game session with seed
  • GET /{game_id} - Get current game state
  • POST /{game_id}/action - Perform game action with validation
  • POST /{game_id}/submit - Submit final score to leaderboard
  • GET /leaderboard/{seed} - Get leaderboard for specific seed
  • GET /daily - Get current daily seed and leaderboard

Social (/api/social)

  • GET /friends - Get user's friends list with online status
  • POST /friends/request/{user_id} - Send friend request
  • POST /friends/accept/{request_id} - Accept friend request
  • DELETE /friends/reject/{request_id} - Reject friend request
  • GET /friends/requests/incoming - Get incoming friend requests
  • GET /friends/requests/outgoing - Get outgoing friend requests
  • DELETE /friends/{friend_id} - Remove friend
  • GET /search - Search users by username

Presence (/api/presence)

  • WS /ws - WebSocket connection for online presence tracking
  • Real-time updates on friends' online/offline status and leaderboard changes

Admin (/api/admin)

  • GET /users - List all users (requires admin API key)
  • DELETE /users/{user_id} - Delete user account
  • GET /stats - Get system statistics

System

  • GET /health - Health check endpoint
  • GET / - Serve game UI

Project Structure

CriticalRegion/
├── engine/                      # Core game engine (decoupled)
│   ├── core/                   # Core game components
│   │   ├── board.py           # Board logic
│   │   ├── piece.py           # Piece logic
│   │   ├── pentomino.py       # The 12 pentominoes
│   │   └── game_state.py      # Game state management
│   └── modes/                 # Game mode implementations
│       ├── base_mode.py       # Base game mode interface
│       └── critical_region.py # Critical Region rules
│
├── server/                     # Server API layer
│   ├── api/                   # API routes
│   │   ├── main.py           # FastAPI app entry point
│   │   └── routes/           # Route modules
│   │       ├── auth.py       # Authentication endpoints
│   │       ├── game.py       # Game management endpoints
│   │       ├── social.py     # Social features (friends)
│   │       ├── presence.py   # Online presence tracking
│   │       ├── admin.py      # Admin API
│   │       └── public_game.py # Anonymous game endpoints
│   ├── core/                 # Core server logic
│   │   ├── config.py         # Configuration management
│   │   ├── security.py       # JWT auth & password hashing
│   │   ├── validation.py     # Input validation & sanitization
│   │   ├── database.py       # SQLite database operations
│   │   ├── game_manager.py   # Game session management
│   │   ├── presence_manager.py # Online presence WebSocket manager
│   │   ├── token_blacklist.py  # JWT token revocation
│   │   ├── rate_limiter.py   # Rate limiting configuration
│   │   └── email_service.py  # Brevo email integration
│   └── models/               # Pydantic models
│       ├── user.py          # User models
│       ├── game.py          # Game models
│       └── social.py        # Social feature models
│
├── client/                    # Client interface
│   ├── static/               # Static assets
│   │   ├── js/              # JavaScript for canvas rendering
│   │   └── css/             # Stylesheets
│   └── templates/           # HTML templates
│       └── index.html       # Game UI
│
├── tests/                    # Test suite
│
├── start.py                  # Production entry point
├── gunicorn.conf.py         # Gunicorn production config
├── requirements.txt         # Production dependencies
├── requirements-dev.txt     # Development dependencies
├── render.yaml              # Render deployment config
├── .env.example            # Environment template
├── .gitignore              # Git ignore rules
├── start_local.bat         # Windows start script
├── start_local.sh          # Unix start script
│
├── Critical_Region.md      # Full game rules
├── DEPLOYMENT.md           # Deployment guide
├── RENDER_DEPLOYMENT.md    # Render-specific deployment
└── RUNNING_LOCALLY.md      # Local development guide

Development

Running Tests

# Install dev dependencies
pip install -r requirements-dev.txt

# Run all tests
pytest

# Run with coverage
pytest --cov=server --cov-report=html

Code Style

  • Follow PEP 8 guidelines
  • Use type hints throughout
  • Document all security-critical functions
  • Validate all user inputs server-side
  • Use parameterized SQL queries exclusively

Development Tools

  • pytest: Testing framework
  • black: Code formatting
  • flake8: Linting
  • mypy: Type checking (optional)

Environment Variables

Key environment variables (see .env.example for full list):

Variable Description Required
SECRET_KEY JWT signing key (generate random 32+ bytes) Yes
ADMIN_API_KEY Admin API authentication key Yes
BREVO_API_KEY Brevo email service API key Yes (if email enabled)
DATABASE_URL SQLite database path Yes
CORS_ORIGINS JSON list of allowed CORS origins Yes
ALLOWED_HOSTS JSON list of allowed host headers Yes
EMAIL_VERIFICATION_ENABLED Enable email verification No (default: true)
DEBUG Enable debug mode (disables in production) No (default: false)

Rate limiting and security settings are also configurable via environment variables.

Security Considerations

For Developers

  • Never commit .env file with secrets
  • Generate strong SECRET_KEY using: python -c "import secrets; print(secrets.token_urlsafe(32))"
  • Always validate and sanitize user inputs
  • Use parameterized queries for all database operations
  • Keep dependencies updated regularly

For Production

  • HTTPS Required: Always use HTTPS in production
  • Strong Secrets: Use cryptographically random keys (32+ bytes)
  • Email Verification: Keep EMAIL_VERIFICATION_ENABLED=true
  • Rate Limiting: Configure appropriate rate limits for your traffic
  • Database: Consider migrating from SQLite to PostgreSQL for better concurrency
  • Monitoring: Implement logging and monitoring for security events
  • Backups: Regular database backups
  • Updates: Keep Python and dependencies up to date

Technology Stack

  • Backend: FastAPI 0.115+, Python 3.13+
  • Server: Uvicorn (dev), Gunicorn (production)
  • Database: SQLite (aiosqlite), upgradeable to PostgreSQL
  • Authentication: JWT (python-jose), bcrypt password hashing
  • Email: Brevo API for email verification
  • Real-time: WebSockets for game updates and presence
  • Rate Limiting: SlowAPI
  • Security: Pydantic validation, CORS, Trusted Host middleware

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes with tests
  4. Commit your changes (git commit -m 'Add amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

Support

For deployment issues, see:

License

MIT. See LICENSE.

About

An online server-authoritative seed-based puzzle game with user auth, daily seeds, friend system and Brevo mail integration

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages