Détection d'anomalies et prévention des fraudes en temps réel
🤖 Comment l'IA Protège les Transactions NFC
Les systèmes d'IA peuvent analyser en temps réel des millions de transactions NFC pour:
• Détecter des patterns anormaux (relay attacks, clonage)
• Identifier des comportements suspects
• Bloquer automatiquement les tentatives de fraude
• Apprendre continuellement de nouvelles menaces
Transactions Total
0
Légitimes
0
Suspectes
0
Bloquées
0
📊 MONITEUR DE TRANSACTIONS EN TEMPS RÉEL
🧠 Modèle 1: Isolation Forest
Usage: Détection d'anomalies
Accuracy: 94.7%
False Positives: 0.8%
Temps d'inférence: 2ms
🎯 Modèle 2: LSTM
Usage: Analyse séquentielle
Accuracy: 96.3%
False Positives: 0.5%
Temps d'inférence: 5ms
🔍 Modèle 3: Random Forest
Usage: Classification
Accuracy: 97.1%
False Positives: 0.3%
Temps d'inférence: 3ms
💻 Architecture de Défense IA
INPUT LAYER
UID
LAT
LOC
€
⏰
→
HIDDEN LAYERS
128
64
32
→
OUTPUT
✓
⚠
✗
// ai-defense.js - Système de Défense par IA
class NFCFraudDetectionSystem {
constructor() {
// Ensemble de modèles (ensemble learning)
this.models = {
isolationForest: this.loadIsolationForest(),
lstm: this.loadLSTMModel(),
randomForest: this.loadRandomForest()
};
// Historique pour l'analyse comportementale
this.transactionHistory = [];
this.userProfiles = new Map();
}
async analyzeTransaction(transaction) {
console.log('🔍 Analyse de la transaction:', transaction.id);
// Extraction des features
const features = this.extractFeatures(transaction);
// Analyse par chaque modèle
const predictions = await Promise.all([
this.models.isolationForest.predict(features),
this.models.lstm.predict(this.getSequence(transaction)),
this.models.randomForest.predict(features)
]);
// Vote majoritaire pondéré
const finalScore = this.ensembleVoting(predictions);
// Analyse comportementale
const behaviorScore = this.analyzeBehavior(transaction);
// Score final
const riskScore = (finalScore * 0.7) + (behaviorScore * 0.3);
return {
riskScore: riskScore,
verdict: this.getVerdict(riskScore),
details: this.getAnalysisDetails(predictions, behaviorScore)
};
}
extractFeatures(tx) {
return {
// Features temporelles
hour: new Date(tx.timestamp).getHours(),
dayOfWeek: new Date(tx.timestamp).getDay(),
timeSinceLastTx: this.getTimeSinceLastTransaction(tx.uid),
// Features de transaction
amount: tx.amount,
amountNormalized: this.normalizeAmount(tx.amount),
// Features de carte
uid: tx.uid,
uidEntropy: this.calculateEntropy(tx.uid),
// Features de communication
latency: tx.latency,
signalStrength: tx.rssi,
// Features géographiques
latitude: tx.location.lat,
longitude: tx.location.lon,
distanceFromLastTx: this.calculateDistance(tx),
// Features de séquence
txVelocity: this.calculateVelocity(tx.uid),
consecutiveTx: this.getConsecutiveTxCount(tx.uid)
};
}
analyzeBehavior(tx) {
const profile = this.userProfiles.get(tx.uid) || this.createProfile(tx.uid);
// Détection d'anomalies comportementales
const anomalies = {
// Localisation inhabituelle
unusualLocation: this.isUnusualLocation(tx, profile),
// Montant inhabituel
unusualAmount: this.isUnusualAmount(tx, profile),
// Heure inhabituelle
unusualTime: this.isUnusualTime(tx, profile),
// Fréquence inhabituelle
unusualFrequency: this.isUnusualFrequency(tx, profile),
// Impossible travel (vitesse > vitesse possible)
impossibleTravel: this.detectImpossibleTravel(tx, profile)
};
// Calcul du score comportemental
const anomalyCount = Object.values(anomalies).filter(a => a).length;
return anomalyCount / Object.keys(anomalies).length;
}
detectImpossibleTravel(tx, profile) {
if (!profile.lastTransaction) return false;
const lastTx = profile.lastTransaction;
const distance = this.calculateDistance(tx, lastTx); // en km
const timeDiff = (tx.timestamp - lastTx.timestamp) / 1000 / 60; // en minutes
// Vitesse en km/h
const speed = (distance / timeDiff) * 60;
// Vitesse maximale réaliste (avion): 900 km/h
const MAX_SPEED = 900;
if (speed > MAX_SPEED) {
console.log(`⚠️ IMPOSSIBLE TRAVEL: ${speed.toFixed(0)} km/h`);
return true;
}
return false;
}
async detectRelayAttack(tx) {
// Détection de relay attack par analyse de latence
const baselineLatency = 15; // ms (latence normale NFC)
const threshold = 50; // ms
if (tx.latency > threshold) {
console.log(`⚠️ RELAY ATTACK SUSPECTÉ: latence ${tx.latency}ms`);
return {
detected: true,
confidence: Math.min((tx.latency / threshold) * 100, 100),
reason: 'Latence anormale détectée'
};
}
// Analyse du pattern de communication
const commPattern = this.analyzeCommPattern(tx.nfcTrace);
if (commPattern.anomalyScore > 0.7) {
return {
detected: true,
confidence: commPattern.anomalyScore * 100,
reason: 'Pattern de communication suspect'
};
}
return { detected: false };
}
async detectCloning(tx) {
// Détection de clonage de carte
const uid = tx.uid;
// Vérifier les transactions simultanées
const recentTx = this.getRecentTransactions(uid, 60000); // 1 minute
if (recentTx.length > 1) {
const locations = recentTx.map(t => t.location);
const distances = this.calculateDistances(locations);
// Si 2 transactions avec la même carte à >10km en <1min
if (Math.max(...distances) > 10) {
return {
detected: true,
confidence: 95,
reason: 'Transactions simultanées dans des lieux distants'
};
}
}
// Analyse de l'entropie de l'UID
if (this.calculateEntropy(uid) < 3) {
return {
detected: true,
confidence: 70,
reason: 'UID suspect (faible entropie)'
};
}
return { detected: false };
}
getVerdict(riskScore) {
if (riskScore < 0.3) {
return { status: 'APPROVED', color: 'success', action: 'allow' };
} else if (riskScore < 0.7) {
return { status: 'REVIEW', color: 'warning', action: 'review' };
} else {
return { status: 'BLOCKED', color: 'danger', action: 'block' };
}
}
// Mise à jour du profil utilisateur (apprentissage continu)
updateProfile(uid, transaction, verdict) {
let profile = this.userProfiles.get(uid) || {
transactions: [],
locations: [],
amounts: [],
hours: []
};
if (verdict.status === 'APPROVED') {
profile.transactions.push(transaction);
profile.locations.push(transaction.location);
profile.amounts.push(transaction.amount);
profile.hours.push(new Date(transaction.timestamp).getHours());
profile.lastTransaction = transaction;
this.userProfiles.set(uid, profile);
}
}
}
// Utilisation en production
const fraudDetector = new NFCFraudDetectionSystem();
// Webhook pour chaque transaction NFC
app.post('/nfc/transaction', async (req, res) => {
const transaction = req.body;
// Analyse par IA
const analysis = await fraudDetector.analyzeTransaction(transaction);
// Détections spécifiques
const relayAttack = await fraudDetector.detectRelayAttack(transaction);
const cloning = await fraudDetector.detectCloning(transaction);
if (analysis.verdict.action === 'block' || relayAttack.detected || cloning.detected) {
// Blocage de la transaction
await blockTransaction(transaction);
// Alerte de sécurité
await sendSecurityAlert({
transaction: transaction,
reason: analysis.details,
relayAttack: relayAttack,
cloning: cloning
});
return res.status(403).json({
approved: false,
reason: 'Transaction bloquée pour raisons de sécurité'
});
}
// Mise à jour du profil
fraudDetector.updateProfile(transaction.uid, transaction, analysis.verdict);
return res.status(200).json({
approved: true,
riskScore: analysis.riskScore
});
});