/**
 * Secrets Rotation Service
 *
 * Manages automatic rotation of sensitive secrets like JWT signing keys,
 * encryption keys, and API credentials. Provides graceful rotation with
 * overlapping validity periods, audit logging, and event emission.
 *
 * Security Features:
 * - Never logs secret values
 * - Secure memory handling via SecureString/SecureBuffer
 * - Multiple active versions during rotation grace period
 * - Comprehensive audit trail for all operations
 * - Event emission for integration with monitoring systems
 *
 * @packageDocumentation
 * @module security/secrets-rotation
 */
import { EventEmitter } from 'node:events';
import { z } from 'zod';
import { VorionError } from '../common/errors.js';
import { type EncryptedEnvelope } from '../common/encryption.js';
import { SecureString } from './secure-memory.js';
/**
 * Types of secrets that can be managed by the rotation service
 */
export declare enum SecretType {
    JWT_SIGNING_KEY = "jwt_signing_key",
    ENCRYPTION_KEY = "encryption_key",
    API_SECRET = "api_secret",
    SESSION_SECRET = "session_secret",
    WEBHOOK_SECRET = "webhook_secret"
}
export declare const secretTypeSchema: z.ZodNativeEnum<typeof SecretType>;
export declare const secretStatusSchema: z.ZodEnum<["active", "rotating", "deprecated", "revoked"]>;
export type SecretStatus = z.infer<typeof secretStatusSchema>;
export declare const secretMetadataSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
export declare const secretSchema: z.ZodObject<{
    id: z.ZodString;
    type: z.ZodNativeEnum<typeof SecretType>;
    version: z.ZodNumber;
    value: z.ZodObject<{
        ciphertext: z.ZodString;
        iv: z.ZodString;
        authTag: z.ZodString;
        version: z.ZodLiteral<1>;
        kdfVersion: z.ZodOptional<z.ZodNumber>;
    }, "strip", z.ZodTypeAny, {
        version?: 1;
        kdfVersion?: number;
        ciphertext?: string;
        iv?: string;
        authTag?: string;
    }, {
        version?: 1;
        kdfVersion?: number;
        ciphertext?: string;
        iv?: string;
        authTag?: string;
    }>;
    createdAt: z.ZodDate;
    expiresAt: z.ZodOptional<z.ZodDate>;
    rotatedAt: z.ZodOptional<z.ZodDate>;
    status: z.ZodEnum<["active", "rotating", "deprecated", "revoked"]>;
    metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
}, "strip", z.ZodTypeAny, {
    version?: number;
    value?: {
        version?: 1;
        kdfVersion?: number;
        ciphertext?: string;
        iv?: string;
        authTag?: string;
    };
    id?: string;
    status?: "deprecated" | "active" | "revoked" | "rotating";
    type?: SecretType;
    metadata?: Record<string, unknown>;
    createdAt?: Date;
    expiresAt?: Date;
    rotatedAt?: Date;
}, {
    version?: number;
    value?: {
        version?: 1;
        kdfVersion?: number;
        ciphertext?: string;
        iv?: string;
        authTag?: string;
    };
    id?: string;
    status?: "deprecated" | "active" | "revoked" | "rotating";
    type?: SecretType;
    metadata?: Record<string, unknown>;
    createdAt?: Date;
    expiresAt?: Date;
    rotatedAt?: Date;
}>;
export declare const rotationPolicySchema: z.ZodObject<{
    secretType: z.ZodNativeEnum<typeof SecretType>;
    rotationIntervalDays: z.ZodNumber;
    gracePeriodHours: z.ZodNumber;
    notifyBeforeDays: z.ZodNumber;
    autoRotate: z.ZodBoolean;
    validationFn: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodString], z.ZodUnknown>, z.ZodBoolean>>;
}, "strip", z.ZodTypeAny, {
    secretType?: SecretType;
    rotationIntervalDays?: number;
    gracePeriodHours?: number;
    notifyBeforeDays?: number;
    autoRotate?: boolean;
    validationFn?: (args_0: string, ...args: unknown[]) => boolean;
}, {
    secretType?: SecretType;
    rotationIntervalDays?: number;
    gracePeriodHours?: number;
    notifyBeforeDays?: number;
    autoRotate?: boolean;
    validationFn?: (args_0: string, ...args: unknown[]) => boolean;
}>;
/**
 * Represents a managed secret with encrypted value
 */
export interface Secret {
    /** Unique identifier for the secret */
    id: string;
    /** Type of secret */
    type: SecretType;
    /** Version number (monotonically increasing) */
    version: number;
    /** Encrypted secret value */
    value: EncryptedEnvelope;
    /** When the secret was created */
    createdAt: Date;
    /** When the secret expires */
    expiresAt?: Date;
    /** When the secret was rotated (marked for retirement) */
    rotatedAt?: Date;
    /** Current status of the secret */
    status: SecretStatus;
    /** Custom metadata attributes */
    metadata?: Record<string, unknown>;
}
/**
 * Configuration for automatic secret rotation
 */
export interface RotationPolicy {
    /** Type of secret this policy applies to */
    secretType: SecretType;
    /** Days between rotations */
    rotationIntervalDays: number;
    /** Hours to keep old secret valid after rotation */
    gracePeriodHours: number;
    /** Days before expiration to send notification */
    notifyBeforeDays: number;
    /** Whether to automatically rotate secrets */
    autoRotate: boolean;
    /** Optional custom validation function for generated secrets */
    validationFn?: (value: string) => boolean;
}
/**
 * Events emitted by the secrets rotation service
 */
export interface SecretRotationEvents {
    'secret:registered': {
        secret: Omit<Secret, 'value'>;
        type: SecretType;
    };
    'secret:rotated': {
        oldVersion: number;
        newVersion: number;
        type: SecretType;
    };
    'secret:deprecated': {
        secretId: string;
        version: number;
        type: SecretType;
    };
    'secret:revoked': {
        secretId: string;
        version: number;
        type: SecretType;
        reason: string;
    };
    'secret:expiring': {
        secretId: string;
        version: number;
        type: SecretType;
        daysUntilExpiry: number;
    };
    'rotation:scheduled': {
        type: SecretType;
        nextRotation: Date;
    };
    'rotation:due': {
        type: SecretType;
        secretId: string;
    };
    'rotation:error': {
        type: SecretType;
        error: Error;
    };
}
/**
 * Input for registering a new secret
 */
export interface RegisterSecretInput {
    type: SecretType;
    value: string;
    expiresAt?: Date;
    metadata?: Record<string, unknown>;
}
/**
 * Result of checking which secrets need rotation
 */
export interface RotationDueResult {
    type: SecretType;
    secretId: string;
    version: number;
    daysUntilExpiry: number;
    needsRotation: boolean;
    needsNotification: boolean;
}
/**
 * Audit log entry for secret operations
 */
export interface SecretAuditEntry {
    timestamp: Date;
    operation: string;
    secretType: SecretType;
    secretId?: string;
    version?: number;
    actorId?: string;
    reason?: string;
    success: boolean;
    errorMessage?: string;
}
/**
 * Error thrown for secrets rotation operations
 */
export declare class SecretsRotationError extends VorionError {
    code: string;
    statusCode: number;
    constructor(message: string, details?: Record<string, unknown>);
}
/**
 * Error thrown when a secret is not found
 */
export declare class SecretNotFoundError extends VorionError {
    code: string;
    statusCode: number;
    constructor(secretId: string, details?: Record<string, unknown>);
}
/**
 * Error thrown when secret validation fails
 */
export declare class SecretValidationError extends VorionError {
    code: string;
    statusCode: number;
    constructor(message: string, details?: Record<string, unknown>);
}
/**
 * Generate a JWT signing secret with 256-bit entropy
 *
 * Uses cryptographically secure random bytes encoded as base64url
 * for safe use in JWT headers.
 *
 * @returns Base64url-encoded JWT secret
 */
export declare function generateJWTSecret(): string;
/**
 * Generate an AES-256 encryption key
 *
 * @returns Hex-encoded 256-bit key
 */
export declare function generateEncryptionKey(): string;
/**
 * Generate a URL-safe random API secret
 *
 * Uses base64url encoding for safe use in URLs and headers.
 *
 * @param length - Number of random bytes (default: 32)
 * @returns URL-safe base64-encoded secret
 */
export declare function generateAPISecret(length?: number): string;
/**
 * Generate a secret based on its type
 */
export declare function generateSecretByType(type: SecretType): string;
/**
 * Default rotation policies for each secret type
 */
export declare const DEFAULT_ROTATION_POLICIES: Record<SecretType, RotationPolicy>;
/**
 * Service for managing automatic rotation of sensitive secrets
 *
 * Provides comprehensive secret lifecycle management including:
 * - Registration of secrets with automatic encryption
 * - Graceful rotation with overlapping validity periods
 * - Version tracking for rollback support
 * - Automatic scheduling and notification
 * - Full audit trail of all operations
 *
 * @example
 * ```typescript
 * const service = getSecretsRotationService();
 * await service.initialize();
 *
 * // Register a new JWT secret
 * const secret = await service.registerSecret({
 *   type: SecretType.JWT_SIGNING_KEY,
 *   value: generateJWTSecret(),
 * });
 *
 * // Get the active secret for signing
 * const activeSecret = await service.getActiveSecret(SecretType.JWT_SIGNING_KEY);
 * activeSecret.use((value) => {
 *   // Use the secret value
 * });
 *
 * // Rotate the secret
 * await service.rotateSecret(SecretType.JWT_SIGNING_KEY);
 * ```
 */
