23 Commits

Author SHA1 Message Date
d69a14d80b Migrate frontend to SvelteKit with comprehensive deployment (#2)
* Migrate frontend to SvelteKit with comprehensive deployment
documentation

- Create new SvelteKit project structure with routing, stores, and
  components
- Implement complete authentication system with auth store and protected
  routes
- Build all application pages: Home, Login, Register, Dashboard, Games,
  Stats, Commanders, Profile, and Round Counter
- Configure Vite, TailwindCSS, PostCSS, and Nginx for production
  deployment
- Add Dockerfile.svelte for containerized builds with multi-stage
  optimization
- Create comprehensive SVELTE_DEPLOYMENT.md and SVELTE_MIGRATION.md
  guides
- Update deployment scripts and package dependencies for SvelteKit
  ecosystem

* feat: Add user authentication and game tracking pages to EDH Stats
Tracker

* Migrate frontend to SvelteKit and update Docker configuration

- Replace Alpine.js with SvelteKit for improved DX and hot module
  replacement
- Switch frontend service to `Dockerfile.dev` with volume mounts and
  Vite dev server
- Update `docker-compose.yml` to map ports 5173 and use
  `http://localhost:5173` for CORS
- Add `Dockerfile.svelte` for production static builds
- Configure Vite proxy to target `http://backend:3000` in containers and
  `localhost:3002` locally
- Migrate existing components to new routes and update authentication
  store logic
- Add Chart.js integration to stats page and handle field name mapping
  for forms
- Include static assets (`fonts/Beleren-Bold.ttf`) and update deployment
  scripts
- Document migration status, testing checklist, and known minor issues
  in guides

* Refactor frontend state properties from snake_case to camelCase

This commit standardizes frontend property access across Dashboard,
Games, and Stats pages.
Changes include:
- Renaming API data fields (e.g., `commanderName`, `playerCount`,
  `winRate`).
- Updating `startEdit` logic to normalize mixed snake_case/camelCase
  inputs.
- Replacing template literals like `_player_won` with camelCase
  versions.
- Consistent usage of `totalGames` and `wins` instead of snake_case
  variants.

* Update version to 2.1.12 and refactor commander management

- Upgrade application version to 2.1.12
- Add Footer component and include in all pages
- Refactor `/commanders` page to fetch commanders and stats separately
- Fix commander API endpoint to load all commanders instead of only
  those with stats
- Add stats merging logic to calculate wins, win rate, and avg rounds
- Split add/edit command logic into shared `loadCommanders` function
- Fix color toggle logic to work with both new and editing command modes
- Update API methods for update requests to send `PUT` for existing
  commanders
- Enhance commander delete functionality with proper API response
  handling
- Refactor dashboard and stats pages to reuse shared data loading logic
- Add chart cleanup on destroy for both dashboard and stats pages
- Implement Chart.js for Win Rate by Color and Player Count charts
- Reorganize round counter component state and timer functions
- Add localStorage persistence for round counter with pause/resume
  support
- Update game log page to integrate footer component

* Refactor auth store and backend to use stable user ID

*   Backend: Switch user lookup from username to ID in auth routes to
    maintain stability across username changes.
*   Frontend: Update user store to reflect ID-based updates.
*   UI: Refactor user menu Svelte component to use ID-based user data.
*   Profile: Switch profile page to use ID-based user data for
    validation and state management.

* format date formatting options consistently across dashboard and games
pages

* format date formatting options consistently across dashboard and games
pages

* Refactor card action buttons to use icons with semantic text

- Switch "Edit" and "Delete" button text to SVG icons in `commanders`
  and `games` pages
- Update icon colors and font styles to match standard design tokens
  (indigo/red, bold text)
- Improve responsive spacing by adding `lg:grid-cols-3`

* grids
- Clarify hover states and titles for better UX accessibility
  Bump application versions to 2.2.0 and update deployment configuration

* Convert `+page.svelte` to use template strings for multiline strings and
fix syntax errors.

* Update static version to 2.2.2 and tighten nginx cache headers
2026-04-11 10:42:46 +02:00
2b69a07cf6 Update deploy.sh 2026-04-10 13:58:34 +02:00
df8495a9b5 Format logs, bump version, update Traefik config
- Reformat logging calls in server.js for readability
- Bump API version from 1.0.0 to 2.1.2
- Update Traefik labels; switch TLS certresolver to
  letsencrypt-cloudflare
2026-01-19 19:29:37 +01:00
1fdc55afa1 Add max user registration limit
- Parse MAX_USERS from env in registrationConfig
- Count total users with new UserRepository.countUsers()
- Enforce registration cap in the signup flow
- Expose MAX_USERS in docker-compose and env example
- Bump frontend version to 2.1.2
2026-01-18 16:42:42 +01:00
de829d4b06 Update docker-compose volumes and remove init-db
- Bump frontend version from 2.0.2 to 2.0.4
- Add scripts:ro and backups volumes in deployment and compose
- Remove backend/init-db mount from docker-compose
2026-01-18 13:09:56 +01:00
4986c4f6b8 feat: add complete password requirements to registration form
- Display all 5 backend password validation requirements
- Added: minimum 8 characters (existing)
- Added: maximum 100 characters
- Added: at least one lowercase letter
- Added: at least one uppercase letter
- Added: at least one number
- Each requirement shows real-time validation with green checkmark
- Requirements match exactly with backend/src/utils/validators.js

feat: add Traefik labels to frontend container

- Enable Traefik auto-discovery for frontend service
- Configure HTTP routing with Host rule
- Setup both web (HTTP) and websecure (HTTPS) entrypoints
- Configure load balancer backend port (80)
- Include optional TLS/Let's Encrypt configuration
- Change edh.example.com to your actual domain

feat: configure production compose file to use Traefik network

- Generated docker-compose.prod.deployed.yml now uses traefik-network
- Frontend service joined to both edh-stats-network and traefik-network
- Added Traefik labels for routing and TLS configuration
- traefik-network configured as external (must be created by Traefik)
- Removed external ports from frontend (Traefik handles routing)
- Updated setup instructions to mention Traefik prerequisites
- Changed TLS to enabled by default in production

refactor: remove frontend port exposure and Traefik labels from dev compose

- Removed port 8081 exposure from development docker-compose.yml
- Removed Traefik labels from development environment
- Development compose now simple and focused on local testing
- Production compose (via deploy.sh) handles Traefik routing via DNS
- Frontend only accessible through backend API in development
- Cleaner separation: dev is simple, prod uses Traefik

Switch Postgres data to host path and bump version Update Traefik rule,
expose port, bump version

feat: add database migration script for PostgreSQL

- Created migrate-database.sh script for exporting/importing databases
- Supports source and target database configuration via CLI options
- Validates connections before migration
- Verifies data integrity after import (table and row counts)
- Can skip import and just export to file for manual restore
- Supports Docker Compose container names
- Includes comprehensive error handling and user prompts
- Added DATABASE_MIGRATION.md documentation with usage examples
- Handles common scenarios: dev→prod, backups, restore
- Security considerations for password handling

refactor: simplify migration script to run directly in PostgreSQL container

- Removed network/remote host configuration (no longer needed)
- Script now runs inside PostgreSQL container with docker compose exec
- Simplified to use only source-db, target-db, output-file, skip-import options
- No external dependencies - uses container's pg_dump and psql
- Much simpler usage: docker compose exec postgres /scripts/migrate-database.sh
- Updated documentation with container-based examples
- Added real-world integration examples (daily backups, deployments, recovery)
- Includes troubleshooting and access patterns for backup files

feat: mount scripts directory into PostgreSQL container

- Added ./scripts:/scripts:ro volume mount to postgres service
- Makes migrate-database.sh and other scripts accessible inside container
- Read-only mount for security (scripts can't be modified inside container)
- Allows running: docker compose exec postgres /scripts/migrate-database.sh
- Scripts are shared between host and container for easy access

docs: clarify that migration script must run as postgres user

- Added -u postgres flag to all docker compose exec commands
- Explains why postgres user is required (PostgreSQL role authentication)
- Created shell alias for convenience
- Updated all scenarios and examples
- Updated troubleshooting section
- Clarifies connection issues related to user authentication

feat: save database backups to host by default

- Added ./backups volume mount to postgres container
- Changed default backup location from /tmp to /backups
- /backups is mounted to ./backups on host for easy access
- Script automatically creates /backups directory if needed
- Updated help and examples with -u postgres flag
- Summary now shows both container and host backup paths
- Backups are immediately available on host machine
- No need for docker cp to retrieve backups

feat: add --skip-export flag for import-only database operations

- Allows importing from existing backup files without re-exporting
- Added validate_backup_file() function to check backup existence
- Updated main() to handle import-only mode with proper validation
- Updated summary output to show import-only mode details
- Updated help text with import-only example
- Prevents using both --skip-import and --skip-export together

docs: update database migration guide for import-only mode

- Document new --skip-export flag for import-only operations
- Add example for quick restore from backup without re-export
- Update command options table with mode combinations
- Update all scenarios and examples to use /backups mount
- Clarify file location and volume mounting (./backups on host)
- Add Scenario 5 for quick restore from backup
- Simplify examples and fix container paths

feat: clear existing data before importing in migration script

- Added clear_database() function to drop all tables, views, and sequences
- Drops and recreates public schema with proper permissions
- Ensures clean import without data conflicts
- Updated warning message to clarify data deletion
- clear_database() called before import starts
- Maintains database integrity and grants

docs: update migration guide to explain data clearing on import

- Clarify that existing data is deleted before import
- Explain the drop/recreate schema process
- Add notes to scenarios about data clearing
- Document the import process sequence
- Update version to 2.2

fix: remove verbose flag from pg_dump to prevent SQL syntax errors

- Removed -v flag from pg_dump export command
- Verbose output was being included in SQL file as comments
- These comments caused 'syntax error at or near pg_dump' errors during import
- Backup files will now be clean SQL without pg_dump metadata comments

docs: document pg_dump verbose output fix and troubleshooting

- Added troubleshooting section for pg_dump syntax errors
- Noted that v2.3 fixes this issue
- Directed users to create new backups if needed
- Updated version to 2.3
- Clarified file location is /backups/

docs: add critical warning about using migration script for imports

- Added prominent warning against using psql directly with -f flag
- Explained why direct psql causes 'relation already exists' errors
- Added troubleshooting section for these errors
- Emphasized that script handles data clearing automatically
- Clear examples of wrong vs right approach

fix: remove pg_dump restrict commands that block data import

- Added clean_backup_file() function to remove \restrict and \unrestrict
- pg_dump adds these security commands which prevent data loading
- Script now automatically cleans backup files before importing
- Removes lines starting with \restrict or \unrestrict
- Ensures all data (users, games, commanders) imports successfully
- Called automatically during import process

docs: add troubleshooting for pg_dump restrict commands blocking imports

- Document the \restrict and \unrestrict security commands issue
- Explain why they block data from being imported
- Show that migration script v2.4+ removes them automatically
- Update version to 2.4
- Add detailed troubleshooting section for empty imports
2026-01-18 13:09:53 +01:00
1a81a6d191 fix: correct indentation in deploy.sh docker-compose generation
- Fixed docker-compose.prod.deployed.yml YAML indentation
- postgres service now uses consistent 2-space indents
- db-migrate, backend, and frontend services properly aligned as siblings
- All healthcheck, deploy, and networks sections correctly indented
- Fixed comment indentation in file header
- Fixed print_summary() function echo statement indentation
2026-01-17 21:22:19 +01:00
b7306a963a Migration from SQlite3 to PostgreSQL (#1)
* Migrate from SQLite to PostgreSQL for dev and prod environments

- Replace better-sqlite3 with pg library in backend
- Update database.js to use PostgreSQL connection pooling
- Convert migrations.sql to PostgreSQL syntax with proper triggers and constraints
- Convert seeds.sql to PostgreSQL syntax with JSONB for colors and ON CONFLICT handling
- Update docker-compose.yml with PostgreSQL service and db-migrate container
- Update deploy.sh to generate production docker-compose with PostgreSQL configuration
- Configure environment variables for database connection (DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD)

* Update database models to use PostgreSQL async API

- Convert User.js from better-sqlite3 to PostgreSQL async queries
  - Use parameterized queries with ,  placeholders
  - Update all methods to use async/await
  - Use result.rowCount instead of result.changes
  - Use result.rows[0].id for RETURNING clause results

- Convert Commander.js from better-sqlite3 to PostgreSQL async queries
  - Implement proper async methods with pg library
  - Update JSONB color handling (no longer needs JSON.parse/stringify)
  - Use ILIKE for case-insensitive search instead of LIKE
  - Use proper numeric casting for win rate calculations

- Convert Game.js from better-sqlite3 to PostgreSQL async queries
  - All query methods now properly async
  - Update boolean handling (true/false instead of 1/0)
  - Use ILIKE for case-insensitive commander name search
  - Use RETURNING clause instead of lastInsertRowid

All models now use dbManager.query(), dbManager.get(), and dbManager.all() methods

* Add PostgreSQL cleanup and repository pattern for improved DB abstraction

Database Improvements:
- Fix migrate.js to use async PostgreSQL API with proper error handling
- Update .env.example to reflect PostgreSQL configuration variables
- Update GitHub Actions workflow to generate production docker-compose with PostgreSQL

Architectural Improvements:
- Create base Repository class providing common CRUD operations
- Implement UserRepository for user-specific database operations
- Implement CommanderRepository for commander-specific database operations
- Implement GameRepository for game-specific database operations
- All repositories use parameterized queries to prevent SQL injection
- Centralized database access patterns for better maintainability

Benefits:
- Cleaner separation of concerns (repositories handle data access)
- Reusable repository pattern can be extended for new entities
- Better error handling and transaction support
- Improved code organization and maintainability
- All database queries now properly handle PostgreSQL async operations

* Add comprehensive PostgreSQL migration documentation

- Complete migration summary with before/after comparison
- Detailed changes to each component
- Architecture improvements and benefits
- Repository pattern explanation
- Quick start guide for development and production
- Deployment instructions
- Testing guidelines
- Verification checklist

* Fix Docker build: update package-lock.json and npm syntax

- Run npm install to update package-lock.json with pg dependencies
- Replace deprecated --only=production with --omit=dev (npm 7+)
- Resolves Docker build error about missing pg packages in lock file

* Add migration status document

- Executive summary of completed migration
- Detailed commits history with verification
- Architecture before/after comparison
- Deployment instructions (dev & prod)
- Testing procedures
- Performance characteristics
- Troubleshooting guide
- Rollback instructions (if needed)
- Final sign-off for production readiness

* Add comprehensive deployment checklist

- Pre-deployment verification checklist
- Development deployment step-by-step guide
- Production deployment procedures
- Rollback instructions for emergency cases
- Monitoring and maintenance procedures
- Common issues and solutions
- Performance monitoring commands
- Sign-off checklist for deployment readiness

* Fix PostgreSQL user authentication in docker-compose

- Use postgres superuser instead of creating custom user
- Add init-db script directory for database initialization
- Update docker-compose to mount init scripts
- Simplify credentials: use 'postgres' user for dev
- Update .env.example with correct default credentials
- Health check now uses postgres user

This resolves the 'role edh_user does not exist' error on container startup.
The postgres superuser can create and manage databases and migrations.

* Add Docker Compose testing guide

- Prerequisites checklist
- Step-by-step startup instructions
- Service verification procedures
- API and database testing commands
- Frontend verification steps
- Troubleshooting guide for common issues
- Cleanup procedures
- Expected results checklist

* Fix PostgreSQL password authentication - use correct default user

- Remove incorrect POSTGRES_USER setting (defaults to postgres)
- Set POSTGRES_PASSWORD=edh_password for the default postgres user
- Set POSTGRES_DB=edh_stats to create database automatically
- Update db-migrate and backend services to use password: edh_password
- Update .env.example with correct credentials

PostgreSQL Docker image automatically creates the 'postgres' superuser
when POSTGRES_PASSWORD is set. This resolves the authentication error.

* Add final verification document for completed migration

- Complete migration status verification
- All issues resolved checklist
- Final commit log with all 10 commits
- Quick start command for docker-compose
- Development credentials reference
- Complete list of deliverables
- Documentation index
- Ready-to-deploy status confirmation

* Fix PostgreSQL initialization and SQL migration execution

- Fix 01-init.sql: Remove invalid MySQL syntax and rely on POSTGRES_DB for database creation
- Fix database.js: Execute entire migration/seed SQL files as single queries instead of splitting by semicolon
  This prevents issues with multi-statement SQL constructs (functions, views, triggers)
- Fix docker-compose.yml: Add listen_addresses=* to allow connections from Docker network containers
  and add PGPASSWORD to healthcheck for proper password authentication

All services now start successfully:
- PostgreSQL accepts connections from Docker network
- Migrations run without errors
- Seed data is properly inserted
- Backend API starts and health checks pass
- Database schema with tables, views, and triggers created correctly

* Fix production docker-compose configuration in deploy.sh

- Add listen_addresses=* to PostgreSQL command for Docker network connectivity
- Use 'postgres' superuser instead of DB_USER variable (matches development setup)
- Fix PostgreSQL healthcheck to include PGPASSWORD environment variable
- Fix frontend healthcheck to check root path instead of non-existent /health endpoint
- Add resource limits to frontend container for consistency
- Update .env documentation to reflect correct PostgreSQL user

* Fix DB_USER configuration consistency

- Change default DB_USER in database.js from 'edh_user' to 'postgres'
- Aligns with .env.example, docker-compose.yml, and deploy.sh
- Add clarifying comment in .env.example explaining superuser requirement
- DB_USER must be a superuser to run migrations and create schema objects

The PostgreSQL superuser 'postgres' is created automatically by the Docker image
and has the necessary privileges for all application operations.

* Add DB_SEED environment variable to toggle automatic seeding

- Add DB_SEED environment variable to db-migrate service (default: false)
- Update migrate.js to check DB_SEED and automatically seed if enabled
- Fix seeds.sql ON CONFLICT clauses and sequence resets to use dynamic MAX(id)
- Seeds can now be triggered by setting DB_SEED=true in docker-compose or .env
- Add documentation to .env.example explaining DB_SEED option
- Update deploy.sh to support DB_SEED in production configuration

This allows developers to quickly populate test data during development
without manual seeding commands, while keeping it opt-in for clean databases.

* Fix Commander model: properly convert colors array to JSON for JSONB storage

- Convert JavaScript arrays to JSON strings before inserting into JSONB column
- Add ::jsonb type cast in SQL queries for explicit JSONB conversion
- Handle both array and string inputs in create() and update() methods
- Fixes 'invalid input syntax for type json' error when creating/updating commanders

The pg library doesn't automatically convert JS arrays to JSON, so we must
stringify them before passing to PostgreSQL. The ::jsonb cast ensures proper
type conversion in the database.

* Fix JSON parsing in routes: PostgreSQL JSONB is already parsed

PostgreSQL's pg library automatically parses JSONB columns into JavaScript objects.
The routes were incorrectly calling JSON.parse() on already-parsed JSONB data,
which would fail or cause errors.

Fixed in:
- backend/src/routes/commanders.js (3 occurrences)
- backend/src/routes/games.js (3 occurrences)
- backend/src/routes/stats.js (1 occurrence)

Changed from: JSON.parse(colors) or JSON.parse(commander_colors)
Changed to: colors || [] or commander_colors || []

This matches how the models already handle JSONB data correctly.

* Fix seeds.sql: correct bcrypt hash for password123

The previous bcrypt hash was incorrect and did not match 'password123'.
Generated the correct hash using bcryptjs with 12 rounds.

Correct credentials for seeded test users:
  - Username: testuser
    Password: password123

  - Username: magictg
    Password: password123

This allows developers to login to the application with seeded data.

* Fix stats routes: convert from SQLite to PostgreSQL async methods

- Replace db.prepare().get() with await dbManager.get()
- Replace db.prepare().all() with await dbManager.all()
- Update parameterized query placeholders from ? to $1, $2, etc
- Change boolean comparisons from 'won = 1' to 'won = TRUE' for PostgreSQL
- Remove unnecessary db.initialize() calls
- Both /api/stats/overview and /api/stats/commanders now working correctly

* Fix games routes: remove SQLite boolean conversions and unnecessary JSON parsing

- Remove boolean-to-integer conversion (was converting true/false to 1/0)
- Remove JSON.parse() on JSONB colors column (PostgreSQL pg driver already parses JSONB)
- Fix in both POST create response and PUT update response
- Colors array now correctly returned as already-parsed JavaScript array
- Boolean fields now correctly returned as native boolean type

* Fix frontend: remove JSON.parse() on colors from API responses

- colors field is now pre-parsed array from PostgreSQL JSONB
- Simplified stats.html line 124: remove JSON.parse(stat.colors)
- Simplified dashboard.html line 279: remove defensive type checking for colors
- Frontend now properly handles colors as JavaScript arrays

* Simplify: remove defensive type checking for commanderColors in
dashboard

- game.commanderColors is always an array from PostgreSQL JSONB
- Changed from complex ternary to simple: game.commanderColors || []

* feat: improve environment variable handling in docker-compose and .env.example

- Add RATE_LIMIT_WINDOW and RATE_LIMIT_MAX to .env.example (commented for now)
- Update docker-compose.yml to use environment variables with defaults
  - All DB_* variables now use default format
  - NODE_ENV, JWT_SECRET, CORS_ORIGIN, LOG_LEVEL, ALLOW_REGISTRATION now respect env vars
  - DB_SEED now uses environment variable
- Improves flexibility for development, testing, and production deployments
- Maintains backward compatibility with defaults
- Reduces hardcoded values and increases configurability

* fix: use DB_PASSWORD environment variable in postgres healthcheck

- PGPASSWORD in healthcheck was hardcoded to 'edh_password'
- Changed to use ${DB_PASSWORD:-edh_password} for consistency
- Ensures healthcheck respects DB_PASSWORD environment variable
- Fixes issue where custom DB_PASSWORD would cause healthcheck to fail

* fix: make PostgreSQL external port configurable via DB_PORT

- Changed postgres port mapping from hardcoded '5432:5432' to '${DB_PORT:-5432}:5432'
- Allows users to expose PostgreSQL on different external port via DB_PORT env variable
- Internal container port remains 5432 (unchanged)
- Enables non-standard port usage in constrained environments
- Maintains backward compatibility with default of 5432

* fix: update production docker-compose template in deploy.sh for environment variables

Changes to generated docker-compose.prod.deployed.yml:

Postgres Service:
- Added configurable external port: ${DB_PORT:-5432}:5432
- Ensures port mapping respects DB_PORT environment variable

DB-Migrate Service:
- DB_HOST: postgres -> ${DB_HOST:-postgres}
- DB_PORT: 5432 -> ${DB_PORT:-5432}
- DB_USER: postgres -> ${DB_USER:-postgres}
- Maintains configuration consistency with development

Backend Service:
- DB_HOST: postgres -> ${DB_HOST:-postgres}
- DB_PORT: 5432 -> ${DB_PORT:-5432}
- DB_USER: postgres -> ${DB_USER:-postgres}
- LOG_LEVEL: warn -> ${LOG_LEVEL:-warn}
- Removed hardcoded RATE_LIMIT_* variables (not used yet)
- All variables now properly parameterized

Documentation:
- Updated .env example to include DB_USER, LOG_LEVEL, DB_SEED
- Better guidance for production deployment

Ensures production deployments have same flexibility as development

* fix: update GitHub Actions workflow for PostgreSQL and environment variables

Postgres Service:
- POSTGRES_USER: edh_user -> postgres (matches .env.example and deploy.sh)
- POSTGRES_PASSWORD: change-this-in-production -> edh_password (matches .env.example)
- Added ports configuration: ${DB_PORT:-5432}:5432 (allows external access)
- Fixed healthcheck to use PGPASSWORD and proper variable syntax

DB-Migrate Service:
- DB_HOST: postgres -> ${DB_HOST:-postgres}
- DB_PORT: 5432 -> ${DB_PORT:-5432}
- DB_USER: edh_user -> postgres
- DB_PASSWORD: change-this-in-production -> edh_password
- Added DB_SEED=${DB_SEED:-false}

Backend Service:
- DB_HOST: postgres -> ${DB_HOST:-postgres}
- DB_PORT: 5432 -> ${DB_PORT:-5432}
- DB_USER: edh_user -> postgres
- DB_PASSWORD: change-this-in-production -> edh_password
- JWT_SECRET: removed unsafe default (must be provided)
- LOG_LEVEL: warn -> ${LOG_LEVEL:-warn}

Ensures GitHub Actions workflow is consistent with:
- docker-compose.yml (development)
- deploy.sh (production script)
- .env.example (configuration template)

* feat: implement global rate limiting and request/response logging

- Added rateLimitConfig to jwt.js with configurable window (minutes) and max requests
- Integrated global rate limiting into server.js using RATE_LIMIT_WINDOW and RATE_LIMIT_MAX env vars
- Default: 100 requests per 15 minutes (overridable via environment)
- Added request/response logging hooks for debugging (logged at debug level)
- Logs include method, URL, IP, status code, and duration
- Updated .env.example to document rate limiting configuration

* docs: update README for PostgreSQL migration and new features

- Updated intro to mention PostgreSQL instead of SQLite
- Added rate limiting and request logging features to infrastructure
  section
- Updated Technology Stack to reflect PostgreSQL and rate-limiting
- Revised environment variables section with PostgreSQL config
- Added Custom Environment Variables section with examples
- Expanded Database section with PostgreSQL-specific details
- Added Tips & Common Operations for PostgreSQL management
- Updated Recent Changes to document Session 3 migration work
- Updated Development Notes for async database operations
- Added JSONB field documentation

* security: remove exposed PostgreSQL port from docker-compose

PostgreSQL no longer needs to be exposed to the host since:
- Backend container accesses postgres via internal Docker network
- DB_PORT=5432 is only for internal container connections, not port mapping
- Removes unnecessary attack surface in production

Changes:
- Removed 'ports:' section from postgres service in docker-compose.yml
- Removed port mapping from production deploy.sh template
- Clarified DB_PORT usage in .env.example (internal only)
- Added DB_USER to .env.example with explanation

Security Impact:
- PostgreSQL only accessible within Docker network
- Reduced container exposure to host network
- More secure production deployments

Tested:
- All services start successfully
- Backend connects to postgres via internal network
- Login works, database queries successful
- Frontend accessible on 8081, Backend on 3002

* refactor: remove hardcoded DB_PORT, use PostgreSQL standard port 5432

Simplified database configuration by removing configurable DB_PORT since
PostgreSQL always runs on standard port 5432:

Changes:
- Updated backend/src/config/database.js to hardcode port 5432
- Removed DB_PORT from all docker-compose services
- Removed DB_PORT from production deploy.sh template
- Updated .env.example with clearer documentation
- Clarified that port 5432 is not configurable

Benefits:
- Simpler configuration (fewer environment variables)
- Standard PostgreSQL port is expected behavior
- Reduced configuration surface area
- Still flexible: can adjust DB_HOST for different database servers

Tested:
- All services start successfully
- Database connections work via internal Docker network
- User authentication functional
- API endpoints respond correctly

* docs: update README to reflect DB_PORT removal and configuration simplification

Updated documentation to reflect latest changes:
- Removed DB_PORT from environment variables section (port 5432 is standard)
- Added note that PostgreSQL port is not configurable
- Clarified connection details (port 5432 is standard, not configurable)
- Updated project structure: postgres_data instead of database
- Added deployment script to project structure
- Updated Recent Changes section with configuration simplification details
- Added DB_SEED documentation to environment variables
- Improved clarity on which settings are configurable vs. standard

Emphasizes the security and simplicity improvements from removing
unnecessary port configuration.

* Remove migration docs and init scripts

* refactor: migrate routes from models to repositories

Replaced all data access layer calls in routes from Model classes to Repository classes.

Changes:
- auth.js: Now uses UserRepository instead of User model
  * User.create() → UserRepository.createUser()
  * User.findByUsername() → UserRepository.findByUsername()
  * User.findById() → UserRepository.findById()
  * User.verifyPassword() → UserRepository.verifyPassword()
  * User.updatePassword() → UserRepository.updatePassword()
  * User.updateUsername() → UserRepository.updateUsername()
  * User.updateProfile() → UserRepository.updateProfile()

- commanders.js: Now uses CommanderRepository instead of Commander model
  * Commander.create() → CommanderRepository.createCommander()
  * Commander.findByUserId() → CommanderRepository.getCommandersByUserId()
  * Commander.search() → CommanderRepository.searchCommandersByName()
  * Commander.findById() → CommanderRepository.findById()
  * Commander.update() → CommanderRepository.updateCommander()
  * Commander.delete() → CommanderRepository.deleteCommander()
  * Commander.getStats() → CommanderRepository.getCommanderStats()
  * Commander.getPopular() → CommanderRepository.getPopularCommandersByUserId()

- games.js: Now uses GameRepository instead of Game model
  * Game.findByUserId() → GameRepository.getGamesByUserId()
  * Game.findById() → GameRepository.getGameById()
  * Game.create() → GameRepository.createGame()
  * Game.update() → GameRepository.updateGame()
  * Game.delete() → GameRepository.deleteGame()
  * Game.exportByUserId() → GameRepository.exportGamesByUserId()

Benefits:
 Clean separation of concerns (routes vs data access)
 Better testability (can mock repositories)
 More maintainable (database logic centralized)
 Consistent patterns across all data access
 Easier to add caching or logging layers

Testing:
✓ All syntax checks pass
✓ Authentication working
✓ Commanders endpoint returning 5 commanders
✓ Games endpoint returning 16 games
✓ All endpoints functional

* refactor: remove unused model classes

Models (User, Commander, Game) have been fully replaced by their
corresponding Repository classes. All functionality is preserved in
the repositories with no loss of capability or breaking changes.

Deleted files:
- User.js (136 lines)
- Commander.js (195 lines)
- Game.js (204 lines)

Total: ~535 lines of unused code removed

Benefits:
 Cleaner codebase - no duplicate data access logic
 Single source of truth - repositories handle all data access
 Better maintainability - clear separation of concerns
 No confusion - developers only use repositories
 Follows DRY principle - no code duplication

Testing:
✓ All routes verified to use repositories only
✓ All endpoints tested and working
✓ Authentication (8 endpoints)
✓ Commanders (7 endpoints)
✓ Games (6 endpoints)
✓ Stats (read-only)

No breaking changes - all functionality identical to before.

* Configure DB env defaults and add health checks

- Use DB_USER, DB_PASSWORD, and DB_NAME with defaults in deploy.sh and
  docker-compose.yml
- Replace wget-based health check with curl to /health in the frontend
  service
- Remove listen_addresses configuration from Postgres in
  deploy/docker-compose
- Delete frontend/public/status.html

* Return camelCase game data and richer responses

* Add validation utilities and stricter schemas

* Update commanders.html
2026-01-17 21:14:10 +01:00
aca34942b7 Consolidate into version.txt for deployment and frontent 2026-01-17 10:58:24 +01:00
e7036da5a6 Update healthcheck, nginx caching, and frontend version
- Replace healthcheck test with curl in deploy.sh
- Add backend as a dependency for the frontend service
- Bump frontend version to 1.1.1
- Remove frontend/public/test.html
- Update nginx caching: separate hashed CSS/JS and non-hashed assets
2026-01-16 16:36:27 +01:00
b0e52a778f Add rate limiting and extend JWT expiry
- Wire in Fastify rate-limit (backend) and add dependency
- Update JWT expiresIn to 24h in config
- Remove legacy auth middleware
- Add healthcheck to deployment (deploy.sh)
- Minor frontend tweaks: include average time per round in logs
- Remove Dashboard link from dashboard.html
2026-01-16 09:53:35 +01:00
eb29fc543b Limit builds to AMD64 and bump to 1.0.16 2026-01-15 12:05:28 +01:00
40aaa46e52 Add x-cloak to modals and CSS, minor deploy tweaks 2026-01-15 11:41:51 +01:00
4aef139135 Bump frontend VERSION to 1.0.9 Bump frontend VERSION to 1.0.9
- Update frontend/VERSION from 1.0.8 to 1.0.9 and add
  frontend/public/version.txt
- Write new version to frontend/public/version.txt during deploy
- Serve version.txt via nginx with caching (location /version.txt)
- Dockerfile.prod updated to copy public assets (incl. version.txt) to
  nginx
- Extend static asset rules to include txt files for caching
- Inject a version footer into public HTML pages and load version.txt on
  load
- Load Tailwind CSS via CDN on public pages and remove CSS stylesheet
  link tag
2026-01-15 11:05:30 +01:00
6e45db55ea Add frontend version management and display 2026-01-15 10:43:56 +01:00
8575539a08 Use permanent frontend Dockerfile and drop CDN 2026-01-15 10:41:16 +01:00
2c641296d2 Update frontend ports to 38080 and 30443 to avoid conflicts with other containers
- Changed frontend HTTP port from 80 to 38080
- Changed frontend HTTPS port from 443 to 30443
- Updated deploy.sh to generate docker-compose with new ports
- Updated QUICK_FIX.md with port configuration details
- Updated QUICK_DEPLOY.md with port information and verification steps
2026-01-15 10:04:07 +01:00
c4f599835a Fix Docker deployment issues: nginx resolver for backend hostname, improved volume permissions, init-db service improvements
- Fix frontend nginx config: Use resolver directive to dynamically resolve 'backend' hostname instead of resolving at startup
- Remove SSL/HTTPS enforcing from nginx - HTTP works without certs, SSL can be added later with Traefik
- Simplify nginx config: Remove duplicate location blocks, consolidate to single HTTP server
- Improve init-db service: Change permissions from 755 to 777 for full container write access
- Add init-db restart policy: Set to 'no' so service exits after initialization
- Create QUICK_FIX.md: Step-by-step guide to fix current deployment issues on server
- Create server-init.sh: Pre-deployment script to prepare Docker host for EDH Stats
2026-01-15 10:03:16 +01:00
89df3ed9e3 Add init-db service and update deployment docs 2026-01-15 10:02:13 +01:00
a7e1826140 Enable multi-arch Docker builds with buildx
Implement multi-architecture builds in deploy.sh via docker buildx
Auto-create a multiarch builder if buildx is missing Build and push
images for linux/amd64 and linux/arm64 Update messaging to reflect
multi-arch pushes
2026-01-15 09:51:26 +01:00
36a26f55c2 Stop deleting temporary frontend Dockerfile.prod
Treat Dockerfile.prod as permanent and remove its deletion from
cleanup_temp_files; always report no temporary files
2026-01-15 09:31:32 +01:00
3c20e4fded Migrate to Env Secret and Add Frontend Dockerfile 2026-01-15 09:27:45 +01:00
fc85985317 Add deployment tooling and GHCR publish workflow 2026-01-15 09:22:22 +01:00