All files / src credential-generator.ts

0% Statements 0/368
0% Branches 0/1
0% Functions 0/1
0% Lines 0/368

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * Credential Generator - CVE-3 Remediation
 *
 * Fixes hardcoded default credentials by providing secure random
 * credential generation for installation and runtime.
 *
 * Security Properties:
 * - Uses crypto.randomBytes for cryptographically secure randomness
 * - Configurable entropy levels
 * - No hardcoded defaults stored in code
 * - Secure credential storage recommendations
 *
 * @module v3/security/credential-generator
 */

import { randomBytes, randomUUID } from 'crypto';

export interface CredentialConfig {
  /**
   * Length of generated passwords.
   * Default: 32 characters
   */
  passwordLength?: number;

  /**
   * Length of generated API keys.
   * Default: 48 characters
   */
  apiKeyLength?: number;

  /**
   * Length of generated secrets (JWT, session, etc.).
   * Default: 64 characters
   */
  secretLength?: number;

  /**
   * Character set for password generation.
   * Default: alphanumeric + special
   */
  passwordCharset?: string;

  /**
   * Character set for API key generation.
   * Default: alphanumeric only (URL-safe)
   */
  apiKeyCharset?: string;
}

export interface GeneratedCredentials {
  adminPassword: string;
  servicePassword: string;
  jwtSecret: string;
  sessionSecret: string;
  encryptionKey: string;
  generatedAt: Date;
  expiresAt?: Date;
}

export interface ApiKeyCredential {
  key: string;
  prefix: string;
  keyId: string;
  createdAt: Date;
}

export class CredentialGeneratorError extends Error {
  constructor(
    message: string,
    public readonly code: string,
  ) {
    super(message);
    this.name = 'CredentialGeneratorError';
  }
}

/**
 * Character sets for credential generation
 */
const CHARSETS = {
  UPPERCASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
  LOWERCASE: 'abcdefghijklmnopqrstuvwxyz',
  DIGITS: '0123456789',
  SPECIAL: '!@#$%^&*()_+-=[]{}|;:,.<>?',
  // URL-safe characters for API keys
  URL_SAFE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
  // Hex characters for secrets
  HEX: '0123456789abcdef',
} as const;

/**
 * Secure credential generator.
 *
 * This class provides cryptographically secure credential generation
 * to replace hardcoded default credentials.
 *
 * @example
 * ```typescript
 * const generator = new CredentialGenerator();
 * const credentials = generator.generateInstallationCredentials();
 * // Store credentials securely (environment variables, secrets manager)
 * ```
 */
export class CredentialGenerator {
  private readonly config: Required<CredentialConfig>;

  constructor(config: CredentialConfig = {}) {
    this.config = {
      passwordLength: config.passwordLength ?? 32,
      apiKeyLength: config.apiKeyLength ?? 48,
      secretLength: config.secretLength ?? 64,
      passwordCharset: config.passwordCharset ??
        CHARSETS.UPPERCASE + CHARSETS.LOWERCASE + CHARSETS.DIGITS + CHARSETS.SPECIAL,
      apiKeyCharset: config.apiKeyCharset ?? CHARSETS.URL_SAFE,
    };

    this.validateConfig();
  }

  /**
   * Validates configuration parameters.
   */
  private validateConfig(): void {
    if (this.config.passwordLength < 16) {
      throw new CredentialGeneratorError(
        'Password length must be at least 16 characters',
        'INVALID_PASSWORD_LENGTH'
      );
    }

    if (this.config.apiKeyLength < 32) {
      throw new CredentialGeneratorError(
        'API key length must be at least 32 characters',
        'INVALID_API_KEY_LENGTH'
      );
    }

    if (this.config.secretLength < 32) {
      throw new CredentialGeneratorError(
        'Secret length must be at least 32 characters',
        'INVALID_SECRET_LENGTH'
      );
    }
  }

  /**
   * 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
   * @returns Random string
   */
  private generateSecureString(length: number, charset: string): string {
    const charsetLength = charset.length;
    const result = new Array(length);

    // 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('');
  }

  /**
   * Generates a secure random password.
   *
   * @param length - Optional custom length (default from config)
   * @returns Secure random password
   */
  generatePassword(length?: number): string {
    const len = length ?? this.config.passwordLength;

    // Ensure password contains at least one of each required character type
    const password = this.generateSecureString(len, this.config.passwordCharset);

    // Validate the generated password meets requirements
    if (!this.hasRequiredCharacterTypes(password)) {
      // Regenerate if requirements not met (rare case)
      return this.generatePassword(length);
    }

    return password;
  }

