Skip to content

omkhandare55/PromptWar

Repository files navigation

QuickFlow ⚑

"Scan once, avoid crowds everywhere."

A production-grade, real-time smart crowd management system for stadiums and large venues. Built with Firebase Realtime Database, Google Gemini AI, and deployed on Google Cloud Run β€” QuickFlow guides attendees through the fastest routes with zero app downloads.

CI/CD Pipeline Node.js Express Firebase Google Cloud Gemini AI License


🎯 Problem Statement

Large venues like stadiums face severe crowd congestion at entry gates, food stalls, and exits β€” leading to long wait times, safety risks, and poor attendee experience. Traditional crowd management relies on manual staff coordination with zero visibility into real-time bottlenecks.

QuickFlow solves this with a lightweight, QR-code-driven web application that provides:

  • Real-time crowd visibility across all zones
  • AI-powered smart routing via Google Gemini
  • Digital token queuing to eliminate physical lines
  • Staff alert broadcasting for instant communication

πŸš€ Features

πŸ‘€ User Dashboard (index.html)

Feature Description
Live Crowd Status Real-time wait times for all gates and food stalls via Firebase
Color-Coded Indicators 🟒 Low (≀5 min) Β· 🟑 Medium (≀15 min) Β· πŸ”΄ High (>15 min)
AI Smart Advice Google Gemini generates optimal routing suggestions
Digital Token System Scan QR β†’ get token number β†’ roam freely (no physical queue)
Live Alerts Receive real-time staff announcements
PWA / Offline Support Service Worker caches static assets for offline access

πŸ›‘οΈ Admin Panel (admin.html)

Feature Description
Crowd Control Increment/decrement wait times per gate and stall
Alert Broadcaster Send instant alerts to all connected users
Token Monitoring Track tokens served per food stall

πŸ€– AI-Powered API Endpoints (Google Gemini 2.0 Flash)

Endpoint Method Description
/api/smart-advice POST AI-generated crowd routing recommendations
/api/analyze-crowd POST Zone-based density analysis with risk levels
/api/emergency-plan POST AI emergency response action plans
/api/predict-crowd POST Predictive crowd analytics for upcoming events
/api/health GET Cloud Run liveness probe with memory stats
/api/ready GET Cloud Run readiness probe
/api/metrics GET Cache stats, uptime, and system metrics

πŸ› οΈ Tech Stack

Layer Technology Purpose
Frontend HTML5, CSS3, Vanilla JS Lightweight, no-build UI
Backend Node.js 18+, Express 5 Modular API server
Real-time DB Firebase Realtime Database Live crowd data sync
AI Engine Google Gemini 2.0 Flash 4 AI endpoints
Security Helmet, CORS, Rate Limiting, CSP Defense-in-depth
Testing Jest, Supertest 60+ automated tests
CI/CD GitHub Actions Multi-version test + auto-deploy
Container Docker (multi-stage) Non-root, health checked
Deployment Google Cloud Run Serverless containers
Build Google Cloud Build Automated Docker builds
Hosting Firebase Hosting Global CDN with security headers
Logging Google Cloud Logging Structured JSON logs
Performance Compression, LRU Cache Gzip + API response caching
PWA Service Worker, Manifest Offline support, installable

πŸ“ Project Structure

