# @bernierllc/validators-crypto-parameters

Primitive validator for cryptographic parameter validation, ensuring secure configurations for JWT algorithms, key sizes, KDF parameters, hash algorithms, and cipher suites.

## Installation

```bash
npm install @bernierllc/validators-crypto-parameters
```

## Features

- **JWT Algorithm Validation** - Detects weak or insecure JWT algorithms (especially `none`, `HS256`)
- **Key Size Validation** - Ensures minimum key sizes for RSA (2048-bit), ECC (256-bit), and AES (128-bit)
- **KDF Parameters Validation** - Validates PBKDF2 iterations, bcrypt cost factors, and scrypt N parameters
- **Hash Algorithm Validation** - Detects weak hash algorithms (MD5, SHA-1)
- **Cipher Suite Validation** - Identifies weak or deprecated TLS/SSL cipher suites and protocol versions

## Usage

### Basic Validation

```typescript
import { validateCryptoParameters } from '@bernierllc/validators-crypto-parameters';

const code = `
  const token = jwt.sign(payload, secret, { alg: 'none' });
  const hash = crypto.createHash('md5');
  const key = crypto.generateKeyPair('rsa', { modulusLength: 1024 });
`;

const problems = await validateCryptoParameters(code);

console.log(`Found ${problems.length} crypto issues`);
problems.forEach((problem) => {
  console.log(`${problem.severity}: ${problem.message}`);
  console.log(`  Location: Line ${problem.location?.line}`);
  console.log(`  Suggestion: ${problem.suggestion}`);
});
```

### Quick Checks

```typescript
import { hasCryptoIssues, getCryptoIssueCounts, getCryptoIssueSummary } from '@bernierllc/validators-crypto-parameters';

// Quick boolean check
if (await hasCryptoIssues(code)) {
  console.log('Crypto issues detected!');
}

// Get counts by type
const counts = await getCryptoIssueCounts(code);
console.log(`JWT: ${counts.jwtAlgorithms}, Hash: ${counts.hashAlgorithms}`);

// Get detailed summary
const summary = await getCryptoIssueSummary(code);
console.log(`${summary.errors} errors, ${summary.warnings} warnings`);
```

### Custom Options

```typescript
import { validateCryptoParameters } from '@bernierllc/validators-crypto-parameters';

const problems = await validateCryptoParameters(code, {
  // Enable/disable specific checks
  checkJwtAlgorithms: true,
  checkKeySizes: true,
  checkKdfParameters: true,
  checkHashAlgorithms: true,
  checkCipherSuites: true,

  // Custom minimum values
  minRsaKeySize: 4096,        // Default: 2048
  minEccKeySize: 384,          // Default: 256
  minAesKeySize: 256,          // Default: 128
  minPbkdf2Iterations: 200000, // Default: 100000
  minBcryptCost: 12,           // Default: 10
  minScryptN: 32768,           // Default: 16384

  // Allow specific algorithms
  allowedJwtAlgorithms: ['RS256', 'ES256'],
  allowedHashAlgorithms: ['SHA256', 'SHA384', 'SHA512'],

  // Permissive options (not recommended for production)
  allowJwtNoneAlgorithm: false, // Default: false
  allowWeakHashes: false,        // Default: false
  allowExportCiphers: false,     // Default: false
});
```

## API Reference

### `validateCryptoParameters(content, options?, utils?)`

Main validation function that checks all cryptographic parameters.

**Parameters:**
- `content` (string) - Source code or configuration to validate
- `options` (CryptoParameterOptions) - Optional validation options
- `utils` (SharedUtils) - Optional shared utilities

**Returns:** `Promise<Problem[]>` - Array of validation problems

### `hasCryptoIssues(content, options?)`

Quick check for any cryptographic issues.

**Returns:** `Promise<boolean>` - True if issues detected

### `getCryptoIssueCounts(content, options?)`

Get count of issues by type.

**Returns:** `Promise<IssueCounts>` - Object with counts:
- `jwtAlgorithms` - JWT algorithm issues
- `keySizes` - Key size issues
- `kdfParameters` - KDF parameter issues
- `hashAlgorithms` - Hash algorithm issues
- `cipherSuites` - Cipher suite issues
- `total` - Total issue count

### `getCryptoIssueSummary(content, options?)`

Get detailed summary with severity breakdown.

**Returns:** `Promise<Summary>` - Object with:
- `total` - Total issues
- `errors` - Error count
- `warnings` - Warning count
- `byType` - Breakdown by type

## Options Reference

### CryptoParameterOptions

```typescript
interface CryptoParameterOptions {
  // Check toggles
  checkJwtAlgorithms?: boolean;      // Default: true
  checkKeySizes?: boolean;           // Default: true
  checkKdfParameters?: boolean;      // Default: true
  checkHashAlgorithms?: boolean;     // Default: true
  checkCipherSuites?: boolean;       // Default: true

  // Minimum key sizes (bits)
  minRsaKeySize?: number;            // Default: 2048
  minEccKeySize?: number;            // Default: 256
  minAesKeySize?: number;            // Default: 128

  // Minimum KDF parameters
  minPbkdf2Iterations?: number;      // Default: 100000
  minBcryptCost?: number;            // Default: 10
  minScryptN?: number;               // Default: 16384

  // Allow weak options
  allowJwtNoneAlgorithm?: boolean;   // Default: false
  allowWeakHashes?: boolean;         // Default: false
  allowExportCiphers?: boolean;      // Default: false

  // Custom allowed lists
  allowedJwtAlgorithms?: string[];
  allowedHashAlgorithms?: string[];
}
```