export declare class SecretsRotationService extends EventEmitter {
    private initialized;
    private redis;
    private policies;
    private schedulerTimer;
    private auditLog;
    private checkIntervalMs;
    /**
     * Initialize the secrets rotation service
     */
    initialize(): Promise<void>;
    /**
     * Ensure the service is initialized
     */
    private ensureInitialized;
    /**
     * Get the Redis client
     */
    private getRedis;
    /**
     * Load custom policies from Redis storage
     */
    private loadPoliciesFromStorage;
    /**
     * Record an audit entry
     */
    private recordAudit;
    /**
     * Get the next version number for a secret type
     */
    private getNextVersion;
    /**
     * Register a new secret for rotation management
     *
     * @param input - Secret registration input
     * @returns The registered secret (without value)
     */
    registerSecret(input: RegisterSecretInput): Promise<Omit<Secret, 'value'>>;
    /**
     * Get a secret by ID (internal use only)
     */
    private getSecretById;
    /**
     * Get the active secret internal (without SecureString wrapping)
     */
    private getActiveSecretInternal;
    /**
     * Get the current active secret for a type
     *
     * Returns a SecureString containing the decrypted value for safe usage.
     *
     * @param type - Type of secret to retrieve
     * @returns SecureString containing the secret value, or null if not found
     */
    getActiveSecret(type: SecretType): Promise<SecureString | null>;
    /**
     * Get all secrets that are currently valid (active or rotating)
     *
     * This is useful during rotation when both old and new secrets need to be valid.
     *
     * @param type - Type of secrets to retrieve
     * @returns Array of valid secrets with SecureString values
     */
    getValidSecrets(type: SecretType): Promise<Array<{
        metadata: Omit<Secret, 'value'>;
        value: SecureString;
    }>>;
    /**
     * Get all versions of a secret type for rollback support
     *
     * @param type - Type of secrets to retrieve
     * @returns Array of secret metadata (without values)
     */
    getSecretVersions(type: SecretType): Promise<Array<Omit<Secret, 'value'>>>;
    /**
     * Perform secret rotation
     *
     * Generates a new secret, marks the old one as rotating, and keeps both
     * valid during the grace period.
     *
     * @param type - Type of secret to rotate
     * @param customValue - Optional custom value for the new secret
     * @returns The new secret metadata
     */
    rotateSecret(type: SecretType, customValue?: string): Promise<Omit<Secret, 'value'>>;
    /**
     * Mark a secret version as deprecated
     *
     * Deprecated secrets can no longer be used for new operations but may still
     * be used for verification during a transition period.
     *
     * @param secretId - ID of the secret to deprecate
     * @param reason - Reason for deprecation
     */
    deprecateVersion(secretId: string, reason?: string): Promise<void>;
    /**
     * Immediately revoke a secret version
     *
     * Revoked secrets are immediately invalid and cannot be used for any operations.
     * Use this for emergency key compromise situations.
     *
     * @param secretId - ID of the secret to revoke
     * @param reason - Reason for revocation
     */
    revokeVersion(secretId: string, reason: string): Promise<void>;
    /**
     * Set or update a rotation policy for a secret type
     *
     * @param policy - The rotation policy to set
     */
    setRotationPolicy(policy: RotationPolicy): Promise<void>;
    /**
     * Get the rotation policy for a secret type
     *
     * @param type - Type of secret
     * @returns The rotation policy
     */
    getRotationPolicy(type: SecretType): RotationPolicy;
    /**
     * Check which secrets need rotation or notification
     *
     * @returns Array of rotation due results
     */
    checkRotationDue(): Promise<RotationDueResult[]>;
    /**
     * Schedule automatic rotation checks
     *
     * @param options - Scheduler options
     */
    scheduleRotation(options?: {
        checkIntervalMs?: number;
    }): void;
    /**
     * Run a scheduled rotation check
     */
    private runScheduledRotationCheck;
    /**
     * Stop the rotation scheduler
     */
    stopScheduler(): void;
    /**
     * Get the audit log
     *
     * @param filters - Optional filters
     * @returns Filtered audit entries
     */
    getAuditLog(filters?: {
        secretType?: SecretType;
        operation?: string;
        since?: Date;
        limit?: number;
    }): SecretAuditEntry[];
    /**
     * Shutdown the service
     */
    shutdown(): void;
}
/**
 * Get the singleton instance of the SecretsRotationService
 */
export declare function getSecretsRotationService(): SecretsRotationService;
/**
 * Reset the singleton instance (primarily for testing)
 */
export declare function resetSecretsRotationService(): void;
/**
 * Type-safe event listener registration
 */
export type SecretRotationEventHandler<K extends keyof SecretRotationEvents> = (payload: SecretRotationEvents[K]) => void;
/**
 * Helper type for adding typed event listeners to the service
 */
export interface TypedSecretsRotationService {
    on<K extends keyof SecretRotationEvents>(event: K, listener: SecretRotationEventHandler<K>): SecretsRotationService;
    once<K extends keyof SecretRotationEvents>(event: K, listener: SecretRotationEventHandler<K>): SecretsRotationService;
    emit<K extends keyof SecretRotationEvents>(event: K, payload: SecretRotationEvents[K]): boolean;
}
//# sourceMappingURL=secrets-rotation.d.ts.map