Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

checkpoint: File edit:

rUve0098d926cd3
diff --git a/v3/@claude-flow/security/src/credential-generator.ts b/v3/@claude-flow/security/src/credential-generator.ts
index 7a93ec9870..290d47107e 100644
--- a/v3/@claude-flow/security/src/credential-generator.ts
+++ b/v3/@claude-flow/security/src/credential-generator.ts
@@ -144,7 +144,8 @@ export class CredentialGenerator {
}
/**
- * Generates a cryptographically secure random string.
+ * Generates a cryptographically secure random string using rejection sampling
+ * to eliminate modulo bias.
*
* @param length - Length of the string to generate
* @param charset - Character set to use
@@ -152,12 +153,28 @@ export class CredentialGenerator {
*/
private generateSecureString(length: number, charset: string): string {
const charsetLength = charset.length;
- const randomBuffer = randomBytes(length);
const result = new Array(length);
- for (let i = 0; i < length; i++) {
- // Use modulo with rejection sampling to avoid bias
- result[i] = charset[randomBuffer[i] % charsetLength];
+ // Calculate rejection threshold to eliminate modulo bias
+ // For a byte (0-255), we reject values >= (256 - (256 % charsetLength))
+ // This ensures uniform distribution over charset indices
+ const maxValidValue = 256 - (256 % charsetLength);
+
+ let i = 0;
+ while (i < length) {
+ // Generate more random bytes than needed to reduce iterations
+ const randomBuffer = randomBytes(Math.max(length - i, 16));
+
+ for (let j = 0; j < randomBuffer.length && i < length; j++) {
+ const randomValue = randomBuffer[j];
+
+ // Rejection sampling: only accept values below threshold
+ if (randomValue < maxValidValue) {
+ result[i] = charset[randomValue % charsetLength];
+ i++;
+ }
+ // Values >= maxValidValue are rejected to avoid bias
+ }
}
return result.join('');
diff --git a/v3/@claude-flow/shared/src/utils/secure-logger.ts b/v3/@claude-flow/shared/src/utils/secure-logger.ts
new file mode 100644
index 0000000000..b45d2ee1a8
--- /dev/null
+++ b/v3/@claude-flow/shared/src/utils/secure-logger.ts
@@ -0,0 +1,257 @@
+/**
+ * Secure Logger Utility
+ *
+ * Provides sanitized error logging that strips sensitive information
+ * before logging to prevent information disclosure.
+ *
+ * Security features:
+ * - Removes stack traces in production
+ * - Sanitizes file paths to prevent internal structure disclosure
+ * - Filters sensitive keys from error objects
+ * - Truncates long messages to prevent log injection
+ *
+ * @module @claude-flow/shared/utils/secure-logger
+ */
+
+// ============================================================================
+// Configuration
+// ============================================================================
+
+interface LoggerConfig {
+ /** Environment mode */
+ environment: 'development' | 'production' | 'test';
+ /** Maximum message length */
+ maxMessageLength: number;
+ /** Whether to include stack traces */
+ includeStackTrace: boolean;
+ /** Sensitive keys to filter */
+ sensitiveKeys: string[];
+ /** Path patterns to sanitize */
+ pathPatterns: RegExp[];
+}
+
+const DEFAULT_CONFIG: LoggerConfig = {
+ environment: (process.env.NODE_ENV as LoggerConfig['environment']) || 'development',
+ maxMessageLength: 1000,
+ includeStackTrace: process.env.NODE_ENV === 'development',
+ sensitiveKeys: [
+ 'password', 'passwd', 'secret', 'token', 'apikey', 'api_key',
+ 'authorization', 'auth', 'credential', 'private', 'key',
+ 'session', 'cookie', 'jwt', 'bearer', 'access_token', 'refresh_token',
+ ],
+ pathPatterns: [
+ /\/home\/[^/]+/g, // Unix home directories
+ /\/Users\/[^/]+/g, // macOS home directories
+ /C:\\Users\\[^\\]+/gi, // Windows user directories
+ /\/var\/[^/]+/g, // Var directories
+ /\/tmp\/[^/]+/g, // Temp directories
+ ],
+};
+
+// ============================================================================
+// Sanitization Functions
+// ============================================================================
+
+/**
+ * Sanitize a string message
+ */
+function sanitizeMessage(message: string, config: LoggerConfig): string {
+ let sanitized = message;
+
+ // Truncate long messages
+ if (sanitized.length > config.maxMessageLength) {
+ sanitized = sanitized.substring(0, config.maxMessageLength) + '... [truncated]';
+ }
+
+ // Sanitize paths
+ for (const pattern of config.pathPatterns) {
+ sanitized = sanitized.replace(pattern, '[PATH]');
+ }
+
+ // Remove potential sensitive data patterns
+ sanitized = sanitized.replace(/[a-zA-Z0-9+/]{40,}={0,2}/g, '[REDACTED_KEY]');
+ sanitized = sanitized.replace(/Bearer\s+[^\s]+/gi, 'Bearer [REDACTED]');
+ sanitized = sanitized.replace(/token[=:]\s*[^\s&]+/gi, 'token=[REDACTED]');
+
+ return sanitized;
+}
+
+/**
+ * Sanitize an error object
+ */
+function sanitizeError(error: unknown, config: LoggerConfig): Record<string, unknown> {
+ if (error === null || error === undefined) {
+ return { message: 'Unknown error' };
+ }
+
+ if (typeof error === 'string') {
+ return { message: sanitizeMessage(error, config) };
+ }
+
+ if (error instanceof Error) {
+ const sanitized: Record<string, unknown> = {
+ name: error.name,
+ message: sanitizeMessage(error.message, config),
+ };
+
+ // Only include stack in development
+ if (config.includeStackTrace && error.stack) {
+ sanitized.stack = sanitizeMessage(error.stack, config);
+ }
+
+ // Include code if present (common in Node.js errors)
+ if ('code' in error) {
+ sanitized.code = (error as { code: unknown }).code;
+ }
+
+ return sanitized;
+ }
+
+ if (typeof error === 'object') {
+ return sanitizeObject(error as Record<string, unknown>, config);
+ }
+
+ return { message: String(error) };
+}
+
+/**
+ * Sanitize a plain object
+ */
+function sanitizeObject(obj: Record<string, unknown>, config: LoggerConfig): Record<string, unknown> {
+ const sanitized: Record<string, unknown> = {};
+
+ for (const [key, value] of Object.entries(obj)) {
+ const lowerKey = key.toLowerCase();
+
+ // Skip sensitive keys
+ if (config.sensitiveKeys.some(sk => lowerKey.includes(sk))) {
+ sanitized[key] = '[REDACTED]';
+ continue;
+ }
+
+ // Recursively sanitize nested objects
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
+ sanitized[key] = sanitizeObject(value as Record<string, unknown>, config);
+ } else if (typeof value === 'string') {
+ sanitized[key] = sanitizeMessage(value, config);
+ } else {
+ sanitized[key] = value;
+ }
+ }
+
+ return sanitized;
+}
+
+// ============================================================================
+// Logger Class
+// ============================================================================
+
+export class SecureLogger {
+ private config: LoggerConfig;
+ private prefix: string;
+
+ constructor(prefix: string = '', config: Partial<LoggerConfig> = {}) {
+ this.prefix = prefix;
+ this.config = { ...DEFAULT_CONFIG, ...config };
+ }
+
+ /**
+ * Log an info message
+ */
+ info(message: string, data?: Record<string, unknown>): void {
+ const sanitizedMessage = sanitizeMessage(message, this.config);
+ const sanitizedData = data ? sanitizeObject(data, this.config) : undefined;
+
+ if (sanitizedData) {
+ console.info(`[INFO]${this.prefix ? ` [${this.prefix}]` : ''} ${sanitizedMessage}`, sanitizedData);
+ } else {
+ console.info(`[INFO]${this.prefix ? ` [${this.prefix}]` : ''} ${sanitizedMessage}`);
+ }
+ }
+
+ /**
+ * Log a warning message
+ */
+ warn(message: string, data?: Record<string, unknown>): void {
+ const sanitizedMessage = sanitizeMessage(message, this.config);
+ const sanitizedData = data ? sanitizeObject(data, this.config) : undefined;
+
+ if (sanitizedData) {
+ console.warn(`[WARN]${this.prefix ? ` [${this.prefix}]` : ''} ${sanitizedMessage}`, sanitizedData);
+ } else {
+ console.warn(`[WARN]${this.prefix ? ` [${this.prefix}]` : ''} ${sanitizedMessage}`);
+ }
+ }
+
+ /**
+ * Log an error (sanitized for security)
+ */
+ error(message: string, error?: unknown): void {
+ const sanitizedMessage = sanitizeMessage(message, this.config);
+ const sanitizedError = error ? sanitizeError(error, this.config) : undefined;
+
+ if (sanitizedError) {
+ console.error(`[ERROR]${this.prefix ? ` [${this.prefix}]` : ''} ${sanitizedMessage}`, sanitizedError);
+ } else {
+ console.error(`[ERROR]${this.prefix ? ` [${this.prefix}]` : ''} ${sanitizedMessage}`);
+ }
+ }
+
+ /**
+ * Log debug message (only in development)
+ */
+ debug(message: string, data?: Record<string, unknown>): void {
+ if (this.config.environment !== 'development') {
+ return;
+ }
+
+ const sanitizedMessage = sanitizeMessage(message, this.config);
+ const sanitizedData = data ? sanitizeObject(data, this.config) : undefined;
+
+ if (sanitizedData) {
+ console.debug(`[DEBUG]${this.prefix ? ` [${this.prefix}]` : ''} ${sanitizedMessage}`, sanitizedData);
+ } else {
+ console.debug(`[DEBUG]${this.prefix ? ` [${this.prefix}]` : ''} ${sanitizedMessage}`);
+ }
+ }
+
+ /**
+ * Create a child logger with a sub-prefix
+ */
+ child(subPrefix: string): SecureLogger {
+ const newPrefix = this.prefix ? `${this.prefix}:${subPrefix}` : subPrefix;
+ return new SecureLogger(newPrefix, this.config);
+ }
+}
+
+// ============================================================================
+// Factory Functions
+// ============================================================================
+
+/**
+ * Create a secure logger instance
+ */
+export function createSecureLogger(prefix?: string, config?: Partial<LoggerConfig>): SecureLogger {
+ return new SecureLogger(prefix, config);
+}
+
+/**
+ * Default logger instance
+ */
+export const logger = createSecureLogger('claude-flow');
+
+/**
+ * Sanitize an error for safe logging/display
+ */
+export function sanitizeErrorForLogging(error: unknown): Record<string, unknown> {
+ return sanitizeError(error, DEFAULT_CONFIG);
+}
+
+/**
+ * Sanitize a message for safe logging/display
+ */
+export function sanitizeMessageForLogging(message: string): string {
+ return sanitizeMessage(message, DEFAULT_CONFIG);
+}
+
+export default SecureLogger;