Pull Request: Major Fork with PostgreSQL, Modern Deployment, House Players, and Production Hardening - #4
Open
fapulito wants to merge 90 commits into
Open
Pull Request: Major Fork with PostgreSQL, Modern Deployment, House Players, and Production Hardening#4fapulito wants to merge 90 commits into
fapulito wants to merge 90 commits into
Conversation
- Created complete Node.js/Express application in vercel/ folder - Implemented Facebook authentication using Passport.js - Added Vercel configuration (vercel.json) - Created basic poker game UI with Facebook login - Copied essential assets from original project - Added README with setup and deployment instructions - Configured API endpoints for authentication and game listing
…ls, Add safet to migration
…hase spec Security fixes: - Replace mock verifySignedRequest() with real HMAC-SHA256 verification - Fix hardcoded CORS origins to use environment variables - Make Facebook credentials optional for local development Windows support (experimental): - Add mojopoker_win.pl Windows-compatible startup script - Add install_win.bat Windows installation script - Add FB::Compat::Timer module as EV fallback for Windows - Patch FB/User.pm, FB/Login.pm, FB.pm to make EV optional - Add WebSocket ready-state check in jquery.poker.main.js Documentation: - Fix markdown linting issues in CODE_REVIEW.md - Update .env.example with APP_URL variable New feature spec: - Create Stripe chip purchase system spec (.kiro/specs/stripe-chip-purchase/) - Requirements for Stripe payments, daily bonus, Facebook Canvas - Design with 12 correctness properties - Implementation task list with 12 main tasks Note: Windows native Perl server has compatibility issues with EV event loop. Recommend using WSL2 or the Vercel/Node.js version instead. feat: Add optional Facebook auth, dev guest login, and NeonDB/DigitalOcean deployment - Fix syntax error in server.js (unescaped apostrophe in "Texas Hold'em") - Make Facebook OAuth optional - server starts without credentials - Add dev guest login bypass when FB auth not configured - Update FB/Db.pm to support both SQLite (local) and PostgreSQL (NeonDB) - Add comprehensive DEPLOYMENT_GUIDE.md for production setup: - NeonDB PostgreSQL configuration - DigitalOcean VPS setup with Perl/Mojolicious - Vercel frontend deployment - Nginx reverse proxy with SSL - Facebook app configuration - Cost estimates and scaling notes
Fixed vercel.json to properly route requests: API routes go to the serverless function Static files served from /public All other routes serve index.html Rewrote api/index.js as a proper serverless Express app (no server.listen()) Cleaned up package.json (removed unused deps, updated Node version)
…hich counts tests dynamically. Also removed plan tests => N from subtests. migrate_integration.t - Added parse_database_url() helper function that converts postgresql://user:pass@host:port/db to proper DBI format dbi:Pg:dbname=db;host=host;port=port. Also uses done_testing(). test.yaml - Updated to explicitly install DBD::Pg and other required modules.
Verifies db directory exists before entering Uses pushd/popd for proper directory handling Checks both fb.schema and poker.schema exist Finds sqlite3 in PATH or Strawberry location, fails with clear error if missing Runs each sqlite3 command and checks ERRORLEVEL immediately after Prints descriptive error messages for each failure case Always popd before exiting on error
Tests: - Fix migrate.t and migrate_integration.t to use done_testing() instead of fixed plan - Add parse_database_url() helper to convert postgresql:// URLs to DBI format - Add DBD::SQLite to CI workflow dependencies Timer (FB::Compat::Timer): - Fix recurring timer fallback to match EV::timer semantics (fire after $after, then every $repeat) - Add cancel() method to properly remove both initial and recurring timers - Use defined-or (//) instead of logical-or (||) to preserve explicit 0 values - Fix remaining() to correctly compute time until next firing for recurring timers Security: - Restrict dev guest login to NODE_ENV=development only - Return 403 in production when Facebook auth not configured - Log warnings for blocked guest login attempts Windows installer (install_win.bat): - Add cpanm prerequisite check with clear error message - Validate db directory and schema files exist before initialization - Use pushd/popd for proper directory handling - Check ERRORLEVEL after each sqlite3 command - Add descriptive error messages for all failure cases Vercel: - Fix vercel.json routing for serverless deployment - Rewrite api/index.js as proper serverless Express app
validate() - Removed bcrypt hashing, now only performs format validation register() - Added _bcrypt_hash() call to hash password before storing via new_user() login() - Now fetches user by username only, then verifies password using _bcrypt_verify() which compares plaintext against stored hash Added helper methods _bcrypt_hash() and _bcrypt_verify() for proper bcrypt operations
Security (FB.pm): - Remove bcrypt hashing from validate() - now only performs format checks - Add _bcrypt_hash() helper with cost factor 12 for registration - Add _bcrypt_verify() for secure password comparison in login() - Hash passwords only once during register(), verify against stored hash in login() Security (vercel/api/index.js): - Validate FACEBOOK_APP_ID and FACEBOOK_APP_SECRET are non-empty before registering strategy - Restrict guest login to NODE_ENV=development only - Return 403 in production when Facebook auth not configured - Add clear logging for auth configuration status CI: - Add DBD::SQLite to workflow dependencies for test compatibility
…re line since it already uses done_testing() at the end. The unique constraint error in migrate.t is expected behavior - it's testing that the database correctly rejects duplicate usernames using dies_ok.
…les) Confirmed architecture: static HTML (public/index.html) + Express API (api/index.js) No Next.js dependencies needed FILEPATHS: Deleted vercel/pages/index.js, vercel/pages/_app.js
Previous State (Problem): Used express-session with default MemoryStore Sessions lost on serverless function restart No JWT used anywhere Users logged out randomly on Vercel New State (Solution): Replaced session-based auth with JWT tokens Tokens stored in HTTP-only cookies (secure, not accessible via JS) Stateless - works perfectly with Vercel serverless No external store (Redis) needed Changes Made: vercel/package.json - Added jsonwebtoken dependency vercel/api/index.js - Rewrote to use JWT instead of sessions vercel/lib/server.js - Same JWT approach for local dev vercel/.env.example - Added JWT_SECRET config DEPLOYMENT_GUIDE.md - Updated env vars documentation JWT Features Implemented: 7-day token expiration HTTP-only cookies (XSS protection) Secure flag in production (HTTPS only) SameSite=lax (CSRF protection) User payload: id, displayName, email, photo, isGuest
…ystem" }. This lets Vercel serve any existing static file directly before falling back to the catch-all route, which is more flexible and efficient.
Verify before Merge with Main FUIYOHHHH
Modern architecture diagram (Vercel + DigitalOcean + NeonDB) Quick start for local development Production deployment reference Environment variables documentation Windows development instructions CodeRabbit integration section explaining how automated code review works Testing instructions Project structure overview Recent improvements list Updated contact info
…r.pl, removed the unsupported daemon arguments, and added a note that the server listens on port 3000.
…d fix EV::timer compatibility - Convert all EV::timer calls to FB::Compat::Timer for cross-platform support - Send turn_clock value to client with begin_new_action message - Display countdown timer on active player's seat - Timer changes color: green -> yellow (10s) -> red pulsing (5s) - Clear timer on action change and game end"
Add visible turn clock countdown and convert timer calls to FB::Compat::Timer
…making Implement complete house player strategy system for automated poker gameplay across multiple game variants (Texas Hold'em, Omaha, Draw poker). Core Strategy Module (Tasks 1-2): - Add Strategy::Manager as central coordinator for house player decisions - Add Strategy::Config with validation for aggression, tightness, bluff frequency - Add Strategy::ActionDecider with bet sizing, bluffing, and randomization logic - Add HandEvaluator role with game-variant-specific implementations - Add Holdem, Omaha, and Draw evaluators with proper hand strength calculation - Integrate with existing FB::Poker::Eval for 7-card hand evaluation Action Decision System (Task 4): - Implement decide() method with hand strength and game state analysis - Add calculate_bet_amount() with min/max bounds checking - Add should_bluff() with configurable probability (5-15%) - Add randomization with ±15% threshold variation per player - Add slow-play logic for strong hands (>0.85 strength) - Add independent RNG seeding for each house player Game Integration (Tasks 5-7): - Register evaluators for holdem, omaha, omahahilo, and draw variants - Hook strategy manager into FB::Poker::Table action cycle - Add auto-play trigger for house player turns - Add automatic blind/ante posting for house players - Add automatic rebuy logic when chips fall below table minimum - Create test tables with house players on server startup Authentication & Persistence (Tasks 8-9): - Document Facebook OAuth HMAC-SHA256 signature verification flow - Verify new user creation with facebook_id storage - Verify 400 chips and 400 invested initialization - Verify HMAC-SHA1 bookmark generation for session persistence - Document user retrieval and chip balance persistence mechanisms - Add comprehensive verification documentation for auth flows Testing: - Add unit tests for strategy evaluators (holdem, omaha, draw) - Add unit tests for action decider logic - Add unit tests for strategy manager evaluator selection - Add unit tests for configuration validation - Add unit tests for house player autoplay integration Requirements: 1.1-1.4, 2.1-2.4, 3.1-3.4, 4.1-4.4, 5.1-5.4, 6.1-6.4, 7.1-7.4, 8.1-8.4, 9.1-9.4
…(tasks 10-14) This commit completes the final phase of the house player strategy implementation, including verification of existing systems and mobile player disconnection handling. Task 10: Checkpoint - All tests passing - Verified all strategy module tests pass - Confirmed integration with existing game engine Task 11: Chip management verification - Verified chip balance consistency across bank and table operations - Confirmed reload logic correctly credits chips to reach 400 minimum - Validated daily reset functionality resets all users to 400 chips/invested - Documented chip management flows in verification files Task 12: House player account management verification - Verified house player naming convention (HousePlayer\d+) - Confirmed mock WebSocket usage prevents network transmission - Validated house player chip limits (1000000 chips) - Added tests for naming patterns and mock WebSocket interface Task 13: Mobile player disconnection handling - Implemented FB::Session::Manager for grace period management - Added disconnected_sessions and grace_timers tracking - Implemented on_disconnect(), on_reconnect(), and grace_expired() handlers - Extended FB::Poker::Chair with auto_action settings (fold, check_fold, call_N) - Added auto_call_limit and disconnected flag to chairs - Integrated Session Manager with WebSocket close/reconnect events - Implemented apply_auto_action() for disconnected player turns - Added set_auto_action command for player preference configuration Task 14: Final checkpoint and CI fixes - Fixed test file library paths (mojopoker-1.1.1/lib -> lib) - All 75 tests passing successfully across 12 test files - Updated cpanfile with missing dependencies: * Algorithm::Combinatorics (for Omaha evaluator) * Mojo::IOLoop and Mojolicious (web framework) * Digest::SHA, JSON, MIME::Base64 (auth/serialization) - Updated GitHub Actions workflow to use cpanm --installdeps - Ensures CI environment matches local development setup Test Results: - 12 test files executed - 75 tests passed - 0 failures - 2 skipped (PostgreSQL integration - requires DATABASE_URL) All house player strategy module functionality is now complete and verified.
Created FB::Poker::Strategy::Evaluator::OmahaHiLo.pm
Implements proper Omaha Hi-Lo (Eight-or-Better) split-pot evaluation
Evaluates both high and low hands separately
Enforces 8-or-better qualification for low hands
Treats Aces as 1 for low evaluation
Ignores pairs, straights, and flushes for low hand ranking
Uses exactly 2 hole cards + 3 community cards (Omaha rule)
Returns combined strength considering both high and low potential
Updated FB.pm
Added use FB::Poker::Strategy::Evaluator::OmahaHiLo;
Changed line 121 from registering regular Omaha evaluator to OmahaHiLo evaluator:
$manager->register_evaluator('omahahilo', FB::Poker::Strategy::Evaluator::OmahaHiLo->new);
Created comprehensive test t/omaha_hilo_evaluator.t
Tests basic functionality
Tests high hand evaluation
Tests low hand qualification (8-or-better)
Tests that Aces count as low
Tests edge cases
Verifies exactly 2+3 card rule
Updated t/strategy_manager.t
Added OmahaHiLo evaluator registration test
Verifies correct evaluator retrieval for 'omahahilo' game class
Test Results:
✅ All 85 tests passing
✅ 13 test files executed successfully
✅ New OmahaHiLo evaluator properly integrated
Created FB::Poker::Strategy::Evaluator::OmahaHiLo with proper split-pot evaluation Updated FB.pm to register the OmahaHiLo evaluator for 'omahahilo' game class Added comprehensive tests for OmahaHiLo functionality 2. Removed Duplicate House Player Detection Logic Changed in mojopoker-1.1.1/lib/FB/Poker.pm (lines ~1367-1370):
File: mojopoker-1.1.1/lib/FB/Poker.pm (line ~1427)
File: mojopoker-1.1.1/lib/FB/Poker/Strategy/ActionDecider.pm
Fixed the CI/CD test failure
…iLo.pm, lines 103-160) Issue: The low-hand score was being built in ascending rank order (A-2-3-4-5 → 12345), but the normalizer expected descending order where the highest rank is the most significant digit (8-7-6-5-4 → 87654). Fixes: Reversed the iteration order when building the score to produce descending rank order Updated the normalization constants: best low changed from 12345 to 54321 (representing 5-4-3-2-A) Updated comments to clarify the scoring format Fixed the test expectation to match the actual hand strength Added Tie::IxHash to the dependency installation step in the GitHub Actions workflow.
Fixed Database Constraint Test Failures (t/migrate.t)
The cpanfile - so it's declared as a dependency The workflow file - so it's explicitly installed during CI
feat: implement house player strategy module with automated decision-…
Author
|
There's a couple issues with creating users that will be resolved soon and added to this PR. |
…ting both SQLite (for local development) and PostgreSQL (for production deployment) with proper error handling, transaction support, and database-specific optimizations.
…s ✅ Uses safe file operations - Opens and reads the schema file directly using Perl's open() ✅ Uses DBI directly - Connects to SQLite using DBI and executes SQL statements without shell ✅ Proper error handling - Dies with error message if schema file cannot be opened
Updated task status in .kiro/specs/database-abstraction/tasks.md
Fix 2: Parse Timestamps in new_user Method
…ties in all database operations.
The database abstraction layer is fully functional and tested, suppor…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Overview
This is a comprehensive fork (~80 commits ahead) that transforms Mojo Poker into a production-ready, cloud-native poker platform. Major additions include PostgreSQL support, automated house players with AI strategy, modern deployment infrastructure (Vercel + Fly.io), security hardening, and extensive bug fixes.
🎯 Major Features Added
1. PostgreSQL Database Support ✨
Complete migration from SQLite to PostgreSQL with NeonDB integration
mojopoker-1.1.1/lib/FB/Db.pm- Complete rewrite for PostgreSQLmojopoker-1.1.1/db/migrate.pl- SQLite to PostgreSQL migrationmojopoker-1.1.1/db/postgres.schema- PostgreSQL-optimized schemaDATABASE_URLor individual env varsImpact: Production-ready database with ACID compliance, better concurrency, and cloud hosting support.
2. Automated House Players with AI Strategy 🤖
Complete AI opponent system with configurable strategies
New Modules:
FB::Poker::Strategy::Manager- Orchestrates house player decisionsFB::Poker::Strategy::ActionDecider- Makes betting decisions based on hand strengthFB::Poker::Strategy::Config- Configurable aggression, tightness, bluffingFB::Poker::Strategy::Evaluator::*- Game-specific hand evaluators (Holdem, Omaha, Draw, OmahaHiLo)Features:
Tests: Comprehensive property-based tests for RNG independence and strategy evaluation
Impact: Tables can run 24/7 with AI opponents, no need for minimum human players.
3. Modern Cloud Deployment Infrastructure ☁️
Vercel Frontend (Serverless)
/api/auth/*,/api/poker/*Fly.io Backend (Docker)
Ansible Deployment (Traditional VPS)
New Files:
FLY_IO_DEPLOYMENT.md- Complete Fly.io guideDEPLOYMENT_GUIDE.md- Multi-platform deploymentansible/- Complete Ansible playbooks.github/workflows/deploy-fly.yml- CI/CD automation4. Security Hardening 🔒
Files Changed:
mojopoker-1.1.1/lib/FB.pm- Bcrypt integrationmojopoker-1.1.1/lib/Ships/Main.pm- SQL injection fixesvercel/lib/middleware/jwt.js- JWT authentication5. Session Management & Reconnection 🔄
New Module:
FB::Session::Manager- Complete session lifecycle management6. Guest User Support 👤
7. Windows Support 🪟
mojopoker_win.plfor Windows🐛 Critical Bug Fixes (7 issues)
1. Session Manager - login_watch Storage Bug
File:
lib/FB/Session/Manager.pm(line 118)table_idinstead of login object inlogin_watch$self->fb->login_watch->{$login_id} = $login2. OmahaHiLo - Low Hand Scoring Algorithm
File:
lib/FB/Poker/Strategy/Evaluator/OmahaHiLo.pm(lines 103-175)3. Player ID Comparison
File:
lib/FB/Poker.pm(lines 1383-1396)$player->idmethod$player->login->user->idwith defensive checks4. Session Grace Period Cleanup
File:
lib/FB/Session/Manager.pm(grace_expired method)5. ActionDecider RNG Independence
File:
lib/FB/Poker/Strategy/ActionDecider.pm(lines 11-38)rand()for seed generation, affecting process-wide RNG(time() ^ ($$ << 15))for per-instance seed generation6. Channel Cleanup in Grace Expiry
File:
lib/FB/Session/Manager.pm(lines 169-175)delete $channel->logins->{$login_id}with defensive checks7. Test Constraint Handling
File:
t/migrate.t(lines 255-285)RaiseError => 1RaiseError => 0and check return values instead of exceptionsDependency Fixes
Added missing Perl modules to
cpanfileand.github/workflows/test.yaml:Tie::IxHash- Required by house player autoplay testsSQL::Abstract- Required byFB::DbmoduleCrypt::Eksblowfish- Required byFB.pmfor password hashingModern Deployment Infrastructure
Fly.io Deployment (New)
Added complete Docker-based deployment for Fly.io with WebSocket support:
New Files:
mojopoker-1.1.1/Dockerfile- Optimized Perl/Mojolicious containermojopoker-1.1.1/fly.toml- Fly.io configuration with WebSocket supportmojopoker-1.1.1/.dockerignore- Build optimizationFLY_IO_DEPLOYMENT.md- Comprehensive 13-part deployment guide.github/workflows/deploy-fly.yml- Automatic deployment on pushWhy Fly.io?
Testing
All tests pass:
cd mojopoker-1.1.1 prove -v t/Key test improvements:
📊 Statistics
🏗️ Architecture Changes
Before (Original)
After (This Fork)
📦 New Dependencies
Perl Modules (cpanfile)
Crypt::Eksblowfish- Bcrypt password hashingSQL::Abstract- Query builder for PostgreSQLTie::IxHash- Ordered hash supportDBD::Pg- PostgreSQL driverAlgorithm::Combinatorics- Hand evaluationNode.js (Vercel)
jsonwebtoken- JWT authenticationbcryptjs- Password hashingcookie-parser- Cookie managementexpress- API server🧪 Testing Improvements
New Test Files
t/action_decider_rng_independence.t- RNG independence verificationt/omaha_hilo_evaluator.t- Omaha Hi-Lo hand evaluationt/strategy_evaluator.t- Strategy module testst/user_persistence.t- Database persistence testst/migrate.t- Migration script testst/migrate_integration.t- Integration testsCI/CD
📚 Documentation Added
🎮 Game Improvements
New Game Support
Bug Fixes
🔧 Developer Experience
Local Development
Environment Setup
# .env file DATABASE_URL=postgresql://user:pass@host/db FACEBOOK_APP_ID=your_app_id FACEBOOK_APP_SECRET=your_secret JWT_SECRET=random_32_char_stringDocker Development
docker build -t mojopoker . docker run -p 8080:8080 --env-file .env mojopoker🚀 Deployment Options
This PR provides two production-ready deployment paths:
Both support:
💰 Cost Comparison
🔄 Migration Path
From Original Mojo Poker
Database Migration:
cd mojopoker-1.1.1 perl db/migrate.pl --from sqlite.db --to postgresql://...Environment Setup:
cp .env.example .env # Edit .env with your credentialsDeploy:
Backward Compatibility
🎯 Use Cases
This Fork is Perfect For:
Production Poker Sites
Private Poker Rooms
Poker AI Research
Learning Projects
None. All changes are backward compatible with the original Mojo Poker.
What Still Works:
What's New (Optional):
Files Changed
Core Application
mojopoker-1.1.1/lib/FB/Session/Manager.pm- Session cleanup fixesmojopoker-1.1.1/lib/FB/Poker/Strategy/Evaluator/OmahaHiLo.pm- Low-hand scoring fixmojopoker-1.1.1/lib/FB/Poker.pm- Player ID comparison fixmojopoker-1.1.1/lib/FB/Poker/Strategy/ActionDecider.pm- RNG independence fixTests
mojopoker-1.1.1/t/migrate.t- Constraint test fixesmojopoker-1.1.1/t/omaha_hilo_evaluator.t- Updated test expectationsDependencies
mojopoker-1.1.1/cpanfile- Added missing modules.github/workflows/test.yaml- Updated CI dependenciesDeployment (New)
mojopoker-1.1.1/Dockerfile- Docker container definitionmojopoker-1.1.1/fly.toml- Fly.io configurationmojopoker-1.1.1/.dockerignore- Build optimizationFLY_IO_DEPLOYMENT.md- Deployment guide.github/workflows/deploy-fly.yml- CI/CD automationChecklist
Related Issues
Fixes multiple runtime bugs discovered during production testing and adds modern deployment infrastructure for easier scaling.
Additional Notes
For Reviewers
For Users
🤝 Contributing
This fork maintains compatibility with the original while adding production features. Contributions welcome for:
📝 License
Maintains original Artistic License 2.0. All additions are compatible with the original license.
🙏 Acknowledgments
📞 Contact
🗺️ Roadmap
Completed ✅
Planned 🚧
📸 Screenshots
Original
This Fork
⚡ Quick Start
Try It Now (5 minutes)
Deploy to Production (10 minutes)
📊 Comparison Matrix
🎓 Learning Resources
This fork is great for learning:
💡 Why This Fork?
The original Mojo Poker is excellent but designed for local/hobby use. This fork transforms it into a production-ready platform suitable for:
All while maintaining 100% compatibility with the original!
Contact