SYS.ID: THEORIONGD
INNOVATE. BUILD. IMPACT.
BACK TO MASTER CATALOG
SPEC-ID: INTELLICREDIT-RISKENGINEDOM: [APPLIED DATA & DOMAIN INTELLIGENCE]DEPLOYED

IntelliCredit Risk Engine

Multi-Tenant AI Credit Risk Engine with 10 Quantitative Models & SHAP Explainability.

TECHNICAL SPECIFICATION SHEETREVISION: 2025
SYSTEM NAME:IntelliCredit Risk Engine
VERIFIED MATURITY:DEPLOYED
DEPLOYMENT CLASSIFICATION:PRODUCTION (Vercel)
DEVELOPMENT YEAR:2025
DOMAIN CATEGORY:Applied Data & Domain Intelligence
COLLABORATORS:GRISH-SWIZZ | Girijesh26
SYSTEM PERFORMANCE PARAMETERS:
Model Suite:10 Quantitative Risk Calculators
Explainability:SHAP (SHapley Additive exPlanations)
Architecture:Multi-tenant Isolation
TECH STACK:React 18TypeScriptTailwind CSSRechartsMongoDBSHAP Explainability
SYSTEM ARCHITECTURE & TECHNICAL OVERVIEW

ARCHITECTURAL SPECIFICATION

Corporate credit intelligence platform automating underwriting risk scores using 10 quantitative risk models, cash flow velocity math, economic sentiment tracking, and SHAP explainability visualizations via Spotlight navigation.

ORIGINAL REPOSITORY DOCUMENTATION (README)
README DOCUMENT
IntelliCredit Logo

System Status Vercel Deployment TypeScript JavaScript React Node.js Express MongoDB SQLite Firebase Tailwind CSS HTML5 CSS3 Vite Framer Motion Three.js Recharts AI Models Security Git
Girijesh26 TheOrionGD GRISH-SWIZZ


IntelliCredit is an institutional-grade, multi-tenant AI-powered credit risk intelligence platform designed to replace manual credit underwriting workflows with a real-time, explainable, and secure decisioning system.

The platform connects directly to Account Aggregator networks, GSTN filing portals, MCA-21 registries, and public litigation databases. Using ten parallel quantitative machine learning models and SHAP (SHapley Additive exPlanations) feature attributions, IntelliCredit evaluates multi-crore corporate credit proposals in under 1.2 seconds, outputting audit-ready decision memos.


Table of Contents

  1. System Architecture
  2. Multi-Tenant Isolation, Auth & Onboarding Architecture
  3. The 10 Quantitative AI Risk Engines
  4. Autonomous Ingestion & Analysis Pipeline
  5. Role-Based Dashboard Specifications
  6. Spotlight Navigation Interface
  7. REST API Specification
  8. Database Architecture & Indexes
  9. UI/UX Design System & Theme Tokens
  10. Local Development Setup
  11. Production Deployment Guide
  12. Testing & Quality Assurance
  13. Security, Cryptography & Compliance
  14. Scalability & Sharding Design
  15. Developer Story & Journey
  16. Troubleshooting & Support Matrix
  17. Frequently Asked Questions (FAQs)
  18. License & Distribution

System Architecture

The IntelliCredit platform is built on a decoupled, three-tier service architecture optimized for zero-trust data access, high concurrent throughput, and auditable AI execution.

┌────────────────────────────────────────────────────────────────────────┐
│                              CLIENT TIER                               │
│  ┌──────────────────────────────────────────────────────────────────┐  │
│  │                     React 19 SPA (TypeScript)                    │  │
│  │  - Spotlight Command Palette (⌘K)                                │  │
│  │  - Recharts Quantitative Visualizations                          │  │
│  │  - Motion Scroll-Driven Storytelling Component Layout            │  │
│  └─────────────────────────────────┬────────────────────────────────┘  │
└────────────────────────────────────┼───────────────────────────────────┘
                                     │ HTTPS / REST (Port 3466)
                                     │ Headers: x-tenant-id, x-user-role, x-user-uid
┌────────────────────────────────────▼───────────────────────────────────┐
│                             APPLICATION TIER                           │
│  ┌──────────────────────────────────────────────────────────────────┐  │
│  │                   Express.js Orchestration Server                 │  │
│  │  - Session Validation & Dynamic Header Injection Checks           │  │
│  │  - MongoDB Database Connection Pool Routing                      │  │
│  │  - Firebase Authentication Middleware Gateways                   │  │
│  └─────────────────────────────────┬────────────────────────────────┘  │
│                                    │
│       ┌────────────────────────────┴──────────────────────────┐
│       ▼                                                       ▼
│  ┌──────────────────────────────┐                       ┌───────────┐
│  │     10 Parallel AI Engines   │                       │ Groq/LLaMA│
│  │  - Cash Flow Analyzer        │                       │ System    │
│  │  - Graph Fraud Detection     │                       │ - Prompt  │
│  │  - GSTR-3B Tax Cross-Match   │                       │   Context │
│  │  - promoter CIBIL sweeps     │                       │ - XAI     │
│  └──────────────────────────────┘                       └───────────┘
└────────────────────────────────────────────────────────────────────────┘
                                     │
┌────────────────────────────────────▼───────────────────────────────────┐
│                                DATA TIER                               │
│  ┌──────────────────────────────┐                       ┌───────────┐
│  │        MongoDB Cluster       │                       │ Firebase  │
│  │  - Isolated Tenant Shards    │                       │ Identity  │
│  │  - Audit Log Ledger          │                       │ Provider  │
│  └──────────────────────────────┘                       └───────────┘
└────────────────────────────────────────────────────────────────────────┘

Ingestion Data Flow

The platform processes multiple financial and operational document formats through an asynchronous, secure ingestion pathway:

  1. Ingestion Trigger: A user submits files (PDF, XLSX) via the drag-and-drop file intake dashboard interface.
  2. Dynamic Header Injection: The client framework intercepts the fetch call, appending the user's cryptographically confirmed x-tenant-id, x-user-role, and x-user-uid headers.
  3. Parsing Tier: The server ingests the files, extracting raw table structures, transaction ledgers, and registry fields.
  4. AI Synthesis (Groq Pipeline): The parsed text is contextualized against prompt schemas and dispatched to the Groq/LLaMA inference system.
  5. Collection Storage: Resulting metrics, SHAP weights, comparative indices, and generated credit memos are written to MongoDB inside collections filtered by tenantId.
  6. Audit Ledger Logging: The transaction is permanently logged in the audit trail database collection.

Multi-Tenant Isolation, Auth & Onboarding Architecture

This section describes the database isolation models, credentials synchronization, and user provisioning flow.

A. Multi-Tenant Data Isolation Model

Data privacy is enforced at the database query level. To prevent cross-tenant data leakage, the platform utilizes a shared-database, isolated-collection schema pattern with absolute partition scoping.

Authentication Header Scoping

