LifeLink is an emergency response web application powered by Google Cloud Firestore & Firebase Auth with Express.js and React. It bridges standby blood donors, individuals in critical need, and medical facilities through smart donor matching, real-time inventory management, spatial UI design, and role-based workflows.
Warning
Security Note: Real credentials and .env files are never committed to GitHub. Copy .env.example templates to .env in both server/ and client/ directories and configure your credentials locally.
- 📍 Smart Donor Matching Engine: In-code spatial distance calculation and compatibility matrix ranking standby donors based on ABO/Rh RBC compatibility, 90-day donation cooldown eligibility, proximity distance, and availability.
- ⚡ Emergency Request Broadcast & Tracking: Instant creation of emergency blood requests (
/individual/create) with live matched donor rankings and automated notification dispatch. Recipients can monitor progress in real time via an interactive stepper tracking portal (/individual/track/:id). - 🏥 Hospital Command Hub & Reserve Stock: Medical facilities manage reserve stock across all 8 standard blood groups, process incoming requests, allocate inventory units, and track donor fulfillments with atomic transaction guarantees.
- 👤 Donor Portal & Google Sign-In: Standby donors manage availability, track donation history and cooldown eligibility, and authenticate via traditional credentials or verified Google Single Sign-On (Firebase Auth ID Token verification).
- 🛡️ Role-Based Access Control: Strict JWT authentication with distinct access controls for standard
user(donor & recipient), verifiedhospital, and systemadmin. - 💎 Liquid Glass & Spatial UI: Apple-inspired translucent glass aesthetic with 5 spatial elevation tiers, 4 harmonic drifting atmospheric orbs, dynamic refraction filters, and full light/dark mode support.
- 📊 AI Insights & Platform Analytics: Administrative dashboard with emergency response time indicators, platform health metrics, shortage prediction alerts, and an interactive AI Chatbot assistant.
- 🧪 Comprehensive Automated Testing & QA: 333 automated Jest + Supertest backend tests (23 test suites, 100% pass) alongside automated WCAG 2.1 AA/AAA contrast checks and Playwright visual audits.
LifeLink features a refined "Midnight Navy + Crimson + Ice" design system built for life-critical healthcare applications, balancing visceral cinematic depth with clinical calm and uncompromising accessibility across both dark and light modes:
-
Midnight Navy + Crimson + Ice Direction:
-
Clinical, Trustworthy, Calm: Midnight Navy (
#0A0F1C) dark foundation and Cool White (#F4F7FB) light canvas base, paired with Silver-blue neutrals and clear semantic signals. -
10% Emergency Crimson Budget: Crimson is reserved strictly for life-critical signals (primary CTAs, emergency/critical badges, urgent request status indicators, active nav indicator). It represents
$\le 10%$ of any viewport, preserving its immediate urgency. -
Semantic Mapping: ONLINE / Verified Facility / Confirmed / Fulfilled
$\rightarrow$ success; cooldown / low stock / pending$\rightarrow$ warning; critical stock / urgent request$\rightarrow$ danger; informational / focus$\rightarrow$ info. Always paired with icons and text labels (never color alone).
-
Clinical, Trustworthy, Calm: Midnight Navy (
| Token | Dark Mode | Light Mode | Usage & Purpose |
|---|---|---|---|
canvas |
#0A0F1C |
#F4F7FB |
Base viewport foundation |
surface |
#111A2E |
#FFFFFF |
Core data cards, inputs, containers |
raised |
#18233D |
#E9EFF7 |
Filter panels, interactive forms, active cards |
overlay |
#1F2C4A |
#FFFFFF + shadow |
Dialog modals, full-screen sheets |
text-primary |
#E8EEF9 |
#0F1A2E |
High-contrast headings and key data values |
text-muted |
#9DAAC6 |
#4A5A78 |
Captions, secondary subtitles, metadata |
hairline |
rgba(147,161,189,0.16) |
rgba(15,26,46,0.12) |
Subtle glass borders and divider lines |
specular rim |
rgba(255,255,255,0.08) |
rgba(255,255,255,0.90) |
Top-edge optical specular highlight |
danger (text/icon/badge) |
#E5484D |
#C8102E |
Critical shortages, emergency request badges |
danger-solid (button fill) |
#D13438 |
#C8102E |
Primary emergency CTAs with white text ( |
danger hover |
#FF6166 |
#A80D26 |
Interactive hover state for danger buttons |
danger pressed |
#B82C30 |
#8A0A1F |
Pressed active state for danger buttons |
success |
#34D399 |
#0A7A62 |
ONLINE status, verified facilities, fulfilled donations |
warning |
#FBBF24 |
#9A5B00 |
Cooldown warnings, low stock, pending reviews |
info / focus |
#60A5FA |
#1D6FD6 |
Keyboard focus ring (2px with 2px offset), info pills |
ice (accent) |
#A5D8FF |
#1D6FD6 |
AI assistance, secondary highlights, subtle glow accents |
-
5-Tier Spatial Elevation System:
-
elevation-canvas(Level 0): Viewport foundation and atmospheric canvas. -
elevation-base(Level 1): Standard data cards, list tiles, and tabular rows. -
elevation-raised(Level 2): Active items, interactive forms, and filter panels. -
elevation-floating(Level 3): Floating navigation bar, AI chat widget, and toast alerts. -
elevation-overlay(Level 4): High-priority dialog modals and full-screen drawers.
-
-
Atmospheric Canvas: 4 harmonic, hardware-accelerated (
translate3d) ambient orbs (dim crimson, royal blue#2B4C8C, ice blue#A5D8FF, and silver-blue#93A1BD), dimmed to$\le 12%$ opacity in dark mode and$\le 8%$ in light mode withprefers-reduced-motionfallback. -
Optics & Refraction: Neutral navy-tinted glass in dark mode, clean white glass with genuine elevation shadows (
0 1px 2px rgba(15,26,46,.06),0 8px 24px rgba(15,26,46,.08)) in light mode, SVG displacement map filters (#liquid-refraction), and top specular rims. -
Accessibility & Contrast: 100% WCAG 2.1 AA/AAA compliance verified across all routes and state views in both modes (body text
$\ge 11.8:1$ dark,$\ge 15.0:1$ light; white text on danger-solid$\ge 4.9:1$ dark,$\ge 5.8:1$ light; focus rings$\ge 4.5:1$ ). Tabular numeric fonts (tabular-nums) prevent layout shifts.
| Layer | Technologies |
|---|---|
| Frontend | React 18, Vite 5, Tailwind CSS 3, Framer Motion, Lucide Icons, Recharts, Axios |
| Backend | Node.js, Express.js 4, firebase-admin 14, JWT, bcryptjs, Zod validation |
| Database & Cloud | Google Cloud Firestore (Uniform Repository Architecture), Firebase Auth |
| Authentication | Custom JWT + bcryptjs & Google Login (Firebase Auth ID Token verification) |
| Testing & QA | Jest, Supertest, Playwright, @axe-core/playwright (333 automated tests) |
| Role / Account Type | Registration | Key Privileges |
|---|---|---|
user (Donor & Recipient) |
Public registration / Google Sign-In | Post emergency requests, track request progress, pledge donations, manage availability & donor profile |
hospital |
Public registration (requires admin approval) | Broadcast emergency requests, manage RBC inventory units, ping matching donors, confirm fulfilled donations |
admin |
Database seed script | Approve hospital registrations, manage platform users & requests, view AI insights & analytics |
Note
Role Elevation Guard: Google Sign-In strictly provisions accounts with accountType: "user". Hospital and Admin accounts cannot be provisioned via Google Sign-In, protecting elevated system roles.
- Node.js (v18.0.0 or higher) and
npm - A Firebase Project with Cloud Firestore and Firebase Authentication (Email/Password & Google Provider) enabled
git clone https://github.com/tejas-coder28/LifeLink.git
cd LifeLinkYou can install dependencies for the root, server, and client simultaneously from the repository root:
# Install all dependencies across client and server
npm run install:allOr install them individually:
# Server dependencies
cd server
npm install
# Client dependencies
cd ../client
npm installCopy server/.env.example to server/.env:
cp server/.env.example server/.envGenerate a Firebase Service Account key:
- In the Firebase Console, navigate to Project Settings > Service accounts.
- Click Generate new private key and download the resulting JSON file.
- Save the JSON file securely (e.g.
server/service-account.json— already included in.gitignore). - Configure
server/.env:
PORT=5000
JWT_SECRET=your_super_secret_jwt_key
FIREBASE_SERVICE_ACCOUNT_PATH=./service-account.json
NODE_ENV=developmentCopy client/.env.example to client/.env:
cp client/.env.example client/.envPopulate the Firebase Web SDK credentials from Project Settings > General > Your apps > Web app:
VITE_API_URL=http://localhost:5000/api
VITE_FIREBASE_API_KEY=your_api_key
VITE_FIREBASE_AUTH_DOMAIN=your_project.firebaseapp.com
VITE_FIREBASE_PROJECT_ID=your_project_id
VITE_FIREBASE_STORAGE_BUCKET=your_project.appspot.com
VITE_FIREBASE_MESSAGING_SENDER_ID=your_sender_id
VITE_FIREBASE_APP_ID=your_app_idVerify backend health:
# Start backend in development
npm run dev:serverVisit GET http://localhost:5000/api/health to confirm operational status:
{
"success": true,
"status": "operational",
"dbType": "firestore",
"projectId": "your-firebase-project",
"timestamp": "..."
}Seed initial demo accounts and inventory stock:
# From root
npm run seed
# Or to reset and re-seed clean data
npm run seed:resetYou can run both client and server using the root convenience scripts or dedicated terminals:
# Terminal 1 — Start the API Server (Port 5000)
npm run dev:server
# Terminal 2 — Start the React Client (Port 5180)
npm run dev:client# Terminal 1:
cd server && npm run dev
# Terminal 2:
cd client && npm run devOpen your browser at http://localhost:5180.
Tip
The client Vite dev server runs on port 5180 with an automated proxy forwarding /api/* requests to the Express backend on http://127.0.0.1:5000.
LifeLink includes a rigorous automated testing and accessibility assurance suite:
# Run 333 automated backend tests
cd server
npm test- 23 Test Suites / 333 Tests: 100% pass rate.
- Covers authentication, blood compatibility scoring, spatial matching algorithms, donation fulfillment, hospital workflows, transaction integrity, rate limiting, and role guards.
# Run automated color contrast validation
npm run check:contrast- Evaluates all token foreground and background color combinations in both Dark and Light modes.
- Enforces WCAG 2.1 AA/AAA compliance (normal text
$\ge 4.5:1$ , large text / UI elements$\ge 3.0:1$ ).
# Run headless browser audit with automated screenshot capture
npm run audit:pages- Traverses every public, donor, hospital, and admin route.
- Verifies contrast, focus rings, interactive states, and saves high-resolution screenshots to
scripts/screenshots/.
Seeded automatically by npm run seed:
| Role | Password | Access & Privileges | |
|---|---|---|---|
| User / Donor | user@lifelink.com |
user123 |
Standby donor dashboard, pledge donations, track requests, update availability & location |
| Hospital | hospital@lifelink.com |
hospital123 |
Broadcast emergency requests, manage 8-group RBC inventory stock, ping donors, confirm pledges |
| Admin | admin@lifelink.com |
admin123 |
Approve hospital registrations, manage platform accounts, view AI insights & analytics |
| Endpoint | Method | Role | Description |
|---|---|---|---|
/api/auth/register |
POST |
Public | Register standard donor or hospital account |
/api/auth/login |
POST |
Public | Authenticate with email/password and obtain JWT |
/api/auth/google |
POST |
Public | Verify Firebase Google ID token and issue JWT session |
/api/requests |
GET |
Public / Auth | List blood requests with filter criteria |
/api/requests |
POST |
user, hospital |
Create a new emergency blood request |
/api/requests/:id |
GET |
Authenticated | Retrieve request details with live matched donors |
/api/donors |
GET |
Public / Auth | Query standby donors by blood group and radius |
/api/donations/pledge |
POST |
user |
Pledge donation for an active emergency request (requires { requestId, units }) |
/api/donations/:id/fulfill |
POST |
hospital, admin |
Confirm donation fulfillment and update inventory |
/api/hospitals/inventory |
GET, PUT |
hospital |
View and update RBC reserve units |
/api/hospitals/pending |
GET |
admin |
View hospital accounts awaiting verification |
/api/hospitals/:id/approve |
PUT |
admin |
Approve registered hospital |
/api/analytics |
GET |
admin |
Aggregate platform donation metrics and trends |
/api/ai/insights |
GET |
admin |
Predictive regional blood supply insights |
/api/ai/chat |
POST |
Public / Auth | Role-aware, data-aware AI Assistant powered by Google Gemini (strictly read-only) |
/api/health |
GET |
Public | Backend health check and Firestore connection status |
LifeLink implements clinical donor safety standards and volume transparency based on hospital and National Blood Transfusion Council (NBTC) guidelines:
-
Shared Blood Unit Configuration (
bloodUnits.js):-
ML_PER_UNIT = 450: Single whole-blood donation unit equivalent to$\approx 450\text{ ml}$ . -
MAX_UNITS_PER_DONOR_PER_PLEDGE = 1: Standard whole-blood donations are strictly capped at 1 unit per donor per donation to safeguard donor health and prevent post-donation syncope. -
formatUnits(n, options): Consistent volumetric display helper used across both server and client:"1 unit (≈ 450 ml)""2 units (≈ 900 ml)"-
"77 units (≈ 34.7 L)"(with litres formatting for facility stock reserves$\ge 1000\text{ ml}$ )
-
-
Pledge Confirmation Dialog (
PledgeModal):- Clicking "Respond / Pledge" never triggers a direct API call; it opens an accessible confirmation modal.
-
Request Overview: Displays patient name, medical facility, urgency badge, and units still needed with volume (
"Still needed from donors: 2 units (≈ 900 ml)"). - Donor Eligibility Check: Real-time evaluation of 90-day cooldown and standby availability. Ineligible donors are warned with their remaining cooldown days and next eligible date; confirmation is disabled.
- Unit Selector: Default and fixed at 1 unit with clear medical guidance.
- Mandatory Health Affirmation: Checkbox "I confirm that I am feeling healthy today, am aged 18-65, weigh at least 50 kg, and have not donated whole blood in the last 90 days." must be checked before confirmation is enabled.
-
Safe Submission: Displays loading spinner, prevents double submission, handles errors inline, and updates card display to
"Pledged: 1 unit (≈ 450 ml)"with a "View Pledge" shortcut.
-
Strict Server Validation:
- Zod schema
pledgeDonationSchemaenforces required integerunits >= 1. - Rejects missing units (
400), units exceedingMAX_UNITS_PER_DONOR_PER_PLEDGE(400), units exceeding remaining donor shortfall (400), ineligible donors in cooldown or offline (403), and duplicate active pledges (409).
- Zod schema
-
AI Assistant Read-Only Guarantee:
- The AI assistant is strictly informational and read-only; it can never trigger or submit a pledge.
- Pledge CTAs in chat navigate to
/donor/dashboard?tab=requests&request=<id>&action=pledgeas "Review & Pledge", scrolling to the card and opening the modal for donor review without auto-submitting.
LifeLink includes an embedded, role-aware, data-aware, and navigation-aware assistant powered by Google Gemini with a deterministic Keyword Router Fallback (Provider A):
-
Strict App-Only Scope: The assistant exclusively answers questions relating to LifeLink (blood requests, standby donors, blood bank inventory, cooldown eligibility, and platform navigation). Any off-topic query (weather, sports, politics, math, general programming, recipes, entertainment) immediately returns a fixed, polite refusal:
"I can only help with LifeLink: blood requests, donors, inventory and finding your way around the app."
-
Role-Scoped Read-Only Tools:
-
user/donor:getMyProfile,getEligibility(90-day cooldown calculation),getOpenRequestsForMe,getMyRequests,getMyDonationHistory,getMyAlerts. -
hospital:getInventory(all 8 RBC groups, total, low stock$\le 3$ , critical$= 0$ ),getIncomingDemands,getActiveRequests,getPendingPledges,getMatchingDonors(requestId),getMyVerificationStatus. -
admin:getPlatformStats,getPendingHospitals,getShortageAlerts,getRequestOverview. -
shared:getHowToGuide(topic)(returns navigation instructions and one-click deep-link action buttons).
-
-
Security & Data Isolation:
- Identity parameters (
userId,donorId,hospitalId) cannot be spoofed by the client or model; the server always injects identity directly from the verified JWTreq.user. - Hospital A cannot query requests or matching donors belonging to Hospital B (fails closed).
- Donors cannot see other users' contact information or exact coordinates.
- Identity parameters (
- Immediate Greeting Shortcut: Simple greetings ("hi", "hello", "thanks", "help") bypass external LLM calls and return an immediate role-specific greeting with 3 suggestion chips.
-
Zero-Downtime Fallback Guarantee: If
AI_PROVIDER=keyword,AI_API_KEYis omitted, the network fails, or the request times out ($\ge 8000\text{ms}$ ), the server logs a single structured warning (with zero secrets) and seamlessly fulfills the user query via the rule-based keyword router (Provider A).
- Authentication: Optional. If
Authorization: Bearer <token>is provided, the session inherits the user's role and data scope; otherwise it runs inpublicmode. - Rate Limit: 20 requests per minute per IP / user session. Returns
429 Too Many Requestswhen exceeded. - Request Payload:
{ "message": "What is our blood bank inventory?", "history": [ { "role": "user", "content": "hello" }, { "role": "assistant", "content": "Welcome to LifeLink Hospital Support..." } ], "currentPath": "/hospital/dashboard" } - Response Format:
{ "success": true, "message": "Chat response generated", "data": { "reply": "Total stock: 12 units. Critical (0 units): AB-, O-. Low (1-3 units): A-.", "actions": [ { "type": "navigate", "label": "Inventory Reserves", "path": "/hospital/dashboard", "tab": "inventory" } ], "suggestions": [ "Review incoming demands", "View active blood requests", "Check verification status" ], "provider": "gemini" } }
Configure in server/.env:
| Variable | Default | Purpose |
|---|---|---|
AI_PROVIDER |
gemini |
gemini (primary) or keyword (fallback-only mode) |
AI_API_KEY |
None | Google Gemini API key (or GEMINI_API_KEY) |
AI_MODEL |
gemini-2.5-flash |
Official Google GenAI model ID |
AI_TIMEOUT_MS |
8000 |
Timeout in milliseconds before falling back to Provider A |
LifeLink/
├── client/ # React + Vite frontend (Port 5180)
│ ├── src/
│ │ ├── api/ # Axios service API clients
│ │ ├── components/ # Modular UI component library
│ │ │ ├── ai/ # AI Chat Widget & Insight Cards
│ │ │ ├── auth/ # Google Login Button & Auth Panels
│ │ │ ├── cards/ # Donor, Request, and Stat Cards
│ │ │ ├── charts/ # Recharts Visualizations (Blood Group Bar, Trends, Status Pie)
│ │ │ ├── common/ # GlassCard, GlassModal, Navbar, Footer, ThemeToggle
│ │ │ └── forms/ # DonorProfileForm, InventoryForm, RequestForm
│ │ ├── context/ # AuthContext, ThemeContext, ToastContext
│ │ ├── hooks/ # useTheme, useChartTheme, useTypewriterFill
│ │ ├── pages/ # Application views
│ │ │ ├── admin/ # AdminDashboard, UserManagement, RequestManagement, AIInsights
│ │ │ ├── auth/ # Login, Register, ForgotPassword
│ │ │ ├── donor/ # DonorDashboard, DonorProfile, DonationHistory
│ │ │ ├── hospital/ # HospitalDashboard, InventoryManager, MatchingDonors
│ │ │ ├── individual/ # CreateRequest, TrackRequest, IndividualDashboard
│ │ │ └── public/ # Home, About, FindDonors, EmergencyRequest
│ │ ├── routes/ # ProtectedRoute and AccountTypeRoute wrappers
│ │ ├── theme/ # Central design system tokens (tokens.js)
│ │ ├── utils/ # statusHelper, date formatting, geo helpers
│ │ ├── firebase.js # Firebase Web SDK initialization
│ │ └── index.css # Liquid Glass design system styles & CSS variables
│ ├── tailwind.config.js # Tailwind configuration with spatial elevations
│ ├── vite.config.js # Vite server configuration & API proxy
│ └── .env.example
├── server/ # Express API backend (Port 5000)
│ ├── src/
│ │ ├── config/ # Firebase Admin & Firestore initialization
│ │ ├── controllers/ # Express route handler controllers
│ │ ├── middleware/ # JWT Auth, RoleGuard, Zod Validation, RateLimiter
│ │ ├── repositories/ # Google Cloud Firestore Uniform Repository layer
│ │ ├── routes/ # Express API routers
│ │ ├── services/ # Domain logic, matching engine, atomic transactions
│ │ ├── utils/ # ABO/Rh compatibility, geo math, response helpers
│ │ ├── validations/ # Zod input validation schemas
│ │ ├── app.js # Express application setup
│ │ ├── index.js # Server entry point
│ │ └── seed.js # Database seed and reset script
│ ├── tests/ # Automated Jest + Supertest suites (333 tests)
│ └── .env.example
├── docs/ # Documentation
│ ├── design-system.md # Liquid Glass & Spatial UI specification
│ └── ui-audit.md # Comprehensive UI inventory and audit
├── scripts/ # QA & Verification Tools
│ ├── check-contrast.js # Automated WCAG 2.1 AA/AAA token contrast checker
│ └── audit-pages.js # Playwright + axe-core full-route auditor
├── firestore.indexes.json # Composite Firestore database indexes
├── package.json # Monorepo management scripts
└── README.md
| Script | Command | Purpose |
|---|---|---|
npm run install:all |
npm install --prefix server && npm install --prefix client |
Install all dependencies across both projects |
npm run dev:server |
npm run dev --prefix server |
Start Express backend in watch mode (Port 5000) |
npm run dev:client |
npm run dev --prefix client |
Start Vite frontend dev server (Port 5180) |
npm run seed |
npm run seed --prefix server |
Seed demo accounts, inventory, and sample requests |
npm run seed:reset |
npm run seed:reset --prefix server |
Clear and re-seed database |
npm run build |
npm run build --prefix client |
Build optimized client production bundle |
npm run check:contrast |
node scripts/check-contrast.js |
Run automated WCAG AA/AAA contrast audit |
npm run audit:pages |
node scripts/audit-pages.js |
Run Playwright visual and accessibility route audit |
This project is open-source and available under the MIT License.