Files
impersonator/utils/monitoring.ts

175 lines
4.1 KiB
TypeScript
Raw Permalink Normal View History

feat: comprehensive project improvements and fixes - Fix all TypeScript compilation errors (40+ fixes) - Add missing type definitions (TransactionRequest, SafeInfo) - Fix TransactionRequestStatus vs TransactionStatus confusion - Fix import paths and provider type issues - Fix test file errors and mock providers - Implement comprehensive security features - AES-GCM encryption with PBKDF2 key derivation - Input validation and sanitization - Rate limiting and nonce management - Replay attack prevention - Access control and authorization - Add comprehensive test suite - Integration tests for transaction flow - Security validation tests - Wallet management tests - Encryption and rate limiter tests - E2E tests with Playwright - Add extensive documentation - 12 numbered guides (setup, development, API, security, etc.) - Security documentation and audit reports - Code review and testing reports - Project organization documentation - Update dependencies - Update axios to latest version (security fix) - Update React types to v18 - Fix peer dependency warnings - Add development tooling - CI/CD workflows (GitHub Actions) - Pre-commit hooks (Husky) - Linting and formatting (Prettier, ESLint) - Security audit workflow - Performance benchmarking - Reorganize project structure - Move reports to docs/reports/ - Clean up root directory - Organize documentation - Add new features - Smart wallet management (Gnosis Safe, ERC4337) - Transaction execution and approval workflows - Balance management and token support - Error boundary and monitoring (Sentry) - Fix WalletConnect configuration - Handle missing projectId gracefully - Add environment variable template
2026-01-14 02:17:26 -08:00
/**
* Monitoring and error tracking utilities
* Provides centralized logging and error reporting
*/
export enum LogLevel {
DEBUG = "debug",
INFO = "info",
WARN = "warn",
ERROR = "error",
}
export interface LogEntry {
level: LogLevel;
message: string;
timestamp: number;
context?: Record<string, any>;
error?: Error;
}
class MonitoringService {
private logs: LogEntry[] = [];
private maxLogs = 1000;
private errorTrackingEnabled = false;
private errorTrackingService?: any; // Sentry or similar
/**
* Initialize error tracking service
* @param service - Error tracking service (e.g., Sentry)
*/
initErrorTracking(service: any): void {
this.errorTrackingService = service;
this.errorTrackingEnabled = true;
}
/**
* Log a message
*/
log(level: LogLevel, message: string, context?: Record<string, any>, error?: Error): void {
const entry: LogEntry = {
level,
message,
timestamp: Date.now(),
context,
error,
};
// Add to local logs
this.logs.push(entry);
if (this.logs.length > this.maxLogs) {
this.logs.shift(); // Remove oldest
}
// Console logging
const logMethod = console[level] || console.log;
if (error) {
logMethod(`[${level.toUpperCase()}] ${message}`, context, error);
} else {
logMethod(`[${level.toUpperCase()}] ${message}`, context);
}
// Send to error tracking service
if (this.errorTrackingEnabled && level === LogLevel.ERROR && this.errorTrackingService) {
try {
if (error) {
this.errorTrackingService.captureException(error, { extra: context });
} else {
this.errorTrackingService.captureMessage(message, { level, extra: context });
}
} catch (e) {
console.error("Failed to send error to tracking service:", e);
}
}
}
/**
* Log debug message
*/
debug(message: string, context?: Record<string, any>): void {
this.log(LogLevel.DEBUG, message, context);
}
/**
* Log info message
*/
info(message: string, context?: Record<string, any>): void {
this.log(LogLevel.INFO, message, context);
}
/**
* Log warning message
*/
warn(message: string, context?: Record<string, any>): void {
this.log(LogLevel.WARN, message, context);
}
/**
* Log error message
*/
error(message: string, error?: Error, context?: Record<string, any>): void {
this.log(LogLevel.ERROR, message, context, error);
}
/**
* Get recent logs
*/
getLogs(level?: LogLevel, limit?: number): LogEntry[] {
let filtered = this.logs;
if (level) {
filtered = filtered.filter(log => log.level === level);
}
if (limit) {
filtered = filtered.slice(-limit);
}
return filtered;
}
/**
* Clear logs
*/
clearLogs(): void {
this.logs = [];
}
/**
* Track security event
*/
trackSecurityEvent(event: string, details: Record<string, any>): void {
this.warn(`Security Event: ${event}`, details);
// In production, send to security monitoring service
if (process.env.NODE_ENV === "production") {
// Example: sendToSecurityMonitoring(event, details);
}
}
/**
* Track rate limit hit
*/
trackRateLimit(key: string): void {
this.warn("Rate limit exceeded", { key, timestamp: Date.now() });
}
/**
* Track validation failure
*/
trackValidationFailure(field: string, value: any, reason: string): void {
this.warn("Validation failed", { field, value, reason });
}
/**
* Track encryption failure
*/
trackEncryptionFailure(operation: string, error: Error): void {
this.error(`Encryption failure: ${operation}`, error);
}
/**
* Track transaction event
*/
trackTransaction(event: string, txId: string, details?: Record<string, any>): void {
this.info(`Transaction ${event}`, { txId, ...details });
}
}
// Singleton instance
export const monitoring = new MonitoringService();
// Initialize in production
if (typeof window !== "undefined" && process.env.NODE_ENV === "production") {
// Example: Initialize Sentry
// import * as Sentry from "@sentry/nextjs";
// monitoring.initErrorTracking(Sentry);
}