PromptWar/
β”‚
β”œβ”€β”€ config/
β”‚   └── index.js                  # Centralized config β€” zero magic numbers
β”‚
β”œβ”€β”€ middleware/
β”‚   β”œβ”€β”€ security.js               # Helmet CSP, CORS whitelist, request ID tracking
β”‚   β”œβ”€β”€ rateLimiter.js            # Dual rate limiting (global + API-specific)
β”‚   β”œβ”€β”€ validator.js              # Input sanitization & validation middleware
β”‚   β”œβ”€β”€ logger.js                 # Google Cloud Logging compatible structured logs
β”‚   β”œβ”€β”€ cache.js                  # LRU in-memory cache with TTL & stats
β”‚   └── errorHandler.js           # Custom AppError class, centralized error handling
β”‚
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ api.js                    # 4 Gemini AI endpoints with caching + validation
β”‚   └── health.js                 # Health, readiness, metrics probes for Cloud Run
β”‚
β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ css/
β”‚   β”‚   └── style.css             # Dark-mode glassmorphism UI, accessibility utils
β”‚   β”œβ”€β”€ js/
β”‚   β”‚   β”œβ”€β”€ firebase-config.js    # Firebase Realtime DB init & auto-seeding
β”‚   β”‚   β”œβ”€β”€ main.js               # User-side real-time rendering logic
β”‚   β”‚   └── admin.js              # Admin panel controls
β”‚   β”œβ”€β”€ icons/
β”‚   β”‚   β”œβ”€β”€ icon-192.png          # PWA icon 192x192
β”‚   β”‚   └── icon-512.png          # PWA icon 512x512
β”‚   β”œβ”€β”€ index.html                # User dashboard (ARIA, semantic, skip links)
β”‚   β”œβ”€β”€ admin.html                # Staff panel (accessible, noindex)
β”‚   β”œβ”€β”€ manifest.json             # PWA Web App Manifest
β”‚   └── sw.js                     # Service Worker β€” offline support
β”‚
β”œβ”€β”€ .github/
β”‚   └── workflows/
β”‚       └── ci.yml                # CI/CD: Test on Node 18/20 β†’ Deploy to Cloud Run
β”‚
β”œβ”€β”€ server.js                     # Entry point β€” clean composition of all modules
β”œβ”€β”€ server.test.js                # 60+ automated tests across 12 suites
β”œβ”€β”€ Dockerfile                    # Multi-stage build, non-root user, health check
β”œβ”€β”€ .dockerignore                 # Excludes tests, docs, git from container
β”œβ”€β”€ cloudbuild.yaml               # Google Cloud Build configuration
β”œβ”€β”€ firebase.json                 # Firebase Hosting config with security headers
β”œβ”€β”€ database.rules.json           # Firebase DB rules β€” auth + field validation
β”œβ”€β”€ package.json                  # Dependencies, scripts, engine constraints
└── README.md

πŸ”’ Security Implementation

Layer Measure Details
HTTP Headers Helmet.js Strict CSP, HSTS preload, X-Frame DENY, hide X-Powered-By
Cross-Origin CORS Whitelist Origin validation, production enforcement
Rate Limiting Dual Limiters Global: 200 req/15min Β· API: 10 req/min
Input Sanitization HTML tag stripping via sanitizeInput()
Input Validation Type checking, range (0–999), length limits (3–500)
Payload Size Limit JSON body capped at 10KB
Errors Centralized Handler Stack traces hidden in production, request ID correlation
Tracing Request IDs Auto-generated X-Request-ID on every response
Container Docker Multi-stage build, non-root appuser, health check
Database Firebase Rules Auth-required writes, type + range validation
Permissions Policy Header Camera, microphone, geolocation disabled
Transport HSTS 1-year max-age, includeSubDomains, preload

πŸ§ͺ Testing β€” 60+ Automated Tests

npm test              # Run all tests
npm run test:verbose  # Verbose output
npm run test:coverage # With coverage report
Suite Tests Coverage
sanitizeInput() unit tests 12 XSS, HTML stripping, null/undefined, edge cases
validateCrowdData() unit tests 16 Types, ranges, boundaries, NaN, Infinity
Cache module tests 7 Set/get, TTL expiry, key generation, stats, clear
Static file serving 6 HTML, CSS, JS, Firebase config, 404
Security headers (Helmet) 10 CSP, HSTS, X-Frame, XSS, Referrer, Request ID
Input validation & XSS 9 Missing fields, injection, out-of-range, arrays
/api/smart-advice 3 Valid data, fallback, single-gate
/api/analyze-crowd 2 Valid zones, fallback with structure check
/api/emergency-plan 4 Valid, fallback, XSS stripping, optional fields
/api/predict-crowd 2 Valid prediction, fallback
Cloud Run probes 3 Health (memory, version), readiness, metrics
Error handling 3 404 JSON, unknown routes, invalid JSON

⚑ Quick Start

Prerequisites

Install & Run

git clone https://github.com/omkhandare55/PromptWar.git
cd PromptWar
npm install
node server.js
Page URL
User App http://localhost:8080
Admin Panel http://localhost:8080/admin.html
Health Check http://localhost:8080/api/health
Metrics http://localhost:8080/api/metrics

