/** * Secure File Reader * * Core file reader implementation with 3-layer security architecture: * - Layer 1: Input Validation & Sanitization * - Layer 2: Security & Resource Controls * - Layer 3: Business Logic & Execution * * Security features: * - O_NOFOLLOW flag to prevent symlink attacks * - TOCTOU-safe file opening via openAndValidateFile() * - Rate limiting per operation * - Audit logging for all operations * - Configurable max read size (default 10MB) * - SHA-256 checksum calculation for integrity * * Performance features: * - Streaming for large files (>100KB) * - Backpressure handling * - Efficient buffer allocation * * @module SecureFileReader * @version 3.2.0 */ import { Readable } from "stream"; import { PathValidatorService } from "../services/path-validator.service.js"; import { RateLimiter } from "../services/security/rate-limiter.service.js"; import { Result } from "./result.js"; import { FileReadOptions, FileReadResult } from "./types.js"; import { FileReadError } from "./errors.js"; /** * Audit logger interface for logging file operations * Part of Layer 2 (Security & Resource Controls) */ export interface IAuditLogger { /** * Log an operation start * @param operation - The operation type * @param path - The file path * @param context - Additional context */ logOperationStart(operation: string, path: string, context?: Record): void; /** * Log a successful operation * @param operation - The operation type * @param path - The file path * @param result - Operation result details */ logOperationSuccess(operation: string, path: string, result: Record): void; /** * Log a failed operation * @param operation - The operation type * @param path - The file path * @param error - The error that occurred */ logOperationFailure(operation: string, path: string, error: Error): void; } /** * Secure file reader implementation with comprehensive security controls * Implements IFileReader interface with Result-based error handling * * @example * ```typescript * const reader = new SecureFileReader( * pathValidator, * rateLimiter, * auditLogger, * 10 * 1024 * 1024 // 10MB limit * ); * * const result = await reader.read('/path/to/file.txt'); * if (result.ok) { * console.log(result.value.data); * } else { * console.error(result.error.message); * } * ``` */ export declare class SecureFileReader { private readonly pathValidator; private readonly rateLimiter; private readonly auditLogger; private readonly maxReadSize; /** Threshold for switching to streaming (100KB) */ private static readonly STREAMING_THRESHOLD; /** Default encoding for text reads */ private static readonly DEFAULT_ENCODING; /** * Creates a new SecureFileReader instance * * @param pathValidator - Service for validating and securing file paths * @param rateLimiter - Rate limiter for operation throttling * @param auditLogger - Logger for audit trail * @param maxReadSize - Maximum bytes to read (default: 10MB) */ constructor(pathValidator: PathValidatorService, rateLimiter: RateLimiter, auditLogger: IAuditLogger, maxReadSize?: number); /** * Read a file completely into memory as string * Uses streaming for files > 100KB for better memory efficiency * * Layer 1: Path validation * Layer 2: Rate limiting, audit logging, size checks * Layer 3: TOCTOU-safe opening, content reading, checksum calculation * * @param filePath - Path to the file to read * @param options - Read options (encoding, maxBytes, offset, signal) * @returns Result with FileReadResult or FileReadError */ read(filePath: string, options?: Partial): Promise>; /** * Create a readable stream for a file * Provides backpressure handling for large files * * Layer 1: Path validation * Layer 2: Rate limiting, audit logging * Layer 3: Stream creation with proper cleanup * * @param filePath - Path to the file to stream * @param options - Read options * @returns Result with Readable stream or FileReadError */ readStream(filePath: string, options?: Partial): Promise>; /** * Read a file into a Buffer * Always returns raw bytes regardless of encoding option * * Layer 1: Path validation * Layer 2: Rate limiting, audit logging, size checks * Layer 3: TOCTOU-safe opening, buffer reading, checksum calculation * * @param filePath - Path to the file to read * @param options - Read options (maxBytes, offset, signal) * @returns Result with Buffer or FileReadError */ readBuffer(filePath: string, options?: Partial): Promise>; /** * Validate file path (Layer 1) * Checks path format, symlinks, and access permissions * * @param filePath - Path to validate * @returns Result with validated path or PathValidationError */ private validatePath; /** * Check for sensitive file patterns * Blocks access to system files, credentials, and sensitive configs * * @param filePath - Path to check * @returns Result with path or PathValidationError */ private checkSensitivePatterns; /** * Check rate limit for operation (Layer 2) * * @param operation - Operation type identifier * @param filePath - File path for context * @returns Result with void or RateLimitError */ private checkRateLimit; /** * Read file content via streaming (for large files) * * @param fileHandle - Open file handle * @param filePath - Path for metadata * @param stats - File stats * @param options - Read options * @returns Result with FileReadResult or FileReadError */ private readViaStream; /** * Read file content via direct buffer (for small files) * * @param fileHandle - Open file handle * @param filePath - Path for metadata * @param stats - File stats * @param options - Read options * @returns Result with FileReadResult or FileReadError */ private readViaBuffer; /** * Calculate SHA-256 checksum of buffer * * @param buffer - Data to hash * @returns Hex-encoded SHA-256 checksum */ private calculateChecksum; /** * Get MIME type from file extension * * @param filePath - File path * @returns MIME type string */ private getMimeType; /** * Merge user options with defaults * * @param options - User-provided options * @returns Merged options with defaults */ private mergeOptions; /** * Convert unknown error to FileReadError * * @param filePath - File path for context * @param error - Error to convert * @returns FileReadError instance */ private convertToFileReadError; /** * Generate unique operation ID for tracing * * @returns Unique operation identifier */ private generateOperationId; } //# sourceMappingURL=secure-file-reader.d.ts.map