Every request to the backend server must carry valid authorization credentials alongside structural routing headers:

  • x-tenant-id: The unique identifier representing the client institution (e.g., tenant-ssr-industries).
  • x-user-role: The user's system role (super_admin | tenant_admin | underwriter | credit_officer).
  • x-user-uid: The verified Firebase authentication UID matching the user's active session.

Database Query Interception

Backend database queries pass through the getTenantQuery decorator to filter documents automatically by the requesting user's tenant scope:

LANG: typescript
function getTenantQuery(req: any, baseQuery: any = {}) {
  const tenantId = req.headers['x-tenant-id'];
  const userRole = req.headers['x-user-role'];
  
  // Super Admin bypasses tenant isolation to view global metrics
  if (userRole === 'super_admin') {
    return baseQuery;
  }
  
  // All other roles are strictly constrained to their tenant partition
  return { ...baseQuery, tenantId: tenantId || 'tenant-acme-fincorp' };
}

This partition design guarantees that users belonging to tenant-ssr-industries can never request, list, modify, or analyze records belonging to tenant-swiztek, even if they attempt direct API endpoint manipulation.


B. Firebase Auth & MongoDB Integration Architecture

The synchronization flow decouples authentication credentials from organizational profile metadata:

┌──────────────────────────────────────┐        ┌──────────────────────────────────────┐
│        FIREBASE AUTHENTICATION       │        │          MONGODB DATA STORE          │
├──────────────────────────────────────┤        ├──────────────────────────────────────┤
│  - Hashed Passwords & Sign-In Rails  │        │  - Custom Tenant Identifiers         │
│  - Google OAuth Handshakes           │  Sync  │  - Assigned System Roles             │
│  - Phone OTP SMS verification        ├───────►│  - User Metadata & Profiles          │
│  - Session Token Signing & Refresh   │  (UID) │  - Credit Applications & Portfolios  │
│  - JWT Verification Gateway          │        │  - Immutable Audit Logs              │
└──────────────────────────────────────┘        └──────────────────────────────────────┘

1. Dynamic Registration Flow

When a new user registers on the portal, the synchronization is handled asynchronously via a client-side listener and a backend synchronization gateway:

[ User Register Form ]
         │
         ├── 1. Store Pending Role & Tenant ID in memory (window._pendingRole / window._pendingTenantId)
         ▼
[ Firebase Client SDK ]
         │
         ├── 2. Create User Account (createUserWithEmailAndPassword)
         ▼
[ onAuthStateChanged Listener ] (AuthContext.tsx)
         │
         ├── 3. Firebase Auth succeeds and returns user credential profile
         ▼
[ POST /api/users/sync ] (Express API endpoint)
         │
         ├── 4. Extracts Firebase UID, Email, and memory-stored Role/Tenant parameters
         ▼
[ MongoDB users Collection ]
         └── 5. Saves user metadata linked to the unique Firebase UID (Single Source of Truth)
  1. Capture Metadata: The registration form saves the selected role (e.g., tenant_admin or underwriter) and target organization (e.g., tenant-ssr-industries) into memory parameters window._pendingRole and window._pendingTenantId.
  2. Firebase Creation: The client calls Firebase Client SDK createUserWithEmailAndPassword to register the credentials.
  3. State Observer: Firebase triggers the observer hook onAuthStateChanged(auth, callback).
  4. Sync Dispatch: If a user is logged in, the callback intercepts the session, gathers properties (uid, email, displayName), appends the memory-stored metadata, and dispatches them to /api/users/sync.
  5. MongoDB Ingestion: The Express server checks if the UID exists in MongoDB. If not, it saves the new document in the users collection.

2. Session & Cross-Device Sign-In Flow

When an existing user signs in from a new device or opens a new browser window, the synchronization handles the session creation without duplications:

[ New Device / New Session Login ]
         │
         ▼
[ Firebase Client SDK ]
         │
         ├── 1. Authenticate credentials (via Email/Password, Google, or OTP)
         ▼
[ onAuthStateChanged Listener ]
         │
         ├── 2. Extracts authenticated user's Firebase UID
         ▼
[ POST /api/users/sync ]
         │
         ├── 3. Checks MongoDB: users.findOne({ uid: FirebaseUID })
         │      - Profile is retrieved from database (role, tenantId matching SSR Industries)
         │      - Server updates only "lastLogin" timestamp
         ▼
[ Client Session Storage ]
         └── 4. Injects headers x-tenant-id and x-user-role into session memory
  1. Credentials Validation: The user enters credentials on the new device. Firebase verifies the account and issues a temporary JWT session token.
  2. Authentication State Activation: The client-side observer onAuthStateChanged catches the state update, extracting the user's uid.
  3. Database Check: The client dispatches the profile details to /api/users/sync. The backend queries the MongoDB collection:
    LANG: typescript
    const existingUser = await collection.findOne({ uid: firebaseUid });
    
  4. Update Session Context: The server updates the lastLogin timestamp and returns the profile details containing the role and tenantId registered on the previous device.
  5. Enforce Isolation: The client receives the data, updates sessionStorage (setting tenantId, role, and uid), and directs the user to their customized workspace layout.

3. Secure Session Terminations (Logout)

When the user logs out, session state is cleared to ensure zero-trust access:

[ User Clicks Sign Out ]
         │
         ▼
[ Firebase Client SDK ]
         │
         ├── 1. Terminate Firebase session (signOut(auth))
         ▼
[ onAuthStateChanged Observer ]
         │
         ├── 2. Callback receives null user state
         ▼
[ Client-Side Session Flush ]
         └── 3. Clears context state and removes sessionStorage keys (tenantId, role, uid)

C. Tenant & User Onboarding Flow Architecture

The onboarding flow describes the step-by-step sequence of onboarding new tenants and users:

Onboarding Sequence Flow

  1. Firebase Account Creation: Generates the authentication node (REST Sign-Up or manual Firebase console addition).
  2. Database Profile Binding: POST call to /api/users/sync syncs the Firebase UID with the MongoDB users collection to store RBAC roles and tenant bindings.

Firebase Sign-Up REST Endpoint Request:

LANG: http
POST https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=VITE_FIREBASE_API_KEY
Content-Type: application/json

{
  "email": "manager@ssrindustries.com",
  "password": "SSRAdminPass2026",
  "returnSecureToken": true
}

Response Payload:

LANG: json
{
  "localId": "iYgZyrRlkMRDhY2c0jiOXQIvAgE3",
  "email": "manager@ssrindustries.com",
  "idToken": "eyJhbGciOi...",
  "refreshToken": "AMf-vJy...",
  "expiresIn": "3600"
}

D. Tenant & User Provisioning Specification

Predefined tenant and testing credentials details:

1. Architectural Entities

  • Platform Operator (Swiztek): Database Tenant ID tenant-swiztek, super admin console.
  • Client Tenant (SSR Industries): Database Tenant ID tenant-ssr-industries, commercial credit operations.

2. Predefined Users & Credentials

The following default users are provisioned in both Firebase Auth and MongoDB:

