Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

24 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿšข ShipGuard AI

Real-time Shipment Risk Monitoring & Logistics Intelligence Platform

React Node.js Firebase Vite Tailwind Express

Real-time Tracking โ€ข Risk Assessment โ€ข Intelligent Alerts โ€ข Analytics Dashboard โ€ข Webhook Integration

Live Demo โ€ข Features โ€ข Quick Start โ€ข API Docs


๐Ÿ“– About

ShipGuard AI is an enterprise-grade logistics monitoring platform that provides real-time visibility into shipment operations, automated risk assessment, and predictive analytics. Built for modern supply chains, it seamlessly integrates with Transportation Management Systems (TMS), Enterprise Resource Planning (ERP) systems, and carrier APIs.

The platform leverages Firebase Firestore for real-time data synchronization, enabling instant updates across dashboards, alerts, and analytics. With intelligent webhook ingestion, weather integration, and logistics news aggregation, ShipGuard AI delivers actionable insights that help businesses proactively manage shipment risks and optimize operations.

Whether you're tracking a single shipment or managing thousands across multiple carriers and modes, ShipGuard AI provides the tools you need for complete logistics visibility and control.


โœจ Features

  • โœ… Real-time Shipment Tracking โ€” Monitor shipments across multiple carriers and transport modes
  • โœ… Automated Risk Scoring โ€” Dynamic risk calculation with visual distribution analytics
  • โœ… Intelligent Alert System โ€” Proactive notifications for high-risk events and delays
  • โœ… Live Analytics Dashboard โ€” Trend analysis, operational metrics, and KPIs
  • โœ… Webhook Integration โ€” Seamless ingestion from TMS/ERP systems with secure authentication
  • โœ… Webhook Security Hardening โ€” HMAC signature verification, payload validation, and rate limiting
  • โœ… Weather Monitoring โ€” Location-based weather forecasts for route planning
  • โœ… Logistics News Feed โ€” Real-time industry news aggregation
  • โœ… Route Intelligence โ€” Alternative route recommendations with operational risk context
  • โœ… Firestore Real-time Sync โ€” Instant updates across all connected clients
  • โœ… Multi-carrier Support โ€” DHL, FedEx, UPS, and custom carrier integration
  • โœ… Custom Reporting โ€” Configurable views, filters, and data exports
  • โœ… User Settings Persistence โ€” Firestore-backed preferences and configurations
  • โœ… Secure API Routes โ€” Weather, news, and route proxy endpoints with backend-only provider keys
  • โœ… Session Protection โ€” Frontend session timeout controls and protected route enforcement
  • โœ… Resilience Layer โ€” Frontend retry/timeout handling and offline/online status UX
  • โœ… Observability Ready โ€” Optional Sentry integration for frontend and backend error monitoring
  • โœ… CI Automation โ€” Frontend and backend GitHub Actions workflows

๐Ÿ› ๏ธ Tech Stack

Frontend

  • React 18 โ€” Modern component-based UI framework
  • Vite โ€” Lightning-fast build tool and dev server
  • Tailwind CSS โ€” Utility-first styling with custom design system
  • Recharts โ€” Interactive data visualization and charting
  • Firebase Web SDK โ€” Client-side Firestore subscriptions and authentication

Backend

  • Node.js โ€” JavaScript runtime for server-side logic
  • Express โ€” Minimal and flexible web application framework
  • Firebase Admin SDK โ€” Server-side Firestore operations and authentication
  • CORS + Helmet + Morgan โ€” Cross-origin controls, security headers, and request logging
  • Joi + express-rate-limit โ€” Payload validation and abuse protection

Monitoring & Quality

  • Sentry โ€” Optional application error monitoring (frontend + backend)
  • GitHub Actions โ€” Frontend build checks and backend syntax validation

Database & Authentication

  • Cloud Firestore โ€” Scalable NoSQL document database with real-time sync
  • Firebase Authentication โ€” Secure user authentication and authorization

External Integrations

  • OpenWeather API โ€” Weather data and location-based forecasts
  • News API โ€” Logistics and supply chain news aggregation

๐Ÿ“ Project Structure

