From 6c4e3a088cc220561c28f0d67dda246b9cd38879 Mon Sep 17 00:00:00 2001 From: Ayaanshaikh12243 Date: Sat, 7 Mar 2026 22:41:06 +0530 Subject: [PATCH 1/4] done --- dlp/README.md | 21 +++++ dlp/dlp-config.js | 17 ++++ dlp/dlp-engine.js | 43 +++++++++ dlp/dlp-logger.js | 15 ++++ dlp/dlp-middleware.js | 29 +++++++ dlp/dlp-test.js | 25 ++++++ dlp/dlp-utils.js | 15 ++++ portfolio-rebalancer.js | 91 ++++++++++++++++++++ portfolio-rebalancer/README.md | 16 ++++ portfolio-rebalancer/allocation-monitor.js | 28 ++++++ portfolio-rebalancer/market-data.js | 30 +++++++ portfolio-rebalancer/portfolio-data-model.js | 46 ++++++++++ portfolio-rebalancer/portfolio-ui.js | 45 ++++++++++ portfolio-rebalancer/rebalancing-strategy.js | 41 +++++++++ portfolio-rebalancer/trade-automation.js | 33 +++++++ portfolio-rebalancer/user-preferences.js | 23 +++++ routes/compliance.js | 4 + 17 files changed, 522 insertions(+) create mode 100644 dlp/README.md create mode 100644 dlp/dlp-config.js create mode 100644 dlp/dlp-engine.js create mode 100644 dlp/dlp-logger.js create mode 100644 dlp/dlp-middleware.js create mode 100644 dlp/dlp-test.js create mode 100644 dlp/dlp-utils.js create mode 100644 portfolio-rebalancer.js create mode 100644 portfolio-rebalancer/README.md create mode 100644 portfolio-rebalancer/allocation-monitor.js create mode 100644 portfolio-rebalancer/market-data.js create mode 100644 portfolio-rebalancer/portfolio-data-model.js create mode 100644 portfolio-rebalancer/portfolio-ui.js create mode 100644 portfolio-rebalancer/rebalancing-strategy.js create mode 100644 portfolio-rebalancer/trade-automation.js create mode 100644 portfolio-rebalancer/user-preferences.js diff --git a/dlp/README.md b/dlp/README.md new file mode 100644 index 00000000..28c8dad9 --- /dev/null +++ b/dlp/README.md @@ -0,0 +1,21 @@ +# Real-Time Data Loss Prevention (DLP) + +## Overview +This module provides real-time DLP for outgoing data in ExpenseFlow. It scans API responses and exports for sensitive information and enforces policies (block, alert, log). + +## Components +- `dlp-engine.js`: Core detection and policy evaluation +- `dlp-middleware.js`: Express middleware for outgoing responses +- `dlp-config.js`: Patterns and policies configuration +- `dlp-logger.js`: Audit trail for DLP events +- `dlp-utils.js`: Helper functions (masking, etc.) +- `dlp-test.js`: Unit tests + +## Usage +1. Add `dlp-middleware` to your Express routes. +2. Configure patterns and policies in `dlp-config.js`. +3. Check `dlp-audit.log` for DLP events. + +## Extending +- Add new patterns/policies in `dlp-config.js`. +- Integrate with alerting systems as needed. diff --git a/dlp/dlp-config.js b/dlp/dlp-config.js new file mode 100644 index 00000000..804d97bf --- /dev/null +++ b/dlp/dlp-config.js @@ -0,0 +1,17 @@ +// DLP Configuration: Patterns and policies +// ...existing code... + +module.exports = { + patterns: [ + { type: 'email', regex: '[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+', severity: 'high' }, + { type: 'ssn', regex: '\b\d{3}-\d{2}-\d{4}\b', severity: 'high' }, + { type: 'credit_card', regex: '\b(?:\d[ -]*?){13,16}\b', severity: 'high' }, + { type: 'phone', regex: '\b\d{3}[-.\s]?\d{3}[-.\s]?\d{4}\b', severity: 'medium' }, + // Add more patterns as needed + ], + policies: [ + { types: ['email', 'ssn', 'credit_card'], action: 'block', message: 'Sensitive data detected. Action blocked.' }, + { types: ['phone'], action: 'alert', message: 'Phone number detected. Alert logged.' }, + // Add more policies as needed + ], +}; diff --git a/dlp/dlp-engine.js b/dlp/dlp-engine.js new file mode 100644 index 00000000..edebd5d5 --- /dev/null +++ b/dlp/dlp-engine.js @@ -0,0 +1,43 @@ +// DLP Engine: Core detection and policy evaluation +// ...existing code... + +class DLPEngine { + constructor(config) { + this.config = config; + this.patterns = config.patterns || []; + this.policies = config.policies || []; + } + + scanData(data) { + let findings = []; + for (const pattern of this.patterns) { + const regex = new RegExp(pattern.regex, 'gi'); + if (regex.test(data)) { + findings.push({ + type: pattern.type, + match: data.match(regex), + severity: pattern.severity || 'medium', + }); + } + } + return findings; + } + + evaluatePolicies(findings) { + let actions = []; + for (const policy of this.policies) { + for (const finding of findings) { + if (policy.types.includes(finding.type)) { + actions.push({ + action: policy.action, + finding, + message: policy.message || 'Policy violation detected', + }); + } + } + } + return actions; + } +} + +module.exports = DLPEngine; diff --git a/dlp/dlp-logger.js b/dlp/dlp-logger.js new file mode 100644 index 00000000..19cfc16f --- /dev/null +++ b/dlp/dlp-logger.js @@ -0,0 +1,15 @@ +// DLP Logger: Audit trail for DLP events +// ...existing code... +const fs = require('fs'); +const path = require('path'); + +const LOG_FILE = path.join(__dirname, 'dlp-audit.log'); + +function logDLPEvent(event) { + const entry = `${new Date().toISOString()} | ${event.action} | ${event.finding.type} | ${event.finding.match} | ${event.message}\n`; + fs.appendFile(LOG_FILE, entry, err => { + if (err) console.error('DLP Logger error:', err); + }); +} + +module.exports = logDLPEvent; diff --git a/dlp/dlp-middleware.js b/dlp/dlp-middleware.js new file mode 100644 index 00000000..57777048 --- /dev/null +++ b/dlp/dlp-middleware.js @@ -0,0 +1,29 @@ +// DLP Middleware: Intercepts outgoing responses +// ...existing code... + +const DLPEngine = require('./dlp-engine'); +const dlpConfig = require('./dlp-config'); +const logDLPEvent = require('./dlp-logger'); + +const dlpEngine = new DLPEngine(dlpConfig); + +function dlpMiddleware(req, res, next) { + const originalSend = res.send; + res.send = function (body) { + const findings = dlpEngine.scanData(typeof body === 'string' ? body : JSON.stringify(body)); + const actions = dlpEngine.evaluatePolicies(findings); + actions.forEach(action => logDLPEvent(action)); + if (actions.some(a => a.action === 'block')) { + res.status(403); + return originalSend.call(this, { error: 'DLP policy violation', details: actions }); + } + if (actions.some(a => a.action === 'alert')) { + // Log or alert (implementation below) + console.log('DLP Alert:', actions); + } + return originalSend.call(this, body); + }; + next(); +} + +module.exports = dlpMiddleware; diff --git a/dlp/dlp-test.js b/dlp/dlp-test.js new file mode 100644 index 00000000..3bf6fff2 --- /dev/null +++ b/dlp/dlp-test.js @@ -0,0 +1,25 @@ +// DLP Test: Unit tests for DLP engine +// ...existing code... + +const DLPEngine = require('./dlp-engine'); +const dlpConfig = require('./dlp-config'); + +const engine = new DLPEngine(dlpConfig); + +function testScanData() { + const testData = 'User email: test@example.com, SSN: 123-45-6789, Card: 4111 1111 1111 1111'; + const findings = engine.scanData(testData); + console.log('Findings:', findings); +} + +function testEvaluatePolicies() { + const findings = [ + { type: 'email', match: ['test@example.com'], severity: 'high' }, + { type: 'ssn', match: ['123-45-6789'], severity: 'high' }, + ]; + const actions = engine.evaluatePolicies(findings); + console.log('Actions:', actions); +} + +testScanData(); +testEvaluatePolicies(); diff --git a/dlp/dlp-utils.js b/dlp/dlp-utils.js new file mode 100644 index 00000000..8e5badbf --- /dev/null +++ b/dlp/dlp-utils.js @@ -0,0 +1,15 @@ +// DLP Utilities: Helper functions for sensitive data detection +// ...existing code... + +function maskSensitiveData(data, patterns) { + let masked = data; + for (const pattern of patterns) { + const regex = new RegExp(pattern.regex, 'gi'); + masked = masked.replace(regex, '[MASKED]'); + } + return masked; +} + +module.exports = { + maskSensitiveData, +}; diff --git a/portfolio-rebalancer.js b/portfolio-rebalancer.js new file mode 100644 index 00000000..78482a7d --- /dev/null +++ b/portfolio-rebalancer.js @@ -0,0 +1,91 @@ +// Smart Investment Portfolio Rebalancer +// Monitors portfolio allocations, suggests optimal rebalancing, and automates trades + +class Portfolio { + constructor(assets = []) { + this.assets = assets; // [{symbol, allocation, value}] + } + + getTotalValue() { + return this.assets.reduce((sum, asset) => sum + asset.value, 0); + } + + getAllocations() { + const total = this.getTotalValue(); + return this.assets.map(asset => ({ + symbol: asset.symbol, + allocation: asset.value / total + })); + } + + updateAsset(symbol, value) { + const asset = this.assets.find(a => a.symbol === symbol); + if (asset) asset.value = value; + } + + addAsset(symbol, value) { + this.assets.push({symbol, value, allocation: 0}); + } +} + +class Rebalancer { + constructor(targetAllocations) { + this.targetAllocations = targetAllocations; // {symbol: targetPercent} + } + + suggestRebalance(portfolio) { + const allocations = portfolio.getAllocations(); + const total = portfolio.getTotalValue(); + let actions = []; + allocations.forEach(asset => { + const target = this.targetAllocations[asset.symbol] || 0; + const diff = target - asset.allocation; + if (Math.abs(diff) > 0.01) { + actions.push({ + symbol: asset.symbol, + action: diff > 0 ? 'buy' : 'sell', + amount: Math.abs(diff) * total + }); + } + }); + return actions; + } + + automateTrades(portfolio, executeTrade) { + const actions = this.suggestRebalance(portfolio); + actions.forEach(({symbol, action, amount}) => { + executeTrade(symbol, action, amount); + }); + } +} + +// Example trade executor +function executeTrade(symbol, action, amount) { + console.log(`Executing ${action} of ${amount} for ${symbol}`); + // Integrate with brokerage API here +} + +// Portfolio risk analysis utility +function analyzeRisk(portfolio) { + const allocations = portfolio.getAllocations(); + let riskScore = 0; + allocations.forEach(asset => { + // Example: higher allocation to volatile assets increases risk + if (asset.symbol === 'TSLA') riskScore += asset.allocation * 2; + else riskScore += asset.allocation; + }); + return riskScore; +} + +// Portfolio performance tracker +function trackPerformance(portfolio, historicalValues) { + // historicalValues: [{date, values: {symbol: value}}] + return historicalValues.map(entry => { + const total = Object.values(entry.values).reduce((sum, v) => sum + v, 0); + return { date: entry.date, totalValue: total }; + }); +} + +module.exports = { Portfolio, Rebalancer, executeTrade }; +module.exports.analyzeRisk = analyzeRisk; +module.exports.trackPerformance = trackPerformance; \ No newline at end of file diff --git a/portfolio-rebalancer/README.md b/portfolio-rebalancer/README.md new file mode 100644 index 00000000..b052b0c6 --- /dev/null +++ b/portfolio-rebalancer/README.md @@ -0,0 +1,16 @@ +// README.md +# Smart Investment Portfolio Rebalancer + +This tool monitors investment portfolio allocations, suggests optimal rebalancing actions, and automates trades based on user preferences and market conditions. + +## Modules +- portfolio-data-model.js: Portfolio structure and asset management +- allocation-monitor.js: Allocation drift detection +- rebalancing-strategy.js: Rebalancing algorithms +- trade-automation.js: Trade execution +- user-preferences.js: User settings +- market-data.js: Market price simulation +- portfolio-ui.js: CLI demo + +## Usage +Run portfolio-ui.js to see a demo of the rebalancer in action. diff --git a/portfolio-rebalancer/allocation-monitor.js b/portfolio-rebalancer/allocation-monitor.js new file mode 100644 index 00000000..c0b17887 --- /dev/null +++ b/portfolio-rebalancer/allocation-monitor.js @@ -0,0 +1,28 @@ +// allocation-monitor.js +// Monitors portfolio allocations and detects drift from target allocations + +const Portfolio = require('./portfolio-data-model'); + +class AllocationMonitor { + constructor(portfolio) { + this.portfolio = portfolio; + } + + getDriftReport() { + const allocations = this.portfolio.getAllocations(); + return allocations.map(asset => ({ + symbol: asset.symbol, + currentAllocation: asset.allocation, + targetAllocation: asset.targetAllocation, + drift: asset.allocation - asset.targetAllocation + })); + } + + isRebalancingNeeded(threshold = 0.02) { + // threshold: minimum drift to trigger rebalancing (e.g., 2%) + const report = this.getDriftReport(); + return report.some(asset => Math.abs(asset.drift) > threshold); + } +} + +module.exports = AllocationMonitor; diff --git a/portfolio-rebalancer/market-data.js b/portfolio-rebalancer/market-data.js new file mode 100644 index 00000000..0c15edac --- /dev/null +++ b/portfolio-rebalancer/market-data.js @@ -0,0 +1,30 @@ +// market-data.js +// Fetches and updates market data for assets + +class MarketData { + constructor() { + this.data = {}; + } + + updateMarketData(symbol, price) { + this.data[symbol] = price; + } + + getMarketPrice(symbol) { + return this.data[symbol]; + } + + getAllMarketData() { + return this.data; + } + + fetchMarketData(symbols) { + // Placeholder: Simulate fetching market prices + symbols.forEach(symbol => { + this.data[symbol] = Math.random() * 100 + 50; // Random price between 50-150 + }); + return this.data; + } +} + +module.exports = MarketData; diff --git a/portfolio-rebalancer/portfolio-data-model.js b/portfolio-rebalancer/portfolio-data-model.js new file mode 100644 index 00000000..0e22f91e --- /dev/null +++ b/portfolio-rebalancer/portfolio-data-model.js @@ -0,0 +1,46 @@ +// portfolio-data-model.js +// Smart Investment Portfolio Rebalancer - Portfolio Data Model +// Handles portfolio structure, asset classes, and user holdings + +class Portfolio { + constructor(userId, assets = []) { + this.userId = userId; + this.assets = assets; // [{ symbol, allocation, currentValue, targetAllocation }] + } + + addAsset(symbol, allocation, currentValue, targetAllocation) { + this.assets.push({ symbol, allocation, currentValue, targetAllocation }); + } + + updateAsset(symbol, allocation, currentValue, targetAllocation) { + const asset = this.assets.find(a => a.symbol === symbol); + if (asset) { + asset.allocation = allocation; + asset.currentValue = currentValue; + asset.targetAllocation = targetAllocation; + } + } + + removeAsset(symbol) { + this.assets = this.assets.filter(a => a.symbol !== symbol); + } + + getTotalValue() { + return this.assets.reduce((sum, asset) => sum + asset.currentValue, 0); + } + + getAsset(symbol) { + return this.assets.find(a => a.symbol === symbol); + } + + getAllocations() { + const total = this.getTotalValue(); + return this.assets.map(asset => ({ + symbol: asset.symbol, + allocation: asset.currentValue / total, + targetAllocation: asset.targetAllocation + })); + } +} + +module.exports = Portfolio; diff --git a/portfolio-rebalancer/portfolio-ui.js b/portfolio-rebalancer/portfolio-ui.js new file mode 100644 index 00000000..8ff2ca75 --- /dev/null +++ b/portfolio-rebalancer/portfolio-ui.js @@ -0,0 +1,45 @@ +// portfolio-ui.js +// Provides a simple CLI interface for portfolio rebalancer + +const Portfolio = require('./portfolio-data-model'); +const AllocationMonitor = require('./allocation-monitor'); +const RebalancingStrategy = require('./rebalancing-strategy'); +const TradeAutomation = require('./trade-automation'); +const UserPreferences = require('./user-preferences'); +const MarketData = require('./market-data'); + +function runPortfolioRebalancerDemo() { + // Demo user and portfolio + const userId = 'user123'; + const portfolio = new Portfolio(userId); + portfolio.addAsset('AAPL', 0.4, 40000, 0.35); + portfolio.addAsset('GOOGL', 0.3, 30000, 0.30); + portfolio.addAsset('TSLA', 0.3, 30000, 0.35); + + const monitor = new AllocationMonitor(portfolio); + const strategy = new RebalancingStrategy(portfolio, monitor); + const userPrefs = new UserPreferences(userId, { + maxTradeSize: 10000, + preferredBrokers: ['BrokerX'], + autoConfirm: true + }); + const marketData = new MarketData(); + marketData.fetchMarketData(['AAPL', 'GOOGL', 'TSLA']); + + // Show drift report + console.log('--- Drift Report ---'); + console.table(monitor.getDriftReport()); + + // Suggest rebalancing actions + const actions = strategy.suggestRebalancingActions(); + console.log('--- Suggested Actions ---'); + console.table(actions); + + // Execute trades + const tradeAutomation = new TradeAutomation(portfolio, strategy); + const tradeHistory = tradeAutomation.executeTrades(actions, userPrefs.getAllPreferences()); + console.log('--- Trade History ---'); + console.table(tradeHistory); +} + +runPortfolioRebalancerDemo(); diff --git a/portfolio-rebalancer/rebalancing-strategy.js b/portfolio-rebalancer/rebalancing-strategy.js new file mode 100644 index 00000000..296619b3 --- /dev/null +++ b/portfolio-rebalancer/rebalancing-strategy.js @@ -0,0 +1,41 @@ +// rebalancing-strategy.js +// Provides optimal rebalancing actions based on portfolio drift and user preferences + +class RebalancingStrategy { + constructor(portfolio, monitor) { + this.portfolio = portfolio; + this.monitor = monitor; + } + + suggestRebalancingActions() { + const driftReport = this.monitor.getDriftReport(); + const actions = []; + driftReport.forEach(asset => { + if (Math.abs(asset.drift) > 0.02) { // 2% threshold + if (asset.drift > 0) { + actions.push({ + symbol: asset.symbol, + action: 'Sell', + amount: asset.drift * this.portfolio.getTotalValue() + }); + } else { + actions.push({ + symbol: asset.symbol, + action: 'Buy', + amount: Math.abs(asset.drift) * this.portfolio.getTotalValue() + }); + } + } + }); + return actions; + } + + optimizeRebalancing(costs = {}) { + // costs: { symbol: transactionCost } + // Advanced: minimize transaction costs, taxes, etc. + // Placeholder for future optimization logic + return this.suggestRebalancingActions(); + } +} + +module.exports = RebalancingStrategy; diff --git a/portfolio-rebalancer/trade-automation.js b/portfolio-rebalancer/trade-automation.js new file mode 100644 index 00000000..56f68590 --- /dev/null +++ b/portfolio-rebalancer/trade-automation.js @@ -0,0 +1,33 @@ +// trade-automation.js +// Automates trades based on rebalancing actions and user preferences + +class TradeAutomation { + constructor(portfolio, strategy) { + this.portfolio = portfolio; + this.strategy = strategy; + this.tradeHistory = []; + } + + executeTrades(actions, userPreferences = {}) { + // userPreferences: { maxTradeSize, preferredBrokers, autoConfirm } + actions.forEach(action => { + // Simulate trade execution + const trade = { + symbol: action.symbol, + action: action.action, + amount: action.amount, + broker: userPreferences.preferredBrokers ? userPreferences.preferredBrokers[0] : 'DefaultBroker', + timestamp: new Date(), + status: userPreferences.autoConfirm ? 'Executed' : 'Pending Confirmation' + }; + this.tradeHistory.push(trade); + }); + return this.tradeHistory; + } + + getTradeHistory() { + return this.tradeHistory; + } +} + +module.exports = TradeAutomation; diff --git a/portfolio-rebalancer/user-preferences.js b/portfolio-rebalancer/user-preferences.js new file mode 100644 index 00000000..dd632ed3 --- /dev/null +++ b/portfolio-rebalancer/user-preferences.js @@ -0,0 +1,23 @@ +// user-preferences.js +// Handles user preferences for rebalancing and trading + +class UserPreferences { + constructor(userId, preferences = {}) { + this.userId = userId; + this.preferences = preferences; + } + + setPreference(key, value) { + this.preferences[key] = value; + } + + getPreference(key) { + return this.preferences[key]; + } + + getAllPreferences() { + return this.preferences; + } +} + +module.exports = UserPreferences; diff --git a/routes/compliance.js b/routes/compliance.js index 5c5af8ae..3f8b489c 100644 --- a/routes/compliance.js +++ b/routes/compliance.js @@ -5,6 +5,7 @@ const reportGenerator = require('../compliance/reportGenerator'); const scheduler = require('../compliance/scheduler'); const submissionService = require('../compliance/submissionService'); const rateLimiter = require('../adaptive/rate-limiter'); +const dlpMiddleware = require('../dlp/dlp-middleware'); function rateLimitMiddleware(req, res, next) { const userId = req.body.userId || req.ip; @@ -20,6 +21,9 @@ function rateLimitMiddleware(req, res, next) { // Apply rate limiting to all compliance routes router.use(rateLimitMiddleware); +// Apply DLP middleware to all compliance routes +router.use(dlpMiddleware); + // Generate GDPR report router.post('/gdpr', async (req, res) => { const { userId, startDate, endDate } = req.body; From 1d66145e34d181fe382768a769ece5cebe6b8249 Mon Sep 17 00:00:00 2001 From: Ayaanshaikh12243 Date: Sat, 7 Mar 2026 22:53:23 +0530 Subject: [PATCH 2/4] ISSUE-1008 --- vuln-scan/README.md | 13 ++++++++++ vuln-scan/api-integration.js | 22 +++++++++++++++++ vuln-scan/patch-deployment.js | 39 ++++++++++++++++++++++++++++++ vuln-scan/remediation-dashboard.js | 34 ++++++++++++++++++++++++++ vuln-scan/vuln-scan-ui.js | 24 ++++++++++++++++++ vuln-scan/vulnerability-scanner.js | 37 ++++++++++++++++++++++++++++ 6 files changed, 169 insertions(+) create mode 100644 vuln-scan/README.md create mode 100644 vuln-scan/api-integration.js create mode 100644 vuln-scan/patch-deployment.js create mode 100644 vuln-scan/remediation-dashboard.js create mode 100644 vuln-scan/vuln-scan-ui.js create mode 100644 vuln-scan/vulnerability-scanner.js diff --git a/vuln-scan/README.md b/vuln-scan/README.md new file mode 100644 index 00000000..7f6b7147 --- /dev/null +++ b/vuln-scan/README.md @@ -0,0 +1,13 @@ +# Continuous Vulnerability Scanning & Patch Management + +This tool automates vulnerability scanning and patch deployment for financial APIs, with dashboards for remediation tracking. + +## Modules +- vulnerability-scanner.js: Scans APIs for vulnerabilities +- patch-deployment.js: Automates patching +- remediation-dashboard.js: Tracks remediation status +- api-integration.js: Integrates scanning and reporting +- vuln-scan-ui.js: CLI demo + +## Usage +Run vuln-scan-ui.js to see a demo of the scanning and patching workflow. diff --git a/vuln-scan/api-integration.js b/vuln-scan/api-integration.js new file mode 100644 index 00000000..e32c0715 --- /dev/null +++ b/vuln-scan/api-integration.js @@ -0,0 +1,22 @@ +// api-integration.js +// Integrates API scanning and reporting for financial APIs + +const VulnerabilityScanner = require('./vulnerability-scanner'); +const PatchDeployment = require('./patch-deployment'); +const RemediationDashboard = require('./remediation-dashboard'); + +class ApiIntegration { + constructor(apiEndpoints) { + this.scanner = new VulnerabilityScanner(apiEndpoints); + this.patchDeployment = new PatchDeployment(this.scanner); + this.dashboard = new RemediationDashboard(this.scanner, this.patchDeployment); + } + + runFullScanAndPatch() { + this.scanner.scanAll(); + this.patchDeployment.deployPatches(); + return this.dashboard.generateDashboard(); + } +} + +module.exports = ApiIntegration; diff --git a/vuln-scan/patch-deployment.js b/vuln-scan/patch-deployment.js new file mode 100644 index 00000000..763111b1 --- /dev/null +++ b/vuln-scan/patch-deployment.js @@ -0,0 +1,39 @@ +// patch-deployment.js +// Automates patch deployment for detected vulnerabilities + +class PatchDeployment { + constructor(scanner) { + this.scanner = scanner; + this.patchLog = []; + } + + deployPatches() { + const results = this.scanner.getScanResults(); + results.forEach(result => { + result.vulnerabilities.forEach(vuln => { + if (!vuln.patched) { + this.applyPatch(result.endpoint, vuln); + } + }); + }); + return this.patchLog; + } + + applyPatch(endpoint, vuln) { + // Simulate patching + vuln.patched = true; + const logEntry = { + endpoint, + vulnerabilityId: vuln.id, + status: 'Patched', + timestamp: new Date() + }; + this.patchLog.push(logEntry); + } + + getPatchLog() { + return this.patchLog; + } +} + +module.exports = PatchDeployment; diff --git a/vuln-scan/remediation-dashboard.js b/vuln-scan/remediation-dashboard.js new file mode 100644 index 00000000..89d14f5a --- /dev/null +++ b/vuln-scan/remediation-dashboard.js @@ -0,0 +1,34 @@ +// remediation-dashboard.js +// Dashboard for remediation tracking and reporting + +class RemediationDashboard { + constructor(scanner, patchDeployment) { + this.scanner = scanner; + this.patchDeployment = patchDeployment; + } + + generateDashboard() { + const scanResults = this.scanner.getScanResults(); + const patchLog = this.patchDeployment.getPatchLog(); + const dashboard = scanResults.map(result => { + return { + endpoint: result.endpoint, + vulnerabilities: result.vulnerabilities.map(vuln => ({ + id: vuln.id, + severity: vuln.severity, + description: vuln.description, + patched: vuln.patched, + patchTimestamp: this.getPatchTimestamp(patchLog, result.endpoint, vuln.id) + })) + }; + }); + return dashboard; + } + + getPatchTimestamp(patchLog, endpoint, vulnId) { + const entry = patchLog.find(log => log.endpoint === endpoint && log.vulnerabilityId === vulnId); + return entry ? entry.timestamp : null; + } +} + +module.exports = RemediationDashboard; diff --git a/vuln-scan/vuln-scan-ui.js b/vuln-scan/vuln-scan-ui.js new file mode 100644 index 00000000..102d77f7 --- /dev/null +++ b/vuln-scan/vuln-scan-ui.js @@ -0,0 +1,24 @@ +// vuln-scan-ui.js +// CLI demo for Continuous Vulnerability Scanning & Patch Management + +const ApiIntegration = require('./api-integration'); + +function runVulnScanDemo() { + const apiEndpoints = [ + 'https://api.finance.com/v1/accounts', + 'https://api.finance.com/v1/transactions', + 'https://api.finance.com/v1/payments' + ]; + const apiIntegration = new ApiIntegration(apiEndpoints); + const dashboard = apiIntegration.runFullScanAndPatch(); + + console.log('--- Remediation Dashboard ---'); + dashboard.forEach(entry => { + console.log(`Endpoint: ${entry.endpoint}`); + entry.vulnerabilities.forEach(vuln => { + console.log(` - ${vuln.id} | ${vuln.severity} | ${vuln.description} | Patched: ${vuln.patched} | Patch Time: ${vuln.patchTimestamp}`); + }); + }); +} + +runVulnScanDemo(); diff --git a/vuln-scan/vulnerability-scanner.js b/vuln-scan/vulnerability-scanner.js new file mode 100644 index 00000000..bc325b40 --- /dev/null +++ b/vuln-scan/vulnerability-scanner.js @@ -0,0 +1,37 @@ +// vulnerability-scanner.js +// Continuous Vulnerability Scanning Engine +// Scans financial APIs for known vulnerabilities + +class VulnerabilityScanner { + constructor(apiEndpoints = []) { + this.apiEndpoints = apiEndpoints; + this.scanResults = []; + } + + addApiEndpoint(endpoint) { + this.apiEndpoints.push(endpoint); + } + + scanAll() { + this.scanResults = this.apiEndpoints.map(endpoint => this.scanEndpoint(endpoint)); + return this.scanResults; + } + + scanEndpoint(endpoint) { + // Simulate vulnerability scanning + const vulnerabilities = [ + { id: 'CVE-2026-1001', severity: 'High', description: 'SQL Injection', patched: false }, + { id: 'CVE-2026-1002', severity: 'Medium', description: 'Sensitive Data Exposure', patched: false } + ]; + return { + endpoint, + vulnerabilities + }; + } + + getScanResults() { + return this.scanResults; + } +} + +module.exports = VulnerabilityScanner; From 9bdc8469775fc4e2c2bfdc9675e6e56fb39f8e0b Mon Sep 17 00:00:00 2001 From: Ayaanshaikh12243 Date: Sat, 7 Mar 2026 22:57:11 +0530 Subject: [PATCH 3/4] ISSUE-1016 --- behavioral-auth/README.md | 13 ++++++ behavioral-auth/anomaly-detector.js | 34 ++++++++++++++ behavioral-auth/behavioral-auth-ui.js | 36 +++++++++++++++ .../behavioral-biometrics-engine.js | 36 +++++++++++++++ behavioral-auth/continuous-auth.js | 44 +++++++++++++++++++ behavioral-auth/session-manager.js | 33 ++++++++++++++ 6 files changed, 196 insertions(+) create mode 100644 behavioral-auth/README.md create mode 100644 behavioral-auth/anomaly-detector.js create mode 100644 behavioral-auth/behavioral-auth-ui.js create mode 100644 behavioral-auth/behavioral-biometrics-engine.js create mode 100644 behavioral-auth/continuous-auth.js create mode 100644 behavioral-auth/session-manager.js diff --git a/behavioral-auth/README.md b/behavioral-auth/README.md new file mode 100644 index 00000000..bcac3867 --- /dev/null +++ b/behavioral-auth/README.md @@ -0,0 +1,13 @@ +# Continuous Authentication Using Behavioral Biometrics + +This tool implements continuous authentication by monitoring user behavior (keystrokes, mouse movements) and triggering re-authentication or session termination on anomalies. + +## Modules +- behavioral-biometrics-engine.js: Monitors user behavior +- anomaly-detector.js: Detects anomalies +- continuous-auth.js: Integrates authentication workflow +- session-manager.js: Manages sessions +- behavioral-auth-ui.js: CLI demo + +## Usage +Run behavioral-auth-ui.js to see a demo of continuous authentication and anomaly detection. diff --git a/behavioral-auth/anomaly-detector.js b/behavioral-auth/anomaly-detector.js new file mode 100644 index 00000000..ec6bc0c7 --- /dev/null +++ b/behavioral-auth/anomaly-detector.js @@ -0,0 +1,34 @@ +// anomaly-detector.js +// Detects anomalies in user behavior for continuous authentication + +class AnomalyDetector { + constructor() { + this.keystrokeBaseline = []; + this.mouseBaseline = []; + } + + setBaseline(keystrokePatterns, mousePatterns) { + this.keystrokeBaseline = keystrokePatterns; + this.mouseBaseline = mousePatterns; + } + + detectKeystrokeAnomaly(currentPatterns) { + // Simple anomaly detection: compare length and timing + if (currentPatterns.length < this.keystrokeBaseline.length * 0.5) return true; + // Advanced: compare timing, sequence, etc. + return false; + } + + detectMouseAnomaly(currentPatterns) { + // Simple anomaly detection: compare movement frequency + if (currentPatterns.length < this.mouseBaseline.length * 0.5) return true; + // Advanced: compare speed, direction, etc. + return false; + } + + detectAnomaly(currentKeystrokes, currentMouse) { + return this.detectKeystrokeAnomaly(currentKeystrokes) || this.detectMouseAnomaly(currentMouse); + } +} + +module.exports = AnomalyDetector; diff --git a/behavioral-auth/behavioral-auth-ui.js b/behavioral-auth/behavioral-auth-ui.js new file mode 100644 index 00000000..51375496 --- /dev/null +++ b/behavioral-auth/behavioral-auth-ui.js @@ -0,0 +1,36 @@ +// behavioral-auth-ui.js +// CLI demo for Continuous Authentication Using Behavioral Biometrics + +const ContinuousAuth = require('./continuous-auth'); +const SessionManager = require('./session-manager'); + +function runBehavioralAuthDemo() { + const userId = 'user123'; + const sessionManager = new SessionManager(); + const sessionId = sessionManager.createSession(userId); + + // Baseline patterns (simulate normal user behavior) + const baselineKeystrokes = Array(20).fill().map((_, i) => ({ key: 'a', timestamp: Date.now() + i * 100 })); + const baselineMouse = Array(20).fill().map((_, i) => ({ x: i * 10, y: i * 5, timestamp: Date.now() + i * 120 })); + + const continuousAuth = new ContinuousAuth(); + continuousAuth.startSession(sessionId, baselineKeystrokes, baselineMouse); + + // Simulate normal user activity + baselineKeystrokes.forEach(event => continuousAuth.recordKeystroke(event)); + baselineMouse.forEach(event => continuousAuth.recordMouseMovement(event)); + + // Simulate anomaly (sudden drop in activity) + const anomalyKeystrokes = Array(5).fill().map((_, i) => ({ key: 'b', timestamp: Date.now() + i * 200 })); + anomalyKeystrokes.forEach(event => continuousAuth.recordKeystroke(event)); + + // Session status + if (!continuousAuth.sessionActive) { + sessionManager.terminateSession(sessionId); + console.log('Session terminated due to anomaly.'); + } else { + console.log('Session remains active.'); + } +} + +runBehavioralAuthDemo(); diff --git a/behavioral-auth/behavioral-biometrics-engine.js b/behavioral-auth/behavioral-biometrics-engine.js new file mode 100644 index 00000000..eb0a0f92 --- /dev/null +++ b/behavioral-auth/behavioral-biometrics-engine.js @@ -0,0 +1,36 @@ +// behavioral-biometrics-engine.js +// Monitors user keystrokes and mouse movements for continuous authentication + +class BehavioralBiometricsEngine { + constructor() { + this.keystrokePatterns = []; + this.mousePatterns = []; + this.sessionId = null; + } + + startSession(sessionId) { + this.sessionId = sessionId; + this.keystrokePatterns = []; + this.mousePatterns = []; + } + + recordKeystroke(event) { + // event: { key, timestamp } + this.keystrokePatterns.push(event); + } + + recordMouseMovement(event) { + // event: { x, y, timestamp } + this.mousePatterns.push(event); + } + + getKeystrokePatterns() { + return this.keystrokePatterns; + } + + getMousePatterns() { + return this.mousePatterns; + } +} + +module.exports = BehavioralBiometricsEngine; diff --git a/behavioral-auth/continuous-auth.js b/behavioral-auth/continuous-auth.js new file mode 100644 index 00000000..bf931703 --- /dev/null +++ b/behavioral-auth/continuous-auth.js @@ -0,0 +1,44 @@ +// continuous-auth.js +// Integrates behavioral biometrics and anomaly detection for continuous authentication + +const BehavioralBiometricsEngine = require('./behavioral-biometrics-engine'); +const AnomalyDetector = require('./anomaly-detector'); + +class ContinuousAuth { + constructor() { + this.engine = new BehavioralBiometricsEngine(); + this.detector = new AnomalyDetector(); + this.sessionActive = false; + } + + startSession(sessionId, baselineKeystrokes, baselineMouse) { + this.engine.startSession(sessionId); + this.detector.setBaseline(baselineKeystrokes, baselineMouse); + this.sessionActive = true; + } + + recordKeystroke(event) { + this.engine.recordKeystroke(event); + this.checkForAnomaly(); + } + + recordMouseMovement(event) { + this.engine.recordMouseMovement(event); + this.checkForAnomaly(); + } + + checkForAnomaly() { + const keystrokes = this.engine.getKeystrokePatterns(); + const mouse = this.engine.getMousePatterns(); + if (this.detector.detectAnomaly(keystrokes, mouse)) { + this.triggerReauthentication(); + } + } + + triggerReauthentication() { + this.sessionActive = false; + console.log('Anomaly detected! Triggering re-authentication or session termination.'); + } +} + +module.exports = ContinuousAuth; diff --git a/behavioral-auth/session-manager.js b/behavioral-auth/session-manager.js new file mode 100644 index 00000000..be665453 --- /dev/null +++ b/behavioral-auth/session-manager.js @@ -0,0 +1,33 @@ +// session-manager.js +// Manages user sessions and handles re-authentication + +class SessionManager { + constructor() { + this.sessions = {}; + } + + createSession(userId) { + const sessionId = `${userId}-${Date.now()}`; + this.sessions[sessionId] = { userId, active: true }; + return sessionId; + } + + terminateSession(sessionId) { + if (this.sessions[sessionId]) { + this.sessions[sessionId].active = false; + } + } + + isSessionActive(sessionId) { + return this.sessions[sessionId] && this.sessions[sessionId].active; + } + + reauthenticate(sessionId) { + if (this.sessions[sessionId]) { + this.sessions[sessionId].active = true; + console.log(`Session ${sessionId} re-authenticated.`); + } + } +} + +module.exports = SessionManager; From 1c8e3bd23f9ef69f61f6a4b3d5a348ccc17c7e2c Mon Sep 17 00:00:00 2001 From: Ayaanshaikh12243 Date: Sat, 7 Mar 2026 23:02:01 +0530 Subject: [PATCH 4/4] ISSUE-1017 --- thirdparty-risk/README.md | 13 +++++ thirdparty-risk/compliance-evaluator.js | 19 +++++++ thirdparty-risk/data-access-risk-checker.js | 19 +++++++ thirdparty-risk/risk-assessment-engine.js | 50 +++++++++++++++++++ thirdparty-risk/risk-reporting-ui.js | 52 ++++++++++++++++++++ thirdparty-risk/security-posture-analyzer.js | 19 +++++++ 6 files changed, 172 insertions(+) create mode 100644 thirdparty-risk/README.md create mode 100644 thirdparty-risk/compliance-evaluator.js create mode 100644 thirdparty-risk/data-access-risk-checker.js create mode 100644 thirdparty-risk/risk-assessment-engine.js create mode 100644 thirdparty-risk/risk-reporting-ui.js create mode 100644 thirdparty-risk/security-posture-analyzer.js diff --git a/thirdparty-risk/README.md b/thirdparty-risk/README.md new file mode 100644 index 00000000..365390b9 --- /dev/null +++ b/thirdparty-risk/README.md @@ -0,0 +1,13 @@ +# Automated Third-Party Risk Assessment + +This module automatically assesses third-party integrations for compliance, security posture, and data access risks. + +## Modules +- risk-assessment-engine.js: Core assessment engine +- compliance-evaluator.js: Compliance checks +- security-posture-analyzer.js: Security posture analysis +- data-access-risk-checker.js: Data access risk evaluation +- risk-reporting-ui.js: CLI dashboard demo + +## Usage +Run risk-reporting-ui.js to see a demo of the risk assessment dashboard. diff --git a/thirdparty-risk/compliance-evaluator.js b/thirdparty-risk/compliance-evaluator.js new file mode 100644 index 00000000..37d89dc1 --- /dev/null +++ b/thirdparty-risk/compliance-evaluator.js @@ -0,0 +1,19 @@ +// compliance-evaluator.js +// Evaluates third-party integrations for compliance + +class ComplianceEvaluator { + constructor() {} + + evaluate(integration) { + // Check for certifications, policies, audits + if (integration.complianceCerts && integration.complianceCerts.includes('ISO27001')) { + return 'Compliant'; + } + if (integration.complianceCerts && integration.complianceCerts.includes('SOC2')) { + return 'Compliant'; + } + return 'Non-Compliant'; + } +} + +module.exports = ComplianceEvaluator; diff --git a/thirdparty-risk/data-access-risk-checker.js b/thirdparty-risk/data-access-risk-checker.js new file mode 100644 index 00000000..4549c070 --- /dev/null +++ b/thirdparty-risk/data-access-risk-checker.js @@ -0,0 +1,19 @@ +// data-access-risk-checker.js +// Checks data access risks for third-party integrations + +class DataAccessRiskChecker { + constructor() {} + + check(integration) { + // Evaluate scope of data access + if (integration.dataAccess === 'minimal') { + return 'Low'; + } + if (integration.dataAccess === 'moderate') { + return 'Medium'; + } + return 'High'; + } +} + +module.exports = DataAccessRiskChecker; diff --git a/thirdparty-risk/risk-assessment-engine.js b/thirdparty-risk/risk-assessment-engine.js new file mode 100644 index 00000000..a624cc45 --- /dev/null +++ b/thirdparty-risk/risk-assessment-engine.js @@ -0,0 +1,50 @@ +// risk-assessment-engine.js +// Automated Third-Party Risk Assessment Engine +// Assesses integrations for compliance, security posture, and data access risks + +class RiskAssessmentEngine { + constructor(integrations = []) { + this.integrations = integrations; + this.assessmentResults = []; + } + + addIntegration(integration) { + this.integrations.push(integration); + } + + assessAll() { + this.assessmentResults = this.integrations.map(integration => this.assessIntegration(integration)); + return this.assessmentResults; + } + + assessIntegration(integration) { + // Simulate assessment + return { + name: integration.name, + compliance: this.evaluateCompliance(integration), + securityPosture: this.analyzeSecurityPosture(integration), + dataAccessRisk: this.checkDataAccessRisk(integration) + }; + } + + evaluateCompliance(integration) { + // Placeholder: Check for certifications, policies + return integration.complianceCerts && integration.complianceCerts.length > 0 ? 'Compliant' : 'Non-Compliant'; + } + + analyzeSecurityPosture(integration) { + // Placeholder: Analyze security features + return integration.securityFeatures && integration.securityFeatures.includes('encryption') ? 'Strong' : 'Weak'; + } + + checkDataAccessRisk(integration) { + // Placeholder: Evaluate data access scope + return integration.dataAccess && integration.dataAccess === 'minimal' ? 'Low' : 'High'; + } + + getAssessmentResults() { + return this.assessmentResults; + } +} + +module.exports = RiskAssessmentEngine; diff --git a/thirdparty-risk/risk-reporting-ui.js b/thirdparty-risk/risk-reporting-ui.js new file mode 100644 index 00000000..17067293 --- /dev/null +++ b/thirdparty-risk/risk-reporting-ui.js @@ -0,0 +1,52 @@ +// risk-reporting-ui.js +// CLI dashboard for Automated Third-Party Risk Assessment + +const RiskAssessmentEngine = require('./risk-assessment-engine'); +const ComplianceEvaluator = require('./compliance-evaluator'); +const SecurityPostureAnalyzer = require('./security-posture-analyzer'); +const DataAccessRiskChecker = require('./data-access-risk-checker'); + +function runRiskAssessmentDemo() { + const integrations = [ + { + name: 'VendorA', + complianceCerts: ['ISO27001'], + securityFeatures: ['encryption', 'MFA'], + dataAccess: 'minimal' + }, + { + name: 'VendorB', + complianceCerts: [], + securityFeatures: ['encryption'], + dataAccess: 'moderate' + }, + { + name: 'VendorC', + complianceCerts: ['SOC2'], + securityFeatures: [], + dataAccess: 'extensive' + } + ]; + + const complianceEvaluator = new ComplianceEvaluator(); + const securityAnalyzer = new SecurityPostureAnalyzer(); + const dataRiskChecker = new DataAccessRiskChecker(); + + const engine = new RiskAssessmentEngine(integrations); + engine.integrations.forEach(integration => { + integration.compliance = complianceEvaluator.evaluate(integration); + integration.securityPosture = securityAnalyzer.analyze(integration); + integration.dataAccessRisk = dataRiskChecker.check(integration); + }); + const results = engine.assessAll(); + + console.log('--- Third-Party Risk Assessment Dashboard ---'); + results.forEach(result => { + console.log(`Integration: ${result.name}`); + console.log(` Compliance: ${result.compliance}`); + console.log(` Security Posture: ${result.securityPosture}`); + console.log(` Data Access Risk: ${result.dataAccessRisk}`); + }); +} + +runRiskAssessmentDemo(); diff --git a/thirdparty-risk/security-posture-analyzer.js b/thirdparty-risk/security-posture-analyzer.js new file mode 100644 index 00000000..d6bd4083 --- /dev/null +++ b/thirdparty-risk/security-posture-analyzer.js @@ -0,0 +1,19 @@ +// security-posture-analyzer.js +// Analyzes security posture of third-party integrations + +class SecurityPostureAnalyzer { + constructor() {} + + analyze(integration) { + // Check for encryption, MFA, vulnerability management + if (integration.securityFeatures && integration.securityFeatures.includes('encryption') && integration.securityFeatures.includes('MFA')) { + return 'Strong'; + } + if (integration.securityFeatures && integration.securityFeatures.includes('encryption')) { + return 'Moderate'; + } + return 'Weak'; + } +} + +module.exports = SecurityPostureAnalyzer;