EmailPasswordDisplay NameRoleTenant ID
admin@swiztek.comSwiztekPass2026Grishsuper_admintenant-swiztek
manager@ssrindustries.comSSRAdminPass2026Godfreytenant_admintenant-ssr-industries
underwriter@ssrindustries.comSSRUwPass2026Girijeshunderwritertenant-ssr-industries
officer@ssrindustries.comSSRCoPass2026TheOrionGDcredit_officertenant-ssr-industries

The 10 Quantitative AI Risk Engines

IntelliCredit executes ten specialized machine learning models and analytical routines in parallel on every application proposal. Rather than producing a single credit score, the platform provides multidimensional audit traces.

1. Cash Flow & Liquidity Engine

  • Methodology: Time-series volatility modeling on daily ledger balances.
  • Data Sources: Current account and Cash Credit (CC) bank statements.
  • Metric Formula: $$\text{Volatility Score} = \sqrt{\frac{1}{N}\sum_{i=1}^{N}(x_i - \bar{x})^2}$$
  • Thresholds: A daily closing balance drop below 10% of monthly average for $>3$ consecutive business days triggers a low-liquidity warning flag.

2. Circular Trading & Fraud Radar

  • Methodology: Graph Neural Networks (GNN) for circular transaction loop analysis.
  • Data Sources: GST return sales and purchase invoice matrices.
  • Analysis: Detects self-dealing loops where Entity A sells to Entity B, who sells to Entity C, who sells back to Entity A to artificially inflate revenue.
  • Thresholds: Loop path length $\le 4$ with matching invoice values within a 7-day window triggers an automatic critical warning in the dashboard.

3. Tax & Statutory Compliance Check

  • Methodology: Automated mismatch analysis between GST returns.
  • Data Sources: Direct GSTR-1, GSTR-2A, and GSTR-3B filings.
  • Analysis: Matches claimed input tax credit against actual supplier declarations.
  • Thresholds: Input Tax Credit (ITC) discrepancies exceeding 5% or unclaimed returns over 2 quarters trigger a high-risk rating.

4. Collateral & LTV Valuation Matrix

  • Methodology: Dynamic collateral value haircut simulation.
  • Data Sources: Registered valuer reports, land registration indexes, inventory audits.
  • Metric Formula: $$\text{Adjusted Value} = \text{Market Value} \times (1 - \text{Haircut Coefficient})$$
  • Thresholds: Haircut adjusts dynamically between 15% (liquid cash equivalents) and 45% (specialized industrial real estate) based on market volatility indices.

5. Management & Promoters Audit

  • Methodology: Directorship network analysis and litigation sweeps.
  • Data Sources: MCA-21 company registry, e-Courts, CIBIL consumer credit records.
  • Analysis: Identifies cross-directorships linked to defaulted, bankrupt, or high-litigation entities.
  • Thresholds: If any promoter is linked to an entity with an active NCLT insolvency case, the promoter index drops to zero.

6. Risk-Adjusted Pricing Calculator

  • Methodology: RAROC (Risk-Adjusted Return on Capital) modeling.
  • Data Sources: Probability of Default (PD), Loss Given Default (LGD), internal fund transfer pricing index.
  • Metric Formula: $$\text{RAROC} = \frac{\text{Revenues} - \text{Expenses} - \text{Expected Loss}}{\text{Economic Capital}}$$
  • Thresholds: The system dynamically outputs the recommended pricing spread required to achieve the target RAROC threshold.

7. Digital Twin Stress Tester

  • Methodology: Monte Carlo simulations ($10,000+$ iterations).
  • Data Sources: Operational expense models, loan repayment schedules.
  • Analysis: Projects cash reserve runway under severe macroeconomic events, including interest rate surges and supply shocks.
  • Thresholds: Simulates cash reserve depletion timeline; a runway $<90$ days under stress triggers a negative recommendation.

8. GST Time Series Oracle

  • Methodology: LSTM (Long Short-Term Memory) recursive neural networks.
  • Data Sources: 36-month invoice trends.
  • Analysis: Forecasts monthly sales and purchase volumes for the upcoming 6 months, identifying seasonal contractions.
  • Thresholds: Projected revenue drop of $\ge 20%$ within the upcoming quarter triggers an automated warning insight.

9. Network Contagion Scoring

  • Methodology: Supplier-buyer network dependency modeling.
  • Data Sources: GSTR-1 sales distribution reports.
  • Analysis: Calculates concentration risk. If a borrower relies on a single customer for $>40%$ of revenue, the buyer's credit score is incorporated into the model.
  • Thresholds: High buyer concentration combined with declining buyer credit rating triggers a cascading risk warning.

10. UPI Cash Velocity Engine

  • Methodology: Flow rate volatility mapping.
  • Data Sources: Payment gateway settlements, UPI ledger logs.
  • Analysis: Tracks daily cash conversion cycles and transaction frequencies to monitor consumer-facing liquidity.
  • Thresholds: Sudden transaction frequency drops of $>50%$ over a rolling 48-hour window trigger liquidity alerts.

Autonomous Ingestion & Analysis Pipeline

The IntelliCredit ingestion pipeline processes raw files into credit metrics via a continuous, stateful workflow:

                  ┌──────────────────────┐
                  │   Drag & Drop File   │
                  │     Ingestion        │
                  └──────────┬───────────┘
                             │
                             ▼
                  ┌──────────────────────┐
                  │    PDF/XLSX Parsing  │
                  │   & Text Extraction  │
                  └──────────┬───────────┘
                             │
                             ▼
                  ┌──────────────────────┐
                  │    Groq AI Pipeline  │
                  │  (Prompt Context ML) │
                  └──────────┬───────────┘
                             │
                             ▼
                  ┌──────────────────────┐
                  │  MongoDB Collection  │
                  │      Storage         │
                  └──────────┬───────────┘
                             │
                             ▼
                  ┌──────────────────────┐
                  │  Audit Trail Logging │
                  │  & User Notification │
                  └──────────────────────┘
  1. Upload: Files are loaded using drop-zone components, validated for size, and converted to clean streams.
  2. Extraction: Financial statements are read, parsing tables, transactional lines, and metadata.
  3. AI Inference: The system matches data to credit schemas, extracting metrics, risk indicators, and ledger events.
  4. Serialization: Structured output is written to MongoDB collections partitioned by tenantId.
  5. Auditing: Ingestion, validation, and analysis steps are logged to the audit ledger for institutional compliance.

Role-Based Dashboard Specifications

IntelliCredit provides customized workspaces tailored to each user's organizational role, ensuring appropriate access controls and workflow focus.

1. Platform Super Admin Dashboard (/dashboard/super-admin)

The system dashboard for the platform operator:

  • Metric Overview: Tracks active tenant instances, database storage usage, global API latency, and uptime indices.
  • Tenant Console: Provision new tenant environments, update storage allocations, configure base risk parameters, and revoke system access.
  • Platform Security Logs: View the global system audit log with filtering for tenant IDs, user roles, and action types.

2. Tenant Admin Dashboard (/dashboard/tenant-admin)