shipguard-ai/
โ”œโ”€โ”€ backend/
โ”‚   โ”œโ”€โ”€ server.js                 # Express server, API routes, webhook handler
โ”‚   โ”œโ”€โ”€ .env                      # Backend environment variables
โ”‚   โ”œโ”€โ”€ .env.example              # Backend env template
โ”‚   โ”œโ”€โ”€ service-account.json      # Firebase Admin credentials (gitignored)
โ”‚   โ”œโ”€โ”€ package.json              # Backend dependencies
โ”‚   โ””โ”€โ”€ node_modules/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ components/               # Reusable React components
โ”‚   โ”œโ”€โ”€ pages/                    # Page-level components (Dashboard, Analytics, Alerts)
โ”‚   โ”œโ”€โ”€ lib/                      # Firebase client & API integrations
โ”‚   โ”‚   โ”œโ”€โ”€ api/                  # Backend proxy API clients + retry utility
โ”‚   โ”‚   โ””โ”€โ”€ ml/                   # Risk prediction and recommendation utilities
โ”‚   โ”œโ”€โ”€ App.jsx                   # Main application component
โ”‚   โ””โ”€โ”€ main.jsx                  # React entry point
โ”œโ”€โ”€ public/                       # Static assets
โ”œโ”€โ”€ .env                          # Frontend environment variables
โ”œโ”€โ”€ .env.example                  # Frontend env template
โ”œโ”€โ”€ .gitignore                    # Git ignore configuration
โ”œโ”€โ”€ package.json                  # Frontend dependencies and scripts
โ”œโ”€โ”€ vite.config.js                # Vite build configuration
โ”œโ”€โ”€ tailwind.config.js            # Tailwind CSS customization
โ”œโ”€โ”€ postcss.config.js             # PostCSS configuration
โ””โ”€โ”€ README.md                     # Project documentation

๐Ÿš€ Quick Start

Prerequisites

Ensure you have the following installed:

  • Node.js v16 or higher
  • npm or yarn
  • Firebase project with Firestore and Authentication enabled
  • API keys for OpenWeather and News API

Installation

# Clone the repository
git clone https://github.com/LegendarySumit/shipguard-ai.git
cd shipguard-ai

# Install frontend dependencies
npm install

# Install backend dependencies
cd backend
npm install
cd ..

Configuration

Create .env file in project root:

# Firebase Client Configuration
VITE_FIREBASE_API_KEY=your_firebase_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_id

# Backend API URL
VITE_BACKEND_URL=http://localhost:8787

Create backend/.env file:

# Server Configuration
PORT=8787
NODE_ENV=development
ALLOWED_ORIGINS=http://localhost:5173,http://127.0.0.1:5173

# Webhook Security
WEBHOOK_SECRET=your_secure_webhook_secret_min_32_chars
WEBHOOK_URL=http://localhost:8787
WEBHOOK_REQUIRE_HMAC=true
WEBHOOK_ALLOW_LEGACY_SECRET=false

# External APIs
OPENWEATHER_API_KEY=your_openweather_api_key
NEWS_API_KEY=your_news_api_key

# PII encryption (required for encrypted storage of customer/product fields)
PII_ENCRYPTION_KEY=replace_with_strong_random_secret

# Webhook retry queue (prevents data loss on transient failures)
WEBHOOK_RETRY_ENABLED=true
WEBHOOK_RETRY_INTERVAL_SEC=60
WEBHOOK_RETRY_MAX_ATTEMPTS=6
WEBHOOK_RETRY_BATCH_SIZE=25

# Firestore retention policy
RETENTION_ENABLED=true
RETENTION_DAYS=365
RETENTION_RUN_EVERY_HOURS=24

# Firebase Admin (choose one method)
FIREBASE_SERVICE_ACCOUNT_PATH=backend/service-account.json
# OR FIREBASE_SERVICE_ACCOUNT_JSON={"type":"service_account",...}
# OR FIREBASE_SERVICE_ACCOUNT_JSON_BASE64=base64_encoded_json

Generate Webhook Secret

node -e "console.log(require('crypto').randomBytes(48).toString('base64url'))"

Deploy Firestore Security Rules

This project includes hardened rules in firestore.rules.

firebase deploy --only firestore:rules

Run the Application

Terminal 1 โ€” Start Frontend:

npm run dev

Frontend available at http://localhost:5173

Terminal 2 โ€” Start Backend:

npm run backend:dev

Backend available at http://localhost:8787

Build for Production

