feat(logging): hash IP addresses in logs and Sentry integration
- Implemented IP hashing using SHA256 in logs for enhanced privacy. - Updated Sentry integration to hash IP addresses before sending events. - Enhanced `AllExceptionsFilter` and `crawler-detection.middleware` to use hashed IPs in logs and error handling. - Refined request logging in `auth.service` to include hashed email instead of plain text email.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||
import { Inject, Injectable, Logger, NestMiddleware } from "@nestjs/common";
|
||||
import type { Cache } from "cache-manager";
|
||||
import { createHash } from "node:crypto";
|
||||
import type { NextFunction, Request, Response } from "express";
|
||||
|
||||
@Injectable()
|
||||
@@ -48,11 +49,15 @@ export class CrawlerDetectionMiddleware implements NestMiddleware {
|
||||
const { method, url, ip } = req;
|
||||
const userAgent = req.get("user-agent") || "unknown";
|
||||
|
||||
const hashedIp = createHash("sha256")
|
||||
.update(ip as string)
|
||||
.digest("hex");
|
||||
|
||||
// Vérifier si l'IP est bannie
|
||||
try {
|
||||
const isBanned = await this.cacheManager.get(`banned_ip:${ip}`);
|
||||
if (isBanned) {
|
||||
this.logger.warn(`Banned IP attempt: ${ip} -> ${method} ${url}`);
|
||||
this.logger.warn(`Banned IP attempt: ${hashedIp} -> ${method} ${url}`);
|
||||
res.status(403).json({
|
||||
message: "Access denied: Your IP has been temporarily banned.",
|
||||
});
|
||||
@@ -60,7 +65,7 @@ export class CrawlerDetectionMiddleware implements NestMiddleware {
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Error checking ban status for IP ${ip}: ${error.message}`,
|
||||
`Error checking ban status for IP ${hashedIp}: ${error.message}`,
|
||||
);
|
||||
// On continue même en cas d'erreur Redis pour ne pas bloquer les utilisateurs légitimes
|
||||
}
|
||||
@@ -76,14 +81,14 @@ export class CrawlerDetectionMiddleware implements NestMiddleware {
|
||||
|
||||
if (isSuspiciousPath || isBotUserAgent) {
|
||||
this.logger.warn(
|
||||
`Potential crawler detected: [${ip}] ${method} ${url} - User-Agent: ${userAgent}`,
|
||||
`Potential crawler detected: [${hashedIp}] ${method} ${url} - User-Agent: ${userAgent}`,
|
||||
);
|
||||
|
||||
// Bannir l'IP pour 24h via Redis
|
||||
try {
|
||||
await this.cacheManager.set(`banned_ip:${ip}`, true, 86400000);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error banning IP ${ip}: ${error.message}`);
|
||||
this.logger.error(`Error banning IP ${hashedIp}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user