/**
 * Hardware Security Module (HSM) Integration Layer
 *
 * This module provides a unified interface for enterprise key management
 * across multiple HSM providers including:
 * - AWS CloudHSM
 * - Azure Dedicated/Managed HSM
 * - Google Cloud HSM
 * - Thales Luna Network HSM
 * - SoftHSM (for development)
 *
 * Features:
 * - Provider abstraction with automatic failover
 * - Key lifecycle management
 * - Multi-party key ceremonies with Shamir's Secret Sharing
 * - Health monitoring and audit logging
 * - Transparent integration with application code
 *
 * @module security/hsm
 */
// ============================================================================
// Provider Interface and Base Types
// ============================================================================
export { KeyType, KeyUsage, ECCurve, EncryptionAlgorithm, SigningAlgorithm, 
// Base Implementation
BaseHSMProvider, 
// Error Types
HSMError, HSMConnectionError, HSMKeyNotFoundError, HSMOperationError, HSMPermissionError, } from './provider';
// ============================================================================
// Provider Implementations
// ============================================================================
// AWS CloudHSM
export { AWSCloudHSMProvider, } from './aws-cloudhsm';
// Azure Managed HSM
export { AzureHSMProvider, AzureHSMRole, } from './azure-hsm';
// Google Cloud HSM
export { GCPHSMProvider, GCPKeyAlgorithm, KeyVersionState, CloudKMSRole, } from './gcp-hsm';
// Thales Luna HSM
export { ThalesLunaProvider, } from './thales-luna';
// SoftHSM (Development)
export { SoftHSMProvider, } from './local-softHSM';
// ============================================================================
// Key Ceremony
// ============================================================================
export { KeyCeremonyManager, CeremonyType, CeremonyStatus, CeremonyAction, CustodianRole, } from './key-ceremony';
// ============================================================================
// Key Operations
// ============================================================================
export { KeyOperationsService, createKeyOperationsService, KeyPurpose, FIPSComplianceLevel, getFIPSKeySpec, } from './key-operations';
// ============================================================================
// PKCS#11 Wrapper
// ============================================================================
export { PKCS11WrapperProvider, createPKCS11Provider, 
// PKCS#11 Types
CKM, CKO, CKK, CKA, CKU, CKR, } from './pkcs11-wrapper';
// ============================================================================
// HSM Service (Orchestration)
// ============================================================================
export { HSMService, createHSMService, } from './hsm-service';
// ============================================================================
// Convenience Types for Common Use Cases
// ============================================================================
/**
 * Standard key specifications for common use cases
 */
export const StandardKeySpecs = {
    /**
     * AES-256 key for data encryption
     */
    DataEncryptionKey: {
        type: 'AES',
        size: 256,
        usage: ['encrypt', 'decrypt'],
        extractable: false,
    },
    /**
     * AES-256 key for wrapping other keys
     */
    KeyEncryptionKey: {
        type: 'AES',
        size: 256,
        usage: ['wrap', 'unwrap'],
        extractable: false,
    },
    /**
     * RSA-2048 key pair for signing
     */
    RSASigningKey: {
        type: 'RSA',
        size: 2048,
        usage: ['sign', 'verify'],
        extractable: false,
    },
    /**
     * RSA-2048 key pair for encryption
     */
    RSAEncryptionKey: {
        type: 'RSA',
        size: 2048,
        usage: ['encrypt', 'decrypt'],
        extractable: false,
    },
    /**
     * ECDSA P-256 key pair for signing
     */
    ECDSASigningKey: {
        type: 'EC',
        curve: 'P-256',
        usage: ['sign', 'verify'],
        extractable: false,
    },
    /**
     * HMAC-SHA256 key for message authentication
     */
    HMACKey: {
        type: 'HMAC',
        size: 256,
        usage: ['sign', 'verify'],
        extractable: false,
    },
};
/**
 * Environment-based provider recommendations
 */
export const ProviderRecommendations = {
    development: ['softhsm'],
    staging: ['softhsm', 'aws', 'azure', 'gcp'],
    production: ['aws', 'azure', 'gcp', 'thales'],
};
// ============================================================================
// Quick Start Functions
// ============================================================================
import { createHSMService as createService } from './hsm-service';
import { KeyType, KeyUsage, ECCurve } from './provider';
/**
 * Quick start: Create and initialize HSM service for the current environment
 *
 * @example
 * ```typescript
 * const hsm = await quickStart('development');
 * const key = await hsm.generateMasterKey('my-app-key');
 * const encrypted = await hsm.encrypt(key.id, Buffer.from('secret data'));
 * ```
 */
export async function quickStart(environment = 'development') {
    const service = createService(environment);
    await service.initialize();
    return service;
}
/**
 * Create a simple encryption service using SoftHSM
 * Useful for development and testing
 *
 * @example
 * ```typescript
 * const crypto = await createSimpleCryptoService();
 * const { keyId, ciphertext } = await crypto.encrypt('my-data', Buffer.from('hello'));
 * const plaintext = await crypto.decrypt(keyId, ciphertext);
 * ```
 */
