import { EventEmitter } from 'events'; /** * Safe Command Mode - Flexible security for Battle Framework * Allows legitimate complex commands while blocking malicious ones */ declare enum SecurityLevel { STRICT = "strict",// Block all shell metacharacters BALANCED = "balanced",// Allow safe patterns, block dangerous ones PERMISSIVE = "permissive" } declare class SafeCommandMode { /** * Validates commands based on security level and use case */ static validateCommand(command: string, level?: SecurityLevel, context?: string): { valid: boolean; sanitized?: string; error?: string; }; /** * STRICT mode - Block all shell metacharacters * Good for: Public APIs, untrusted input */ private static validateStrict; /** * BALANCED mode - Allow legitimate use cases * Good for: Testing interactive applications, scripting */ private static validateBalanced; /** * PERMISSIVE mode - Allow most legitimate uses * Good for: Internal tools, development, advanced users */ private static validatePermissive; /** * Creates a safe command execution context */ static createSafeContext(level: SecurityLevel): SafeCommandContext; } /** * Safe command execution context */ declare class SafeCommandContext { private level; private executedCommands; constructor(level: SecurityLevel); /** * Validates and executes a command safely */ validateAndExecute(command: string, args?: string[]): { valid: boolean; fullCommand?: string; error?: string; }; /** * Gets execution history */ getHistory(): string[]; /** * Clears execution history */ clearHistory(): void; } interface BattleOptions { command?: string; args?: string[]; cols?: number; rows?: number; cwd?: string; env?: NodeJS.ProcessEnv; timeout?: number; screenshotDir?: string; logDir?: string; verbose?: boolean; securityLevel?: SecurityLevel; safeCommandMode?: boolean; } interface TestResult { success: boolean; duration: number; output: string; screenshots: string[]; logs: string[]; error: string | null; replayPath?: string; } type InteractionHandler = (data: string, fullOutput: string) => Promise | string | null; interface TestCase { name: string; command: string; args?: string[]; interactions?: Array<{ expect: string | RegExp; respond: string; }>; expectations?: Array; timeout?: number; } interface TestSuite { name: string; tests: TestCase[]; beforeAll?: () => Promise | void; afterAll?: () => Promise | void; beforeEach?: () => Promise | void; afterEach?: () => Promise | void; } interface ReplayEvent { type: 'spawn' | 'output' | 'input' | 'resize' | 'key' | 'screenshot' | 'expect' | 'exit'; timestamp: number; data: any; } interface ReplayData { version: string; timestamp: string; duration: number; events: ReplayEvent[]; metadata: { cols: number; rows: number; command: string; args: string[]; env: Record; }; } /** * Battle Replay System * Records and replays terminal sessions like StarCraft replays */ declare class Replay { data: ReplayData; events: ReplayEvent[]; startTime: number; constructor(); record(event: ReplayEvent): void; save(path: string): string; load(path: string): void; play(options?: any): Promise; export(format: 'json' | 'html'): string; } /** * Battle Test Framework Core * Universal terminal testing with real PTY emulation */ declare class Battle { options: BattleOptions; pty: any; output: string; screenshots: string[]; logs: string[]; startTime: number; replay: Replay; constructor(options?: BattleOptions); spawn(command: string, args?: string[]): Promise; interact(handler: InteractionHandler): Promise; screenshot(name?: string): string; expect(pattern: string | RegExp, timeout?: number): Promise; expectVisualChange(timeout?: number): Promise; sendKeyAndDetectResponse(key: string, timeout?: number): Promise; log(level: string, message: string): void; cleanup(): void; run(testFn: (battle: Battle) => Promise): Promise; resize(cols: number, rows: number): void; sendKey(key: string): void; write(data: string): void; wait(ms: number): Promise; getCursor(): Promise<{ x: number; y: number; } | null>; } /** * Battle Test Runner * Executes test suites and reports results */ declare class Runner { suites: TestSuite[]; results: any[]; options: any; constructor(options?: any); suite(name: string, tests: TestCase[]): void; test(name: string, testCase: TestCase): void; run(): Promise<{ total: number; passed: number; failed: number; }>; report(): void; } /** * Silent - Testing for non-interactive/system apps * Tests commands that don't need PTY emulation */ declare class Silent { private logs; private startTime; /** * Run a command and capture output * WARNING: This is inherently unsafe - use Battle.spawn() for secure command execution */ exec(command: string, options?: any): { success: boolean; stdout: string; stderr: string; exitCode: number | null; }; /** * Check if a process is running (DEPRECATED - security risk) * @deprecated Use process monitoring libraries instead of shell commands */ isRunning(pattern: string): boolean; /** * Check if a port is open */ isPortOpen(port: number, host?: string): boolean; /** * Check if a file exists */ fileExists(filepath: string): boolean; /** * Read file content with security validation */ readFile(filepath: string): string; /** * Check system resources (DEPRECATED - security risk) * @deprecated Use Node.js process.cpuUsage() and process.memoryUsage() instead */ checkResources(): { cpu: number; memory: number; disk: number; }; /** * Wait for condition */ waitFor(condition: () => boolean, timeout?: number, interval?: number): Promise; private log; getLogs(): string[]; } /** * Security utilities for Battle Framework * Provides comprehensive input validation, sanitization, and security measures */ /** * Validates and sanitizes command input to prevent injection attacks */ declare class CommandSanitizer { private static readonly ALLOWED_CHARS; private static readonly DANGEROUS_PATTERNS; /** * Validates if a command is safe to execute */ static validate(command: string): { valid: boolean; error?: string; }; /** * Sanitizes command arguments */ static sanitizeArgs(args: string[]): string[]; /** * Escapes shell arguments properly */ static escapeShellArg(arg: string): string; } /** * Environment variable sanitizer */ declare class EnvSanitizer { private static readonly BLOCKED_VARS; private static readonly SENSITIVE_PATTERNS; /** * Sanitizes environment variables */ static sanitize(env: Record): Record; /** * Creates safe environment for PTY */ static createSafeEnv(userEnv?: Record): Record; } /** * JSON Schema validator for replay files */ declare class ReplayValidator { private static readonly SCHEMA; /** * Validates replay data structure */ static validate(data: any): { valid: boolean; error?: string; }; /** * Safely parse JSON with validation */ static parse(json: string): any; } /** * Path security utilities */ declare class PathSecurity { /** * Validates and normalizes file paths */ static validatePath(filePath: string, basePath: string): { valid: boolean; normalized?: string; error?: string; }; /** * Creates safe temporary directory */ static createSafeTempDir(): string; } /** * Resource limiter to prevent DoS */ declare class ResourceLimiter { private static readonly MAX_OUTPUT_SIZE; private static readonly MAX_EVENTS; private static readonly MAX_PTY_INSTANCES; private static ptyInstances; /** * Checks if resource limit is exceeded */ static checkOutputSize(size: number): boolean; /** * Checks if event count limit is exceeded */ static checkEventCount(count: number): boolean; /** * Tracks PTY instance creation */ static acquirePTY(): boolean; /** * Releases PTY instance */ static releasePTY(): void; } /** * Secure error handler that prevents information disclosure */ declare class SecureErrorHandler { private static readonly ERROR_MAP; /** * Sanitizes error messages to prevent information disclosure */ static sanitize(error: any): string; /** * Logs error securely */ static log(error: any, context?: string): void; } declare const _default: { CommandSanitizer: typeof CommandSanitizer; EnvSanitizer: typeof EnvSanitizer; ReplayValidator: typeof ReplayValidator; PathSecurity: typeof PathSecurity; ResourceLimiter: typeof ResourceLimiter; SecureErrorHandler: typeof SecureErrorHandler; }; type index_CommandSanitizer = CommandSanitizer; declare const index_CommandSanitizer: typeof CommandSanitizer; type index_EnvSanitizer = EnvSanitizer; declare const index_EnvSanitizer: typeof EnvSanitizer; type index_PathSecurity = PathSecurity; declare const index_PathSecurity: typeof PathSecurity; type index_ReplayValidator = ReplayValidator; declare const index_ReplayValidator: typeof ReplayValidator; type index_ResourceLimiter = ResourceLimiter; declare const index_ResourceLimiter: typeof ResourceLimiter; type index_SafeCommandContext = SafeCommandContext; declare const index_SafeCommandContext: typeof SafeCommandContext; type index_SafeCommandMode = SafeCommandMode; declare const index_SafeCommandMode: typeof SafeCommandMode; type index_SecureErrorHandler = SecureErrorHandler; declare const index_SecureErrorHandler: typeof SecureErrorHandler; type index_SecurityLevel = SecurityLevel; declare const index_SecurityLevel: typeof SecurityLevel; declare namespace index { export { index_CommandSanitizer as CommandSanitizer, index_EnvSanitizer as EnvSanitizer, index_PathSecurity as PathSecurity, index_ReplayValidator as ReplayValidator, index_ResourceLimiter as ResourceLimiter, index_SafeCommandContext as SafeCommandContext, index_SafeCommandMode as SafeCommandMode, index_SecureErrorHandler as SecureErrorHandler, index_SecurityLevel as SecurityLevel, _default as default }; } /** * Circular buffer implementation to prevent unbounded memory growth * Maintains a fixed-size buffer that overwrites old data when full */ declare class CircularBuffer { private buffer; private maxSize; private totalBytes; private maxBytes; private head; private tail; private count; constructor(maxSize?: number, maxBytes?: number); /** * Appends data to the buffer */ append(data: string): void; /** * Removes the oldest item from the buffer */ private removeOldest; /** * Gets all data as a single string */ toString(): string; /** * Gets the last N characters */ getLastChars(n: number): string; /** * Searches for a pattern in the buffer */ includes(pattern: string): boolean; /** * Tests a regex pattern against the buffer */ test(pattern: RegExp): boolean; /** * Clears the buffer */ clear(): void; /** * Gets buffer statistics */ getStats(): { count: number; bytes: number; maxSize: number; maxBytes: number; usage: number; }; /** * Creates a snapshot of the buffer */ snapshot(): string[]; } /** * Specialized circular buffer for terminal output */ declare class TerminalOutputBuffer extends CircularBuffer { private ansiRegex; /** * Gets clean output without ANSI codes */ getCleanOutput(): string; /** * Searches for pattern in clean output */ includesClean(pattern: string): boolean; /** * Tests regex against clean output */ testClean(pattern: RegExp): boolean; /** * Gets the last N lines */ getLastLines(n: number): string[]; } /** * Resource management system to prevent leaks and ensure proper cleanup */ /** * Tracks and manages disposable resources */ declare class ResourceManager extends EventEmitter { private resources; private cleanupCallbacks; private disposed; private maxResources; private registrationTimestamps; private lastCleanup; private readonly CLEANUP_INTERVAL; private readonly MAX_REGISTRATIONS_PER_MINUTE; /** * Registers a resource for tracking with rate limiting */ register(id: string, resource: IResource, cleanup?: () => Promise): void; /** * Unregisters and cleans up a resource */ unregister(id: string): Promise; /** * Gets a registered resource */ get(id: string): T | undefined; /** * Checks if a resource is registered */ has(id: string): boolean; /** * Disposes all resources */ dispose(): Promise; /** * Cleans up old timestamps for rate limiting */ private cleanupOldTimestamps; /** * Gets resource statistics */ getStats(): ResourceStats; } /** * Manages PTY lifecycle to prevent race conditions */ declare class PTYLifecycleManager { private state; private pty; private exitPromise; private exitResolve; private killTimeout; /** * Spawns a new PTY, ensuring previous one is cleaned up */ spawn(ptyFactory: () => any): Promise; /** * Kills the PTY with proper cleanup */ kill(signal?: string): Promise; /** * Waits for PTY to exit with timeout */ private waitForExit; /** * Handles PTY exit */ private handleExit; /** * Cleans up resources */ private cleanup; /** * Gets current state */ getState(): PTYState; /** * Gets PTY instance */ getPTY(): any; } /** * Tracks event listeners for cleanup */ declare class EventListenerTracker { private listeners; /** * Tracks an event listener */ track(target: any, event: string, listener: Function): void; /** * Removes all tracked listeners for a target */ removeAll(target: any): void; /** * Removes all tracked listeners */ clear(): void; /** * Removes a single listener */ private removeListener; /** * Gets a unique key for a target */ private getKey; /** * Gets statistics */ getStats(): { targets: number; totalListeners: number; }; } interface IResource { dispose?(): Promise | void; } interface ResourceStats { count: number; maxResources: number; disposed: boolean; resources: string[]; } type PTYState = 'idle' | 'spawning' | 'running' | 'killing' | 'killed' | 'exited' | 'error'; declare function test(name: string, command: string, interactions?: Array<{ expect: string | RegExp; respond: string; }>, expectations?: Array): Promise; export { Battle, type BattleOptions, CircularBuffer, EventListenerTracker, type InteractionHandler, PTYLifecycleManager, Replay, type ReplayData, type ReplayEvent, ResourceManager, Runner, SafeCommandMode, index as Security, SecurityLevel, Silent, TerminalOutputBuffer, type TestCase, type TestResult, type TestSuite, test };