Latest commit

History

36 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SecureFlow

🛡️ SecureFlow

Intent-Aware UPI Fraud Prevention — In Real Time

Live Demo

₹10,000 Cr lost to UPI fraud in 2023 alone. 55 Cr+ users are at risk every day.
SecureFlow intercepts risky payments before they happen — scoring intent, applying intelligent friction, and explaining exactly why.


� About

SecureFlow is a real-time UPI fraud prevention system that acts as an intelligent security layer between users and their payments. Unlike traditional fraud detection that alerts users after the damage is done, SecureFlow analyzes every transaction before confirmation — evaluating recipient trust, spending behavior, transaction patterns, and message semantics to assign a risk score in under 80ms.

Based on the risk score, SecureFlow applies calibrated friction — safe payments go through instantly, suspicious ones trigger warnings with cooldown periods, and high-risk transactions are blocked entirely. Every decision is fully transparent: users see exactly which rules fired, how much each contributed to the score, and why the system intervened.

Built as a full-stack web application with a React + TypeScript frontend and a FastAPI Python backend, SecureFlow demonstrates how intelligent UX design combined with rule-based behavioral analysis can prevent fraud without degrading the payment experience for legitimate users.


�📌 The Problem

India's UPI ecosystem processes billions of transactions monthly, but existing fraud detection is reactive — users discover losses after the money is gone. Current systems:

  • ❌ Flag transactions after they're completed
  • ❌ Provide no explanation for blocks
  • ❌ Apply the same friction to safe and dangerous payments alike
  • ❌ Can't detect social engineering patterns in real time

💡 Our Solution

SecureFlow is a real-time, intent-aware fraud prevention layer that sits between the user and the payment confirmation. It:

  1. Scores every transaction against 9 behavioral + contextual rules in under 80ms
  2. Applies calibrated friction — safe payments flow freely, risky ones get delays or blocks
  3. Explains every decision — no black boxes, every flag comes with a plain-English reason
  4. Persists blocked attempts — even intercepted transactions are logged for full audit trails

🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│ FRONTEND (React + TS) │
│ ┌──────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Landing │ │ Dashboard │ │ SendMoney │ │ History │ │
│ │ (GridScan│ │ (Live │ │ (Multi- │ │ (Filter + │ │
│ │ 3D BG) │ │ Stats) │ │ Step) │ │ Search) │ │
│ └──────────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ └──────────────┼──────────────┘ │
│ axios │ /api/* │
└──────────────────────────────┬──────┘───────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ BACKEND (FastAPI + Python) │
│ │
│ ┌──────────────┐ ┌────────────────┐ ┌─────────────────┐ │
│ │ Risk Engine │ │ Friction Engine│ │ Stats Engine │ │
│ │ (9 Rules, │ │ (4-Tier Gate: │ │ (Security Score,│ │
│ │ 40+ Scam │ │ NONE → TOAST │ │ Trust Rate, │ │
│ │ Keywords) │ │ → DELAY → │ │ Top Rules, │ │
│ │ │ │ BLOCK) │ │ Threat Trend, │ │
│ │ │ │ │ │ Hourly Dist.) │ │
│ └──────────────┘ └────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ In-Memory Transaction Store (seed data + persistence) ││
│ └─────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────┘

🔍 Risk Engine — 9 Detection Rules

#RuleWhat It CatchesScore
1NEW_RECIPIENTFirst-ever payment to this UPI ID+20
2UNUSUAL_AMOUNTAmount exceeds 3× user's average+15
3HIGH_FREQUENCY3+ transactions in the last 10 minutes+15
4LARGE_ROUND_NUMBER₹10,000+ round amounts (common in scams)+10
5SCAM_KEYWORD40+ keywords: "OTP", "KYC", "lottery", "urgent", etc.+25
6BEHAVIORAL_SHIFTAmount exceeds 4× median historical spending+20
7NIGHT_OWLTransactions between 11 PM and 5 AM (higher fraud window)+10
8SUSPICIOUS_UPIUPI ID matches regex scam patterns ("lucky", "prize", "hack", etc.)+20
9TRUSTED_CONTACTRecipient is in user's trusted contacts list (anti-rule)−15

Risk score is capped at 100 (min 0). Each rule contributes a percentage breakdown shown to the user. Rule 9 is an anti-rule that reduces the score for known trusted contacts.


🚦 Friction Engine — 4 Response Tiers

Risk LevelScore RangeFrictionUX Response
NONE0 – 20NONEPayment proceeds silently — no friction applied
🟢 LOW21 – 45TOASTSubtle notification — payment continues after brief info toast
🟡 MEDIUM46 – 65DELAYWarning + 5-second cooldown before user can confirm
🔴 HIGH66 – 100BLOCKTransaction blocked — logged with full reason

✨ Key Features

🖥️ Landing Page

  • Three.js GridScan — interactive 3D background with real-time face-tracking grid animation
  • Animated hero section with blur-text reveal
  • Stats bar, feature cards, step-by-step flow, risk level breakdown

📊 Dashboard

  • Live security score meter (0–100) derived from real transaction history
  • Auto-refresh every 15 seconds with "Updated Xs ago" live timestamp
  • Risk distribution breakdown (LOW / MEDIUM / HIGH percentages)
  • Top Triggered Rules widget — shows the 5 most-fired rules with bar charts
  • Threat Trend — color-coded bar chart of last 7 transactions (green/yellow/red)
  • Hourly Activity — 24-cell heatmap showing transaction distribution across hours
  • Recent transactions with risk badges and relative timestamps
  • Trust rate, flagged count, blocked count — all computed from actual data
  • Deterministic sparkline visualization (sine-wave, not random)

💸 Send Money (Multi-Step Flow)

  • Step 1 — Form: Recipient UPI (validated for @), amount, optional remarks, ⚡ Demo Scenario buttons for instant demo
  • Step 2 — Analysis: Real-time risk scoring with animated loading state
  • Step 3 — Review: Risk meter visualization, rule-by-rule breakdown with severity badges + analysis speed badge ("9 rules evaluated in <1ms")
  • Step 4 — Result: Success confirmation with pulse animation, or block screen with full explanation + "View in History →" link
  • Mandatory 5-second cooldown countdown for MEDIUM-risk (DELAY friction)
  • Keyboard submit — press Enter to send from the form
  • Blocked transactions are persisted to history for audit

📜 Transaction History

  • Filterable tabs: All · Safe · Flagged · Blocked
  • Expandable risk detail panel per transaction
  • Real-time search across recipient name, UPI, amount, remarks, and transaction ID
  • Combined tab + search filtering
  • Sticky header with transaction counts per filter
  • Auto-refresh every 10 seconds for live updates

🧩 App-Wide Enhancements

  • Page transitions — smooth fade + slide animations between pages (AnimatePresence)
  • Error Boundary — graceful error recovery with "Return Home" fallback screen
  • 404 page — custom not-found page for invalid routes
  • Custom scrollbar — dark-themed scrollbar matching the design
  • Selection color — branded green text selection
  • Focus-visible ring — accessible keyboard navigation styling
  • Document title — "SecureFlow — UPI Fraud Prevention"
  • Mobile nav — backdrop overlay + scroll lock when menu is open

🚀 Quick Start

Prerequisites

  • Python 3.10+
  • Node.js 18+ and npm

1. Clone the Repository

git clone https://github.com/Sujith-RMD/SecureFlow.git
cd SecureFlow

2. Start the Backend

cd backend
pip install -r requirements.txt
python -m uvicorn app:app --host 0.0.0.0 --port 5000

The API will be running at http://localhost:5000. Verify with:

curl http://localhost:5000/api/health
# → {"status": "SecureFlow backend operational"}

3. Start the Frontend

cd frontend
npm install
npm run dev

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


📡 API Endpoints

MethodEndpointDescription
POST/api/analyzeRisk-score a potential transaction (doesn't persist)
POST/api/sendAnalyze + persist transaction + deduct balance
GET/api/historyFull transaction history (newest first)
GET/api/userCurrent user profile and balance
GET/api/dashboard-statsAggregated metrics for the dashboard
POST/api/resetClear all history for a fresh start
GET/api/healthBackend status + version + uptime + transaction count

Example — Analyze a Suspicious Transaction

curl -X POST http://localhost:5000/api/analyze \
-H "Content-Type: application/json" \
-d '{"recipientUPI": "unknown@scam", "amount": 50000, "remarks": "urgent send money now"}'
{
"score": 100,
"level": "HIGH",
"reasons": [
{ "ruleId": "NEW_RECIPIENT", "title": "New Recipient Detected", "scoreAdded": 20 },
{ "ruleId": "UNUSUAL_AMOUNT", "title": "Unusual Transaction Amount", "scoreAdded": 15 },
{ "ruleId": "LARGE_ROUND_NUMBER", "title": "Large Round Number", "scoreAdded": 10 },
{ "ruleId": "SCAM_KEYWORD", "title": "Suspicious Keyword Detected", "scoreAdded": 25 },
{ "ruleId": "BEHAVIORAL_SHIFT", "title": "Behavioral Spending Shift", "scoreAdded": 20 }
],
"recommendedAction": "BLOCK",
"friction": { "type": "BLOCK", "delaySeconds": 10, "canOverride": false, "color": "red" },
"analysisTimeMs": 0.74,
"rulesEvaluated": 9
}

5+ out of 9 rules triggered → Score capped at 100 → BLOCKED


🗂️ Project Structure

SecureFlow/
├── backend/
│ ├── app.py # FastAPI app + CORS + logging
│ ├── routes.py # All API endpoints (/api/*)
│ ├── models.py # Pydantic v2 schemas + validators
│ ├── mock_data.py # In-memory transaction store + seed data
│ ├── requirements.txt
│ └── core/
│ ├── risk_engine.py # 9-rule scoring engine (40+ scam keywords)
│ ├── friction_engine.py # 4-tier friction mapping (NONE/TOAST/DELAY/BLOCK)
│ └── stats_engine.py # Dashboard metrics + threat trend + hourly dist
│
├── frontend/
│ ├── src/
│ │ ├── App.tsx # Router + ErrorBoundary + page transitions
│ │ ├── main.tsx # Entry point + document title
│ │ ├── pages/
│ │ │ ├── Landing.tsx # Hero + features + CTA
│ │ │ ├── Dashboard.tsx # Live stats dashboard
│ │ │ ├── SendMoney.tsx # Multi-step transaction flow
│ │ │ └── History.tsx # Filterable transaction log
│ │ ├── components/
│ │ │ ├── GridScan.tsx # Three.js 3D background
│ │ │ ├── Navbar.tsx # Navigation bar + mobile overlay
│ │ │ └── RiskBadge.tsx # Risk level pill
│ │ ├── services/
│ │ │ └── api.ts # Axios API client
│ │ └── types/
│ │ └── index.ts # TypeScript interfaces
│ ├── package.json
│ ├── tailwind.config.js
│ └── vite.config.ts
│
└── README.md

🛠️ Tech Stack

LayerTechnologyPurpose
FrontendReact 18 + TypeScriptComponent-based UI
StylingTailwind CSS v3Utility-first styling
AnimationsMotion (Framer Motion v11)Page transitions + micro-interactions
3D GraphicsThree.js + PostprocessingInteractive GridScan background
HTTP ClientAxiosFrontend ↔ Backend communication
BackendFastAPI (Python)High-performance async API
ValidationPydanticRequest/response schema validation
ServerUvicornASGI server
Build ToolViteLightning-fast HMR + bundling

🧪 Test Scenarios

Try these in the Send Money page to see different risk behaviors:

Use the ⚡ Demo Scenarios buttons on the Send Money page, or try manually:

ScenarioUPIAmountRemarksExpected
✅ Safe paymentalice@upi₹500Dinner splitLOW — instant allow (trusted contact)
⚠️ Medium risknewuser@upi₹15,000Urgent moneyMEDIUM — warn + delay
🔴 Blockedfraud.shark@upi₹50,000Send to lottery prizeHIGH — blocked (suspicious UPI + scam keyword)
🔴 Scam keywordrandom@upi₹1,000send OTP for KYCHIGH — blocked
🌙 Night owlnewperson@upi₹5,000+15 if sent between 11 PM – 5 AM

🎯 What Makes SecureFlow Different

Traditional SystemsSecureFlow
Post-transaction alertsPre-transaction interception
Binary allow/block4-tier calibrated friction
No explanation givenRule-by-rule breakdown with percentages
Same UX for all risk levelsAdaptive UX: none → toast → delay → block
No audit trail for blocksBlocked transactions persisted in history
Keyword blocklists onlyBehavioral + contextual + keyword + temporal analysis
No trusted contactsAnti-rules reduce score for known recipients

👥 Team

Built with ❤️ by:

NameGitHub
Sujith@Sujith-RMD
Abdul Fattah@hydralgorithm
Vaibhav@vaibhavyadavvv2007-ai

SecureFlow — Because every transaction deserves a second look.

About

Real-time UPI fraud prevention system that scores every transaction before confirmation using 6 behavioral rules and 40+ scam keyword detections. Applies calibrated friction — safe payments flow instantly, risky ones get warnings, dangerous ones are blocked. Full-stack: React + TypeScript frontend, FastAPI backend.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

36 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SecureFlow

🛡️ SecureFlow

Intent-Aware UPI Fraud Prevention — In Real Time

Live Demo

₹10,000 Cr lost to UPI fraud in 2023 alone. 55 Cr+ users are at risk every day.
SecureFlow intercepts risky payments before they happen — scoring intent, applying intelligent friction, and explaining exactly why.


� About

SecureFlow is a real-time UPI fraud prevention system that acts as an intelligent security layer between users and their payments. Unlike traditional fraud detection that alerts users after the damage is done, SecureFlow analyzes every transaction before confirmation — evaluating recipient trust, spending behavior, transaction patterns, and message semantics to assign a risk score in under 80ms.

Based on the risk score, SecureFlow applies calibrated friction — safe payments go through instantly, suspicious ones trigger warnings with cooldown periods, and high-risk transactions are blocked entirely. Every decision is fully transparent: users see exactly which rules fired, how much each contributed to the score, and why the system intervened.

Built as a full-stack web application with a React + TypeScript frontend and a FastAPI Python backend, SecureFlow demonstrates how intelligent UX design combined with rule-based behavioral analysis can prevent fraud without degrading the payment experience for legitimate users.


�📌 The Problem

India's UPI ecosystem processes billions of transactions monthly, but existing fraud detection is reactive — users discover losses after the money is gone. Current systems:

  • ❌ Flag transactions after they're completed
  • ❌ Provide no explanation for blocks
  • ❌ Apply the same friction to safe and dangerous payments alike
  • ❌ Can't detect social engineering patterns in real time

💡 Our Solution

SecureFlow is a real-time, intent-aware fraud prevention layer that sits between the user and the payment confirmation. It:

  1. Scores every transaction against 9 behavioral + contextual rules in under 80ms
  2. Applies calibrated friction — safe payments flow freely, risky ones get delays or blocks
  3. Explains every decision — no black boxes, every flag comes with a plain-English reason
  4. Persists blocked attempts — even intercepted transactions are logged for full audit trails

🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│ FRONTEND (React + TS) │
│ ┌──────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Landing │ │ Dashboard │ │ SendMoney │ │ History │ │
│ │ (GridScan│ │ (Live │ │ (Multi- │ │ (Filter + │ │
│ │ 3D BG) │ │ Stats) │ │ Step) │ │ Search) │ │
│ └──────────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ └──────────────┼──────────────┘ │
│ axios │ /api/* │
└──────────────────────────────┬──────┘───────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ BACKEND (FastAPI + Python) │
│ │
│ ┌──────────────┐ ┌────────────────┐ ┌─────────────────┐ │
│ │ Risk Engine │ │ Friction Engine│ │ Stats Engine │ │
│ │ (9 Rules, │ │ (4-Tier Gate: │ │ (Security Score,│ │
│ │ 40+ Scam │ │ NONE → TOAST │ │ Trust Rate, │ │
│ │ Keywords) │ │ → DELAY → │ │ Top Rules, │ │
│ │ │ │ BLOCK) │ │ Threat Trend, │ │
│ │ │ │ │ │ Hourly Dist.) │ │
│ └──────────────┘ └────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ In-Memory Transaction Store (seed data + persistence) ││
│ └─────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────┘

🔍 Risk Engine — 9 Detection Rules

#RuleWhat It CatchesScore
1NEW_RECIPIENTFirst-ever payment to this UPI ID+20
2UNUSUAL_AMOUNTAmount exceeds 3× user's average+15
3HIGH_FREQUENCY3+ transactions in the last 10 minutes+15
4LARGE_ROUND_NUMBER₹10,000+ round amounts (common in scams)+10
5SCAM_KEYWORD40+ keywords: "OTP", "KYC", "lottery", "urgent", etc.+25
6BEHAVIORAL_SHIFTAmount exceeds 4× median historical spending+20
7NIGHT_OWLTransactions between 11 PM and 5 AM (higher fraud window)+10
8SUSPICIOUS_UPIUPI ID matches regex scam patterns ("lucky", "prize", "hack", etc.)+20
9TRUSTED_CONTACTRecipient is in user's trusted contacts list (anti-rule)−15

Risk score is capped at 100 (min 0). Each rule contributes a percentage breakdown shown to the user. Rule 9 is an anti-rule that reduces the score for known trusted contacts.


🚦 Friction Engine — 4 Response Tiers

Risk LevelScore RangeFrictionUX Response
NONE0 – 20NONEPayment proceeds silently — no friction applied
🟢 LOW21 – 45TOASTSubtle notification — payment continues after brief info toast
🟡 MEDIUM46 – 65DELAYWarning + 5-second cooldown before user can confirm
🔴 HIGH66 – 100BLOCKTransaction blocked — logged with full reason

✨ Key Features

🖥️ Landing Page

  • Three.js GridScan — interactive 3D background with real-time face-tracking grid animation
  • Animated hero section with blur-text reveal
  • Stats bar, feature cards, step-by-step flow, risk level breakdown

📊 Dashboard

  • Live security score meter (0–100) derived from real transaction history
  • Auto-refresh every 15 seconds with "Updated Xs ago" live timestamp
  • Risk distribution breakdown (LOW / MEDIUM / HIGH percentages)
  • Top Triggered Rules widget — shows the 5 most-fired rules with bar charts
  • Threat Trend — color-coded bar chart of last 7 transactions (green/yellow/red)
  • Hourly Activity — 24-cell heatmap showing transaction distribution across hours
  • Recent transactions with risk badges and relative timestamps
  • Trust rate, flagged count, blocked count — all computed from actual data
  • Deterministic sparkline visualization (sine-wave, not random)

💸 Send Money (Multi-Step Flow)

  • Step 1 — Form: Recipient UPI (validated for @), amount, optional remarks, ⚡ Demo Scenario buttons for instant demo
  • Step 2 — Analysis: Real-time risk scoring with animated loading state
  • Step 3 — Review: Risk meter visualization, rule-by-rule breakdown with severity badges + analysis speed badge ("9 rules evaluated in <1ms")
  • Step 4 — Result: Success confirmation with pulse animation, or block screen with full explanation + "View in History →" link
  • Mandatory 5-second cooldown countdown for MEDIUM-risk (DELAY friction)
  • Keyboard submit — press Enter to send from the form
  • Blocked transactions are persisted to history for audit

📜 Transaction History

  • Filterable tabs: All · Safe · Flagged · Blocked
  • Expandable risk detail panel per transaction
  • Real-time search across recipient name, UPI, amount, remarks, and transaction ID
  • Combined tab + search filtering
  • Sticky header with transaction counts per filter
  • Auto-refresh every 10 seconds for live updates

🧩 App-Wide Enhancements

  • Page transitions — smooth fade + slide animations between pages (AnimatePresence)
  • Error Boundary — graceful error recovery with "Return Home" fallback screen
  • 404 page — custom not-found page for invalid routes
  • Custom scrollbar — dark-themed scrollbar matching the design
  • Selection color — branded green text selection
  • Focus-visible ring — accessible keyboard navigation styling
  • Document title — "SecureFlow — UPI Fraud Prevention"
  • Mobile nav — backdrop overlay + scroll lock when menu is open

🚀 Quick Start

Prerequisites

  • Python 3.10+
  • Node.js 18+ and npm

1. Clone the Repository

git clone https://github.com/Sujith-RMD/SecureFlow.git
cd SecureFlow

2. Start the Backend

cd backend
pip install -r requirements.txt
python -m uvicorn app:app --host 0.0.0.0 --port 5000

The API will be running at http://localhost:5000. Verify with:

curl http://localhost:5000/api/health
# → {"status": "SecureFlow backend operational"}

3. Start the Frontend

cd frontend
npm install
npm run dev

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


📡 API Endpoints

MethodEndpointDescription
POST/api/analyzeRisk-score a potential transaction (doesn't persist)
POST/api/sendAnalyze + persist transaction + deduct balance
GET/api/historyFull transaction history (newest first)
GET/api/userCurrent user profile and balance
GET/api/dashboard-statsAggregated metrics for the dashboard
POST/api/resetClear all history for a fresh start
GET/api/healthBackend status + version + uptime + transaction count

Example — Analyze a Suspicious Transaction

curl -X POST http://localhost:5000/api/analyze \
-H "Content-Type: application/json" \
-d '{"recipientUPI": "unknown@scam", "amount": 50000, "remarks": "urgent send money now"}'
{
"score": 100,
"level": "HIGH",
"reasons": [
{ "ruleId": "NEW_RECIPIENT", "title": "New Recipient Detected", "scoreAdded": 20 },
{ "ruleId": "UNUSUAL_AMOUNT", "title": "Unusual Transaction Amount", "scoreAdded": 15 },
{ "ruleId": "LARGE_ROUND_NUMBER", "title": "Large Round Number", "scoreAdded": 10 },
{ "ruleId": "SCAM_KEYWORD", "title": "Suspicious Keyword Detected", "scoreAdded": 25 },
{ "ruleId": "BEHAVIORAL_SHIFT", "title": "Behavioral Spending Shift", "scoreAdded": 20 }
],
"recommendedAction": "BLOCK",
"friction": { "type": "BLOCK", "delaySeconds": 10, "canOverride": false, "color": "red" },
"analysisTimeMs": 0.74,
"rulesEvaluated": 9
}

5+ out of 9 rules triggered → Score capped at 100 → BLOCKED


🗂️ Project Structure

SecureFlow/
├── backend/
│ ├── app.py # FastAPI app + CORS + logging
│ ├── routes.py # All API endpoints (/api/*)
│ ├── models.py # Pydantic v2 schemas + validators
│ ├── mock_data.py # In-memory transaction store + seed data
│ ├── requirements.txt
│ └── core/
│ ├── risk_engine.py # 9-rule scoring engine (40+ scam keywords)
│ ├── friction_engine.py # 4-tier friction mapping (NONE/TOAST/DELAY/BLOCK)
│ └── stats_engine.py # Dashboard metrics + threat trend + hourly dist
│
├── frontend/
│ ├── src/
│ │ ├── App.tsx # Router + ErrorBoundary + page transitions
│ │ ├── main.tsx # Entry point + document title
│ │ ├── pages/
│ │ │ ├── Landing.tsx # Hero + features + CTA
│ │ │ ├── Dashboard.tsx # Live stats dashboard
│ │ │ ├── SendMoney.tsx # Multi-step transaction flow
│ │ │ └── History.tsx # Filterable transaction log
│ │ ├── components/
│ │ │ ├── GridScan.tsx # Three.js 3D background
│ │ │ ├── Navbar.tsx # Navigation bar + mobile overlay
│ │ │ └── RiskBadge.tsx # Risk level pill
│ │ ├── services/
│ │ │ └── api.ts # Axios API client
│ │ └── types/
│ │ └── index.ts # TypeScript interfaces
│ ├── package.json
│ ├── tailwind.config.js
│ └── vite.config.ts
│
└── README.md

🛠️ Tech Stack

LayerTechnologyPurpose
FrontendReact 18 + TypeScriptComponent-based UI
StylingTailwind CSS v3Utility-first styling
AnimationsMotion (Framer Motion v11)Page transitions + micro-interactions
3D GraphicsThree.js + PostprocessingInteractive GridScan background
HTTP ClientAxiosFrontend ↔ Backend communication
BackendFastAPI (Python)High-performance async API
ValidationPydanticRequest/response schema validation
ServerUvicornASGI server
Build ToolViteLightning-fast HMR + bundling

🧪 Test Scenarios

Try these in the Send Money page to see different risk behaviors:

Use the ⚡ Demo Scenarios buttons on the Send Money page, or try manually:

ScenarioUPIAmountRemarksExpected
✅ Safe paymentalice@upi₹500Dinner splitLOW — instant allow (trusted contact)
⚠️ Medium risknewuser@upi₹15,000Urgent moneyMEDIUM — warn + delay
🔴 Blockedfraud.shark@upi₹50,000Send to lottery prizeHIGH — blocked (suspicious UPI + scam keyword)
🔴 Scam keywordrandom@upi₹1,000send OTP for KYCHIGH — blocked
🌙 Night owlnewperson@upi₹5,000+15 if sent between 11 PM – 5 AM

🎯 What Makes SecureFlow Different

Traditional SystemsSecureFlow
Post-transaction alertsPre-transaction interception
Binary allow/block4-tier calibrated friction
No explanation givenRule-by-rule breakdown with percentages
Same UX for all risk levelsAdaptive UX: none → toast → delay → block
No audit trail for blocksBlocked transactions persisted in history
Keyword blocklists onlyBehavioral + contextual + keyword + temporal analysis
No trusted contactsAnti-rules reduce score for known recipients

👥 Team

Built with ❤️ by:

NameGitHub
Sujith@Sujith-RMD
Abdul Fattah@hydralgorithm
Vaibhav@vaibhavyadavvv2007-ai

SecureFlow — Because every transaction deserves a second look.

About

Real-time UPI fraud prevention system that scores every transaction before confirmation using 6 behavioral rules and 40+ scam keyword detections. Applies calibrated friction — safe payments flow instantly, risky ones get warnings, dangerous ones are blocked. Full-stack: React + TypeScript frontend, FastAPI backend.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

36 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SecureFlow

🛡️ SecureFlow

Intent-Aware UPI Fraud Prevention — In Real Time

Live Demo

₹10,000 Cr lost to UPI fraud in 2023 alone. 55 Cr+ users are at risk every day.
SecureFlow intercepts risky payments before they happen — scoring intent, applying intelligent friction, and explaining exactly why.


� About

SecureFlow is a real-time UPI fraud prevention system that acts as an intelligent security layer between users and their payments. Unlike traditional fraud detection that alerts users after the damage is done, SecureFlow analyzes every transaction before confirmation — evaluating recipient trust, spending behavior, transaction patterns, and message semantics to assign a risk score in under 80ms.

Based on the risk score, SecureFlow applies calibrated friction — safe payments go through instantly, suspicious ones trigger warnings with cooldown periods, and high-risk transactions are blocked entirely. Every decision is fully transparent: users see exactly which rules fired, how much each contributed to the score, and why the system intervened.

Built as a full-stack web application with a React + TypeScript frontend and a FastAPI Python backend, SecureFlow demonstrates how intelligent UX design combined with rule-based behavioral analysis can prevent fraud without degrading the payment experience for legitimate users.


�📌 The Problem

India's UPI ecosystem processes billions of transactions monthly, but existing fraud detection is reactive — users discover losses after the money is gone. Current systems:

  • ❌ Flag transactions after they're completed
  • ❌ Provide no explanation for blocks
  • ❌ Apply the same friction to safe and dangerous payments alike
  • ❌ Can't detect social engineering patterns in real time

💡 Our Solution

SecureFlow is a real-time, intent-aware fraud prevention layer that sits between the user and the payment confirmation. It:

  1. Scores every transaction against 9 behavioral + contextual rules in under 80ms
  2. Applies calibrated friction — safe payments flow freely, risky ones get delays or blocks
  3. Explains every decision — no black boxes, every flag comes with a plain-English reason
  4. Persists blocked attempts — even intercepted transactions are logged for full audit trails

🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│ FRONTEND (React + TS) │
│ ┌──────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Landing │ │ Dashboard │ │ SendMoney │ │ History │ │
│ │ (GridScan│ │ (Live │ │ (Multi- │ │ (Filter + │ │
│ │ 3D BG) │ │ Stats) │ │ Step) │ │ Search) │ │
│ └──────────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ └──────────────┼──────────────┘ │
│ axios │ /api/* │
└──────────────────────────────┬──────┘───────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ BACKEND (FastAPI + Python) │
│ │
│ ┌──────────────┐ ┌────────────────┐ ┌─────────────────┐ │
│ │ Risk Engine │ │ Friction Engine│ │ Stats Engine │ │
│ │ (9 Rules, │ │ (4-Tier Gate: │ │ (Security Score,│ │
│ │ 40+ Scam │ │ NONE → TOAST │ │ Trust Rate, │ │
│ │ Keywords) │ │ → DELAY → │ │ Top Rules, │ │
│ │ │ │ BLOCK) │ │ Threat Trend, │ │
│ │ │ │ │ │ Hourly Dist.) │ │
│ └──────────────┘ └────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ In-Memory Transaction Store (seed data + persistence) ││
│ └─────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────┘

🔍 Risk Engine — 9 Detection Rules

#RuleWhat It CatchesScore
1NEW_RECIPIENTFirst-ever payment to this UPI ID+20
2UNUSUAL_AMOUNTAmount exceeds 3× user's average+15
3HIGH_FREQUENCY3+ transactions in the last 10 minutes+15
4LARGE_ROUND_NUMBER₹10,000+ round amounts (common in scams)+10
5SCAM_KEYWORD40+ keywords: "OTP", "KYC", "lottery", "urgent", etc.+25
6BEHAVIORAL_SHIFTAmount exceeds 4× median historical spending+20
7NIGHT_OWLTransactions between 11 PM and 5 AM (higher fraud window)+10
8SUSPICIOUS_UPIUPI ID matches regex scam patterns ("lucky", "prize", "hack", etc.)+20
9TRUSTED_CONTACTRecipient is in user's trusted contacts list (anti-rule)−15

Risk score is capped at 100 (min 0). Each rule contributes a percentage breakdown shown to the user. Rule 9 is an anti-rule that reduces the score for known trusted contacts.


🚦 Friction Engine — 4 Response Tiers

Risk LevelScore RangeFrictionUX Response
NONE0 – 20NONEPayment proceeds silently — no friction applied
🟢 LOW21 – 45TOASTSubtle notification — payment continues after brief info toast
🟡 MEDIUM46 – 65DELAYWarning + 5-second cooldown before user can confirm
🔴 HIGH66 – 100BLOCKTransaction blocked — logged with full reason

✨ Key Features

🖥️ Landing Page

  • Three.js GridScan — interactive 3D background with real-time face-tracking grid animation
  • Animated hero section with blur-text reveal
  • Stats bar, feature cards, step-by-step flow, risk level breakdown

📊 Dashboard

  • Live security score meter (0–100) derived from real transaction history
  • Auto-refresh every 15 seconds with "Updated Xs ago" live timestamp
  • Risk distribution breakdown (LOW / MEDIUM / HIGH percentages)
  • Top Triggered Rules widget — shows the 5 most-fired rules with bar charts
  • Threat Trend — color-coded bar chart of last 7 transactions (green/yellow/red)
  • Hourly Activity — 24-cell heatmap showing transaction distribution across hours
  • Recent transactions with risk badges and relative timestamps
  • Trust rate, flagged count, blocked count — all computed from actual data
  • Deterministic sparkline visualization (sine-wave, not random)

💸 Send Money (Multi-Step Flow)

  • Step 1 — Form: Recipient UPI (validated for @), amount, optional remarks, ⚡ Demo Scenario buttons for instant demo
  • Step 2 — Analysis: Real-time risk scoring with animated loading state
  • Step 3 — Review: Risk meter visualization, rule-by-rule breakdown with severity badges + analysis speed badge ("9 rules evaluated in <1ms")
  • Step 4 — Result: Success confirmation with pulse animation, or block screen with full explanation + "View in History →" link
  • Mandatory 5-second cooldown countdown for MEDIUM-risk (DELAY friction)
  • Keyboard submit — press Enter to send from the form
  • Blocked transactions are persisted to history for audit

📜 Transaction History

  • Filterable tabs: All · Safe · Flagged · Blocked
  • Expandable risk detail panel per transaction
  • Real-time search across recipient name, UPI, amount, remarks, and transaction ID
  • Combined tab + search filtering
  • Sticky header with transaction counts per filter
  • Auto-refresh every 10 seconds for live updates

🧩 App-Wide Enhancements

  • Page transitions — smooth fade + slide animations between pages (AnimatePresence)
  • Error Boundary — graceful error recovery with "Return Home" fallback screen
  • 404 page — custom not-found page for invalid routes
  • Custom scrollbar — dark-themed scrollbar matching the design
  • Selection color — branded green text selection
  • Focus-visible ring — accessible keyboard navigation styling
  • Document title — "SecureFlow — UPI Fraud Prevention"
  • Mobile nav — backdrop overlay + scroll lock when menu is open

🚀 Quick Start

Prerequisites

  • Python 3.10+
  • Node.js 18+ and npm

1. Clone the Repository

git clone https://github.com/Sujith-RMD/SecureFlow.git
cd SecureFlow

2. Start the Backend

cd backend
pip install -r requirements.txt
python -m uvicorn app:app --host 0.0.0.0 --port 5000

The API will be running at http://localhost:5000. Verify with:

curl http://localhost:5000/api/health
# → {"status": "SecureFlow backend operational"}

3. Start the Frontend

cd frontend
npm install
npm run dev

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


📡 API Endpoints

MethodEndpointDescription
POST/api/analyzeRisk-score a potential transaction (doesn't persist)
POST/api/sendAnalyze + persist transaction + deduct balance
GET/api/historyFull transaction history (newest first)
GET/api/userCurrent user profile and balance
GET/api/dashboard-statsAggregated metrics for the dashboard
POST/api/resetClear all history for a fresh start
GET/api/healthBackend status + version + uptime + transaction count

Example — Analyze a Suspicious Transaction

curl -X POST http://localhost:5000/api/analyze \
-H "Content-Type: application/json" \
-d '{"recipientUPI": "unknown@scam", "amount": 50000, "remarks": "urgent send money now"}'
{
"score": 100,
"level": "HIGH",
"reasons": [
{ "ruleId": "NEW_RECIPIENT", "title": "New Recipient Detected", "scoreAdded": 20 },
{ "ruleId": "UNUSUAL_AMOUNT", "title": "Unusual Transaction Amount", "scoreAdded": 15 },
{ "ruleId": "LARGE_ROUND_NUMBER", "title": "Large Round Number", "scoreAdded": 10 },
{ "ruleId": "SCAM_KEYWORD", "title": "Suspicious Keyword Detected", "scoreAdded": 25 },
{ "ruleId": "BEHAVIORAL_SHIFT", "title": "Behavioral Spending Shift", "scoreAdded": 20 }
],
"recommendedAction": "BLOCK",
"friction": { "type": "BLOCK", "delaySeconds": 10, "canOverride": false, "color": "red" },
"analysisTimeMs": 0.74,
"rulesEvaluated": 9
}

5+ out of 9 rules triggered → Score capped at 100 → BLOCKED


🗂️ Project Structure

SecureFlow/
├── backend/
│ ├── app.py # FastAPI app + CORS + logging
│ ├── routes.py # All API endpoints (/api/*)
│ ├── models.py # Pydantic v2 schemas + validators
│ ├── mock_data.py # In-memory transaction store + seed data
│ ├── requirements.txt
│ └── core/
│ ├── risk_engine.py # 9-rule scoring engine (40+ scam keywords)
│ ├── friction_engine.py # 4-tier friction mapping (NONE/TOAST/DELAY/BLOCK)
│ └── stats_engine.py # Dashboard metrics + threat trend + hourly dist
│
├── frontend/
│ ├── src/
│ │ ├── App.tsx # Router + ErrorBoundary + page transitions
│ │ ├── main.tsx # Entry point + document title
│ │ ├── pages/
│ │ │ ├── Landing.tsx # Hero + features + CTA
│ │ │ ├── Dashboard.tsx # Live stats dashboard
│ │ │ ├── SendMoney.tsx # Multi-step transaction flow
│ │ │ └── History.tsx # Filterable transaction log
│ │ ├── components/
│ │ │ ├── GridScan.tsx # Three.js 3D background
│ │ │ ├── Navbar.tsx # Navigation bar + mobile overlay
│ │ │ └── RiskBadge.tsx # Risk level pill
│ │ ├── services/
│ │ │ └── api.ts # Axios API client
│ │ └── types/
│ │ └── index.ts # TypeScript interfaces
│ ├── package.json
│ ├── tailwind.config.js
│ └── vite.config.ts
│
└── README.md

🛠️ Tech Stack

LayerTechnologyPurpose
FrontendReact 18 + TypeScriptComponent-based UI
StylingTailwind CSS v3Utility-first styling
AnimationsMotion (Framer Motion v11)Page transitions + micro-interactions
3D GraphicsThree.js + PostprocessingInteractive GridScan background
HTTP ClientAxiosFrontend ↔ Backend communication
BackendFastAPI (Python)High-performance async API
ValidationPydanticRequest/response schema validation
ServerUvicornASGI server
Build ToolViteLightning-fast HMR + bundling

🧪 Test Scenarios

Try these in the Send Money page to see different risk behaviors:

Use the ⚡ Demo Scenarios buttons on the Send Money page, or try manually:

ScenarioUPIAmountRemarksExpected
✅ Safe paymentalice@upi₹500Dinner splitLOW — instant allow (trusted contact)
⚠️ Medium risknewuser@upi₹15,000Urgent moneyMEDIUM — warn + delay
🔴 Blockedfraud.shark@upi₹50,000Send to lottery prizeHIGH — blocked (suspicious UPI + scam keyword)
🔴 Scam keywordrandom@upi₹1,000send OTP for KYCHIGH — blocked
🌙 Night owlnewperson@upi₹5,000+15 if sent between 11 PM – 5 AM

🎯 What Makes SecureFlow Different

Traditional SystemsSecureFlow
Post-transaction alertsPre-transaction interception
Binary allow/block4-tier calibrated friction
No explanation givenRule-by-rule breakdown with percentages
Same UX for all risk levelsAdaptive UX: none → toast → delay → block
No audit trail for blocksBlocked transactions persisted in history
Keyword blocklists onlyBehavioral + contextual + keyword + temporal analysis
No trusted contactsAnti-rules reduce score for known recipients

👥 Team

Built with ❤️ by:

NameGitHub
Sujith@Sujith-RMD
Abdul Fattah@hydralgorithm
Vaibhav@vaibhavyadavvv2007-ai

SecureFlow — Because every transaction deserves a second look.

About

Real-time UPI fraud prevention system that scores every transaction before confirmation using 6 behavioral rules and 40+ scam keyword detections. Applies calibrated friction — safe payments flow instantly, risky ones get warnings, dangerous ones are blocked. Full-stack: React + TypeScript frontend, FastAPI backend.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

36 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SecureFlow

🛡️ SecureFlow

Intent-Aware UPI Fraud Prevention — In Real Time

Live Demo

₹10,000 Cr lost to UPI fraud in 2023 alone. 55 Cr+ users are at risk every day.
SecureFlow intercepts risky payments before they happen — scoring intent, applying intelligent friction, and explaining exactly why.


� About

SecureFlow is a real-time UPI fraud prevention system that acts as an intelligent security layer between users and their payments. Unlike traditional fraud detection that alerts users after the damage is done, SecureFlow analyzes every transaction before confirmation — evaluating recipient trust, spending behavior, transaction patterns, and message semantics to assign a risk score in under 80ms.

Based on the risk score, SecureFlow applies calibrated friction — safe payments go through instantly, suspicious ones trigger warnings with cooldown periods, and high-risk transactions are blocked entirely. Every decision is fully transparent: users see exactly which rules fired, how much each contributed to the score, and why the system intervened.

Built as a full-stack web application with a React + TypeScript frontend and a FastAPI Python backend, SecureFlow demonstrates how intelligent UX design combined with rule-based behavioral analysis can prevent fraud without degrading the payment experience for legitimate users.


�📌 The Problem

India's UPI ecosystem processes billions of transactions monthly, but existing fraud detection is reactive — users discover losses after the money is gone. Current systems:

  • ❌ Flag transactions after they're completed
  • ❌ Provide no explanation for blocks
  • ❌ Apply the same friction to safe and dangerous payments alike
  • ❌ Can't detect social engineering patterns in real time

💡 Our Solution

SecureFlow is a real-time, intent-aware fraud prevention layer that sits between the user and the payment confirmation. It:

  1. Scores every transaction against 9 behavioral + contextual rules in under 80ms
  2. Applies calibrated friction — safe payments flow freely, risky ones get delays or blocks
  3. Explains every decision — no black boxes, every flag comes with a plain-English reason
  4. Persists blocked attempts — even intercepted transactions are logged for full audit trails

🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│ FRONTEND (React + TS) │
│ ┌──────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Landing │ │ Dashboard │ │ SendMoney │ │ History │ │
│ │ (GridScan│ │ (Live │ │ (Multi- │ │ (Filter + │ │
│ │ 3D BG) │ │ Stats) │ │ Step) │ │ Search) │ │
│ └──────────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ └──────────────┼──────────────┘ │
│ axios │ /api/* │
└──────────────────────────────┬──────┘───────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ BACKEND (FastAPI + Python) │
│ │
│ ┌──────────────┐ ┌────────────────┐ ┌─────────────────┐ │
│ │ Risk Engine │ │ Friction Engine│ │ Stats Engine │ │
│ │ (9 Rules, │ │ (4-Tier Gate: │ │ (Security Score,│ │
│ │ 40+ Scam │ │ NONE → TOAST │ │ Trust Rate, │ │
│ │ Keywords) │ │ → DELAY → │ │ Top Rules, │ │
│ │ │ │ BLOCK) │ │ Threat Trend, │ │
│ │ │ │ │ │ Hourly Dist.) │ │
│ └──────────────┘ └────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ In-Memory Transaction Store (seed data + persistence) ││
│ └─────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────┘

🔍 Risk Engine — 9 Detection Rules

#RuleWhat It CatchesScore
1NEW_RECIPIENTFirst-ever payment to this UPI ID+20
2UNUSUAL_AMOUNTAmount exceeds 3× user's average+15
3HIGH_FREQUENCY3+ transactions in the last 10 minutes+15
4LARGE_ROUND_NUMBER₹10,000+ round amounts (common in scams)+10
5SCAM_KEYWORD40+ keywords: "OTP", "KYC", "lottery", "urgent", etc.+25
6BEHAVIORAL_SHIFTAmount exceeds 4× median historical spending+20
7NIGHT_OWLTransactions between 11 PM and 5 AM (higher fraud window)+10
8SUSPICIOUS_UPIUPI ID matches regex scam patterns ("lucky", "prize", "hack", etc.)+20
9TRUSTED_CONTACTRecipient is in user's trusted contacts list (anti-rule)−15

Risk score is capped at 100 (min 0). Each rule contributes a percentage breakdown shown to the user. Rule 9 is an anti-rule that reduces the score for known trusted contacts.


🚦 Friction Engine — 4 Response Tiers

Risk LevelScore RangeFrictionUX Response
NONE0 – 20NONEPayment proceeds silently — no friction applied
🟢 LOW21 – 45TOASTSubtle notification — payment continues after brief info toast
🟡 MEDIUM46 – 65DELAYWarning + 5-second cooldown before user can confirm
🔴 HIGH66 – 100BLOCKTransaction blocked — logged with full reason

✨ Key Features

🖥️ Landing Page

  • Three.js GridScan — interactive 3D background with real-time face-tracking grid animation
  • Animated hero section with blur-text reveal
  • Stats bar, feature cards, step-by-step flow, risk level breakdown

📊 Dashboard

  • Live security score meter (0–100) derived from real transaction history
  • Auto-refresh every 15 seconds with "Updated Xs ago" live timestamp
  • Risk distribution breakdown (LOW / MEDIUM / HIGH percentages)
  • Top Triggered Rules widget — shows the 5 most-fired rules with bar charts
  • Threat Trend — color-coded bar chart of last 7 transactions (green/yellow/red)
  • Hourly Activity — 24-cell heatmap showing transaction distribution across hours
  • Recent transactions with risk badges and relative timestamps
  • Trust rate, flagged count, blocked count — all computed from actual data
  • Deterministic sparkline visualization (sine-wave, not random)

💸 Send Money (Multi-Step Flow)

  • Step 1 — Form: Recipient UPI (validated for @), amount, optional remarks, ⚡ Demo Scenario buttons for instant demo
  • Step 2 — Analysis: Real-time risk scoring with animated loading state
  • Step 3 — Review: Risk meter visualization, rule-by-rule breakdown with severity badges + analysis speed badge ("9 rules evaluated in <1ms")
  • Step 4 — Result: Success confirmation with pulse animation, or block screen with full explanation + "View in History →" link
  • Mandatory 5-second cooldown countdown for MEDIUM-risk (DELAY friction)
  • Keyboard submit — press Enter to send from the form
  • Blocked transactions are persisted to history for audit

📜 Transaction History

  • Filterable tabs: All · Safe · Flagged · Blocked
  • Expandable risk detail panel per transaction
  • Real-time search across recipient name, UPI, amount, remarks, and transaction ID
  • Combined tab + search filtering
  • Sticky header with transaction counts per filter
  • Auto-refresh every 10 seconds for live updates

🧩 App-Wide Enhancements

  • Page transitions — smooth fade + slide animations between pages (AnimatePresence)
  • Error Boundary — graceful error recovery with "Return Home" fallback screen
  • 404 page — custom not-found page for invalid routes
  • Custom scrollbar — dark-themed scrollbar matching the design
  • Selection color — branded green text selection
  • Focus-visible ring — accessible keyboard navigation styling
  • Document title — "SecureFlow — UPI Fraud Prevention"
  • Mobile nav — backdrop overlay + scroll lock when menu is open

🚀 Quick Start

Prerequisites

  • Python 3.10+
  • Node.js 18+ and npm

1. Clone the Repository

git clone https://github.com/Sujith-RMD/SecureFlow.git
cd SecureFlow

2. Start the Backend

cd backend
pip install -r requirements.txt
python -m uvicorn app:app --host 0.0.0.0 --port 5000

The API will be running at http://localhost:5000. Verify with:

curl http://localhost:5000/api/health
# → {"status": "SecureFlow backend operational"}

3. Start the Frontend

cd frontend
npm install
npm run dev

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


📡 API Endpoints

MethodEndpointDescription
POST/api/analyzeRisk-score a potential transaction (doesn't persist)
POST/api/sendAnalyze + persist transaction + deduct balance
GET/api/historyFull transaction history (newest first)
GET/api/userCurrent user profile and balance
GET/api/dashboard-statsAggregated metrics for the dashboard
POST/api/resetClear all history for a fresh start
GET/api/healthBackend status + version + uptime + transaction count

Example — Analyze a Suspicious Transaction

curl -X POST http://localhost:5000/api/analyze \
-H "Content-Type: application/json" \
-d '{"recipientUPI": "unknown@scam", "amount": 50000, "remarks": "urgent send money now"}'
{
"score": 100,
"level": "HIGH",
"reasons": [
{ "ruleId": "NEW_RECIPIENT", "title": "New Recipient Detected", "scoreAdded": 20 },
{ "ruleId": "UNUSUAL_AMOUNT", "title": "Unusual Transaction Amount", "scoreAdded": 15 },
{ "ruleId": "LARGE_ROUND_NUMBER", "title": "Large Round Number", "scoreAdded": 10 },
{ "ruleId": "SCAM_KEYWORD", "title": "Suspicious Keyword Detected", "scoreAdded": 25 },
{ "ruleId": "BEHAVIORAL_SHIFT", "title": "Behavioral Spending Shift", "scoreAdded": 20 }
],
"recommendedAction": "BLOCK",
"friction": { "type": "BLOCK", "delaySeconds": 10, "canOverride": false, "color": "red" },
"analysisTimeMs": 0.74,
"rulesEvaluated": 9
}

5+ out of 9 rules triggered → Score capped at 100 → BLOCKED


🗂️ Project Structure

SecureFlow/
├── backend/
│ ├── app.py # FastAPI app + CORS + logging
│ ├── routes.py # All API endpoints (/api/*)
│ ├── models.py # Pydantic v2 schemas + validators
│ ├── mock_data.py # In-memory transaction store + seed data
│ ├── requirements.txt
│ └── core/
│ ├── risk_engine.py # 9-rule scoring engine (40+ scam keywords)
│ ├── friction_engine.py # 4-tier friction mapping (NONE/TOAST/DELAY/BLOCK)
│ └── stats_engine.py # Dashboard metrics + threat trend + hourly dist
│
├── frontend/
│ ├── src/
│ │ ├── App.tsx # Router + ErrorBoundary + page transitions
│ │ ├── main.tsx # Entry point + document title
│ │ ├── pages/
│ │ │ ├── Landing.tsx # Hero + features + CTA
│ │ │ ├── Dashboard.tsx # Live stats dashboard
│ │ │ ├── SendMoney.tsx # Multi-step transaction flow
│ │ │ └── History.tsx # Filterable transaction log
│ │ ├── components/
│ │ │ ├── GridScan.tsx # Three.js 3D background
│ │ │ ├── Navbar.tsx # Navigation bar + mobile overlay
│ │ │ └── RiskBadge.tsx # Risk level pill
│ │ ├── services/
│ │ │ └── api.ts # Axios API client
│ │ └── types/
│ │ └── index.ts # TypeScript interfaces
│ ├── package.json
│ ├── tailwind.config.js
│ └── vite.config.ts
│
└── README.md

🛠️ Tech Stack

LayerTechnologyPurpose
FrontendReact 18 + TypeScriptComponent-based UI
StylingTailwind CSS v3Utility-first styling
AnimationsMotion (Framer Motion v11)Page transitions + micro-interactions
3D GraphicsThree.js + PostprocessingInteractive GridScan background
HTTP ClientAxiosFrontend ↔ Backend communication
BackendFastAPI (Python)High-performance async API
ValidationPydanticRequest/response schema validation
ServerUvicornASGI server
Build ToolViteLightning-fast HMR + bundling

🧪 Test Scenarios

Try these in the Send Money page to see different risk behaviors:

Use the ⚡ Demo Scenarios buttons on the Send Money page, or try manually:

ScenarioUPIAmountRemarksExpected
✅ Safe paymentalice@upi₹500Dinner splitLOW — instant allow (trusted contact)
⚠️ Medium risknewuser@upi₹15,000Urgent moneyMEDIUM — warn + delay
🔴 Blockedfraud.shark@upi₹50,000Send to lottery prizeHIGH — blocked (suspicious UPI + scam keyword)
🔴 Scam keywordrandom@upi₹1,000send OTP for KYCHIGH — blocked
🌙 Night owlnewperson@upi₹5,000+15 if sent between 11 PM – 5 AM

🎯 What Makes SecureFlow Different

Traditional SystemsSecureFlow
Post-transaction alertsPre-transaction interception
Binary allow/block4-tier calibrated friction
No explanation givenRule-by-rule breakdown with percentages
Same UX for all risk levelsAdaptive UX: none → toast → delay → block
No audit trail for blocksBlocked transactions persisted in history
Keyword blocklists onlyBehavioral + contextual + keyword + temporal analysis
No trusted contactsAnti-rules reduce score for known recipients

👥 Team

Built with ❤️ by:

NameGitHub
Sujith@Sujith-RMD
Abdul Fattah@hydralgorithm
Vaibhav@vaibhavyadavvv2007-ai

SecureFlow — Because every transaction deserves a second look.

About

Real-time UPI fraud prevention system that scores every transaction before confirmation using 6 behavioral rules and 40+ scam keyword detections. Applies calibrated friction — safe payments flow instantly, risky ones get warnings, dangerous ones are blocked. Full-stack: React + TypeScript frontend, FastAPI backend.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

36 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SecureFlow

🛡️ SecureFlow

Intent-Aware UPI Fraud Prevention — In Real Time

Live Demo

₹10,000 Cr lost to UPI fraud in 2023 alone. 55 Cr+ users are at risk every day.
SecureFlow intercepts risky payments before they happen — scoring intent, applying intelligent friction, and explaining exactly why.


� About

SecureFlow is a real-time UPI fraud prevention system that acts as an intelligent security layer between users and their payments. Unlike traditional fraud detection that alerts users after the damage is done, SecureFlow analyzes every transaction before confirmation — evaluating recipient trust, spending behavior, transaction patterns, and message semantics to assign a risk score in under 80ms.

Based on the risk score, SecureFlow applies calibrated friction — safe payments go through instantly, suspicious ones trigger warnings with cooldown periods, and high-risk transactions are blocked entirely. Every decision is fully transparent: users see exactly which rules fired, how much each contributed to the score, and why the system intervened.

Built as a full-stack web application with a React + TypeScript frontend and a FastAPI Python backend, SecureFlow demonstrates how intelligent UX design combined with rule-based behavioral analysis can prevent fraud without degrading the payment experience for legitimate users.


�📌 The Problem

India's UPI ecosystem processes billions of transactions monthly, but existing fraud detection is reactive — users discover losses after the money is gone. Current systems:

  • ❌ Flag transactions after they're completed
  • ❌ Provide no explanation for blocks
  • ❌ Apply the same friction to safe and dangerous payments alike
  • ❌ Can't detect social engineering patterns in real time

💡 Our Solution

SecureFlow is a real-time, intent-aware fraud prevention layer that sits between the user and the payment confirmation. It:

  1. Scores every transaction against 9 behavioral + contextual rules in under 80ms
  2. Applies calibrated friction — safe payments flow freely, risky ones get delays or blocks
  3. Explains every decision — no black boxes, every flag comes with a plain-English reason
  4. Persists blocked attempts — even intercepted transactions are logged for full audit trails

🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│ FRONTEND (React + TS) │
│ ┌──────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Landing │ │ Dashboard │ │ SendMoney │ │ History │ │
│ │ (GridScan│ │ (Live │ │ (Multi- │ │ (Filter + │ │
│ │ 3D BG) │ │ Stats) │ │ Step) │ │ Search) │ │
│ └──────────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ └──────────────┼──────────────┘ │
│ axios │ /api/* │
└──────────────────────────────┬──────┘───────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ BACKEND (FastAPI + Python) │
│ │
│ ┌──────────────┐ ┌────────────────┐ ┌─────────────────┐ │
│ │ Risk Engine │ │ Friction Engine│ │ Stats Engine │ │
│ │ (9 Rules, │ │ (4-Tier Gate: │ │ (Security Score,│ │
│ │ 40+ Scam │ │ NONE → TOAST │ │ Trust Rate, │ │
│ │ Keywords) │ │ → DELAY → │ │ Top Rules, │ │
│ │ │ │ BLOCK) │ │ Threat Trend, │ │
│ │ │ │ │ │ Hourly Dist.) │ │
│ └──────────────┘ └────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ In-Memory Transaction Store (seed data + persistence) ││
│ └─────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────┘

🔍 Risk Engine — 9 Detection Rules

#RuleWhat It CatchesScore
1NEW_RECIPIENTFirst-ever payment to this UPI ID+20
2UNUSUAL_AMOUNTAmount exceeds 3× user's average+15
3HIGH_FREQUENCY3+ transactions in the last 10 minutes+15
4LARGE_ROUND_NUMBER₹10,000+ round amounts (common in scams)+10
5SCAM_KEYWORD40+ keywords: "OTP", "KYC", "lottery", "urgent", etc.+25
6BEHAVIORAL_SHIFTAmount exceeds 4× median historical spending+20
7NIGHT_OWLTransactions between 11 PM and 5 AM (higher fraud window)+10
8SUSPICIOUS_UPIUPI ID matches regex scam patterns ("lucky", "prize", "hack", etc.)+20
9TRUSTED_CONTACTRecipient is in user's trusted contacts list (anti-rule)−15

Risk score is capped at 100 (min 0). Each rule contributes a percentage breakdown shown to the user. Rule 9 is an anti-rule that reduces the score for known trusted contacts.


🚦 Friction Engine — 4 Response Tiers

Risk LevelScore RangeFrictionUX Response
NONE0 – 20NONEPayment proceeds silently — no friction applied
🟢 LOW21 – 45TOASTSubtle notification — payment continues after brief info toast
🟡 MEDIUM46 – 65DELAYWarning + 5-second cooldown before user can confirm
🔴 HIGH66 – 100BLOCKTransaction blocked — logged with full reason

✨ Key Features

🖥️ Landing Page

  • Three.js GridScan — interactive 3D background with real-time face-tracking grid animation
  • Animated hero section with blur-text reveal
  • Stats bar, feature cards, step-by-step flow, risk level breakdown

📊 Dashboard

  • Live security score meter (0–100) derived from real transaction history
  • Auto-refresh every 15 seconds with "Updated Xs ago" live timestamp
  • Risk distribution breakdown (LOW / MEDIUM / HIGH percentages)
  • Top Triggered Rules widget — shows the 5 most-fired rules with bar charts
  • Threat Trend — color-coded bar chart of last 7 transactions (green/yellow/red)
  • Hourly Activity — 24-cell heatmap showing transaction distribution across hours
  • Recent transactions with risk badges and relative timestamps
  • Trust rate, flagged count, blocked count — all computed from actual data
  • Deterministic sparkline visualization (sine-wave, not random)

💸 Send Money (Multi-Step Flow)

  • Step 1 — Form: Recipient UPI (validated for @), amount, optional remarks, ⚡ Demo Scenario buttons for instant demo
  • Step 2 — Analysis: Real-time risk scoring with animated loading state
  • Step 3 — Review: Risk meter visualization, rule-by-rule breakdown with severity badges + analysis speed badge ("9 rules evaluated in <1ms")
  • Step 4 — Result: Success confirmation with pulse animation, or block screen with full explanation + "View in History →" link
  • Mandatory 5-second cooldown countdown for MEDIUM-risk (DELAY friction)
  • Keyboard submit — press Enter to send from the form
  • Blocked transactions are persisted to history for audit

📜 Transaction History

  • Filterable tabs: All · Safe · Flagged · Blocked
  • Expandable risk detail panel per transaction
  • Real-time search across recipient name, UPI, amount, remarks, and transaction ID
  • Combined tab + search filtering
  • Sticky header with transaction counts per filter
  • Auto-refresh every 10 seconds for live updates

🧩 App-Wide Enhancements

  • Page transitions — smooth fade + slide animations between pages (AnimatePresence)
  • Error Boundary — graceful error recovery with "Return Home" fallback screen
  • 404 page — custom not-found page for invalid routes
  • Custom scrollbar — dark-themed scrollbar matching the design
  • Selection color — branded green text selection
  • Focus-visible ring — accessible keyboard navigation styling
  • Document title — "SecureFlow — UPI Fraud Prevention"
  • Mobile nav — backdrop overlay + scroll lock when menu is open

🚀 Quick Start

Prerequisites

  • Python 3.10+
  • Node.js 18+ and npm

1. Clone the Repository

git clone https://github.com/Sujith-RMD/SecureFlow.git
cd SecureFlow

2. Start the Backend

cd backend
pip install -r requirements.txt
python -m uvicorn app:app --host 0.0.0.0 --port 5000

The API will be running at http://localhost:5000. Verify with:

curl http://localhost:5000/api/health
# → {"status": "SecureFlow backend operational"}

3. Start the Frontend

cd frontend
npm install
npm run dev

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


📡 API Endpoints

MethodEndpointDescription
POST/api/analyzeRisk-score a potential transaction (doesn't persist)
POST/api/sendAnalyze + persist transaction + deduct balance
GET/api/historyFull transaction history (newest first)
GET/api/userCurrent user profile and balance
GET/api/dashboard-statsAggregated metrics for the dashboard
POST/api/resetClear all history for a fresh start
GET/api/healthBackend status + version + uptime + transaction count

Example — Analyze a Suspicious Transaction

curl -X POST http://localhost:5000/api/analyze \
-H "Content-Type: application/json" \
-d '{"recipientUPI": "unknown@scam", "amount": 50000, "remarks": "urgent send money now"}'
{
"score": 100,
"level": "HIGH",
"reasons": [
{ "ruleId": "NEW_RECIPIENT", "title": "New Recipient Detected", "scoreAdded": 20 },
{ "ruleId": "UNUSUAL_AMOUNT", "title": "Unusual Transaction Amount", "scoreAdded": 15 },
{ "ruleId": "LARGE_ROUND_NUMBER", "title": "Large Round Number", "scoreAdded": 10 },
{ "ruleId": "SCAM_KEYWORD", "title": "Suspicious Keyword Detected", "scoreAdded": 25 },
{ "ruleId": "BEHAVIORAL_SHIFT", "title": "Behavioral Spending Shift", "scoreAdded": 20 }
],
"recommendedAction": "BLOCK",
"friction": { "type": "BLOCK", "delaySeconds": 10, "canOverride": false, "color": "red" },
"analysisTimeMs": 0.74,
"rulesEvaluated": 9
}

5+ out of 9 rules triggered → Score capped at 100 → BLOCKED


🗂️ Project Structure

SecureFlow/
├── backend/
│ ├── app.py # FastAPI app + CORS + logging
│ ├── routes.py # All API endpoints (/api/*)
│ ├── models.py # Pydantic v2 schemas + validators
│ ├── mock_data.py # In-memory transaction store + seed data
│ ├── requirements.txt
│ └── core/
│ ├── risk_engine.py # 9-rule scoring engine (40+ scam keywords)
│ ├── friction_engine.py # 4-tier friction mapping (NONE/TOAST/DELAY/BLOCK)
│ └── stats_engine.py # Dashboard metrics + threat trend + hourly dist
│
├── frontend/
│ ├── src/
│ │ ├── App.tsx # Router + ErrorBoundary + page transitions
│ │ ├── main.tsx # Entry point + document title
│ │ ├── pages/
│ │ │ ├── Landing.tsx # Hero + features + CTA
│ │ │ ├── Dashboard.tsx # Live stats dashboard
│ │ │ ├── SendMoney.tsx # Multi-step transaction flow
│ │ │ └── History.tsx # Filterable transaction log
│ │ ├── components/
│ │ │ ├── GridScan.tsx # Three.js 3D background
│ │ │ ├── Navbar.tsx # Navigation bar + mobile overlay
│ │ │ └── RiskBadge.tsx # Risk level pill
│ │ ├── services/
│ │ │ └── api.ts # Axios API client
│ │ └── types/
│ │ └── index.ts # TypeScript interfaces
│ ├── package.json
│ ├── tailwind.config.js
│ └── vite.config.ts
│
└── README.md

🛠️ Tech Stack

LayerTechnologyPurpose
FrontendReact 18 + TypeScriptComponent-based UI
StylingTailwind CSS v3Utility-first styling
AnimationsMotion (Framer Motion v11)Page transitions + micro-interactions
3D GraphicsThree.js + PostprocessingInteractive GridScan background
HTTP ClientAxiosFrontend ↔ Backend communication
BackendFastAPI (Python)High-performance async API
ValidationPydanticRequest/response schema validation
ServerUvicornASGI server
Build ToolViteLightning-fast HMR + bundling

🧪 Test Scenarios

Try these in the Send Money page to see different risk behaviors:

Use the ⚡ Demo Scenarios buttons on the Send Money page, or try manually:

ScenarioUPIAmountRemarksExpected
✅ Safe paymentalice@upi₹500Dinner splitLOW — instant allow (trusted contact)
⚠️ Medium risknewuser@upi₹15,000Urgent moneyMEDIUM — warn + delay
🔴 Blockedfraud.shark@upi₹50,000Send to lottery prizeHIGH — blocked (suspicious UPI + scam keyword)
🔴 Scam keywordrandom@upi₹1,000send OTP for KYCHIGH — blocked
🌙 Night owlnewperson@upi₹5,000+15 if sent between 11 PM – 5 AM

🎯 What Makes SecureFlow Different

Traditional SystemsSecureFlow
Post-transaction alertsPre-transaction interception
Binary allow/block4-tier calibrated friction
No explanation givenRule-by-rule breakdown with percentages
Same UX for all risk levelsAdaptive UX: none → toast → delay → block
No audit trail for blocksBlocked transactions persisted in history
Keyword blocklists onlyBehavioral + contextual + keyword + temporal analysis
No trusted contactsAnti-rules reduce score for known recipients

👥 Team

Built with ❤️ by:

NameGitHub
Sujith@Sujith-RMD
Abdul Fattah@hydralgorithm
Vaibhav@vaibhavyadavvv2007-ai

SecureFlow — Because every transaction deserves a second look.

About

Real-time UPI fraud prevention system that scores every transaction before confirmation using 6 behavioral rules and 40+ scam keyword detections. Applies calibrated friction — safe payments flow instantly, risky ones get warnings, dangerous ones are blocked. Full-stack: React + TypeScript frontend, FastAPI backend.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

36 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SecureFlow

🛡️ SecureFlow

Intent-Aware UPI Fraud Prevention — In Real Time

Live Demo

₹10,000 Cr lost to UPI fraud in 2023 alone. 55 Cr+ users are at risk every day.
SecureFlow intercepts risky payments before they happen — scoring intent, applying intelligent friction, and explaining exactly why.


� About

SecureFlow is a real-time UPI fraud prevention system that acts as an intelligent security layer between users and their payments. Unlike traditional fraud detection that alerts users after the damage is done, SecureFlow analyzes every transaction before confirmation — evaluating recipient trust, spending behavior, transaction patterns, and message semantics to assign a risk score in under 80ms.

Based on the risk score, SecureFlow applies calibrated friction — safe payments go through instantly, suspicious ones trigger warnings with cooldown periods, and high-risk transactions are blocked entirely. Every decision is fully transparent: users see exactly which rules fired, how much each contributed to the score, and why the system intervened.

Built as a full-stack web application with a React + TypeScript frontend and a FastAPI Python backend, SecureFlow demonstrates how intelligent UX design combined with rule-based behavioral analysis can prevent fraud without degrading the payment experience for legitimate users.


�📌 The Problem

India's UPI ecosystem processes billions of transactions monthly, but existing fraud detection is reactive — users discover losses after the money is gone. Current systems:

  • ❌ Flag transactions after they're completed
  • ❌ Provide no explanation for blocks
  • ❌ Apply the same friction to safe and dangerous payments alike
  • ❌ Can't detect social engineering patterns in real time

💡 Our Solution

SecureFlow is a real-time, intent-aware fraud prevention layer that sits between the user and the payment confirmation. It:

  1. Scores every transaction against 9 behavioral + contextual rules in under 80ms
  2. Applies calibrated friction — safe payments flow freely, risky ones get delays or blocks
  3. Explains every decision — no black boxes, every flag comes with a plain-English reason
  4. Persists blocked attempts — even intercepted transactions are logged for full audit trails

🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│ FRONTEND (React + TS) │
│ ┌──────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Landing │ │ Dashboard │ │ SendMoney │ │ History │ │
│ │ (GridScan│ │ (Live │ │ (Multi- │ │ (Filter + │ │
│ │ 3D BG) │ │ Stats) │ │ Step) │ │ Search) │ │
│ └──────────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ └──────────────┼──────────────┘ │
│ axios │ /api/* │
└──────────────────────────────┬──────┘───────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ BACKEND (FastAPI + Python) │
│ │
│ ┌──────────────┐ ┌────────────────┐ ┌─────────────────┐ │
│ │ Risk Engine │ │ Friction Engine│ │ Stats Engine │ │
│ │ (9 Rules, │ │ (4-Tier Gate: │ │ (Security Score,│ │
│ │ 40+ Scam │ │ NONE → TOAST │ │ Trust Rate, │ │
│ │ Keywords) │ │ → DELAY → │ │ Top Rules, │ │
│ │ │ │ BLOCK) │ │ Threat Trend, │ │
│ │ │ │ │ │ Hourly Dist.) │ │
│ └──────────────┘ └────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ In-Memory Transaction Store (seed data + persistence) ││
│ └─────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────┘

🔍 Risk Engine — 9 Detection Rules

#RuleWhat It CatchesScore
1NEW_RECIPIENTFirst-ever payment to this UPI ID+20
2UNUSUAL_AMOUNTAmount exceeds 3× user's average+15
3HIGH_FREQUENCY3+ transactions in the last 10 minutes+15
4LARGE_ROUND_NUMBER₹10,000+ round amounts (common in scams)+10
5SCAM_KEYWORD40+ keywords: "OTP", "KYC", "lottery", "urgent", etc.+25
6BEHAVIORAL_SHIFTAmount exceeds 4× median historical spending+20
7NIGHT_OWLTransactions between 11 PM and 5 AM (higher fraud window)+10
8SUSPICIOUS_UPIUPI ID matches regex scam patterns ("lucky", "prize", "hack", etc.)+20
9TRUSTED_CONTACTRecipient is in user's trusted contacts list (anti-rule)−15

Risk score is capped at 100 (min 0). Each rule contributes a percentage breakdown shown to the user. Rule 9 is an anti-rule that reduces the score for known trusted contacts.


🚦 Friction Engine — 4 Response Tiers

Risk LevelScore RangeFrictionUX Response
NONE0 – 20NONEPayment proceeds silently — no friction applied
🟢 LOW21 – 45TOASTSubtle notification — payment continues after brief info toast
🟡 MEDIUM46 – 65DELAYWarning + 5-second cooldown before user can confirm
🔴 HIGH66 – 100BLOCKTransaction blocked — logged with full reason

✨ Key Features

🖥️ Landing Page

  • Three.js GridScan — interactive 3D background with real-time face-tracking grid animation
  • Animated hero section with blur-text reveal
  • Stats bar, feature cards, step-by-step flow, risk level breakdown

📊 Dashboard

  • Live security score meter (0–100) derived from real transaction history
  • Auto-refresh every 15 seconds with "Updated Xs ago" live timestamp
  • Risk distribution breakdown (LOW / MEDIUM / HIGH percentages)
  • Top Triggered Rules widget — shows the 5 most-fired rules with bar charts
  • Threat Trend — color-coded bar chart of last 7 transactions (green/yellow/red)
  • Hourly Activity — 24-cell heatmap showing transaction distribution across hours
  • Recent transactions with risk badges and relative timestamps
  • Trust rate, flagged count, blocked count — all computed from actual data
  • Deterministic sparkline visualization (sine-wave, not random)

💸 Send Money (Multi-Step Flow)

  • Step 1 — Form: Recipient UPI (validated for @), amount, optional remarks, ⚡ Demo Scenario buttons for instant demo
  • Step 2 — Analysis: Real-time risk scoring with animated loading state
  • Step 3 — Review: Risk meter visualization, rule-by-rule breakdown with severity badges + analysis speed badge ("9 rules evaluated in <1ms")
  • Step 4 — Result: Success confirmation with pulse animation, or block screen with full explanation + "View in History →" link
  • Mandatory 5-second cooldown countdown for MEDIUM-risk (DELAY friction)
  • Keyboard submit — press Enter to send from the form
  • Blocked transactions are persisted to history for audit

📜 Transaction History

  • Filterable tabs: All · Safe · Flagged · Blocked
  • Expandable risk detail panel per transaction
  • Real-time search across recipient name, UPI, amount, remarks, and transaction ID
  • Combined tab + search filtering
  • Sticky header with transaction counts per filter
  • Auto-refresh every 10 seconds for live updates

🧩 App-Wide Enhancements

  • Page transitions — smooth fade + slide animations between pages (AnimatePresence)
  • Error Boundary — graceful error recovery with "Return Home" fallback screen
  • 404 page — custom not-found page for invalid routes
  • Custom scrollbar — dark-themed scrollbar matching the design
  • Selection color — branded green text selection
  • Focus-visible ring — accessible keyboard navigation styling
  • Document title — "SecureFlow — UPI Fraud Prevention"
  • Mobile nav — backdrop overlay + scroll lock when menu is open

🚀 Quick Start

Prerequisites

  • Python 3.10+
  • Node.js 18+ and npm

1. Clone the Repository

git clone https://github.com/Sujith-RMD/SecureFlow.git
cd SecureFlow

2. Start the Backend

cd backend
pip install -r requirements.txt
python -m uvicorn app:app --host 0.0.0.0 --port 5000

The API will be running at http://localhost:5000. Verify with:

curl http://localhost:5000/api/health
# → {"status": "SecureFlow backend operational"}

3. Start the Frontend

cd frontend
npm install
npm run dev

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


📡 API Endpoints

MethodEndpointDescription
POST/api/analyzeRisk-score a potential transaction (doesn't persist)
POST/api/sendAnalyze + persist transaction + deduct balance
GET/api/historyFull transaction history (newest first)
GET/api/userCurrent user profile and balance
GET/api/dashboard-statsAggregated metrics for the dashboard
POST/api/resetClear all history for a fresh start
GET/api/healthBackend status + version + uptime + transaction count

Example — Analyze a Suspicious Transaction

curl -X POST http://localhost:5000/api/analyze \
-H "Content-Type: application/json" \
-d '{"recipientUPI": "unknown@scam", "amount": 50000, "remarks": "urgent send money now"}'
{
"score": 100,
"level": "HIGH",
"reasons": [
{ "ruleId": "NEW_RECIPIENT", "title": "New Recipient Detected", "scoreAdded": 20 },
{ "ruleId": "UNUSUAL_AMOUNT", "title": "Unusual Transaction Amount", "scoreAdded": 15 },
{ "ruleId": "LARGE_ROUND_NUMBER", "title": "Large Round Number", "scoreAdded": 10 },
{ "ruleId": "SCAM_KEYWORD", "title": "Suspicious Keyword Detected", "scoreAdded": 25 },
{ "ruleId": "BEHAVIORAL_SHIFT", "title": "Behavioral Spending Shift", "scoreAdded": 20 }
],
"recommendedAction": "BLOCK",
"friction": { "type": "BLOCK", "delaySeconds": 10, "canOverride": false, "color": "red" },
"analysisTimeMs": 0.74,
"rulesEvaluated": 9
}

5+ out of 9 rules triggered → Score capped at 100 → BLOCKED


🗂️ Project Structure

SecureFlow/
├── backend/
│ ├── app.py # FastAPI app + CORS + logging
│ ├── routes.py # All API endpoints (/api/*)
│ ├── models.py # Pydantic v2 schemas + validators
│ ├── mock_data.py # In-memory transaction store + seed data
│ ├── requirements.txt
│ └── core/
│ ├── risk_engine.py # 9-rule scoring engine (40+ scam keywords)
│ ├── friction_engine.py # 4-tier friction mapping (NONE/TOAST/DELAY/BLOCK)
│ └── stats_engine.py # Dashboard metrics + threat trend + hourly dist
│
├── frontend/
│ ├── src/
│ │ ├── App.tsx # Router + ErrorBoundary + page transitions
│ │ ├── main.tsx # Entry point + document title
│ │ ├── pages/
│ │ │ ├── Landing.tsx # Hero + features + CTA
│ │ │ ├── Dashboard.tsx # Live stats dashboard
│ │ │ ├── SendMoney.tsx # Multi-step transaction flow
│ │ │ └── History.tsx # Filterable transaction log
│ │ ├── components/
│ │ │ ├── GridScan.tsx # Three.js 3D background
│ │ │ ├── Navbar.tsx # Navigation bar + mobile overlay
│ │ │ └── RiskBadge.tsx # Risk level pill
│ │ ├── services/
│ │ │ └── api.ts # Axios API client
│ │ └── types/
│ │ └── index.ts # TypeScript interfaces
│ ├── package.json
│ ├── tailwind.config.js
│ └── vite.config.ts
│
└── README.md

🛠️ Tech Stack

LayerTechnologyPurpose
FrontendReact 18 + TypeScriptComponent-based UI
StylingTailwind CSS v3Utility-first styling
AnimationsMotion (Framer Motion v11)Page transitions + micro-interactions
3D GraphicsThree.js + PostprocessingInteractive GridScan background
HTTP ClientAxiosFrontend ↔ Backend communication
BackendFastAPI (Python)High-performance async API
ValidationPydanticRequest/response schema validation
ServerUvicornASGI server
Build ToolViteLightning-fast HMR + bundling

🧪 Test Scenarios

Try these in the Send Money page to see different risk behaviors:

Use the ⚡ Demo Scenarios buttons on the Send Money page, or try manually:

ScenarioUPIAmountRemarksExpected
✅ Safe paymentalice@upi₹500Dinner splitLOW — instant allow (trusted contact)
⚠️ Medium risknewuser@upi₹15,000Urgent moneyMEDIUM — warn + delay
🔴 Blockedfraud.shark@upi₹50,000Send to lottery prizeHIGH — blocked (suspicious UPI + scam keyword)
🔴 Scam keywordrandom@upi₹1,000send OTP for KYCHIGH — blocked
🌙 Night owlnewperson@upi₹5,000+15 if sent between 11 PM – 5 AM

🎯 What Makes SecureFlow Different

Traditional SystemsSecureFlow
Post-transaction alertsPre-transaction interception
Binary allow/block4-tier calibrated friction
No explanation givenRule-by-rule breakdown with percentages
Same UX for all risk levelsAdaptive UX: none → toast → delay → block
No audit trail for blocksBlocked transactions persisted in history
Keyword blocklists onlyBehavioral + contextual + keyword + temporal analysis
No trusted contactsAnti-rules reduce score for known recipients

👥 Team

Built with ❤️ by:

NameGitHub
Sujith@Sujith-RMD
Abdul Fattah@hydralgorithm
Vaibhav@vaibhavyadavvv2007-ai

SecureFlow — Because every transaction deserves a second look.

About

Real-time UPI fraud prevention system that scores every transaction before confirmation using 6 behavioral rules and 40+ scam keyword detections. Applies calibrated friction — safe payments flow instantly, risky ones get warnings, dangerous ones are blocked. Full-stack: React + TypeScript frontend, FastAPI backend.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

36 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SecureFlow

🛡️ SecureFlow

Intent-Aware UPI Fraud Prevention — In Real Time

Live Demo

₹10,000 Cr lost to UPI fraud in 2023 alone. 55 Cr+ users are at risk every day.
SecureFlow intercepts risky payments before they happen — scoring intent, applying intelligent friction, and explaining exactly why.


� About

SecureFlow is a real-time UPI fraud prevention system that acts as an intelligent security layer between users and their payments. Unlike traditional fraud detection that alerts users after the damage is done, SecureFlow analyzes every transaction before confirmation — evaluating recipient trust, spending behavior, transaction patterns, and message semantics to assign a risk score in under 80ms.

Based on the risk score, SecureFlow applies calibrated friction — safe payments go through instantly, suspicious ones trigger warnings with cooldown periods, and high-risk transactions are blocked entirely. Every decision is fully transparent: users see exactly which rules fired, how much each contributed to the score, and why the system intervened.

Built as a full-stack web application with a React + TypeScript frontend and a FastAPI Python backend, SecureFlow demonstrates how intelligent UX design combined with rule-based behavioral analysis can prevent fraud without degrading the payment experience for legitimate users.


�📌 The Problem

India's UPI ecosystem processes billions of transactions monthly, but existing fraud detection is reactive — users discover losses after the money is gone. Current systems:

  • ❌ Flag transactions after they're completed
  • ❌ Provide no explanation for blocks
  • ❌ Apply the same friction to safe and dangerous payments alike
  • ❌ Can't detect social engineering patterns in real time

💡 Our Solution

SecureFlow is a real-time, intent-aware fraud prevention layer that sits between the user and the payment confirmation. It:

  1. Scores every transaction against 9 behavioral + contextual rules in under 80ms
  2. Applies calibrated friction — safe payments flow freely, risky ones get delays or blocks
  3. Explains every decision — no black boxes, every flag comes with a plain-English reason
  4. Persists blocked attempts — even intercepted transactions are logged for full audit trails

🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│ FRONTEND (React + TS) │
│ ┌──────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Landing │ │ Dashboard │ │ SendMoney │ │ History │ │
│ │ (GridScan│ │ (Live │ │ (Multi- │ │ (Filter + │ │
│ │ 3D BG) │ │ Stats) │ │ Step) │ │ Search) │ │
│ └──────────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ └──────────────┼──────────────┘ │
│ axios │ /api/* │
└──────────────────────────────┬──────┘───────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ BACKEND (FastAPI + Python) │
│ │
│ ┌──────────────┐ ┌────────────────┐ ┌─────────────────┐ │
│ │ Risk Engine │ │ Friction Engine│ │ Stats Engine │ │
│ │ (9 Rules, │ │ (4-Tier Gate: │ │ (Security Score,│ │
│ │ 40+ Scam │ │ NONE → TOAST │ │ Trust Rate, │ │
│ │ Keywords) │ │ → DELAY → │ │ Top Rules, │ │
│ │ │ │ BLOCK) │ │ Threat Trend, │ │
│ │ │ │ │ │ Hourly Dist.) │ │
│ └──────────────┘ └────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ In-Memory Transaction Store (seed data + persistence) ││
│ └─────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────┘

🔍 Risk Engine — 9 Detection Rules

#RuleWhat It CatchesScore
1NEW_RECIPIENTFirst-ever payment to this UPI ID+20
2UNUSUAL_AMOUNTAmount exceeds 3× user's average+15
3HIGH_FREQUENCY3+ transactions in the last 10 minutes+15
4LARGE_ROUND_NUMBER₹10,000+ round amounts (common in scams)+10
5SCAM_KEYWORD40+ keywords: "OTP", "KYC", "lottery", "urgent", etc.+25
6BEHAVIORAL_SHIFTAmount exceeds 4× median historical spending+20
7NIGHT_OWLTransactions between 11 PM and 5 AM (higher fraud window)+10
8SUSPICIOUS_UPIUPI ID matches regex scam patterns ("lucky", "prize", "hack", etc.)+20
9TRUSTED_CONTACTRecipient is in user's trusted contacts list (anti-rule)−15

Risk score is capped at 100 (min 0). Each rule contributes a percentage breakdown shown to the user. Rule 9 is an anti-rule that reduces the score for known trusted contacts.


🚦 Friction Engine — 4 Response Tiers

Risk LevelScore RangeFrictionUX Response
NONE0 – 20NONEPayment proceeds silently — no friction applied
🟢 LOW21 – 45TOASTSubtle notification — payment continues after brief info toast
🟡 MEDIUM46 – 65DELAYWarning + 5-second cooldown before user can confirm
🔴 HIGH66 – 100BLOCKTransaction blocked — logged with full reason

✨ Key Features

🖥️ Landing Page

  • Three.js GridScan — interactive 3D background with real-time face-tracking grid animation
  • Animated hero section with blur-text reveal
  • Stats bar, feature cards, step-by-step flow, risk level breakdown

📊 Dashboard

  • Live security score meter (0–100) derived from real transaction history
  • Auto-refresh every 15 seconds with "Updated Xs ago" live timestamp
  • Risk distribution breakdown (LOW / MEDIUM / HIGH percentages)
  • Top Triggered Rules widget — shows the 5 most-fired rules with bar charts
  • Threat Trend — color-coded bar chart of last 7 transactions (green/yellow/red)
  • Hourly Activity — 24-cell heatmap showing transaction distribution across hours
  • Recent transactions with risk badges and relative timestamps
  • Trust rate, flagged count, blocked count — all computed from actual data
  • Deterministic sparkline visualization (sine-wave, not random)

💸 Send Money (Multi-Step Flow)

  • Step 1 — Form: Recipient UPI (validated for @), amount, optional remarks, ⚡ Demo Scenario buttons for instant demo
  • Step 2 — Analysis: Real-time risk scoring with animated loading state
  • Step 3 — Review: Risk meter visualization, rule-by-rule breakdown with severity badges + analysis speed badge ("9 rules evaluated in <1ms")
  • Step 4 — Result: Success confirmation with pulse animation, or block screen with full explanation + "View in History →" link
  • Mandatory 5-second cooldown countdown for MEDIUM-risk (DELAY friction)
  • Keyboard submit — press Enter to send from the form
  • Blocked transactions are persisted to history for audit

📜 Transaction History

  • Filterable tabs: All · Safe · Flagged · Blocked
  • Expandable risk detail panel per transaction
  • Real-time search across recipient name, UPI, amount, remarks, and transaction ID
  • Combined tab + search filtering
  • Sticky header with transaction counts per filter
  • Auto-refresh every 10 seconds for live updates

🧩 App-Wide Enhancements

  • Page transitions — smooth fade + slide animations between pages (AnimatePresence)
  • Error Boundary — graceful error recovery with "Return Home" fallback screen
  • 404 page — custom not-found page for invalid routes
  • Custom scrollbar — dark-themed scrollbar matching the design
  • Selection color — branded green text selection
  • Focus-visible ring — accessible keyboard navigation styling
  • Document title — "SecureFlow — UPI Fraud Prevention"
  • Mobile nav — backdrop overlay + scroll lock when menu is open

🚀 Quick Start

Prerequisites

  • Python 3.10+
  • Node.js 18+ and npm

1. Clone the Repository

git clone https://github.com/Sujith-RMD/SecureFlow.git
cd SecureFlow

2. Start the Backend

cd backend
pip install -r requirements.txt
python -m uvicorn app:app --host 0.0.0.0 --port 5000

The API will be running at http://localhost:5000. Verify with:

curl http://localhost:5000/api/health
# → {"status": "SecureFlow backend operational"}

3. Start the Frontend

cd frontend
npm install
npm run dev

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


📡 API Endpoints

MethodEndpointDescription
POST/api/analyzeRisk-score a potential transaction (doesn't persist)
POST/api/sendAnalyze + persist transaction + deduct balance
GET/api/historyFull transaction history (newest first)
GET/api/userCurrent user profile and balance
GET/api/dashboard-statsAggregated metrics for the dashboard
POST/api/resetClear all history for a fresh start
GET/api/healthBackend status + version + uptime + transaction count

Example — Analyze a Suspicious Transaction

curl -X POST http://localhost:5000/api/analyze \
-H "Content-Type: application/json" \
-d '{"recipientUPI": "unknown@scam", "amount": 50000, "remarks": "urgent send money now"}'
{
"score": 100,
"level": "HIGH",
"reasons": [
{ "ruleId": "NEW_RECIPIENT", "title": "New Recipient Detected", "scoreAdded": 20 },
{ "ruleId": "UNUSUAL_AMOUNT", "title": "Unusual Transaction Amount", "scoreAdded": 15 },
{ "ruleId": "LARGE_ROUND_NUMBER", "title": "Large Round Number", "scoreAdded": 10 },
{ "ruleId": "SCAM_KEYWORD", "title": "Suspicious Keyword Detected", "scoreAdded": 25 },
{ "ruleId": "BEHAVIORAL_SHIFT", "title": "Behavioral Spending Shift", "scoreAdded": 20 }
],
"recommendedAction": "BLOCK",
"friction": { "type": "BLOCK", "delaySeconds": 10, "canOverride": false, "color": "red" },
"analysisTimeMs": 0.74,
"rulesEvaluated": 9
}

5+ out of 9 rules triggered → Score capped at 100 → BLOCKED


🗂️ Project Structure

SecureFlow/
├── backend/
│ ├── app.py # FastAPI app + CORS + logging
│ ├── routes.py # All API endpoints (/api/*)
│ ├── models.py # Pydantic v2 schemas + validators
│ ├── mock_data.py # In-memory transaction store + seed data
│ ├── requirements.txt
│ └── core/
│ ├── risk_engine.py # 9-rule scoring engine (40+ scam keywords)
│ ├── friction_engine.py # 4-tier friction mapping (NONE/TOAST/DELAY/BLOCK)
│ └── stats_engine.py # Dashboard metrics + threat trend + hourly dist
│
├── frontend/
│ ├── src/
│ │ ├── App.tsx # Router + ErrorBoundary + page transitions
│ │ ├── main.tsx # Entry point + document title
│ │ ├── pages/
│ │ │ ├── Landing.tsx # Hero + features + CTA
│ │ │ ├── Dashboard.tsx # Live stats dashboard
│ │ │ ├── SendMoney.tsx # Multi-step transaction flow
│ │ │ └── History.tsx # Filterable transaction log
│ │ ├── components/
│ │ │ ├── GridScan.tsx # Three.js 3D background
│ │ │ ├── Navbar.tsx # Navigation bar + mobile overlay
│ │ │ └── RiskBadge.tsx # Risk level pill
│ │ ├── services/
│ │ │ └── api.ts # Axios API client
│ │ └── types/
│ │ └── index.ts # TypeScript interfaces
│ ├── package.json
│ ├── tailwind.config.js
│ └── vite.config.ts
│
└── README.md

🛠️ Tech Stack

LayerTechnologyPurpose
FrontendReact 18 + TypeScriptComponent-based UI
StylingTailwind CSS v3Utility-first styling
AnimationsMotion (Framer Motion v11)Page transitions + micro-interactions
3D GraphicsThree.js + PostprocessingInteractive GridScan background
HTTP ClientAxiosFrontend ↔ Backend communication
BackendFastAPI (Python)High-performance async API
ValidationPydanticRequest/response schema validation
ServerUvicornASGI server
Build ToolViteLightning-fast HMR + bundling

🧪 Test Scenarios

Try these in the Send Money page to see different risk behaviors:

Use the ⚡ Demo Scenarios buttons on the Send Money page, or try manually:

ScenarioUPIAmountRemarksExpected
✅ Safe paymentalice@upi₹500Dinner splitLOW — instant allow (trusted contact)
⚠️ Medium risknewuser@upi₹15,000Urgent moneyMEDIUM — warn + delay
🔴 Blockedfraud.shark@upi₹50,000Send to lottery prizeHIGH — blocked (suspicious UPI + scam keyword)
🔴 Scam keywordrandom@upi₹1,000send OTP for KYCHIGH — blocked
🌙 Night owlnewperson@upi₹5,000+15 if sent between 11 PM – 5 AM

🎯 What Makes SecureFlow Different

Traditional SystemsSecureFlow
Post-transaction alertsPre-transaction interception
Binary allow/block4-tier calibrated friction
No explanation givenRule-by-rule breakdown with percentages
Same UX for all risk levelsAdaptive UX: none → toast → delay → block
No audit trail for blocksBlocked transactions persisted in history
Keyword blocklists onlyBehavioral + contextual + keyword + temporal analysis
No trusted contactsAnti-rules reduce score for known recipients

👥 Team

Built with ❤️ by:

NameGitHub
Sujith@Sujith-RMD
Abdul Fattah@hydralgorithm
Vaibhav@vaibhavyadavvv2007-ai

SecureFlow — Because every transaction deserves a second look.

About

Real-time UPI fraud prevention system that scores every transaction before confirmation using 6 behavioral rules and 40+ scam keyword detections. Applies calibrated friction — safe payments flow instantly, risky ones get warnings, dangerous ones are blocked. Full-stack: React + TypeScript frontend, FastAPI backend.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

36 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

SecureFlow

🛡️ SecureFlow

Intent-Aware UPI Fraud Prevention — In Real Time

Live Demo

₹10,000 Cr lost to UPI fraud in 2023 alone. 55 Cr+ users are at risk every day.
SecureFlow intercepts risky payments before they happen — scoring intent, applying intelligent friction, and explaining exactly why.


� About

SecureFlow is a real-time UPI fraud prevention system that acts as an intelligent security layer between users and their payments. Unlike traditional fraud detection that alerts users after the damage is done, SecureFlow analyzes every transaction before confirmation — evaluating recipient trust, spending behavior, transaction patterns, and message semantics to assign a risk score in under 80ms.

Based on the risk score, SecureFlow applies calibrated friction — safe payments go through instantly, suspicious ones trigger warnings with cooldown periods, and high-risk transactions are blocked entirely. Every decision is fully transparent: users see exactly which rules fired, how much each contributed to the score, and why the system intervened.

Built as a full-stack web application with a React + TypeScript frontend and a FastAPI Python backend, SecureFlow demonstrates how intelligent UX design combined with rule-based behavioral analysis can prevent fraud without degrading the payment experience for legitimate users.


�📌 The Problem

India's UPI ecosystem processes billions of transactions monthly, but existing fraud detection is reactive — users discover losses after the money is gone. Current systems:

  • ❌ Flag transactions after they're completed
  • ❌ Provide no explanation for blocks
  • ❌ Apply the same friction to safe and dangerous payments alike
  • ❌ Can't detect social engineering patterns in real time

💡 Our Solution

SecureFlow is a real-time, intent-aware fraud prevention layer that sits between the user and the payment confirmation. It:

  1. Scores every transaction against 9 behavioral + contextual rules in under 80ms
  2. Applies calibrated friction — safe payments flow freely, risky ones get delays or blocks
  3. Explains every decision — no black boxes, every flag comes with a plain-English reason
  4. Persists blocked attempts — even intercepted transactions are logged for full audit trails

🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│ FRONTEND (React + TS) │
│ ┌──────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Landing │ │ Dashboard │ │ SendMoney │ │ History │ │
│ │ (GridScan│ │ (Live │ │ (Multi- │ │ (Filter + │ │
│ │ 3D BG) │ │ Stats) │ │ Step) │ │ Search) │ │
│ └──────────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
│ │ │ │ │
│ └──────────────┼──────────────┘ │
│ axios │ /api/* │
└──────────────────────────────┬──────┘───────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ BACKEND (FastAPI + Python) │
│ │
│ ┌──────────────┐ ┌────────────────┐ ┌─────────────────┐ │
│ │ Risk Engine │ │ Friction Engine│ │ Stats Engine │ │
│ │ (9 Rules, │ │ (4-Tier Gate: │ │ (Security Score,│ │
│ │ 40+ Scam │ │ NONE → TOAST │ │ Trust Rate, │ │
│ │ Keywords) │ │ → DELAY → │ │ Top Rules, │ │
│ │ │ │ BLOCK) │ │ Threat Trend, │ │
│ │ │ │ │ │ Hourly Dist.) │ │
│ └──────────────┘ └────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐│
│ │ In-Memory Transaction Store (seed data + persistence) ││
│ └─────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────┘

🔍 Risk Engine — 9 Detection Rules

#RuleWhat It CatchesScore
1NEW_RECIPIENTFirst-ever payment to this UPI ID+20
2UNUSUAL_AMOUNTAmount exceeds 3× user's average+15
3HIGH_FREQUENCY3+ transactions in the last 10 minutes+15
4LARGE_ROUND_NUMBER₹10,000+ round amounts (common in scams)+10
5SCAM_KEYWORD40+ keywords: "OTP", "KYC", "lottery", "urgent", etc.+25
6BEHAVIORAL_SHIFTAmount exceeds 4× median historical spending+20
7NIGHT_OWLTransactions between 11 PM and 5 AM (higher fraud window)+10
8SUSPICIOUS_UPIUPI ID matches regex scam patterns ("lucky", "prize", "hack", etc.)+20
9TRUSTED_CONTACTRecipient is in user's trusted contacts list (anti-rule)−15

Risk score is capped at 100 (min 0). Each rule contributes a percentage breakdown shown to the user. Rule 9 is an anti-rule that reduces the score for known trusted contacts.


🚦 Friction Engine — 4 Response Tiers

Risk LevelScore RangeFrictionUX Response
NONE0 – 20NONEPayment proceeds silently — no friction applied
🟢 LOW21 – 45TOASTSubtle notification — payment continues after brief info toast
🟡 MEDIUM46 – 65DELAYWarning + 5-second cooldown before user can confirm
🔴 HIGH66 – 100BLOCKTransaction blocked — logged with full reason

✨ Key Features

🖥️ Landing Page

  • Three.js GridScan — interactive 3D background with real-time face-tracking grid animation
  • Animated hero section with blur-text reveal
  • Stats bar, feature cards, step-by-step flow, risk level breakdown

📊 Dashboard

  • Live security score meter (0–100) derived from real transaction history
  • Auto-refresh every 15 seconds with "Updated Xs ago" live timestamp
  • Risk distribution breakdown (LOW / MEDIUM / HIGH percentages)
  • Top Triggered Rules widget — shows the 5 most-fired rules with bar charts
  • Threat Trend — color-coded bar chart of last 7 transactions (green/yellow/red)
  • Hourly Activity — 24-cell heatmap showing transaction distribution across hours
  • Recent transactions with risk badges and relative timestamps
  • Trust rate, flagged count, blocked count — all computed from actual data
  • Deterministic sparkline visualization (sine-wave, not random)

💸 Send Money (Multi-Step Flow)

  • Step 1 — Form: Recipient UPI (validated for @), amount, optional remarks, ⚡ Demo Scenario buttons for instant demo
  • Step 2 — Analysis: Real-time risk scoring with animated loading state
  • Step 3 — Review: Risk meter visualization, rule-by-rule breakdown with severity badges + analysis speed badge ("9 rules evaluated in <1ms")
  • Step 4 — Result: Success confirmation with pulse animation, or block screen with full explanation + "View in History →" link
  • Mandatory 5-second cooldown countdown for MEDIUM-risk (DELAY friction)
  • Keyboard submit — press Enter to send from the form
  • Blocked transactions are persisted to history for audit

📜 Transaction History

  • Filterable tabs: All · Safe · Flagged · Blocked
  • Expandable risk detail panel per transaction
  • Real-time search across recipient name, UPI, amount, remarks, and transaction ID
  • Combined tab + search filtering
  • Sticky header with transaction counts per filter
  • Auto-refresh every 10 seconds for live updates

🧩 App-Wide Enhancements

  • Page transitions — smooth fade + slide animations between pages (AnimatePresence)
  • Error Boundary — graceful error recovery with "Return Home" fallback screen
  • 404 page — custom not-found page for invalid routes
  • Custom scrollbar — dark-themed scrollbar matching the design
  • Selection color — branded green text selection
  • Focus-visible ring — accessible keyboard navigation styling
  • Document title — "SecureFlow — UPI Fraud Prevention"
  • Mobile nav — backdrop overlay + scroll lock when menu is open

🚀 Quick Start

Prerequisites

  • Python 3.10+
  • Node.js 18+ and npm

1. Clone the Repository

git clone https://github.com/Sujith-RMD/SecureFlow.git
cd SecureFlow

2. Start the Backend

cd backend
pip install -r requirements.txt
python -m uvicorn app:app --host 0.0.0.0 --port 5000

The API will be running at http://localhost:5000. Verify with:

curl http://localhost:5000/api/health
# → {"status": "SecureFlow backend operational"}

3. Start the Frontend

cd frontend
npm install
npm run dev

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


📡 API Endpoints

MethodEndpointDescription
POST/api/analyzeRisk-score a potential transaction (doesn't persist)
POST/api/sendAnalyze + persist transaction + deduct balance
GET/api/historyFull transaction history (newest first)
GET/api/userCurrent user profile and balance
GET/api/dashboard-statsAggregated metrics for the dashboard
POST/api/resetClear all history for a fresh start
GET/api/healthBackend status + version + uptime + transaction count

Example — Analyze a Suspicious Transaction

curl -X POST http://localhost:5000/api/analyze \
-H "Content-Type: application/json" \
-d '{"recipientUPI": "unknown@scam", "amount": 50000, "remarks": "urgent send money now"}'
{
"score": 100,
"level": "HIGH",
"reasons": [
{ "ruleId": "NEW_RECIPIENT", "title": "New Recipient Detected", "scoreAdded": 20 },
{ "ruleId": "UNUSUAL_AMOUNT", "title": "Unusual Transaction Amount", "scoreAdded": 15 },
{ "ruleId": "LARGE_ROUND_NUMBER", "title": "Large Round Number", "scoreAdded": 10 },
{ "ruleId": "SCAM_KEYWORD", "title": "Suspicious Keyword Detected", "scoreAdded": 25 },
{ "ruleId": "BEHAVIORAL_SHIFT", "title": "Behavioral Spending Shift", "scoreAdded": 20 }
],
"recommendedAction": "BLOCK",
"friction": { "type": "BLOCK", "delaySeconds": 10, "canOverride": false, "color": "red" },
"analysisTimeMs": 0.74,
"rulesEvaluated": 9
}

5+ out of 9 rules triggered → Score capped at 100 → BLOCKED


🗂️ Project Structure

SecureFlow/
├── backend/
│ ├── app.py # FastAPI app + CORS + logging
│ ├── routes.py # All API endpoints (/api/*)
│ ├── models.py # Pydantic v2 schemas + validators
│ ├── mock_data.py # In-memory transaction store + seed data
│ ├── requirements.txt
│ └── core/
│ ├── risk_engine.py # 9-rule scoring engine (40+ scam keywords)
│ ├── friction_engine.py # 4-tier friction mapping (NONE/TOAST/DELAY/BLOCK)
│ └── stats_engine.py # Dashboard metrics + threat trend + hourly dist
│
├── frontend/
│ ├── src/
│ │ ├── App.tsx # Router + ErrorBoundary + page transitions
│ │ ├── main.tsx # Entry point + document title
│ │ ├── pages/
│ │ │ ├── Landing.tsx # Hero + features + CTA
│ │ │ ├── Dashboard.tsx # Live stats dashboard
│ │ │ ├── SendMoney.tsx # Multi-step transaction flow
│ │ │ └── History.tsx # Filterable transaction log
│ │ ├── components/
│ │ │ ├── GridScan.tsx # Three.js 3D background
│ │ │ ├── Navbar.tsx # Navigation bar + mobile overlay
│ │ │ └── RiskBadge.tsx # Risk level pill
│ │ ├── services/
│ │ │ └── api.ts # Axios API client
│ │ └── types/
│ │ └── index.ts # TypeScript interfaces
│ ├── package.json
│ ├── tailwind.config.js
│ └── vite.config.ts
│
└── README.md

🛠️ Tech Stack

LayerTechnologyPurpose
FrontendReact 18 + TypeScriptComponent-based UI
StylingTailwind CSS v3Utility-first styling
AnimationsMotion (Framer Motion v11)Page transitions + micro-interactions
3D GraphicsThree.js + PostprocessingInteractive GridScan background
HTTP ClientAxiosFrontend ↔ Backend communication
BackendFastAPI (Python)High-performance async API
ValidationPydanticRequest/response schema validation
ServerUvicornASGI server
Build ToolViteLightning-fast HMR + bundling

🧪 Test Scenarios

Try these in the Send Money page to see different risk behaviors:

Use the ⚡ Demo Scenarios buttons on the Send Money page, or try manually:

ScenarioUPIAmountRemarksExpected
✅ Safe paymentalice@upi₹500Dinner splitLOW — instant allow (trusted contact)
⚠️ Medium risknewuser@upi₹15,000Urgent moneyMEDIUM — warn + delay
🔴 Blockedfraud.shark@upi₹50,000Send to lottery prizeHIGH — blocked (suspicious UPI + scam keyword)
🔴 Scam keywordrandom@upi₹1,000send OTP for KYCHIGH — blocked
🌙 Night owlnewperson@upi₹5,000+15 if sent between 11 PM – 5 AM

🎯 What Makes SecureFlow Different

Traditional SystemsSecureFlow
Post-transaction alertsPre-transaction interception
Binary allow/block4-tier calibrated friction
No explanation givenRule-by-rule breakdown with percentages
Same UX for all risk levelsAdaptive UX: none → toast → delay → block
No audit trail for blocksBlocked transactions persisted in history
Keyword blocklists onlyBehavioral + contextual + keyword + temporal analysis
No trusted contactsAnti-rules reduce score for known recipients

👥 Team

Built with ❤️ by:

NameGitHub
Sujith@Sujith-RMD
Abdul Fattah@hydralgorithm
Vaibhav@vaibhavyadavvv2007-ai

SecureFlow — Because every transaction deserves a second look.

About

Real-time UPI fraud prevention system that scores every transaction before confirmation using 6 behavioral rules and 40+ scam keyword detections. Applies calibrated friction — safe payments flow instantly, risky ones get warnings, dangerous ones are blocked. Full-stack: React + TypeScript frontend, FastAPI backend.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages