xypriss-security
Version:
XyPriss Security is an advanced JavaScript security library designed for enterprise applications. It provides military-grade encryption, secure data structures, quantum-resistant cryptography, and comprehensive security utilities for modern web applicatio
232 lines (230 loc) • 7.1 kB
JavaScript
/**
* Key Derivation Logger
* Professional logging system for key derivation operations
*/
/**
* Log levels for key derivation operations
*/
var LogLevel;
(function (LogLevel) {
LogLevel["DEBUG"] = "debug";
LogLevel["INFO"] = "info";
LogLevel["WARN"] = "warn";
LogLevel["ERROR"] = "error";
})(LogLevel || (LogLevel = {}));
/**
* Performance-optimized logger for key derivation operations
*/
class KeyDerivationLogger {
constructor(config) {
this.logEntries = [];
this.metricsBuffer = [];
this.config = {
enabled: process.env.NODE_ENV === "development",
level: "info",
includeMetrics: true,
includeStackTrace: false,
maxLogEntries: 1000,
...config
};
}
/**
* Get singleton instance
*/
static getInstance(config) {
if (!KeyDerivationLogger.instance) {
KeyDerivationLogger.instance = new KeyDerivationLogger(config);
}
else if (config) {
KeyDerivationLogger.instance.updateConfig(config);
}
return KeyDerivationLogger.instance;
}
/**
* Update logger configuration
*/
updateConfig(config) {
this.config = { ...this.config, ...config };
}
/**
* Check if logging is enabled for a specific level
*/
shouldLog(level) {
if (!this.config.enabled)
return false;
const levels = ["debug", "info", "warn", "error"];
const currentLevelIndex = levels.indexOf(this.config.level);
const requestedLevelIndex = levels.indexOf(level);
return requestedLevelIndex >= currentLevelIndex;
}
/**
* Add log entry to buffer
*/
addLogEntry(level, component, message, data, metrics) {
if (!this.shouldLog(level))
return;
const entry = {
timestamp: Date.now(),
level,
component,
message,
data,
metrics: this.config.includeMetrics ? metrics : undefined,
stackTrace: this.config.includeStackTrace ? new Error().stack : undefined
};
this.logEntries.push(entry);
// Maintain buffer size
if (this.logEntries.length > this.config.maxLogEntries) {
this.logEntries.shift();
}
// Output to console in development
if (process.env.NODE_ENV === "development") {
this.outputToConsole(entry);
}
}
/**
* Output log entry to console with formatting
*/
outputToConsole(entry) {
const timestamp = new Date(entry.timestamp).toISOString();
const prefix = `[${timestamp}] [Keys:${entry.component}]`;
const message = `${prefix} ${entry.message}`;
switch (entry.level) {
case LogLevel.DEBUG:
console.debug(message, entry.data || "");
break;
case LogLevel.INFO:
console.info(message, entry.data || "");
break;
case LogLevel.WARN:
console.warn(message, entry.data || "");
break;
case LogLevel.ERROR:
console.error(message, entry.data || "");
break;
}
// Log metrics if available
if (entry.metrics && this.config.includeMetrics) {
console.debug(`${prefix} Metrics:`, {
algorithm: entry.metrics.algorithm,
backend: entry.metrics.backend,
executionTime: `${entry.metrics.executionTime}ms`,
memoryUsage: `${Math.round(entry.metrics.memoryUsage / 1024)}KB`,
success: entry.metrics.success
});
}
}
/**
* Log debug message
*/
debug(component, message, data) {
this.addLogEntry(LogLevel.DEBUG, component, message, data);
}
/**
* Log info message
*/
info(component, message, data) {
this.addLogEntry(LogLevel.INFO, component, message, data);
}
/**
* Log warning message
*/
warn(component, message, data) {
this.addLogEntry(LogLevel.WARN, component, message, data);
}
/**
* Log error message
*/
error(component, message, error) {
this.addLogEntry(LogLevel.ERROR, component, message, error);
}
/**
* Log algorithm fallback
*/
logFallback(fromAlgorithm, toAlgorithm, reason) {
this.warn("Fallback", `Algorithm fallback: ${fromAlgorithm} → ${toAlgorithm}`, { reason });
}
/**
* Log performance metrics
*/
logMetrics(metrics) {
this.metricsBuffer.push(metrics);
if (metrics.success) {
this.debug("Performance", `Key derivation completed`, {
algorithm: metrics.algorithm,
backend: metrics.backend,
time: `${metrics.executionTime}ms`,
memory: `${Math.round(metrics.memoryUsage / 1024)}KB`
});
}
else {
this.error("Performance", `Key derivation failed`, {
algorithm: metrics.algorithm,
backend: metrics.backend,
error: metrics.errorMessage
});
}
}
/**
* Log algorithm selection
*/
logAlgorithmSelection(algorithm, backend, reason) {
this.debug("Selection", `Selected algorithm: ${algorithm} with backend: ${backend}`, { reason });
}
/**
* Log environment detection
*/
logEnvironmentDetection(environment, capabilities) {
this.info("Environment", `Detected environment: ${environment}`, capabilities);
}
/**
* Get recent log entries
*/
getLogEntries(count) {
const entries = this.logEntries.slice();
return count ? entries.slice(-count) : entries;
}
/**
* Get performance metrics
*/
getMetrics() {
return this.metricsBuffer.slice();
}
/**
* Clear log entries and metrics
*/
clear() {
this.logEntries.length = 0;
this.metricsBuffer.length = 0;
}
/**
* Get logger statistics
*/
getStats() {
const entriesByLevel = {
[LogLevel.DEBUG]: 0,
[LogLevel.INFO]: 0,
[LogLevel.WARN]: 0,
[LogLevel.ERROR]: 0
};
this.logEntries.forEach(entry => {
entriesByLevel[entry.level]++;
});
const successfulMetrics = this.metricsBuffer.filter(m => m.success);
const averageExecutionTime = successfulMetrics.length > 0
? successfulMetrics.reduce((sum, m) => sum + m.executionTime, 0) / successfulMetrics.length
: 0;
return {
totalEntries: this.logEntries.length,
entriesByLevel,
metricsCount: this.metricsBuffer.length,
averageExecutionTime
};
}
}
/**
* Global logger instance
*/
const keyLogger = KeyDerivationLogger.getInstance();
export { KeyDerivationLogger, LogLevel, keyLogger };
//# sourceMappingURL=keys-logger.js.map