/**
 * Request Integrity Verification Module
 *
 * Implements HMAC-SHA256 request signing with replay attack prevention.
 * Features include:
 * - HMAC-SHA256 signature generation and verification
 * - Nonce tracking using Redis or in-memory storage
 * - Timestamp validation to reject stale requests
 * - Fastify middleware integration
 * - Configurable path exclusions
 *
 * @packageDocumentation
 * @module security/request-integrity
 */
import type { FastifyRequest, preHandlerHookHandler } from 'fastify';
import type { Redis } from 'ioredis';
/**
 * Signed request metadata
 */
export interface SignedRequest {
    /** Unix timestamp in milliseconds when the request was signed */
    timestamp: number;
    /** Unique nonce to prevent replay attacks */
    nonce: string;
    /** HMAC-SHA256 signature of the request */
    signature: string;
    /** Algorithm used for signing */
    algorithm: 'HMAC-SHA256';
}
/**
 * Configuration for request integrity verification
 */
export interface RequestIntegrityConfig {
    /** Whether request integrity verification is enabled */
    enabled: boolean;
    /** Secret key used for HMAC signing (minimum 32 characters) */
    secretKey: string;
    /** Maximum age of requests in milliseconds (default: 300000 = 5 minutes) */
    maxAgeMs: number;
    /** Storage backend for nonce tracking */
    nonceStore: 'memory' | 'redis';
    /** Time-to-live for nonces in milliseconds (default: 600000 = 10 minutes) */
    nonceTTLMs: number;
    /** Paths to exclude from integrity verification */
    excludePaths: string[];
    /** Clock skew tolerance in milliseconds (default: 60000 = 1 minute) */
    clockSkewMs?: number;
}
/**
 * Result of request integrity verification
 */
export interface IntegrityVerificationResult {
    /** Whether the request passed integrity verification */
    valid: boolean;
    /** Error message if verification failed */
    error?: string;
    /** Error code for programmatic handling */
    errorCode?: IntegrityErrorCode;
}
/**
 * Error codes for integrity verification failures
 */
export type IntegrityErrorCode = 'MISSING_SIGNATURE' | 'MISSING_TIMESTAMP' | 'MISSING_NONCE' | 'INVALID_TIMESTAMP' | 'REQUEST_TOO_OLD' | 'REQUEST_FROM_FUTURE' | 'INVALID_SIGNATURE' | 'REPLAY_DETECTED' | 'DISABLED';
/**
 * Input for signing a request
 */
export interface SignRequestInput {
    /** HTTP method (GET, POST, etc.) */
    method: string;
    /** Request path (including query string if applicable) */
    path: string;
    /** Request body (optional, for POST/PUT/PATCH) */
    body?: string | object;
    /** Custom timestamp (optional, defaults to current time) */
    timestamp?: number;
}
/**
 * Default configuration for request integrity
 */
export declare const DEFAULT_REQUEST_INTEGRITY_CONFIG: RequestIntegrityConfig;
/**
 * Request Integrity Service
 *
 * Provides HMAC-SHA256 request signing and verification with replay attack
 * prevention using nonce tracking.
 *
 * @example
 * ```typescript
 * const integrity = new RequestIntegrity({
 *   secretKey: process.env.REQUEST_SIGNING_KEY,
 *   maxAgeMs: 300000,
 *   nonceStore: 'redis',
 * });
 *
 * // Sign a request
 * const signed = integrity.signRequest({
 *   method: 'POST',
 *   path: '/api/sensitive-action',
 *   body: { action: 'transfer', amount: 1000 },
 * });
 *
 * // Verify a request in middleware
 * fastify.addHook('preHandler', integrity.middleware());
 * ```
 */