The control panel for the tenant's system administrator:

  • Tenant KPIs: Monitors total applications, approvals, active risk exposure, and average decision turnaround times.
  • Workspace Settings: Configure user permissions, manage team access, and review the tenant audit trail.
  • Integration Feeds: Monitor data connectors, API endpoints, and credential status.

3. Underwriter Dashboard (/dashboard/underwriter)

The active decision workspace for underwriters:

  • Decision Queue: View applications awaiting credit sign-off.
  • workbench Tools: Direct access to the Risk Explorer, AI Module Monitor, and Credit Memo workbench.
  • Queue Filtering: Filter applications by loan value, risk rating, industry, and submission date.

4. Credit Officer Dashboard (/dashboard/loan-portfolio)

The intake and tracking dashboard for credit officers:

  • Portfolio Board: View the status of active proposals, draft submissions, and completed evaluations.
  • Document Intake: Access the document ingestion interface to trigger the AI analysis pipeline.
  • Status Tracking: Real-time progress updates as proposals move through the ingestion and scoring stages.

Spotlight Navigation Interface

IntelliCredit uses an overlay navigation paradigm: Spotlight Navigation. Traditional UI components like navigation bars and sidebars are excluded.

                  ┌─────────────────────────────────────┐
                  │     Ctrl+K / Cmd+K / / Trigger      │
                  └──────────────────┬──────────────────┘
                                     │
                                     ▼
                  ┌─────────────────────────────────────┐
                  │       Spotlight Search Overlay      │
                  │  - Views Navigation                 │
                  │  - Active Loan Proposals            │
                  │  - Quick Actions (Sign Out)         │
                  └──────────────────┬──────────────────┘
                                     │ Selects Action
                                     ▼
                  ┌─────────────────────────────────────┐
                  │       Client-Side Routing /         │
                  │          Action Dispatch            │
                  └─────────────────────────────────────┘

Navigation Hotkeys

  • ⌘ K or Ctrl K: Opens the Spotlight search overlay.
  • / (Forward Slash): Opens Spotlight (when form fields are not active).
  • Esc (Escape): Closes the overlay interface.

Floating Trigger Pill

A minimal floating pill is positioned at the bottom-right corner of the interface:

  • Clicking the search badge opens the Spotlight command overlay.
  • Clicking the user profile avatar displays a context menu containing workspace options and the logout control.

REST API Specification

All endpoints are hosted on port 3466 (configurable). Requests must include authentication headers:

LANG: http
x-tenant-id: tenant-acme-fincorp
x-user-role: credit_officer
x-user-uid: firebase_user_uid
Content-Type: application/json

1. Retrieve Applications

Returns credit proposals scoped to the user's tenant partition.

  • URL: /api/applications
  • Method: GET
  • Headers Required: x-tenant-id, x-user-role, x-user-uid
  • Success Response (200 OK):
LANG: json
{
  "success": true,
  "data": [
    {
      "id": "1719823746281",
      "tenantId": "tenant-acme-fincorp",
      "companyName": "Nirma Logistics Pvt Ltd",
      "industry": "Transportation",
      "amount": 45000000,
      "status": "ready",
      "riskScore": 84,
      "defaultProbability": 3.2,
      "confidenceLevel": 96
    }
  ]
}

2. Submit Credit Proposal

Creates a new loan application draft.

  • URL: /api/applications
  • Method: POST
  • Request Payload:
LANG: json
{
  "companyName": "Apollo Steel Structures",
  "industry": "Manufacturing",
  "location": "Chennai, Tamil Nadu",
  "amount": 85000000
}
  • Success Response (200 OK):
LANG: json
{
  "success": true,
  "data": {
    "id": "1719823901847",
    "tenantId": "tenant-acme-fincorp",
    "companyName": "Apollo Steel Structures",
    "industry": "Manufacturing",
    "amount": 85000000,
    "status": "draft",
    "riskScore": 0,
    "lastUpdated": "Just now"
  }
}

3. Trigger AI Analysis

Starts parsing and scoring for an application.

  • URL: /api/applications/:id/analyze
  • Method: POST
  • Request Payload:
LANG: json
{
  "files": [
    { "name": "GST_Returns_FY26.pdf", "size": 4192384 },
    { "name": "Bank_Statements_Current_12M.xlsx", "size": 1827402 }
  ]
}
  • Success Response (200 OK):
LANG: json
{
  "success": true,
  "message": "Analysis completed successfully!"
}

4. Submit Underwriting Decision

Records final approval or rejection with pricing parameters.

  • URL: /api/applications/:id/decision
  • Method: POST
  • Request Payload:
LANG: json
{
  "decision": "approve",
  "decisionNotes": "Strong debt service coverage and cash conversion cycle verify repayment capacity.",
  "suggestedConditions": [
    "Escrow account setup for monthly revenue capture",
    "Quarterly submission of certified inventory statements"
  ],
  "interestRate": 9.25,
  "tenure": 24,
  "processingFee": 425000
}
  • Success Response (200 OK):
LANG: json
{
  "success": true,
  "message": "Decision stored successfully!"
}

Database Architecture & Indexes

IntelliCredit uses MongoDB for system state and transaction logging. Collections are partitioned using tenant keys to ensure data isolation.

Collection Schema Definitions

1. users Collection

Stores user profiles, access credentials, and role assignments:

LANG: json
{
  "_id": "ObjectId",
  "uid": "String (Firebase UID)",
  "email": "String",
  "displayName": "String",
  "photoURL": "String",
  "phoneNumber": "String",
  "role": "String (super_admin | tenant_admin | underwriter | credit_officer)",
  "tenantId": "String",
  "lastLogin": "ISODate",
  "createdAt": "ISODate"
}

2. applications Collection

Contains financial evaluations, AI recommendations, and credit metrics:

LANG: json
{
  "_id": "ObjectId",
  "id": "String (Unique ID)",
  "tenantId": "String",
  "companyName": "String",
  "industry": "String",
  "location": "String",
  "amount": "Number",
  "status": "String (draft | analyzing | ready | approved | rejected)",
  "riskScore": "Number",
  "defaultProbability": "Number",
  "confidenceLevel": "Number",
  "aiRecommendationTitle": "String",
  "aiRecommendationNotes": "String",
  "riskIndicators": "Array",
  "insights": "Array",
  "comparisonData": "Array",
  "revenueData": "Array",
  "cashFlowData": "Array",
  "sentimentData": "Array",
  "timelineEvents": "Array",
  "suggestedConditions": "Array",
  "creditMemo": "String",
  "decision": "String (approve | reject | null)",
  "decisionNotes": "String",
  "interestRate": "Number",
  "tenure": "Number",
  "processingFee": "Number",
  "uploadedFiles": "Array",
  "createdAt": "ISODate"
}

3. audit_logs Collection

The auditable ledger tracking all modifications, user actions, and decisions:

LANG: json
{
  "_id": "ObjectId",
  "tenantId": "String",
  "timestamp": "ISODate",
  "type": "String",
  "user": "String",
  "details": "String"
}