Environment Variables

Variable Required Description
PORT No Server port (default: 8080, auto-set by Cloud Run)
NODE_ENV No production or development
GEMINI_API_KEY No Google Gemini API key for AI endpoints
ALLOWED_ORIGINS No Comma-separated CORS whitelist

Run Tests

npm test

☁️ Deployment

Option 1: Google Cloud Run (Recommended)

# Authenticate & configure
gcloud auth login
gcloud config set project promptwar-fcc9a

# Enable required APIs
gcloud services enable run.googleapis.com cloudbuild.googleapis.com

# Deploy from source
gcloud run deploy quickflow-service \
    --source . \
    --region us-central1 \
    --allow-unauthenticated \
    --set-env-vars "NODE_ENV=production,GEMINI_API_KEY=your_key"

Option 2: Firebase Hosting

npm install -g firebase-tools
firebase login
firebase init hosting   # Select: promptwar-fcc9a, public dir: public
firebase deploy

Option 3: CI/CD (Fully Automated)

Every push to main triggers the GitHub Actions pipeline:

  1. βœ… Test β€” 60+ tests on Node.js 18 and 20
  2. πŸ” Audit β€” npm audit for dependency vulnerabilities
  3. πŸš€ Deploy β€” Automatic deployment to Google Cloud Run

🌐 Google Services Integration

# Service How It's Used
1 Firebase Realtime Database Live crowd data sync across all connected clients
2 Google Gemini 2.0 Flash 4 AI endpoints: advice, analysis, emergency, prediction
3 Google Cloud Run Containerized serverless deployment with health probes
4 Google Cloud Build Automated Docker image builds (cloudbuild.yaml)
5 Google Cloud Logging Structured JSON logs with severity, latency, request tracing
6 Firebase Hosting Global CDN delivery with security headers (firebase.json)

β™Ώ Accessibility (WCAG 2.1 AA)

Feature Implementation
Skip Links "Skip to main content" for keyboard navigation
ARIA Labels All interactive elements have descriptive labels
ARIA Roles role="banner", role="list", role="dialog", role="alert"
Live Regions aria-live="polite" for real-time crowd updates
Screen Reader .sr-only helper class for visually hidden text
Focus Management focus-visible outlines for keyboard users
Reduced Motion prefers-reduced-motion media query support
Semantic HTML <header>, <main>, <section>, <nav> landmarks
Form Labels Hidden labels on all inputs for assistive technology
Color Contrast WCAG AA compliant contrast ratios on all text

πŸ“Š Performance Optimizations

Optimization Impact
Gzip Compression ~70% reduction in response sizes
LRU API Cache 30s TTL, max 100 entries β€” reduces Gemini API calls
Static Asset Caching 1-day max-age with ETag validation
Service Worker Cache-first for static, network-first for API
Multi-stage Docker Smaller production image, faster cold starts
Engine Constraints "node": ">=18.0.0" ensures modern runtime

πŸ“± How It Works

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    QR Scan    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    Firebase RT DB    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Attendee   β”‚ ────────────► β”‚  QuickFlow   β”‚ ◄─────────────────► β”‚  Firebase    β”‚
β”‚   (Phone)    β”‚               β”‚  Web App     β”‚                     β”‚  Realtime DB β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜               β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                      β”‚
                               β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”    Gemini API       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                               β”‚  Express     β”‚ ◄─────────────────► β”‚  Google      β”‚
                               β”‚  API Server  β”‚                     β”‚  Gemini AI   β”‚
                               β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                      β”‚
                               β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”
                               β”‚  Google      β”‚
                               β”‚  Cloud Run   β”‚
                               β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  1. Scan QR β†’ Opens web app instantly (no download)
  2. View Live Status β†’ See which gates/stalls have shortest wait
  3. Get AI Advice β†’ Gemini suggests fastest route
  4. Get Digital Token β†’ Skip physical queue at food stalls
  5. Receive Alerts β†’ Staff broadcasts reach all users in real time

πŸ“„ License

ISC

πŸ‘€ Author

Om Khandare β€” @omkhandare55

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors