All files / src token-generator.ts

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

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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * Token Generator - Secure Token Generation
 *
 * Provides cryptographically secure token generation for:
 * - JWT tokens
 * - Session tokens
 * - CSRF tokens
 * - API tokens
 * - Verification codes
 *
 * Security Properties:
 * - Uses crypto.randomBytes for all randomness
 * - Configurable entropy levels
 * - Timing-safe comparison
 * - Token expiration handling
 *
 * @module v3/security/token-generator
 */

import { randomBytes, createHmac, timingSafeEqual } from 'crypto';

export interface TokenConfig {
  /**
   * Default token length in bytes.
   * Default: 32 (256 bits)
   */
  defaultLength?: number;

  /**
   * Token encoding format.
   * Default: 'base64url'
   */
  encoding?: 'hex' | 'base64' | 'base64url';

  /**
   * HMAC secret for signed tokens.
   */
  hmacSecret?: string;

  /**
   * Default expiration time in seconds.
   * Default: 3600 (1 hour)
   */
  defaultExpiration?: number;
}

export interface Token {
  value: string;
  createdAt: Date;
  expiresAt: Date;
  metadata?: Record<string, unknown>;
}

export interface SignedToken {
  token: string;
  signature: string;
  combined: string;
  createdAt: Date;
  expiresAt: Date;
}

export interface VerificationCode {
  code: string;
  createdAt: Date;
  expiresAt: Date;
  attempts: number;
  maxAttempts: number;
}

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

/**
 * Secure token generator.
 *
 * @example
 * ```typescript
 * const generator = new TokenGenerator({ hmacSecret: 'secret' });
 *
 * // Generate session token
 * const session = generator.generateSessionToken();
 *
 * // Generate signed token
 * const signed = generator.generateSignedToken({ userId: '123' });
 *
 * // Verify signed token
 * const isValid = generator.verifySignedToken(signed.combined);
 * ```
 */
export class TokenGenerator {
  private readonly config: Required<TokenConfig>;

  constructor(config: TokenConfig = {}) {
    this.config = {
      defaultLength: config.defaultLength ?? 32,
      encoding: config.encoding ?? 'base64url',
      hmacSecret: config.hmacSecret ?? '',
      defaultExpiration: config.defaultExpiration ?? 3600,
    };

    if (this.config.defaultLength < 16) {
      throw new TokenGeneratorError(
        'Token length must be at least 16 bytes',
        'INVALID_LENGTH'
      );
    }
  }

  /**
   * Generates a random token.
   *
   * @param length - Token length in bytes
   * @returns Random token string
   */
  generate(length?: number): string {
    const len = length ?? this.config.defaultLength;
    const buffer = randomBytes(len);
    return this.encode(buffer);
  }

  /**
   * Generates a token with expiration.
   *
   * @param expirationSeconds - Expiration time in seconds
   * @param metadata - Optional metadata to attach
   * @returns Token with expiration
   */
  generateWithExpiration(
    expirationSeconds?: number,
    metadata?: Record<string, unknown>
  ): Token {
    const expiration = expirationSeconds ?? this.config.defaultExpiration;
    const now = new Date();
    const expiresAt = new Date(now.getTime() + expiration * 1000);

    return {
      value: this.generate(),
      createdAt: now,
      expiresAt,
      metadata,
    };
  }

  /**
   * Generates a session token (URL-safe).
   *
   * @param length - Token length in bytes (default: 32)
   * @returns Session token
   */
  generateSessionToken(length = 32): Token {
    return this.generateWithExpiration(this.config.defaultExpiration);
  }

  /**
   * Generates a CSRF token.
   *
   * @returns CSRF token (shorter expiration)
   */
  generateCsrfToken(): Token {
    return this.generateWithExpiration(1800); // 30 minutes
  }

  /**
   * Generates an API token with prefix.
   *
   * @param prefix - Token prefix (e.g., 'cf_')
   * @returns Prefixed API token
   */
  generateApiToken(prefix = 'cf_'): Token {
    const tokenBody = this.generate(32);
    const now = new Date();

    return {
      value: `${prefix}${tokenBody}`,
      createdAt: now,
      expiresAt: new Date(now.getTime() + 365 * 24 * 60 * 60 * 1000), // 1 year
    };
  }

  /**
   * Generates a numeric verification code.
   *
   * @param length - Number of digits (default: 6)
   * @param expirationMinutes - Expiration in minutes (default: 10)
   * @param maxAttempts - Maximum verification attempts (default: 3)
   * @returns Verification code
   */
  generateVerificationCode(
    length = 6,
    expirationMinutes = 10,
    maxAttempts = 3
  ): VerificationCode {
    const buffer = randomBytes(length);
    let code = '';

    for (let i = 0; i < length; i++) {
      code += (buffer[i] % 10).toString();
    }

    const now = new Date();

    return {
      code,
      createdAt: now,
      expiresAt: new Date(now.getTime() + expirationMinutes * 60 * 1000),
      attempts: 0,
      maxAttempts,
    };
  }