Index Optimization Plan

To maintain sub-millisecond query execution as portfolio histories scale, database indexes are built on the primary query paths:

LANG: javascript
// Compound index for tenant-isolated application querying
db.applications.createIndex({ "tenantId": 1, "id": 1 }, { unique: true });

// Status query index
db.applications.createIndex({ "tenantId": 1, "status": 1 });

// User authentication sync index
db.users.createIndex({ "uid": 1 }, { unique: true });

// Time-series sorting index for audit log queries
db.audit_logs.createIndex({ "tenantId": 1, "timestamp": -1 });

UI/UX Design System & Theme Tokens

IntelliCredit uses a custom color palette tailored for financial risk interfaces. The styling uses a calm beige background offset by deep forest green structural elements and moss green active indicators.

Tailwind Color Customization

The color tokens are configured in the styling configuration:

LANG: css
@theme {
  --color-sage-bg: #E5E9DE;
  --color-forest-text: #1C2B1A;
  --color-moss-accent: #869E2F;
  --color-olive-detail: #5F6F50;
  
  --font-sans: 'Inter', system-ui, sans-serif;
  --font-mono: 'JetBrains Mono', monospace;
}

Component Design Specifications

  • Page Layout: Clean canvas view. Pages do not use traditional header banners, sidebar panels, or persistent navigation trays.
  • Dashboard Cards: Rendered on white backgrounds (bg-white/80) with fine borders (border-forest-text/10) and subtle glassmorphic backdrop filters.
  • Risk Score Visualization: Radial meters transition smoothly from red (high risk, score $<40$) to moss green (low risk, score $>75$) using Recharts.

Local Development Setup

Follow these steps to run the application tier and client tier locally:

1. Clone the Repository

LANG: bash
git clone https://github.com/TheOrionGD/IntelliCredit-RiskEngine.git
cd IntelliCredit-RiskEngine

2. Install Project Dependencies

LANG: bash
npm install

3. Configure the Environment

Create a .env file at the root of the project:

4. Run the Dev Environment

Run both the Express server and Vite development server using a single script:

LANG: bash
npm run dev
  • The Express server initializes on port 3466.
  • The Vite frontend client starts on port 3000.
  • The client proxy automatically routes all /api requests to the backend server.

Production Deployment Guide

Use these steps to prepare the application for production deployment.

1. Build the Production Client Assets

LANG: bash
npm run build

This builds static assets into the /dist directory. The Express server serves these files statically in production environments.

2. Configure a Process Manager (PM2)

To run the server in the background and ensure automatic restarts, use PM2:

Create a ecosystem.config.js file:

LANG: javascript
module.exports = {
  apps: [{
    name: 'intellicredit-api',
    script: './server.ts',
    interpreter: 'npx',
    interpreter_args: 'tsx',
    env: {
      NODE_ENV: 'production',
      PORT: 3466
    }
  }]
};

Start the service:

LANG: bash
pm2 start ecosystem.config.js
pm2 save
pm2 startup

3. Reverse Proxy Configuration (Nginx)

Configure Nginx as a reverse proxy to manage SSL termination and handle client requests:

LANG: nginx
server {
    listen 80;
    server_name risk-engine.yourbank.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name risk-engine.yourbank.com;

    ssl_certificate /etc/letsencrypt/live/risk-engine.yourbank.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/risk-engine.yourbank.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3466;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Testing & Quality Assurance

The system uses a testing framework to verify both data isolation models and the accuracy of the risk engines.

Running TypeScript Validations

Run the compiler check to verify type safety across modified application pages:

LANG: bash
npm run lint

Automated API Endpoint Testing

Integration tests evaluate access controls and isolation partitions:

LANG: bash
# Example script to verify tenant separation
npm run test:security
  • Test Case 1: Authenticate as Tenant A; attempt to request /api/applications/:id belonging to Tenant B. Verify server rejects with 404 Not Found or 403 Forbidden.
  • Test Case 2: Verify that requests missing the x-tenant-id header default to the base demo sandbox partition (tenant-acme-fincorp) and cannot access custom tenant pools.
  • Test Case 3: Attempt access to /api/tenants as an underwriter. Verify access is blocked with a 403 Forbidden response.

Verification with SSR Industries Test Dataset

To facilitate local testing and verification of all 10 parallel risk engines under different conditions for the same tenant, a custom dataset has been compiled: ssr_industries_sample.csv.

Dataset Specifications

  • Target Company: SSR Industries (all 200 rows)
  • Industry Segment: Manufacturing
  • Locations Map: Mumbai (HO), Thane Plant, Pune Facility, Nashik Warehouse, and Nagpur Unit.
  • Dimensions: 200 columns x 200 rows of risk data snapshots.
  • Quarters Covered: 12 quarters (Q1 2023 - Q4 2025) of financial statements, statutory tax filings (GSTR-3B and GSTR-2A), and payment velocity histories.

Simulated Risk Scenarios for Testing

The dataset contains 25 applications for each of the following 8 risk configurations to test the response of the 10 quantitative risk models:

  1. Baseline Low Risk: High CIBIL scores (750-850), low default probability (1.5% - 3.5%), and clean statutory filings.
  2. High Leverage Risk: High debt-to-equity ratios (>1.5) to test the Cash Flow and Debt Service Coverage engines.
  3. Circular Trading Mismatch: Activates loop path detection warnings (loop path = 1) to test the Graph Fraud Neural Network.
  4. Statutory GST Mismatch: Induces wide discrepancies between sales and purchases reporting (GSTR-3B vs 2A up to 18%) to test statutory verification.
  5. Promoter & Legal Risk: Simulates active litigation counts (up to 3 cases) and low promoter CIBIL ratings (550-640).
  6. Liquidity Stress Runway: Triggers low cash runway alerts (30-85 days) to validate the Digital Twin stress tester.
  7. UPI Velocity Anomaly: Generates high payment gateway velocity deviations (15% - 35%) to trigger volatility flags.
  8. Buyer Concentration Risk: Simulates high customer revenue concentration (>45%) to test supplier-buyer network contagion scoring.

Security, Cryptography & Compliance

1. Data Encryption Standards

  • Data in Transit: All traffic is encrypted using TLS 1.3.
  • Data at Rest: MongoDB Atlas storage volumes are encrypted using AES-256.
  • Secure Tokens: Firebase ID tokens are validated on every API call.

2. Multi-Tenant Cryptographic Separation

While database records are stored in a shared collection to optimize index performance, separation is enforced at the query level by appending user tenant IDs to every MongoDB filter statement. Database credentials are encrypted and stored in environment configuration files.

3. Compliance Frameworks

  • RBI Digital Lending Guidelines: Provides audit trail logs for every automated decision, including the specific prompt inputs and outputs.
  • SOC2 Security Auditing: Maintains logging for security audits, showing when tenant parameters were updated or user credentials modified.

Scalability & Sharding Design

As the active user base and historical portfolios scale, the platform architecture supports horizontal database growth:

                                  ┌─────────────────────┐
                                  │   Application Tier  │
                                  └──────────┬──────────┘
                                             │ x-tenant-id Routing
                                             ▼
                                  ┌─────────────────────┐
                                  │  MongoDB Router     │
                                  │     (mongos)        │
                                  └──────────┬──────────┘
                                             │
                       ┌─────────────────────┼─────────────────────┐
                       ▼                     ▼                     ▼
            ┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐
            │   Shard A (Zone 1)  │ │   Shard B (Zone 2)  │ │   Shard C (Zone 3)  │
            │  tenant-acme-*      │ │  tenant-vanguard-*  │ │  tenant-global-*    │
            └─────────────────────┘ └─────────────────────┘ └─────────────────────┘
  • Shard Key Selection: The tenantId field is used as the database shard key.
  • Query Routing: The query router handles request routing, directing database queries directly to the target tenant's database shard.
  • Parallel AI Computation: The 10 machine learning models execute concurrently, using worker threads on the application tier to prevent bottlenecks.

Developer Story & Journey

Why We Built It

Corporate credit analysis is often slow and manual. Analysts frequently spend weeks pulling together data from bank statements, GST filings, and legal records. IntelliCredit was built to automate this data aggregation and risk scoring, providing explainable metrics in real time.

Who We Are

IntelliCredit is developed by Team Swizztek, a group of computer science engineers focused on building intelligent financial systems:

  • Girijesh R — AI/ML Engineering
    Girijesh26
  • Godfrey T R — Full-Stack Architecture
    TheOrionGD
  • Grish Narayanan S — Systems & Data Engineering
    GRISH-SWIZZ

Challenges Faced

  • Real-time Pipeline Synchronization: Managing the response times of multiple data sources while processing the 10 analysis models concurrently.
  • Multi-Tenant Data Security: Ensuring isolation so that client data remains protected within its assigned partition.
  • Spotlight UX Design: Designing a keyboard-first navigation system that maintains ease of use without traditional sidebar menus.

Key Learnings

  • Compound MongoDB indexing using tenantId is critical for fast query execution as collection sizes grow.
  • Splitting AI prompts into separate, targeted queries produces more reliable results than using a single model for the entire analysis.

Future Roadmap

  • Support for uploading other document formats, including native bank formats and unstructured text.
  • Adding a visual builder for risk parameters, allowing institutions to adjust model weights directly.
  • Direct integration with major Core Banking Systems (CBS) via secure APIs.

Developer Message

We built IntelliCredit to modernize institutional credit analysis. By automating repetitive tasks, analysts can focus their time on evaluating risk and structuring complex proposals.


Troubleshooting & Support Matrix

Use this matrix to identify and resolve common issues:

IssueRoot CauseSolution
MongoDB connection failedMongoDB service is not running or the connection string is incorrect.Verify the local service is active or check the MONGODB_URI string in the .env file.
Firebase auth errorsThe credentials in the .env file do not match your Firebase project settings.Double check client config values (VITE_FIREBASE_API_KEY, etc.) in the .env file.
API returns 403 ForbiddenThe user's role is not authorized for the requested route.Check that the x-user-role header is populated and matches target role permissions.
Groq pipeline fallbackThe GROQ_API_KEY is missing or invalid.The system defaults to offline fallback report mode. Generate a valid API key and save it to the .env file.

Frequently Asked Questions (FAQs)

How is data isolation maintained between tenants?

Every database query is automatically filtered by the tenant ID header (x-tenant-id) sent by the client. This database configuration ensures users can only read and write data belonging to their institution.

Can we configure the weights of the 10 risk engines?

Yes. Tenant administrators can customize weight thresholds and parameter values inside their dashboard panel to align the models with their credit policy requirements.

What happens if the AI models cannot parse a document?

The system flags parsing errors on the dashboard timeline, allowing credit officers to review the document and re-upload if needed.

Is the platform compliant with current banking guidelines?

Yes. The platform provides a full audit trail for every analysis, saving the original data inputs alongside the resulting SHAP explanation weights.


License & Distribution

This project is released under the MIT License. It is developed for research, innovation, and product demonstration purposes.

Copyright (c) 2026 Team Swizztek

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

IntelliCredit Risk Engine — Tenant & User Provisioning Specification

This document details the configuration specification for establishing the multi-tenant architecture on IntelliCredit Risk Engine developed by team Swiztek.

It outlines the predefined identities, user accounts, database schemas, and Firebase configurations required to model the system provider context (Swiztek) and the client tenant context (SSR Industries).


1. Architectural Entities

A. The System Provider: Swiztek

  • Context: Overall product developer, vendor, and platform administrator.
  • Database Tenant ID: tenant-swiztek (Reserved for platform orchestration)
  • Predefined Roles: super_admin

B. The Client Tenant: SSR Industries

  • Context: The financial institution requesting credit intelligence services for their commercial lending operations.
  • Database Tenant ID: tenant-ssr-industries
  • Predefined Roles: tenant_admin, underwriter, credit_officer

2. User Roles & Capabilities

System RoleScopeHome DashboardOperations
super_adminPlatform-wide/dashboard/super-adminProvision new client bank partitions, manage fleet state, monitor global SLA metrics.
tenant_adminSingle Tenant (tenant-ssr-industries)/dashboard/tenant-adminConfigure tenant settings, manage user roster, inspect data connectors, view portfolio KPIs.
underwriterSingle Tenant (tenant-ssr-industries)/dashboard/underwriterView decision queue, review explainable AI (SHAP) attributions, submit final credit decisions.
credit_officerSingle Tenant (tenant-ssr-industries)/dashboard/loan-portfolioInitiate document uploads, trigger AI analysis pipeline, review portfolio applications.

3. Database Seeding Specifications (MongoDB)

To initialize the MongoDB database, populate the tenants and users collections with the following JSON documents.

A. tenants Collection Seeding

LANG: json
[
  {
    "id": "tenant-swiztek",
    "name": "Swiztek",
    "contactEmail": "ops@swiztek.com",
    "volume": "Platform Operator",
    "policy": "Global Risk Policy Orchestration",
    "status": "active",
    "createdAt": { "$date": "2026-07-12T00:00:00Z" }
  },
  {
    "id": "tenant-ssr-industries",
    "name": "SSR Industries",
    "contactEmail": "admin@ssrindustries.com",
    "volume": "100 - 500 applications/month",
    "policy": "Commercial & SME Lending",
    "status": "active",
    "createdAt": { "$date": "2026-07-12T00:00:00Z" }
  }
]

B. users Collection Seeding

LANG: json
[
  {
    "uid": "usr_super_admin_swiztek_01",
    "email": "admin@swiztek.com",
    "password": "SwiztekPass2026",
    "displayName": "Grish",
    "role": "super_admin",
    "tenantId": "tenant-swiztek",
    "createdAt": { "$date": "2026-07-12T00:00:00Z" }
  },
  {
    "uid": "usr_tenant_admin_ssr_01",
    "email": "manager@ssrindustries.com",
    "password": "SSRAdminPass2026",
    "displayName": "Godfrey",
    "role": "tenant_admin",
    "tenantId": "tenant-ssr-industries",
    "createdAt": { "$date": "2026-07-12T00:00:00Z" }
  },
  {
    "uid": "usr_underwriter_ssr_01",
    "email": "underwriter@ssrindustries.com",
    "password": "SSRUwPass2026",
    "displayName": "Girijesh",
    "role": "underwriter",
    "tenantId": "tenant-ssr-industries",
    "createdAt": { "$date": "2026-07-12T00:00:00Z" }
  },
  {
    "uid": "usr_credit_officer_ssr_01",
    "email": "officer@ssrindustries.com",
    "password": "SSRCoPass2026",
    "displayName": "TheOrionGD",
    "role": "credit_officer",
    "tenantId": "tenant-ssr-industries",
    "createdAt": { "$date": "2026-07-12T00:00:00Z" }
  }
]

4. Firebase Authentication Setup

To configure these credentials in your Firebase Auth instance:

A. Manual Console Provisioning

  1. Navigate to the Firebase Console -> Build -> Authentication -> Users.
  2. Click Add User and register the following default testing credentials:
EmailPasswordDisplay Name (Setup after registration)Target Role Mapping
admin@swiztek.comSwiztekPass2026GrishSuper Admin
manager@ssrindustries.comSSRAdminPass2026GodfreyTenant Admin
underwriter@ssrindustries.comSSRUwPass2026GirijeshUnderwriter
officer@ssrindustries.comSSRCoPass2026TheOrionGDCredit Officer

B. Automated Profile Synchronization Flow

When a user signs in through the /login portal, the frontend parses their authentication token and dispatches their credentials to the backend:

LANG: http
POST /api/users/sync
Content-Type: application/json

{
  "uid": "firebase_auth_uid",
  "email": "user@ssrindustries.com",
  "displayName": "Godfrey",
  "role": "tenant_admin",
  "tenantId": "tenant-ssr-industries"
}

This sync flow updates the MongoDB users collection dynamically, maintaining MongoDB as the single source of truth for custom application permissions.


5. Security & Session Headers

All dashboard views pass HTTP headers on API transactions to guarantee tenant-level partition security:

LANG: http
x-tenant-id: tenant-ssr-industries
x-user-role: underwriter
x-user-uid: usr_underwriter_ssr_01

MongoDB queries are automatically filtered using the request context:

LANG: javascript
db.applications.find({ "tenantId": "tenant-ssr-industries" })

This partition logic ensures client data isolation across the entire platform.


To deploy the IntelliCredit Risk Engine backend on Render, you should set it up as a Web Service. Here are the exact configurations and settings to apply in the Render dashboard:

1. Create a New Web Service

  1. Log in to Render.
  2. Click New + and select Web Service.
  3. Connect your GitHub repository (TheOrionGD/IntelliCredit-RiskEngine).

2. Configure Service Settings

Under the settings form, configure the following values:

FieldConfiguration Value
Nameintellicredit-backend
Language / RuntimeNode
Branchmain
RegionSelect a region close to your MongoDB database (e.g., Singapore or Oregon)
Build Commandnpm install
Start Commandnpx tsx server.ts

[!NOTE] Since the project uses the tsx package to execute TypeScript directly without compiling to JS, the start command npx tsx server.ts is the most direct and stable choice for Node environments on Render.


3. Add Environment Variables

Scroll down to the Environment Variables section and add the following keys from your .env configuration:

  1. MONGODB_URI: (Required) Your MongoDB connection string.
  2. GROQ_API_KEY: (Required) Your Groq key for LLM-based parsing and analysis.
  3. GEMINI_API_KEY: (Required) Your Google Gemini API key.
  4. VITE_FIREBASE_API_KEY: (Required) Firebase configuration key used by the sync API.
  5. PORT: Render binds to the port automatically, but you can explicitly specify 3466 to match local API configs.

Tenant & User Onboarding Flow Architecture

This document describes the step-by-step architectural workflow for onboarding new tenants and users within the IntelliCredit Risk Engine developed by Swiztek.

Specifically, it details the two-stage onboarding synchronization sequence:

  1. Firebase Account Creation (generating the primary authentication node).
  2. Database Profile Binding (syncing the Firebase UID with the MongoDB users collection to store custom application metadata, tenant mapping, and role permissions).

1. Architectural Overview

To guarantee security, structural isolation, and clean authentication boundaries, we decouple credentials from profile data:

  • Firebase Auth acts as the secure identity provider (retains email, phone, credentials, and password hash).
  • MongoDB acts as the authorization engine (maps user UIDs to roles like underwriter, links them to specific tenants like tenant-ssr-industries, and tracks profile metadata).
 ┌───────────────────────────┐         ┌───────────────────────────┐
 │  Firebase Auth Provider   │         │    MongoDB Data Store     │
 ├───────────────────────────┤         ├───────────────────────────┤
 │ - Email/Password Record   │  Sync   │ - Tenant Mapping ID       │
 │ - Auth Provider Token     ├────────►│ - Custom RBAC Role        │
 │ - Cryptographic UID       │  (UID)  │ - Display Name Profile    │
 └───────────────────────────┘         └───────────────────────────┘

2. Step-by-Step Onboarding Sequence

Below is the execution pathway for onboarding a user, representing both Manual / Self-Service Console Setup and Programmatic API Seeding.

[ User Register Form / Seeder ]
               │
               ▼
┌──────────────────────────────┐
│  1. Create Firebase Account  │ ──► REST / Client SDK: signUp
└──────────────┬───────────────┘
               │
               ├─► Success: Returns cryptographic Firebase UID (e.g., 'iYgZyrRl...')
               ▼
┌──────────────────────────────┐
│   2. Sign UID with MongoDB   │ ──► POST: /api/users/sync
└──────────────┬───────────────┘
               │
               ├─► Inserts user profile matching UID to Tenant (tenant-ssr-industries)
               ▼
      [ Active User Session ]

Walkthrough of Stages:

Stage A: Firebase Identity Creation

  1. The client or administrative seeding tool submits the candidate credentials (email, password) to Firebase.
  2. Firebase registers the user, generates a unique, cryptographically signed user ID (uid), and returns it to the client.

Stage B: MongoDB Profile Synchronization

  1. The client gathers the Firebase uid and marries it with system-level properties:
    • tenantId (e.g., tenant-ssr-industries)
    • role (e.g., tenant_admin | underwriter | credit_officer)
    • displayName (e.g., Godfrey)
  2. A POST dispatch is sent to the backend endpoint /api/users/sync (defined in server.ts).
  3. The Express backend updates/inserts the profile record in the MongoDB users collection, storing the Firebase uid as the primary lookup reference.

3. Implementation Details

A. Programmatic REST Seeding Endpoint

For automated setups (like the client onboarding script), we hit the Firebase Identity Toolkit REST APIs. This bypasses the need for thick browser SDK wrappers during CLI administration.

Request Structure (Firebase Sign-Up API):

LANG: http
POST https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=VITE_FIREBASE_API_KEY
Content-Type: application/json

{
  "email": "manager@ssrindustries.com",
  "password": "SSRAdminPass2026",
  "returnSecureToken": true
}

Response Format:

LANG: json
{
  "localId": "iYgZyrRlkMRDhY2c0jiOXQIvAgE3",
  "email": "manager@ssrindustries.com",
  "idToken": "eyJhbGciOi...",
  "refreshToken": "AMf-vJy...",
  "expiresIn": "3600"
}

B. MongoDB Profile Binding

Once the UID (localId) is retrieved, the sync engine binds it directly with tenant records in MongoDB:

LANG: typescript
const dbUser = {
  uid: "iYgZyrRlkMRDhY2c0jiOXQIvAgE3",
  email: "manager@ssrindustries.com",
  displayName: "Godfrey",
  role: "tenant_admin",
  tenantId: "tenant-ssr-industries",
  createdAt: new Date("2026-07-12T00:00:00Z"),
  lastLogin: new Date().toISOString()
};

// Bind record in MongoDB
await usersCollection.updateOne(
  { email: dbUser.email },
  { $set: dbUser },
  { upsert: true }
);

4. Verification and Security Enforcement

When the onboarded user logs in:

  1. They authenticate with Firebase and get a Session Token.
  2. The client intercepts subsequent API calls, injecting security headers in AuthContext.tsx:
    • x-tenant-id: tenant-ssr-industries
    • x-user-role: tenant_admin
    • x-user-uid: iYgZyrRlkMRDhY2c0jiOXQIvAgE3
  3. The Express middleware decorates the database queries, guaranteeing database query containment:
    LANG: typescript
    function getTenantQuery(req: any, baseQuery: any = {}) {
      const tenantId = req.headers['x-tenant-id'];
      const userRole = req.headers['x-user-role'];
      
      if (userRole === 'super_admin') return baseQuery;
      return { ...baseQuery, tenantId: tenantId };
    }
    

Firebase Auth & MongoDB Integration Architecture

This document explains the synchronization flow between Firebase Authentication and MongoDB inside the IntelliCredit Risk Engine developed by Swiztek.


1. Architectural Roles

Our system decouples authentication credentials from organizational profile metadata:

┌──────────────────────────────────────┐        ┌──────────────────────────────────────┐
│        FIREBASE AUTHENTICATION       │        │          MONGODB DATA STORE          │
├──────────────────────────────────────┤        ├──────────────────────────────────────┤
│  - Hashed Passwords & Sign-In Rails  │        │  - Custom Tenant Identifiers         │
│  - Google OAuth Handshakes           │  Sync  │  - assigned System Roles             │
│  - Phone OTP SMS verification        ├───────►│  - User Metadata & Profiles          │
│  - Session Token Signing & Refresh   │  (UID) │  - Credit Applications & Portfolios  │
│  - JWT Verification Gateway          │        │  - Immutable Audit Logs              │
└──────────────────────────────────────┘        └──────────────────────────────────────┘

2. Dynamic Registration Flow

When a new user registers on the portal, the synchronization is handled asynchronously via a client-side listener and a backend synchronization gateway:

[ User Register Form ]
         │
         ├── 1. Store Pending Role & Tenant ID in memory (window._pendingRole / window._pendingTenantId)
         ▼
[ Firebase Client SDK ]
         │
         ├── 2. Create User Account (createUserWithEmailAndPassword)
         ▼
[ onAuthStateChanged Listener ] (AuthContext.tsx)
         │
         ├── 3. Firebase Auth succeeds and returns user credential profile
         ▼
[ POST /api/users/sync ] (Express API endpoint)
         │
         ├── 4. Extracts Firebase UID, Email, and memory-stored Role/Tenant parameters
         ▼
[ MongoDB users Collection ]
         └── 5. Saves user metadata linked to the unique Firebase UID (Single Source of Truth)

Flow Walkthrough:

  1. Capture Metadata: The registration form saves the selected role (e.g., tenant_admin or underwriter) and target organization (e.g., tenant-ssr-industries) into memory parameters window._pendingRole and window._pendingTenantId.
  2. Firebase Creation: The client calls Firebase Client SDK createUserWithEmailAndPassword to register the credentials.
  3. State Observer: Firebase triggers the observer hook onAuthStateChanged(auth, callback).
  4. Sync Dispatch: If a user is logged in, the callback intercepts the session, gathers properties (uid, email, displayName, phoneNumber), appends the memory-stored metadata, and dispatches them to /api/users/sync.
  5. MongoDB Ingestion: The Express server checks if the UID exists in MongoDB. If not, it saves the new document in the users collection.

3. Session & Cross-Device Sign-In Flow

When an existing user signs in from a new device or opens a new browser window, the synchronization handles the session creation without duplications:

[ New Device / New Session Login ]
         │
         ▼
[ Firebase Client SDK ]
         │
         ├── 1. Authenticate credentials (via Email/Password, Google, or OTP)
         ▼
[ onAuthStateChanged Listener ]
         │
         ├── 2. Extracts authenticated user's Firebase UID
         ▼
[ POST /api/users/sync ]
         │
         ├── 3. Checks MongoDB: users.findOne({ uid: FirebaseUID })
         │      - Profile is retrieved from database (role, tenantId matching SSR Industries)
         │      - Server updates only "lastLogin" timestamp
         ▼
[ Client Session Storage ]
         └── 4. Injects headers x-tenant-id and x-user-role into session memory

How Cross-Device Session Sync Works:

  1. Credentials Validation: The user enters credentials on the new device. Firebase verifies the account and issues a temporary JWT session token.
  2. Authentication State Activation: The client-side observer onAuthStateChanged catches the state update, extracting the user's uid.
  3. Database Check: The client dispatches the profile details to /api/users/sync. The backend queries the MongoDB collection:
    LANG: typescript
    const existingUser = await collection.findOne({ uid: firebaseUid });
    
  4. Update Session Context:
    • Because the profile exists in MongoDB, the server skips creating a new profile.
    • It updates only the lastLogin timestamp.
    • The API returns the profile details containing the role and tenantId registered on the previous device.
  5. Enforce Isolation: The client receives the data, updates sessionStorage (setting tenantId, role, and uid), and directs the user to their customized workspace layout.

4. Secure Session Terminations (Logout)

When the user logs out, session state is cleared to ensure zero-trust access:

[ User Clicks Sign Out ]
         │
         ▼
[ Firebase Client SDK ]
         │
         ├── 1. Terminate Firebase session (signOut(auth))
         ▼
[ onAuthStateChanged Observer ]
         │
         ├── 2. Callback receives null user state
         ▼
[ Client-Side Session Flush ]
         └── 3. Clears context state and removes sessionStorage keys (tenantId, role, uid)

Any subsequent API requests to the Express server will be missing authorization headers, causing backend middlewares to reject requests.