export declare class RequestIntegrity {
    private readonly config;
    private readonly redis;
    private readonly memoryStore;
    /**
     * Creates a new RequestIntegrity instance
     *
     * @param config - Configuration options
     * @param redis - Optional Redis instance (uses shared instance if not provided)
     * @throws {Error} If secret key is not provided or too short
     */
    constructor(config?: Partial<RequestIntegrityConfig>, redis?: Redis);
    /**
     * Signs a request and returns the signature metadata
     *
     * The signature is computed as:
     * HMAC-SHA256(method + path + body + timestamp + nonce, secretKey)
     *
     * @param input - Request data to sign
     * @returns Signed request metadata
     */
    signRequest(input: SignRequestInput): SignedRequest;
    /**
     * Verifies request integrity and checks for replay attacks
     *
     * Performs the following checks:
     * 1. Required headers are present
     * 2. Timestamp is within acceptable range
     * 3. Signature is valid
     * 4. Nonce has not been used before
     *
     * @param request - Fastify request object
     * @param signature - Signature metadata from headers
     * @returns Verification result
     */
    verifyRequest(request: FastifyRequest, signature: SignedRequest): Promise<IntegrityVerificationResult>;
    /**
     * Creates Fastify middleware for request integrity verification
     *
     * @returns Fastify preHandler hook function
     */
    middleware(): preHandlerHookHandler;
    /**
     * Checks if a nonce has already been used
     *
     * @param nonce - The nonce to check
     * @returns True if the nonce has been used (replay attack)
     */
    isReplay(nonce: string): Promise<boolean>;
    /**
     * Records a nonce to prevent replay attacks
     *
     * @param nonce - The nonce to record
     */
    recordNonce(nonce: string): Promise<void>;
    /**
     * Gets the current configuration
     *
     * @returns A copy of the current configuration (with secret redacted)
     */
    getConfig(): Omit<RequestIntegrityConfig, 'secretKey'> & {
        secretKey: string;
    };
    /**
     * Checks if the service is enabled
     */
    isEnabled(): boolean;
    /**
     * Cleans up resources (call when shutting down)
     */
    destroy(): void;
    /**
     * Generates a cryptographically secure nonce
     */
    private generateNonce;
    /**
     * Normalizes request body for signing
     */
    private normalizeBody;
    /**
     * Creates the data string for signing
     */
    private createSignatureData;
    /**
     * Creates an HMAC-SHA256 signature
     */
    private createSignature;
    /**
     * Validates request timestamp
     */
    private validateTimestamp;
    /**
     * Performs constant-time string comparison to prevent timing attacks
     */
    private constantTimeCompare;
    /**
     * Checks if a path should be excluded from verification
     */
    private isPathExcluded;
}
declare module 'fastify' {
    interface FastifyRequest {
        /** Whether request integrity has been verified */
        integrityVerified?: boolean;
    }
}
/**
 * Gets or creates the singleton RequestIntegrity instance
 *
 * Creates the instance on first call using configuration from environment.
 * Subsequent calls return the same instance.
 *
 * @param config - Optional configuration (only used on first call)
 * @returns The RequestIntegrity singleton instance
 * @throws {Error} If secret key is not configured
 *
 * @example
 * ```typescript
 * // Initialize with custom config
 * const integrity = getRequestIntegrity({
 *   secretKey: process.env.REQUEST_SIGNING_KEY,
 *   maxAgeMs: 300000,
 * });
 *
 * // Register middleware
 * fastify.addHook('preHandler', integrity.middleware());
 *
 * // Later, get the same instance
 * const sameIntegrity = getRequestIntegrity();
 * ```
 */
export declare function getRequestIntegrity(config?: Partial<RequestIntegrityConfig>): RequestIntegrity;
/**
 * Resets the singleton instance (useful for testing)
 *
 * @internal
 */
export declare function resetRequestIntegrity(): void;
/**
 * Creates request signing headers from a SignedRequest
 *
 * @param signed - The signed request metadata
 * @returns Headers object to add to the request
 *
 * @example
 * ```typescript
 * const integrity = getRequestIntegrity();
 * const signed = integrity.signRequest({
 *   method: 'POST',
 *   path: '/api/transfer',
 *   body: { amount: 1000 },
 * });
 *
 * const headers = createSignatureHeaders(signed);
 * // Use headers in fetch or HTTP client
 * fetch('/api/transfer', {
 *   method: 'POST',
 *   headers: {
 *     ...headers,
 *     'Content-Type': 'application/json',
 *   },
 *   body: JSON.stringify({ amount: 1000 }),
 * });
 * ```
 */
export declare function createSignatureHeaders(signed: SignedRequest): Record<string, string>;
/**
 * Extracts signature metadata from request headers
 *
 * @param headers - Request headers object
 * @returns SignedRequest or null if headers are missing/invalid
 */
export declare function extractSignatureFromHeaders(headers: Record<string, string | string[] | undefined>): SignedRequest | null;
/**
 * Header names used for request signing
 */
export declare const INTEGRITY_HEADERS: {
    readonly SIGNATURE: "x-vorion-signature";
    readonly TIMESTAMP: "x-vorion-timestamp";
    readonly NONCE: "x-vorion-nonce";
    readonly ALGORITHM: "x-vorion-algorithm";
};
export default RequestIntegrity;
//# sourceMappingURL=request-integrity.d.ts.map