export async function createSimpleCryptoService() {
    const service = await quickStart('development');
    const keyCache = new Map();
    return {
        async encrypt(label, data) {
            let keyId = keyCache.get(`enc:${label}`);
            if (!keyId) {
                const key = await service.generateKey({
                    label,
                    type: KeyType.AES,
                    size: 256,
                    usage: [KeyUsage.ENCRYPT, KeyUsage.DECRYPT],
                    extractable: false,
                });
                keyId = key.id;
                keyCache.set(`enc:${label}`, keyId);
            }
            const ciphertext = await service.encrypt(keyId, data);
            return { keyId, ciphertext };
        },
        async decrypt(keyId, ciphertext) {
            return service.decrypt(keyId, ciphertext);
        },
        async sign(label, data) {
            let keyId = keyCache.get(`sign:${label}`);
            if (!keyId) {
                const key = await service.generateKey({
                    label,
                    type: KeyType.EC,
                    curve: ECCurve.P256,
                    usage: [KeyUsage.SIGN, KeyUsage.VERIFY],
                    extractable: false,
                });
                keyId = key.id;
                keyCache.set(`sign:${label}`, keyId);
            }
            const signature = await service.sign(keyId, data, 'ECDSA-SHA256');
            return { keyId, signature };
        },
        async verify(keyId, data, signature) {
            return service.verify(keyId, data, signature, 'ECDSA-SHA256');
        },
        async destroy() {
            await service.shutdown();
        },
    };
}
/**
 * Create HSM health check for observability integration
 *
 * @example
 * ```typescript
 * import { registerHealthCheck } from '@vorionsys/platform-core/observability';
 * import { createHSMHealthCheck } from '@vorionsys/platform-core/security/hsm';
 *
 * const hsmService = await createHSMService('production');
 * await hsmService.initialize();
 *
 * registerHealthCheck(createHSMHealthCheck(hsmService));
 * ```
 */
export function createHSMHealthCheck(service, options) {
    const critical = options?.critical ?? true;
    const name = options?.name ?? 'hsm';
    const timeoutMs = options?.timeoutMs ?? 5000;
    return {
        name,
        critical,
        check: async () => {
            const start = Date.now();
            try {
                // Create a timeout promise
                const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('HSM health check timeout')), timeoutMs));
                // Get HSM status with timeout
                const statusPromise = service.getStatus();
                const status = await Promise.race([statusPromise, timeoutPromise]);
                const latencyMs = Date.now() - start;
                // Determine health status
                let healthStatus = 'healthy';
                if (!status.initialized) {
                    healthStatus = 'unhealthy';
                }
                else if (!status.activeProvider) {
                    healthStatus = 'unhealthy';
                }
                else {
                    // Check if any provider is unhealthy
                    const unhealthyProviders = status.providers.filter(p => !p.status.healthy);
                    const activeProvider = status.providers.find(p => p.isActive);
                    if (activeProvider && !activeProvider.status.healthy) {
                        healthStatus = 'unhealthy';
                    }
                    else if (unhealthyProviders.length > 0) {
                        healthStatus = 'degraded';
                    }
                }
                return {
                    name,
                    status: healthStatus,
                    latencyMs,
                    details: {
                        initialized: status.initialized,
                        activeProvider: status.activeProvider,
                        providerCount: status.providers.length,
                        healthyProviders: status.providers.filter(p => p.status.healthy).length,
                        metrics: {
                            totalOperations: status.metrics.totalOperations,
                            successRate: status.metrics.totalOperations > 0
                                ? ((status.metrics.successfulOperations /
                                    status.metrics.totalOperations) *
                                    100).toFixed(2) + '%'
                                : 'N/A',
                            averageLatencyMs: Math.round(status.metrics.averageLatency),
                            failoverCount: status.metrics.failoverCount,
                        },
                        isProductionMode: service.isProductionMode(),
                    },
                };
            }
            catch (error) {
                const latencyMs = Date.now() - start;
                return {
                    name,
                    status: 'unhealthy',
                    latencyMs,
                    message: error instanceof Error ? error.message : 'HSM health check failed',
                };
            }
        },
    };
}
/**
 * HSM Configuration Schema for config integration
 *
 * Use this with Zod for configuration validation:
 *
 * @example
 * ```typescript
 * import { z } from 'zod';
 * import { hsmConfigSchema } from '@vorionsys/platform-core/security/hsm';
 *
 * const configSchema = z.object({
 *   // ... other config
 *   hsm: hsmConfigSchema,
 * });
 * ```
 */
export const HSMConfigDefaults = {
    /** Default HSM provider type */
    defaultProvider: 'softhsm',
    /** Available provider types */
    providerTypes: ['aws', 'azure', 'gcp', 'thales', 'softhsm', 'pkcs11'],
    /** Default health check interval in milliseconds */
    healthCheckIntervalMs: 30000,
    /** Default retry configuration */
    retryConfig: {
        maxAttempts: 3,
        initialDelayMs: 100,
        maxDelayMs: 5000,
        backoffMultiplier: 2,
    },
    /** Default key cache TTL in seconds */
    keyCacheTTLSeconds: 300,
    /** Default connection timeout in milliseconds */
    connectionTimeoutMs: 30000,
    /** Default operation timeout in milliseconds */
    operationTimeoutMs: 60000,
};
//# sourceMappingURL=index.js.map