  /**
   * Generates a signed token using HMAC.
   *
   * @param payload - Data to include in token
   * @param expirationSeconds - Token expiration
   * @returns Signed token
   */
  generateSignedToken(
    payload: Record<string, unknown>,
    expirationSeconds?: number
  ): SignedToken {
    if (!this.config.hmacSecret) {
      throw new TokenGeneratorError(
        'HMAC secret required for signed tokens',
        'NO_SECRET'
      );
    }

    const expiration = expirationSeconds ?? this.config.defaultExpiration;
    const now = new Date();
    const expiresAt = new Date(now.getTime() + expiration * 1000);

    const tokenData = {
      ...payload,
      iat: now.getTime(),
      exp: expiresAt.getTime(),
      nonce: this.generate(8),
    };

    const token = Buffer.from(JSON.stringify(tokenData)).toString('base64url');
    const signature = this.sign(token);

    return {
      token,
      signature,
      combined: `${token}.${signature}`,
      createdAt: now,
      expiresAt,
    };
  }

  /**
   * Verifies a signed token.
   *
   * @param combined - Combined token string (token.signature)
   * @returns Decoded payload if valid, null otherwise
   */
  verifySignedToken(combined: string): Record<string, unknown> | null {
    if (!this.config.hmacSecret) {
      throw new TokenGeneratorError(
        'HMAC secret required for signed tokens',
        'NO_SECRET'
      );
    }

    const parts = combined.split('.');
    if (parts.length !== 2) {
      return null;
    }

    const [token, signature] = parts;

    // Verify signature
    const expectedSignature = this.sign(token);

    try {
      const sigBuffer = Buffer.from(signature, 'base64url');
      const expectedBuffer = Buffer.from(expectedSignature, 'base64url');

      if (sigBuffer.length !== expectedBuffer.length) {
        return null;
      }

      if (!timingSafeEqual(sigBuffer, expectedBuffer)) {
        return null;
      }
    } catch {
      return null;
    }

    // Decode and validate payload
    try {
      const payload = JSON.parse(Buffer.from(token, 'base64url').toString());

      // Check expiration
      if (payload.exp && payload.exp < Date.now()) {
        return null;
      }

      return payload;
    } catch {
      return null;
    }
  }

  /**
   * Generates a refresh token pair.
   *
   * @returns Access and refresh tokens
   */
  generateTokenPair(): {
    accessToken: Token;
    refreshToken: Token;
  } {
    return {
      accessToken: this.generateWithExpiration(900), // 15 minutes
      refreshToken: this.generateWithExpiration(604800), // 7 days
    };
  }

  /**
   * Generates a password reset token.
   *
   * @returns Password reset token (short expiration)
   */
  generatePasswordResetToken(): Token {
    return this.generateWithExpiration(1800); // 30 minutes
  }

  /**
   * Generates an email verification token.
   *
   * @returns Email verification token
   */
  generateEmailVerificationToken(): Token {
    return this.generateWithExpiration(86400); // 24 hours
  }

  /**
   * Generates a unique request ID.
   *
   * @returns Request ID (shorter, for logging)
   */
  generateRequestId(): string {
    return this.generate(8);
  }

  /**
   * Generates a correlation ID for distributed tracing.
   *
   * @returns Correlation ID
   */
  generateCorrelationId(): string {
    const timestamp = Date.now().toString(36);
    const random = this.generate(8);
    return `${timestamp}-${random}`;
  }

  /**
   * Checks if a token has expired.
   *
   * @param token - Token to check
   * @returns True if expired
   */
  isExpired(token: Token | VerificationCode): boolean {
    return token.expiresAt < new Date();
  }

  /**
   * Compares two tokens in constant time.
   *
   * @param a - First token
   * @param b - Second token
   * @returns True if equal
   */
  compare(a: string, b: string): boolean {
    if (a.length !== b.length) {
      return false;
    }

    try {
      const bufferA = Buffer.from(a);
      const bufferB = Buffer.from(b);
      return timingSafeEqual(bufferA, bufferB);
    } catch {
      return false;
    }
  }

  /**
   * Signs data using HMAC-SHA256.
   */
  private sign(data: string): string {
    return createHmac('sha256', this.config.hmacSecret)
      .update(data)
      .digest('base64url');
  }

  /**
   * Encodes bytes according to configuration.
   */
  private encode(buffer: Buffer): string {
    switch (this.config.encoding) {
      case 'hex':
        return buffer.toString('hex');
      case 'base64':
        return buffer.toString('base64');
      case 'base64url':
      default:
        return buffer.toString('base64url');
    }
  }
}

/**
 * Factory function to create a production token generator.
 *
 * @param hmacSecret - HMAC secret for signed tokens
 * @returns Configured TokenGenerator
 */
export function createTokenGenerator(hmacSecret: string): TokenGenerator {
  return new TokenGenerator({
    hmacSecret,
    defaultLength: 32,
    encoding: 'base64url',
  });
}

/**
 * Singleton instance for quick token generation without configuration.
 */
let defaultGenerator: TokenGenerator | null = null;

/**
 * Gets or creates the default token generator.
 * Note: Does not support signed tokens without configuration.
 */
export function getDefaultGenerator(): TokenGenerator {
  if (!defaultGenerator) {
    defaultGenerator = new TokenGenerator();
  }
  return defaultGenerator;
}

/**
 * Quick token generation functions.
 */
export const quickGenerate = {
  token: (length = 32) => getDefaultGenerator().generate(length),
  sessionToken: () => getDefaultGenerator().generateSessionToken(),
  csrfToken: () => getDefaultGenerator().generateCsrfToken(),
  apiToken: (prefix = 'cf_') => getDefaultGenerator().generateApiToken(prefix),
  verificationCode: (length = 6) => getDefaultGenerator().generateVerificationCode(length),
  requestId: () => getDefaultGenerator().generateRequestId(),
  correlationId: () => getDefaultGenerator().generateCorrelationId(),
};