A new README for the combined project with setup from the Flashpoint Ultimate torrent. New feature docs for streaming, proxy sign-in and game saves; deployment, upgrade and streaming READMEs updated for the single compose file; the project renamed throughout.
8.9 KiB
Backend Service
The backend is a REST API built with Express and TypeScript that serves as the central hub for the Dotcom Arcade application. It manages game metadata, user accounts, authentication, and serves game content directly via integrated game-proxying (formerly provided by a separate game-service).
Overview
- Framework: Express.js with TypeScript
- Port: 3100
- Databases:
- SQLite (flashpoint.sqlite) - Read-only game metadata
- SQLite (user.db) - User management and application data
- Authentication: JWT-based with RBAC (Role-Based Access Control)
- Architecture: Service layer pattern with middleware
Key Features
- Game metadata queries from Flashpoint Archive database
- User authentication and authorization with JWT
- Role-based permission system (admin, user, guest)
- Play session tracking with automatic cleanup
- Activity logging for auditing
- Database hot-reload when Flashpoint Launcher updates
- Integrated game content serving (proxy and ZIP mounting)
Quick Start
cd backend
npm install
cp .env.example .env
# Edit .env with your Flashpoint installation path
npm run dev # Development server
npm run build # Build for production
npm start # Run production build
Environment Variables
Required:
FLASHPOINT_PATH- Path to Flashpoint installation (all other paths derived automatically)DOMAIN- Frontend URL (default: http://localhost:5173)
See configuration.md for complete environment variable documentation.
Core Concepts
Two-Database Architecture
-
Flashpoint Database (flashpoint.sqlite)
- Read-only access to official Flashpoint game metadata
- Managed by Flashpoint Launcher
- Hot-reloaded when file changes detected
- Contains: games, platforms, tags, playlists
-
User Database (user.db)
- Application-specific data
- Full read/write access
- Schema managed via migrations
- Contains: users, roles, permissions, play sessions, activity logs
Service Layer Pattern
- Routes handle HTTP requests/responses
- Services contain business logic and database queries
- Middleware handles cross-cutting concerns (auth, logging, errors)
JWT Authentication
- Access tokens expire after 1 hour (configurable via JWT_EXPIRES_IN)
- Refresh tokens valid for 30 days
- Token payload includes: userId, username, role
- Permissions loaded from database on each request
Role-Based Access Control (RBAC)
Three default roles:
- Admin (priority 100): Full access
- User (priority 50): Can play games, manage playlists
- Guest (priority 0): Read-only access
Permissions are assigned to roles, and users inherit permissions from their role.
Project Structure
backend/
├── src/
│ ├── config.ts # Environment configuration
│ ├── server.ts # Express app initialization
│ ├── middleware/ # Express middleware
│ ├── routes/ # API route handlers
│ ├── services/ # Business logic layer
│ ├── types/ # TypeScript definitions
│ ├── utils/ # Utility functions
│ ├── game/ # Integrated game content serving
│ │ ├── proxy-request-handler.ts # Legacy htdocs proxy
│ │ ├── gamezipserver.ts # ZIP mounting server
│ │ ├── legacy-server.ts # Legacy file serving
│ │ ├── zip-manager.ts # ZIP mounting logic
│ │ ├── cgi/ # CGI/PHP execution
│ │ ├── services/ # Game data services
│ │ ├── utils/ # Game utilities
│ │ └── config.ts # Game config
│ └── migrations/ # Database migrations
├── user.db # User database (generated)
├── package.json
└── tsconfig.json
API Routes
Main route groups:
/api/auth- Login, register, token refresh/api/users- User management/api/roles- Role and permission management/api/games- Game search and metadata/api/play- Play session tracking/api/activities- Activity logs/api/playlists- User playlists/api/domains- Domain management/game-proxy/*- Legacy htdocs and game file proxying (registered before auth)/game-zip/*- ZIP archive mounting and serving (registered before auth)
See the API Reference for complete API documentation.
Services
- database-service.md - Flashpoint database connection with hot-reload
- user-database-service.md - User database with migrations
- AuthService - Authentication and JWT management
- UserService - User CRUD operations
- GameService - Game metadata queries
- PlayTrackingService - Play session tracking
- DomainService - Domain CRUD with CORS cache
Security Features
- Password hashing with bcrypt (10 rounds)
- JWT token expiration and refresh
- Login attempt tracking and account lockout
- RBAC for fine-grained access control
- Activity logging for audit trails
- Dynamic CORS protection (env var + configured domains)
- Helmet.js security headers
- Input validation and sanitization
Performance Optimizations
- Better-sqlite3 for synchronous database access (faster than async)
- Database connection pooling and reuse
- Pagination for large result sets
- Indexed database queries
- Response compression with gzip
- File watching debouncing (500ms)
Query Optimization Patterns:
- Window functions for pagination:
COUNT(*) OVER()merges count into single query - Scalar subqueries: Multiple aggregates in one SELECT (e.g., distinct counts)
- Map-based data merging: O(1) lookups instead of O(N²) .find() loops
- Direct file access before directory scans: O(1) fast path with O(N) fallback
- Parallel file reads:
Promise.allSettled()for concurrent I/O operations
See architecture.md for implementation details.
Background Jobs
Abandoned Session Cleanup
- Runs every 6 hours
- Ends sessions older than 24 hours
- Updates play statistics
Error Handling
Centralized error middleware:
AppErrorclass for operational errors- Automatic HTTP status code mapping
- Structured error responses
- Error logging with Winston
Logging
Winston logger with:
- Console output with colors (development)
- File logging (production)
- Log levels: error, warn, info, debug
- Structured logging with metadata
Testing
npm test # Run tests
npm test -- --watch # Watch mode
npm test -- --coverage # Coverage report
Common Tasks
Adding a New API Endpoint
- Create route handler in
src/routes/ - Add business logic to appropriate service
- Register route in
src/routes/index.ts - Add middleware for authentication/authorization
- Document in
docs/06-api-reference/
Adding a New Permission
- Insert permission in database
- Assign to roles via
role_permissionstable - Use
requirePermission()middleware in routes
Creating a Database Migration
- Create SQL file in
src/migrations/with sequential number - Add migration logic to
UserDatabaseService.runMigrations() - Test migration on clean database
- Document in migrations/README.md
Troubleshooting
Database Locked Error
- Close Flashpoint Launcher before starting backend
- Ensure only one backend instance is running
- Check file permissions on database files
Authentication Failures
- Verify JWT_SECRET is set correctly
- Check token expiration time
- Ensure user is active in database
Game Files Not Loading
- Verify game content is being served via
/game-proxy/*routes - Check backend logs for game server initialization errors
- Ensure FLASHPOINT_PATH is correct
Development Workflow
- Start backend:
npm run dev - Backend watches for TypeScript changes
- Auto-reloads on file save
- Logs all HTTP requests
- Database hot-reloads when flashpoint.sqlite changes
Production Deployment
NODE_ENV=production npm start
Requirements:
- Set
NODE_ENV=production - Set secure
JWT_SECRET - Configure proper
DOMAIN - Build:
npm run build - Monitor logs and errors
- Set up process manager (PM2, systemd)
Performance Metrics
Typical response times (p95):
- Game search: < 100ms
- Game details: < 50ms
- User login: < 200ms (bcrypt hashing)
- Play session start: < 50ms
- Activity log: < 30ms (non-blocking)
Related Documentation
- Architecture - Backend architecture patterns
- Configuration - Environment configuration
- API Reference - Complete API documentation
- Database Schema - Database schema reference