# Build frontend
npm run build

# Preview production build
npm run preview

# Run backend in production
cd backend
NODE_ENV=production node server.js

๐Ÿ“š Usage

Dashboard

Access the main dashboard at http://localhost:5173 to view:

  • Real-time shipment risk distribution
  • Active alerts and notifications
  • Quick statistics and KPIs

Analytics

Navigate to /analytics for:

  • Trend analysis with historical data
  • Carrier and mode performance metrics
  • Risk score evolution over time

Webhook Testing

Send a test shipment via webhook:

curl -X POST http://localhost:8787/api/webhooks/shipments \
  -H "Content-Type: application/json" \
  -H "x-webhook-secret: YOUR_WEBHOOK_SECRET" \
  -d '{
    "shipment": {
      "trackingId": "TEST-1001",
      "status": "in_transit",
      "origin": "Berlin, DE",
      "destination": "Munich, DE",
      "riskScore": 25
    }
  }'

Verify the shipment appears in Firestore and updates the dashboard in real-time.


๐Ÿ”Œ API Reference

Health Check

GET /api/health

Response:

{
  "ok": true,
  "timestamp": "2026-03-18T10:30:00.000Z",
  "integrations": {
    "firestoreIngestion": true,
    "weatherAPI": true,
    "newsAPI": true
  }
}

Weather Endpoints

Endpoint Method Description
/api/weather/by-city GET Get weather by city name
/api/weather/by-coords GET Get weather by coordinates
/api/weather/geocode GET Convert location to coordinates
/api/weather/forecast GET Get weather forecast
/api/routes/alternatives POST Get route alternatives from backend intelligence layer

Example โ€” Weather by City:

GET /api/weather/by-city?city=London&units=metric

Query Parameters:

  • city (required) โ€” City name
  • units (optional) โ€” metric, imperial, or standard (default: metric)

Example โ€” Weather by Coordinates:

GET /api/weather/by-coords?lat=51.5074&lon=-0.1278&units=metric

Query Parameters:

  • lat (required) โ€” Latitude
  • lon (required) โ€” Longitude
  • units (optional) โ€” Temperature units

News Endpoint

GET /api/news/logistics

Response:

{
  "articles": [
    {
      "title": "Global Shipping Disruptions Continue",
      "description": "Latest updates on supply chain issues...",
      "url": "https://example.com/article",
      "publishedAt": "2026-03-18T10:00:00Z",
      "source": { "name": "Logistics Weekly" }
    }
  ]
}

Webhook Ingestion

POST /api/webhooks/shipments

Headers:

Content-Type: application/json
X-Webhook-Timestamp: <unix-seconds>
X-Webhook-Signature: sha256=<hmac_sha256(secret, timestamp.rawBody)>

Migration compatibility (temporary):

x-webhook-secret: your_webhook_secret

Single Shipment Payload:

{
  "shipment": {
    "trackingId": "TMS-1002",
    "status": "in_transit",
    "carrier": "DHL",
    "mode": "road",
    "origin": "Hamburg, DE",
    "destination": "Cologne, DE",
    "riskScore": 31,
    "riskLevel": "low"
  }
}

Batch Shipments Payload:

{
  "shipments": [
    {
      "trackingId": "TMS-1001",
      "status": "in_transit",
      "carrier": "DHL",
      "mode": "road",
      "origin": "Berlin, DE",
      "destination": "Munich, DE",
      "riskScore": 42,
      "riskLevel": "medium"
    },
    {
      "trackingId": "TMS-1002",
      "status": "delivered",
      "carrier": "FedEx",
      "mode": "air",
      "origin": "London, UK",
      "destination": "Paris, FR",
      "riskScore": 15,
      "riskLevel": "low"
    }
  ]
}

Shipment Schema:

Field Type Required Description
trackingId string โœ… Unique tracking identifier
status string โœ… pending, in_transit, delivered, delayed
carrier string โŒ Carrier name (DHL, FedEx, UPS)
mode string โŒ Transport mode: road, air, sea, rail
origin string โœ… Origin location
destination string โœ… Destination location
riskScore number โœ… Risk score (0-100)
riskLevel string โŒ low, medium, high (auto-calculated)

Success Response:

{
  "ok": true,
  "written": 2,
  "message": "Shipments processed successfully"
}

