import { RequestHandler } from 'express';
import { RateLimiter } from './rate-limiter';
import { ThreatIntelligence } from './threat-intel';
class AISecurityGateway {
private threatIntel: ThreatIntelligence;
private rateLimiter: RateLimiter;
middleware(): RequestHandler {
return async (req, res, next) => {
// Analiza zagrożeń napędzana przez AI
const threatScore = await this.analyzeThreatLevel(req);
return res.status(403).json({ error: 'Wykryto podejrzaną aktywność' });
// Adaptacyjne ograniczanie szybkości
const rateLimit = await this.calculateRateLimit(req, threatScore);
if (!await this.rateLimiter.check(req, rateLimit)) {
return res.status(429).json({ error: 'Przekroczono limit szybkości' });
// Walidacja wejścia z AI
await this.validateInput(req);
// Dodaj nagłówki bezpieczeństwa
this.addSecurityHeaders(res, threatScore);
this.handleSecurityError(error, res);
private async analyzeThreatLevel(req: any): Promise<number> {
userAgent: req.headers['user-agent'],
geoLocation: await this.getGeoLocation(req.ip),
timeOfDay: new Date().getHours(),
requestPattern: await this.getRequestPattern(req)
// Sprawdź inteligencję zagrożeń
const threatData = await this.threatIntel.check(features.ip);
const aiScore = await this.calculateAIThreatScore(features, threatData);
// Loguj do ciągłego uczenia
await this.logThreatAnalysis(features, aiScore);
private async validateInput(req: any) {
// Dynamiczne generowanie schematów na podstawie endpoint'u
const schema = await this.generateValidationSchema(req.path, req.method);
// Walidacja wzbogacona AI
const validationResult = await this.aiValidate(req.body, schema);
if (!validationResult.success) {
throw new SecurityError('Wykryto nieprawidłowe dane wejściowe', validationResult.errors);
async protectAgainstInjection(input: string): Promise<string> {
// Wykrywanie wstrzyknięć oparte na AI
const injectionPatterns = await this.detectInjectionPatterns(input);
if (injectionPatterns.length > 0) {
throw new SecurityError('Wykryto próbę wstrzyknięcia', injectionPatterns);
// Generowanie zapytań parametryzowanych
return this.sanitizeForQuery(input);
async preventXSS(content: string): Promise<string> {
// Kontekstowa ochrona przed XSS
const context = await this.detectRenderContext(content);
return this.escapeHTML(content);
return this.escapeJS(content);
return this.escapeCSS(content);
return this.escapeURL(content);
return this.escapeAll(content);