  /**
   * Checks if password has required character types.
   */
  private hasRequiredCharacterTypes(password: string): boolean {
    const hasUppercase = /[A-Z]/.test(password);
    const hasLowercase = /[a-z]/.test(password);
    const hasDigit = /\d/.test(password);
    const hasSpecial = /[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/.test(password);

    return hasUppercase && hasLowercase && hasDigit && hasSpecial;
  }

  /**
   * Generates a secure API key.
   *
   * @param prefix - Optional prefix for the key (e.g., 'cf_')
   * @returns API key credential with metadata
   */
  generateApiKey(prefix = 'cf_'): ApiKeyCredential {
    const keyBody = this.generateSecureString(
      this.config.apiKeyLength - prefix.length,
      this.config.apiKeyCharset
    );

    const key = `${prefix}${keyBody}`;
    const keyId = randomUUID();

    return {
      key,
      prefix,
      keyId,
      createdAt: new Date(),
    };
  }

  /**
   * Generates a secure secret for JWT, sessions, etc.
   *
   * @param length - Optional custom length (default from config)
   * @returns Hex-encoded secret
   */
  generateSecret(length?: number): string {
    const len = length ?? this.config.secretLength;
    // Generate raw bytes and encode as hex for consistent storage
    return randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len);
  }

  /**
   * Generates an encryption key suitable for AES-256.
   *
   * @returns 32-byte key encoded as hex (64 characters)
   */
  generateEncryptionKey(): string {
    return randomBytes(32).toString('hex');
  }

  /**
   * Generates a complete set of installation credentials.
   *
   * These should be stored securely (environment variables,
   * secrets manager, etc.) and NEVER committed to version control.
   *
   * @param expirationDays - Optional expiration period in days
   * @returns Complete credential set
   */
  generateInstallationCredentials(expirationDays?: number): GeneratedCredentials {
    const now = new Date();
    const expiresAt = expirationDays
      ? new Date(now.getTime() + expirationDays * 24 * 60 * 60 * 1000)
      : undefined;

    return {
      adminPassword: this.generatePassword(),
      servicePassword: this.generatePassword(),
      jwtSecret: this.generateSecret(64),
      sessionSecret: this.generateSecret(64),
      encryptionKey: this.generateEncryptionKey(),
      generatedAt: now,
      expiresAt,
    };
  }

  /**
   * Generates a secure session token.
   *
   * @returns URL-safe session token
   */
  generateSessionToken(): string {
    return this.generateSecureString(64, CHARSETS.URL_SAFE);
  }

  /**
   * Generates a secure CSRF token.
   *
   * @returns CSRF token
   */
  generateCsrfToken(): string {
    return randomBytes(32).toString('base64url');
  }

  /**
   * Generates a secure nonce for one-time use.
   *
   * @returns Unique nonce value
   */
  generateNonce(): string {
    return randomBytes(16).toString('hex');
  }

  /**
   * Creates a setup script output for secure credential deployment.
   *
   * @param credentials - Generated credentials
   * @returns Environment variable export script
   */
  createEnvScript(credentials: GeneratedCredentials): string {
    return `# Claude Flow V3 - Generated Credentials
# Generated: ${credentials.generatedAt.toISOString()}
# IMPORTANT: Store these securely and delete this file after use

export CLAUDE_FLOW_ADMIN_PASSWORD="${credentials.adminPassword}"
export CLAUDE_FLOW_SERVICE_PASSWORD="${credentials.servicePassword}"
export CLAUDE_FLOW_JWT_SECRET="${credentials.jwtSecret}"
export CLAUDE_FLOW_SESSION_SECRET="${credentials.sessionSecret}"
export CLAUDE_FLOW_ENCRYPTION_KEY="${credentials.encryptionKey}"
`;
  }

  /**
   * Creates a JSON configuration output for secure credential deployment.
   *
   * @param credentials - Generated credentials
   * @returns JSON configuration (for secrets manager import)
   */
  createJsonConfig(credentials: GeneratedCredentials): string {
    return JSON.stringify({
      'claude-flow/admin-password': credentials.adminPassword,
      'claude-flow/service-password': credentials.servicePassword,
      'claude-flow/jwt-secret': credentials.jwtSecret,
      'claude-flow/session-secret': credentials.sessionSecret,
      'claude-flow/encryption-key': credentials.encryptionKey,
      'claude-flow/generated-at': credentials.generatedAt.toISOString(),
      'claude-flow/expires-at': credentials.expiresAt?.toISOString() ?? null,
    }, null, 2);
  }
}

/**
 * Factory function to create a production credential generator.
 *
 * @returns Configured CredentialGenerator instance
 */
export function createCredentialGenerator(): CredentialGenerator {
  return new CredentialGenerator();
}

/**
 * Quick credential generation for CLI usage.
 *
 * @returns Generated installation credentials
 */
export function generateCredentials(): GeneratedCredentials {
  const generator = new CredentialGenerator();
  return generator.generateInstallationCredentials();
}