@finite-logic/quantum-rate
Version:
FINITE LOGIC: QuantumRate - Basic Time Series Anomaly Detection Model (Free Tier) Focus: API Security & Anomaly Detection
100 lines (83 loc) • 3.69 kB
JavaScript
/**
* FINITE LOGIC - QuantumRate: API Attack Mitigation (Z-Score Anomaly Detector)
* Tracks request rates and flags statistically significant deviations.
*/
// Simple circular buffer to store recent request counts for a user/IP
class RequestTracker {
constructor(windowSize = 60) {
this.window = new Array(windowSize).fill(0); // e.g., 60 seconds of data
this.index = 0;
}
// Records a hit for the current time slice and advances
hit() {
this.index = (this.index + 1) % this.window.length;
this.window[this.index] = 1; // Mark current slice as active
}
// Calculates the total requests in the window
getRate() {
return this.window.reduce((sum, val) => sum + val, 0);
}
// Resets and prepares the window for the next sampling period (e.g., next second)
advanceWindow() {
// Reset the oldest element before advancing index
this.window[this.index] = 0;
}
}
class AnomalyDetector {
constructor(ip, windowSize = 60) {
this.ip = ip;
this.tracker = new RequestTracker(windowSize);
this.history = []; // Stores recent rate samples
this.limitZScore = 2.5; // Threshold for anomaly (e.g., 2.5 standard deviations)
}
// Simplified calculation of mean (average) and standard deviation
_getStats() {
if (this.history.length < 10) return { mean: 0, stdDev: 1 }; // Need enough data to be significant
const mean = this.history.reduce((a, b) => a + b) / this.history.length;
const variance = this.history.reduce((sum, rate) => sum + Math.pow(rate - mean, 2), 0) / this.history.length;
return { mean, stdDev: Math.sqrt(variance) };
}
// Simulates a tick (e.g., every second) to update the history
sampleRate() {
const currentRate = this.tracker.getRate();
this.history.push(currentRate);
if (this.history.length > 100) this.history.shift(); // Keep history window finite
this.tracker.advanceWindow();
}
/**
* Checks if the current request rate is a statistical anomaly (DoS or abuse).
* @returns {boolean} True if the current rate exceeds the Z-Score threshold.
*/
checkAnomaly(currentRate) {
const { mean, stdDev } = this._getStats();
if (stdDev < 1 || mean === 0) {
return false; // Not enough variance or data to calculate Z-Score reliably
}
const zScore = (currentRate - mean) / stdDev;
if (zScore > this.limitZScore) {
console.warn(`[QuantumRate] 🚨 ANOMALY DETECTED for ${this.ip}: Z-Score ${zScore.toFixed(2)} > ${this.limitZScore}`);
return true;
}
return false;
}
}
// --- Demonstration ---
const detector = new AnomalyDetector('203.0.113.42');
console.log('--- QuantumRate: Z-Score Anomaly Detection ---');
// Phase 1: Normal Traffic (Runs for 15 "seconds")
console.log('\n[Phase 1] Normal, consistent traffic (Rate ≈ 5)');
for (let i = 0; i < 15; i++) {
// Simulate 5 hits per second
for (let j = 0; j < 5; j++) detector.tracker.hit();
detector.sampleRate();
detector.checkAnomaly(detector.tracker.getRate());
}
// Phase 2: Simulating Slow-Burn Attack (Spike to Rate ≈ 15)
console.log('\n[Phase 2] Slow-burn spike (3x normal rate)');
for (let i = 0; i < 5; i++) {
// Simulate 15 hits per second (high deviation)
for (let j = 0; j < 15; j++) detector.tracker.hit();
detector.sampleRate();
detector.checkAnomaly(detector.tracker.getRate());
}
module.exports = { AnomalyDetector };