Error Response:

{
  "ok": false,
  "error": "Invalid webhook secret"
}

๐Ÿ“Š Project Status

Current Implementation

Feature Status
Real-time Firestore Subscriptions โœ… Complete
Webhook Ingestion โœ… Complete
Risk Analytics Dashboard โœ… Complete
Trend Analysis (Firestore Aggregates) โœ… Complete
Weather API Integration โœ… Complete
News API Integration โœ… Complete
Settings Persistence โœ… Complete
Firebase Authentication โœ… Complete
Multi-carrier Support โœ… Complete
Session Timeout Controls โœ… Complete
Route Intelligence Recommendations โœ… Complete
Request Retry + Timeout Layer โœ… Complete
Frontend Error Boundary โœ… Complete
CI Workflows (Frontend + Backend) โœ… Complete

๐Ÿ› Troubleshooting

Backend Won't Start

Error: Cannot find module 'firebase-admin'

Solution:

cd backend
npm install

Webhook Returns 401 Unauthorized

Error: Invalid webhook secret

Solution:

  • Verify x-webhook-secret header matches WEBHOOK_SECRET in backend/.env
  • Ensure secret is at least 32 characters
  • Check for extra spaces or line breaks in the secret

Firestore Permission Denied

Error: Missing or insufficient permissions

Solution:

  1. Check Firebase security rules
  2. Verify user is authenticated
  3. Ensure service account has Firestore read/write permissions
  4. Deploy the repository rules file: firebase deploy --only firestore:rules

Frontend Can't Connect to Backend

Error: Network Error or CORS error

Solution:

  • Verify backend is running on port 8787
  • Check VITE_BACKEND_URL=http://localhost:8787 in frontend .env
  • Verify ALLOWED_ORIGINS in backend/.env includes http://localhost:5173

Weather/News API Not Working

Error: 401 Unauthorized or 403 Forbidden

Solution:

  • Verify API keys are correct in backend/.env
  • Check API key restrictions in provider dashboards
  • Ensure API usage limits haven't been exceeded
  • Test API keys directly: curl "https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_KEY"

๐Ÿ”ฎ Future Enhancements

  • Machine learning-based risk prediction
  • Advanced route optimization algorithms
  • Mobile app for iOS and Android
  • Email/SMS notification system
  • Custom alert rules engine
  • Multi-language support
  • Shipment cost tracking and analytics
  • Carrier performance benchmarking
  • Export reports to PDF/Excel
  • GraphQL API option
  • Role-based access control (RBAC)
  • Integration with more carrier APIs
  • Geofencing and zone-based alerts
  • Carbon footprint tracking

๐Ÿ”’ Security

Best Practices

  • ๐Ÿ” Never commit credentials โ€” Keep .env files out of version control
  • ๐Ÿ”‘ Service account protection โ€” Ensure backend/service-account.json is gitignored
  • ๐Ÿ”„ Rotate secrets regularly โ€” Update webhook secret every 90 days
  • ๐Ÿ”’ Use HTTPS in production โ€” Always use SSL/TLS certificates
  • ๐Ÿšช Restrict CORS โ€” Limit ALLOWED_ORIGINS to your frontend domain only
  • ๐Ÿ›ก๏ธ Firebase security rules โ€” Implement proper read/write restrictions
  • ๐Ÿ” Environment variables โ€” Use secret management in production (Railway, Render, etc.)
  • ๐Ÿšซ API key restrictions โ€” Restrict keys by domain/IP in provider dashboards

Security Checklist

  • .env and backend/.env are in .gitignore
  • Service account JSON is not committed to repository
  • Webhook secret is strong (48+ characters, generated cryptographically)
  • CORS is restricted to frontend domain in production
  • HTTPS is enabled for production deployment
  • Firebase security rules enforce authentication
  • API keys have domain/IP restrictions configured
  • Rate limiting is enabled on webhook endpoint

๐Ÿ“„ License

This project is licensed under the MIT License.

See LICENSE for full terms.


๐Ÿ‘จโ€๐Ÿ’ป Author

LegendarySumit


๐Ÿšข Revolutionizing Logistics with Real-time Intelligence

Built with React, Node.js, Firebase, and dedication to supply chain excellence


โญ Star this repo if you find it helpful!

Releases

Packages

Contributors

Languages