/**
 * API Key Management Service
 *
 * Core service for API key lifecycle management including:
 * - Cryptographically secure key generation
 * - Secure key storage (hashed only)
 * - Key validation with timing-safe comparison
 * - Scope checking
 * - Rate limit tracking per key
 * - Key rotation
 * - Expiration checking
 * - Audit logging integration
 *
 * Security Design:
 * - Raw API keys are NEVER stored or logged
 * - Keys are hashed using SHA-256 before storage
 * - Validation uses timing-safe comparison
 * - Key format: vak_${prefix}_${secret}
 *
 * @packageDocumentation
 */
import { VorionError } from '../../common/errors.js';
import { type ApiKey, type ApiKeyScope, type CreateApiKeyInput, type UpdateApiKeyInput, type ApiKeyValidationResult, type ApiKeyCreationResult, type ApiKeyListFilters, type ApiKeyRateLimitResult, ApiKeyValidationErrorCode } from './types.js';
import { type IApiKeyStore } from './store.js';
import { type ApiKeyMetadataCache } from './cache.js';
import { SecurityAuditLogger } from '../../audit/security-logger.js';
/**
 * Base error class for API key operations
 */
export declare class ApiKeyError extends VorionError {
    code: string;
    statusCode: number;
    constructor(message: string, details?: Record<string, unknown>);
}
/**
 * Error thrown when API key validation fails
 */
export declare class ApiKeyValidationError extends ApiKeyError {
    readonly errorCode: ApiKeyValidationErrorCode;
    code: string;
    statusCode: number;
    constructor(message: string, errorCode: ApiKeyValidationErrorCode, details?: Record<string, unknown>);
}
/**
 * Error thrown when rate limit is exceeded
 */
export declare class ApiKeyRateLimitError extends ApiKeyError {
    readonly retryAfter: number;
    code: string;
    statusCode: number;
    constructor(message: string, retryAfter: number, details?: Record<string, unknown>);
}
/**
 * Audit logging interface (legacy - use SecurityAuditLogger for new code)
 */
export interface IAuditLogger {
    record(input: {
        tenantId: string;
        eventType: string;
        actor: {
            type: 'user' | 'agent' | 'service' | 'system';
            id: string;
            name?: string;
        };
        target: {
            type: string;
            id: string;
            name?: string;
        };
        action: string;
        outcome: 'success' | 'failure' | 'partial';
        reason?: string;
        metadata?: Record<string, unknown>;
    }): Promise<void>;
}
/**
 * API Key Service Dependencies
 */
export interface ApiKeyServiceDependencies {
    /** API key store */
    store?: IApiKeyStore;
    /** Audit logger (legacy) */
    auditLogger?: IAuditLogger;
    /** Security audit logger (preferred) */
    securityLogger?: SecurityAuditLogger;
    /** API key metadata cache */
    cache?: ApiKeyMetadataCache;
}
/**
 * API Key Management Service
 */
export declare class ApiKeyService {
    private store;
    private auditLogger?;
    private securityLogger;
    private cache;
    constructor(deps?: ApiKeyServiceDependencies);
    /**
     * Generate a cryptographically secure API key
     *
     * Key format: vak_${prefix}_${secret}
     * - vak: Vorion API Key identifier
     * - prefix: 8 character alphanumeric identifier (for lookup)
     * - secret: 43 character base64url encoded random bytes (32 bytes)
     *
     * @returns Object with full key and its components
     */
    private generateApiKey;
    /**
     * Hash an API key using SHA-256
     */
    private hashKey;
    /**
     * Parse an API key into its components
     */
    private parseKey;
    /**
     * Create a new API key
     *
     * @param input - Key creation parameters
     * @returns The created key record and raw key (shown only once)
     */
    create(input: CreateApiKeyInput): Promise<ApiKeyCreationResult>;
    /**
     * Get an API key by ID
     */
    getById(id: string, tenantId: string): Promise<ApiKey | null>;
    /**
     * Update an API key
     */
    update(id: string, tenantId: string, input: UpdateApiKeyInput, updatedBy: string): Promise<ApiKey>;
    /**
     * Revoke an API key
     */
    revoke(id: string, tenantId: string, revokedBy: string, reason?: string): Promise<ApiKey>;
    /**
     * Delete an API key permanently
     */
    delete(id: string, tenantId: string, deletedBy: string): Promise<void>;
    /**
     * List API keys with filters
     */
    list(filters: ApiKeyListFilters): Promise<{
        keys: ApiKey[];
        total: number;
    }>;
    /**
     * Validate an API key
     *
     * Uses a two-tier caching strategy for performance:
     * 1. Check in-memory LRU cache (< 0.1ms)
     * 2. Check Redis cache (< 1-2ms)
     * 3. Fall back to database lookup (10-30ms)
     *
     * Uses timing-safe comparison to prevent timing attacks.
     *
     * @param rawKey - The raw API key to validate
     * @param clientIp - Optional client IP for whitelist validation
     * @returns Validation result
     */
    validate(rawKey: string, clientIp?: string): Promise<ApiKeyValidationResult>;
    /**
     * Validate API key from cached metadata
     *
     * Performs timing-safe hash comparison and status checks
     * using cached metadata.
     */
    private validateFromCache;
    /**
     * Validate API key from full database record
     *
     * Used on cache miss after fetching from database.
     */
    private validateApiKey;
    /**
     * Check if an API key has a required scope
     */
    hasScope(apiKey: ApiKey, requiredScope: ApiKeyScope): boolean;
    /**
     * Check if an API key has all required scopes
     */
    hasAllScopes(apiKey: ApiKey, requiredScopes: ApiKeyScope[]): boolean;
    /**
     * Check if an API key has any of the required scopes
     */
    hasAnyScope(apiKey: ApiKey, requiredScopes: ApiKeyScope[]): boolean;
    /**
     * Check and consume rate limit for an API key
     */
    checkRateLimit(apiKey: ApiKey): Promise<ApiKeyRateLimitResult>;
    /**
     * Create initial rate limit state
     */
    private createInitialRateLimitState;
    /**
     * Reset expired windows
     */
    private resetExpiredWindows;
    /**
     * Rotate an API key (create new key, optionally keep old valid for grace period)
     *
     * @param id - ID of the key to rotate
     * @param tenantId - Tenant ID
     * @param rotatedBy - User performing the rotation
     * @param gracePeriodMinutes - Optional grace period to keep old key valid
     * @returns New key creation result
     */
    rotate(id: string, tenantId: string, rotatedBy: string, gracePeriodMinutes?: number): Promise<ApiKeyCreationResult>;
    /**
     * Record an audit event
     */
    private audit;
}
/**
 * Get the API key service singleton
 */
export declare function getApiKeyService(): ApiKeyService;
/**
 * Create a new API key service instance
 */
export declare function createApiKeyService(deps?: ApiKeyServiceDependencies): ApiKeyService;
/**
 * Reset the API key service singleton (for testing)
 */
export declare function resetApiKeyService(): void;
//# sourceMappingURL=service.d.ts.map