Skip to content

Repository files navigation

πŸ—³οΈ AI Secure Voting System

A production-grade, full-stack secure online voting platform built with Node.js, Express, MongoDB, HTML/CSS (Bootstrap 5), and Vanilla JavaScript.


✨ Features

Feature Implementation
6-Factor MFA VoterId β†’ Aadhaar β†’ OTP β†’ Face Recognition β†’ Liveness β†’ CAPTCHA
Face Recognition face-api.js (TinyFaceDetector + FaceRecognitionNet), threshold < 0.6
Liveness Detection EAR blink detection + head yaw via facial landmarks
OTP System In-memory store, 6-digit, 2-minute expiry
Aadhaar Security SHA-256 hash β€” raw value never stored
Tamper-Proof Votes SHA-256 hash chain (each vote links to previous)
AI Anomaly Detection Isolation Forest simulation β€” auto-suspends abusive accounts
Admin Panel Full election lifecycle management, charts, log viewer
WAF Simulation IP blocklist middleware + Cloudflare integration guide
JWT Auth HTTP-only cookies, 1hr expiry
Rate Limiting express-rate-limit (100 req/15min general, 10 auth, 5 vote)
Helmet Secure HTTP headers + Content Security Policy

πŸ“ Project Structure

face-voting-system/
β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ css/style.css             # Dark glassmorphism theme
β”‚   β”œβ”€β”€ js/
β”‚   β”‚   β”œβ”€β”€ register.js
β”‚   β”‚   β”œβ”€β”€ login.js
β”‚   β”‚   β”œβ”€β”€ verify.js
β”‚   β”‚   β”œβ”€β”€ dashboard.js
β”‚   β”‚   β”œβ”€β”€ vote.js
β”‚   β”‚   └── admin.js
β”‚   β”œβ”€β”€ register.html
β”‚   β”œβ”€β”€ login.html
β”‚   β”œβ”€β”€ verify.html
β”‚   β”œβ”€β”€ dashboard.html
β”‚   β”œβ”€β”€ vote.html
β”‚   └── admin.html
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ auth.js                   # 6-step MFA flow
β”‚   β”œβ”€β”€ elections.js              # Public election routes
β”‚   β”œβ”€β”€ votes.js                  # Vote casting + hash chain
β”‚   └── admin.js                  # Admin CRUD + management
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ User.js
β”‚   β”œβ”€β”€ Election.js
β”‚   β”œβ”€β”€ ElectionRequest.js
β”‚   β”œβ”€β”€ Vote.js
β”‚   └── Log.js
β”œβ”€β”€ middleware/
β”‚   β”œβ”€β”€ auth.js                   # JWT cookie middleware
β”‚   β”œβ”€β”€ adminAuth.js              # Admin role gate
β”‚   β”œβ”€β”€ rateLimiter.js            # express-rate-limit configs
β”‚   └── ipBlock.js                # Runtime IP blocklist
β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ hash.js                   # SHA-256 + vote hash chain
β”‚   β”œβ”€β”€ otp.js                    # OTP generate/verify/expire
β”‚   β”œβ”€β”€ captcha.js                # Google reCAPTCHA verification
β”‚   β”œβ”€β”€ logger.js                 # Activity logging to MongoDB
β”‚   └── anomaly.js                # Isolation Forest simulation
β”œβ”€β”€ server.js                     # Express app entry point
β”œβ”€β”€ .env                          # Environment variables
└── README.md

πŸš€ Setup & Installation

Prerequisites

Step 1 β€” Clone & Install

cd face-voting-system
npm install

Step 2 β€” Configure Environment Variables

Edit .env:

PORT=3000
MONGODB_URI=mongodb://localhost:27017/ai_voting_system

JWT_SECRET=your_super_secret_key_here_make_it_long
JWT_EXPIRES_IN=1h

ADMIN_VOTER_ID=ADMIN001
ADMIN_PASSWORD=Admin@12345

# Get from https://www.google.com/recaptcha/admin
RECAPTCHA_SITE_KEY=YOUR_SITE_KEY
RECAPTCHA_SECRET_KEY=YOUR_SECRET_KEY

Note: If reCAPTCHA keys are not configured, the system auto-skips CAPTCHA verification in dev mode (a warning is printed to the console).

Step 3 β€” Start MongoDB

# Windows
mongod --dbpath C:\data\db

# macOS/Linux
mongod --dbpath /data/db

Step 4 β€” Run the Application

npm run dev   # Development (auto-restart with nodemon)
# or
npm start     # Production

Open http://localhost:3000 in your browser.


πŸ—ΊοΈ User Flow

Register β†’ register.html (name, voterId, Aadhaar, face capture)
    ↓
Login Step 1 β†’ login.html  (Voter ID)
Login Step 2 β†’ login.html  (Aadhaar)
Login Step 3 β†’ login.html  (OTP β€” check server console in dev)
    ↓
Login Step 4 β†’ verify.html (Face Recognition)
Login Step 5 β†’ verify.html (Liveness: blink + head turn)
Login Step 6 β†’ verify.html (Google reCAPTCHA)
    ↓
Dashboard β†’ dashboard.html (view elections, request election)
    ↓
Vote β†’ vote.html (select candidate β†’ CAPTCHA β†’ confirm β†’ hash displayed)

βš™οΈ Admin Access

URL: http://localhost:3000/admin

Credential Value
Admin ID ADMIN001 (or whatever you set in .env)
Password Admin@12345 (or whatever you set in .env)