## Validation Rules

### JWT Algorithms

**Weak Algorithms (Warnings/Errors):**
- `none` - **ERROR**: No signature verification
- `HS256`, `HS384`, `HS512` - **WARNING**: Symmetric, shared secret required

**Recommended Algorithms:**
- `RS256`, `RS384`, `RS512` - RSA with SHA-2
- `ES256`, `ES384`, `ES512` - ECDSA with SHA-2
- `PS256`, `PS384`, `PS512` - RSA-PSS with SHA-2

### Key Sizes

**Minimum Sizes:**
- RSA: 2048 bits (recommend 4096 for long-term)
- ECC: 256 bits (P-256, secp256r1)
- AES: 128 bits (recommend 256 for sensitive data)
- DSA: 2048 bits

### KDF Parameters

**PBKDF2:**
- Minimum iterations: 100,000
- OWASP recommendation: 210,000+ for PBKDF2-HMAC-SHA256

**bcrypt:**
- Minimum cost factor: 10
- Recommended: 12 or higher
- Maximum: 31

**scrypt:**
- Minimum N parameter: 16,384 (2^14)
- Recommended: 32,768 or higher
- Maximum: 1,048,576 (2^20)

### Hash Algorithms

**Weak (Not Allowed):**
- MD5 - Cryptographically broken
- SHA-1 - Vulnerable to collision attacks

**Acceptable:**
- SHA-224, SHA-256, SHA-384, SHA-512
- SHA3-256, SHA3-384, SHA3-512

### Cipher Suites

**Weak Patterns:**
- NULL - No encryption
- EXPORT/EXP - Intentionally weakened
- DES/3DES - Weak encryption
- RC4/ARCFOUR - Broken stream cipher
- ADH/AECDH/aNULL - No authentication
- MD5 - Weak hash

**Deprecated Protocols:**
- SSLv2, SSLv3
- TLS 1.0, TLS 1.1

**Recommended:**
- TLS 1.2 or TLS 1.3 only
- Modern ciphers: AES-GCM, ChaCha20-Poly1305
- Perfect forward secrecy: ECDHE

## Examples

### Validating Node.js Crypto Code

```typescript
const code = `
  const crypto = require('crypto');

  // Good: Strong hash
  const hash = crypto.createHash('sha256').update(data).digest('hex');

  // Bad: Weak hash
  const md5 = crypto.createHash('md5').update(data).digest('hex');

  // Good: Strong PBKDF2
  crypto.pbkdf2(password, salt, 200000, 64, 'sha512', callback);

  // Bad: Weak PBKDF2
  crypto.pbkdf2(password, salt, 1000, 64, 'sha512', callback);
`;

const problems = await validateCryptoParameters(code);
// Returns problems for MD5 and low PBKDF2 iterations
```

### Validating JWT Configuration

```typescript
const jwtConfig = `
  const jwtOptions = {
    algorithm: 'RS256',  // Good: Asymmetric
    expiresIn: '1h'
  };

  const weakJwt = jwt.sign(payload, secret, { alg: 'none' });  // Bad: No signature
`;

const problems = await validateCryptoParameters(jwtConfig);
// Returns error for 'none' algorithm
```

### Validating TLS Configuration

```typescript
const tlsConfig = `
  const tlsOptions = {
    minVersion: 'TLSv1.2',
    ciphers: [
      'TLS_AES_128_GCM_SHA256',
      'TLS_AES_256_GCM_SHA384',
      'ECDHE-RSA-AES128-GCM-SHA256'
    ].join(':')
  };

  // Bad configuration
  const weakTls = {
    minVersion: 'TLSv1.0',
    ciphers: 'RC4-SHA:DES-CBC3-SHA'
  };
`;

const problems = await validateCryptoParameters(tlsConfig);
// Returns errors for TLS 1.0, RC4, and 3DES
```

## Integration Status

### Logger Integration
**Status**: Not applicable - Pure validation, no runtime logging

This is a primitive validator package that performs static code analysis. It does not require @bernierllc/logger integration as it has no runtime logging needs. All output is returned as structured Problem objects.

### Docs-Suite Integration
**Status**: Ready - Full TypeDoc documentation

Complete API documentation is available via TypeDoc comments throughout the codebase. Documentation can be exported and integrated into the docs-suite.

### NeverHub Integration
**Status**: Not applicable - Primitive validator, no service dependencies

This is a primitive validator following the validators architecture principles. It has no external service dependencies and does not require @bernierllc/neverhub-adapter integration. The validator operates independently and can be used in any environment.

## Best Practices

1. **Never use `none` algorithm for JWT** - Always require signature verification
2. **Prefer asymmetric JWT algorithms** (RS256, ES256) over symmetric (HS256)
3. **Use minimum 2048-bit RSA keys**, preferably 4096-bit for long-term security
4. **Use SHA-256 or higher** for hashing - never MD5 or SHA-1
5. **Use PBKDF2 with 100,000+ iterations** or bcrypt with cost 10+
6. **Use TLS 1.2 or 1.3** with modern cipher suites (AES-GCM, ChaCha20)
7. **Enable perfect forward secrecy** (ECDHE ciphers)

## Security References

- [OWASP Cryptographic Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html)
- [NIST Key Management Guidelines](https://csrc.nist.gov/publications/detail/sp/800-57-part-1/rev-5/final)
- [Mozilla TLS Configuration Guide](https://wiki.mozilla.org/Security/Server_Side_TLS)
- [JWT Best Current Practices](https://datatracker.ietf.org/doc/html/rfc8725)

## License

Copyright (c) 2025 Bernier LLC. All rights reserved.