Admin Capabilities

  • πŸ“Š Overview dashboard with live stats
  • πŸ›οΈ Create elections, add/remove candidates, start/stop elections
  • πŸ“‹ Approve or reject election requests from voters
  • πŸ‘₯ View registered voters, suspend/unsuspend accounts
  • πŸ“ View activity logs (filterable + paginated)
  • 🚨 AI anomaly detection β€” flagged & suspended users
  • πŸ›‘οΈ IP blocking β€” block/unblock IPs at runtime

πŸ” Security Architecture

Authentication Chain

VoterId ──► Aadhaar Hash Match ──► OTP (2min) ──► Face (dist<0.6) ──► Liveness ──► CAPTCHA ──► JWT Cookie

Data Security

Data How Stored
Aadhaar SHA-256 hash only
Face 128-float descriptor array (not image)
Password (admin) Plain text in .env β€” upgrade to bcrypt for production
JWT HTTP-only, SameSite=Strict cookie

Vote Integrity

Each vote is linked in a hash chain:

hash = SHA-256(userId + candidateId + timestamp + previousHash)

The first vote uses previousHash = '0'. Any tampering breaks the chain.

API Security Layers

  1. Helmet β€” Secure HTTP headers (XSS, clickjacking, etc.)
  2. express-rate-limit β€” Brute force prevention
  3. ipBlock middleware β€” Runtime IP blocklist
  4. Joi validation β€” Input sanitization on all POST routes
  5. JWT β€” HTTP-only cookies prevent XSS token theft

🌐 Cloudflare WAF Integration

For production deployments:

  1. Point your domain to Cloudflare (change nameservers)
  2. Enable WAF Rules in Cloudflare dashboard β†’ Security β†’ WAF
  3. Recommended rules:
    • Block requests with SQL injection patterns
    • Rate limit > 50 req/min per IP
    • Challenge countries you don't serve
  4. IP Blocking: Use Cloudflare β†’ Security β†’ Tools β†’ IP Access Rules
  5. Set SSL mode to "Full (Strict)" in Cloudflare β†’ SSL/TLS

The ipBlock.js middleware acts as a backend fallback for when Cloudflare isn't in front.


πŸ“‘ API Reference

Auth Routes (/api/auth)

Method Endpoint Description
POST /register Register voter with face descriptor
POST /login/step1 Verify Voter ID
POST /login/step2 Verify Aadhaar hash
POST /login/step3 Send OTP
POST /login/step4 Verify OTP
POST /login/step5 Face + liveness verification
POST /login/step6 CAPTCHA β†’ issue JWT cookie
POST /logout Clear session
GET /me Get current user (requires auth)

Elections Routes (/api/elections)

Method Endpoint Description
GET / List active elections
GET /:id Get election detail
POST /request Submit election request (requires auth)

Vote Routes (/api/votes)

Method Endpoint Description
POST /cast Cast vote with CAPTCHA (requires auth)
GET /status Get user's vote status (requires auth)

Admin Routes (/api/admin)

Method Endpoint Description
POST /login Admin login
POST /logout Admin logout
GET /stats System statistics
GET /elections All elections
POST /elections Create election
POST /elections/:id/candidates Add candidate
DELETE /elections/:id/candidates/:cId Remove candidate
PATCH /elections/:id/status Start/stop election
DELETE /elections/:id Delete election
GET /elections/:id/results Election results
GET /requests Election requests
POST /requests/:id/approve Approve request
POST /requests/:id/reject Reject request
GET /users All voters
POST /users/:id/suspend Suspend user
POST /users/:id/unsuspend Unsuspend user
GET /logs Activity logs
GET /anomalies AI anomaly data
GET /blocked-ips Blocked IP list
POST /blocked-ips/block Block an IP
POST /blocked-ips/unblock Unblock an IP

🧠 AI Anomaly Detection

Uses a simulated Isolation Forest algorithm:

  • Monitors a 15-minute sliding window of activity logs per user
  • Assigns weighted scores to suspicious events:
    • face_fail β†’ +5
    • otp_fail β†’ +4
    • login_fail β†’ +3
    • captcha_fail β†’ +3
    • login_success β†’ βˆ’1 (reduces suspicion)
  • Score β‰₯ 10 β†’ Flagged (warning logged)
  • Score β‰₯ 20 β†’ Auto-suspended (account locked)

View flagged accounts in the Admin Panel β†’ 🚨 Anomalies tab.


πŸ”§ OTP in Production

Currently OTPs are printed to the server console. To enable real delivery:

SMS via Twilio:

npm install twilio
// In utils/otp.js, replace console.log with:
const client = require('twilio')(process.env.TWILIO_SID, process.env.TWILIO_TOKEN);
await client.messages.create({ body: `Your OTP: ${otp}`, from: '+1XXXXXXXX', to: user.phone });

Email via SendGrid:

npm install @sendgrid/mail
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_KEY);
await sgMail.send({ to: user.email, from: 'noreply@yourdomain.com', subject: 'Your OTP', text: `OTP: ${otp}` });

πŸ›‘οΈ HTTPS in Production

Never run this system on plain HTTP in production:

# Option A: Use nginx as reverse proxy with Let's Encrypt
sudo certbot --nginx -d yourdomain.com

# Option B: Use Cloudflare SSL (easiest β€” proxy through Cloudflare)
# Set NODE_ENV=production in .env β€” cookie secure flag auto-enables

πŸ“ License

MIT β€” For educational and research purposes. Consult legal counsel before deploying for real elections.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages