import React, { useState, useEffect, useRef } from 'react'; import { InvestigationCase, TerminalLogEntry } from '../../types/forensics'; import { Terminal as TerminalIcon, Activity, MonitorSmartphone, ServerOff, Send, Trash2, Cpu, ShieldCheck, Zap } from 'lucide-react'; import { requestAiAnalysis } from '../../services/forensicApi'; interface TerminalTabProps { currentCase: InvestigationCase; onUpdateStatus: (caseId: string, newStatus: any, note: string) => void; } export const TerminalTab: React.FC = ({ currentCase, onUpdateStatus, }) => { const [logs, setLogs] = useState([ { id: 'log-0', text: `[system] FROI.OS SENTINEL FORENSIC ENCLAVE INITIALIZED v4.2`, type: 'system', timestamp: '15:00:01', }, { id: 'log-1', text: `[enclave] Loaded active docket: ${currentCase.id} (${currentCase.title})`, type: 'success', timestamp: '15:00:02', }, { id: 'log-2', text: `[pcap] BGP Anycast Triangulator & JA4 DPI filter active on interface en0.`, type: 'system', timestamp: '15:00:03', }, { id: 'log-3', text: `Type 'help' or 'commands' for available forensic interrogation tools.\n`, type: 'output', timestamp: '15:00:04', }, ]); const [input, setInput] = useState(''); const [status, setStatus] = useState({ text: 'ENCLAVE ACTIVE (LOOPBACK:3000)', color: 'text-cyan-400', icon: Activity }); const [isExecuting, setIsExecuting] = useState(false); const outputRef = useRef(null); // Auto-scroll useEffect(() => { if (outputRef.current) { outputRef.current.scrollTop = outputRef.current.scrollHeight; } }, [logs]); const addLog = (text: string, type: TerminalLogEntry['type'] = 'output') => { const time = new Date().toTimeString().slice(0, 8); setLogs(prev => [...prev, { id: `log-${Date.now()}-${Math.random()}`, text, type, timestamp: time }]); }; const handleExecuteCommand = async (cmdStr: string) => { const rawCmd = cmdStr.trim(); if (!rawCmd) return; addLog(`$ ${rawCmd}`, 'command'); setInput(''); setIsExecuting(true); const parts = rawCmd.split(' '); const mainCmd = parts[0].toLowerCase(); const arg = parts.slice(1).join(' '); if (mainCmd === 'help' || mainCmd === 'commands') { addLog(` Available Forensic Commands: ============================ triangulate [ip] - Run Anycast BGP speed-of-light t >= 2d/(c*2/3) latency check ja4-inspect [hash] - Inspect TLS ClientHello JA4 / JA3 fingerprint & engine webrtc-stun-probe - Enumerate WebRTC ICE candidates for true physical NIC IP crypto-trace [wallet] - Disassemble multi-hop mixer, structuring, and cash-outs tco-dispatch - Execute EU TCO Reg 2021/784 1-Hour mandatory takedown freeze-rails - Freeze linked financial rails & merchant settlement queues sar-generate - Output official FinCEN Part V Suspicious Activity Report ai-analyze [prompt] - Interrogate the Gemini Deep Forensic Intelligence Analyst status - View current docket security posture & trust score clear - Clear the terminal screen `, 'output'); } else if (mainCmd === 'clear') { setLogs([]); } else if (mainCmd === 'status') { addLog(` [DOCKET STATUS] ID: ${currentCase.id} Target: ${currentCase.entityTarget.primaryAlias} Threat Level: ${currentCase.threatLevel} Composite Trust Score: ${currentCase.compositeTrustScore}/100 Claimed IP: ${currentCase.networkTelemetry.claimedGeo.ip} (${currentCase.networkTelemetry.claimedGeo.city}) Triangulated Location: ${currentCase.networkTelemetry.bgpAnycast.physicalOriginInference} Intercepted Volume: $${currentCase.financialLedger.totalVolumeUsd.toLocaleString()} USD Disposition: ${currentCase.status} `, 'success'); } else if (mainCmd === 'triangulate') { const targetIp = arg || currentCase.networkTelemetry.claimedGeo.ip; addLog(`[bgp-engine] Querying Anycast edge PoPs for IP: ${targetIp}...`, 'system'); await new Promise(r => setTimeout(r, 600)); const popLines = currentCase.networkTelemetry.bgpAnycast.popLatencies.map( p => ` - PoP ${p.pop} (${p.city}): RTT ${p.measuredRttMs.toFixed(1)}ms | MinPhysical: ${p.expectedPhysicalMinRttMs.toFixed(1)}ms | ${p.anomalous ? '[ANOMALY: PROXY DETECTED]' : '[OK]'}` ).join('\n'); addLog(` BGP Speed-of-Light Calculation: t >= 2d / (c * 2/3) --------------------------------------------------- ${popLines} VERDICT: ${currentCase.networkTelemetry.bgpAnycast.speedOfLightViolation ? 'PROVEN PROXY OVERRIDE' : 'PLAUSIBLE PHYSICAL ORIGIN'} Inferred True Origin: ${currentCase.networkTelemetry.bgpAnycast.physicalOriginInference} Delta: ${currentCase.networkTelemetry.bgpAnycast.propagationDeltaMs}ms `, currentCase.networkTelemetry.bgpAnycast.speedOfLightViolation ? 'error' : 'success'); } else if (mainCmd === 'ja4-inspect') { addLog(` TLS ClientHello Fingerprint Analysis: ------------------------------------- JA4: ${currentCase.networkTelemetry.tlsFingerprint.ja4} JA3: ${currentCase.networkTelemetry.tlsFingerprint.ja3} Detected Client Engine: ${currentCase.networkTelemetry.tlsFingerprint.detectedClientEngine} Anomaly Note: ${currentCase.networkTelemetry.tlsFingerprint.anomalyReason} Ciphers Negotiated: ${currentCase.networkTelemetry.tlsFingerprint.cipherSuites.join(', ')} `, 'output'); } else if (mainCmd === 'webrtc-stun-probe') { addLog(`[stun-probe] Binding to ${currentCase.networkTelemetry.clientProbes.webrtcCandidateLeak.stunServerUsed}...`, 'system'); await new Promise(r => setTimeout(r, 500)); addLog(` WebRTC ICE Candidate Resolution: -------------------------------- Local RFC1918 Private IP: ${currentCase.networkTelemetry.clientProbes.webrtcCandidateLeak.localPrivateIp} Unmasked True Public NIC: ${currentCase.networkTelemetry.clientProbes.webrtcCandidateLeak.unmaskedPublicIp} Leak Status: ${currentCase.networkTelemetry.clientProbes.webrtcCandidateLeak.leakDetected ? 'DIRECT HARDWARE INTERFACE EXPOSED (VPN BYPASS)' : 'Clean'} Details: ${currentCase.networkTelemetry.clientProbes.webrtcCandidateLeak.leakDetails} `, currentCase.networkTelemetry.clientProbes.webrtcCandidateLeak.leakDetected ? 'error' : 'success'); } else if (mainCmd === 'crypto-trace') { addLog(` Financial Multi-Hop Transaction Trace: -------------------------------------- Total Volume: $${currentCase.financialLedger.totalVolumeUsd.toLocaleString()} USD Structuring Pattern: ${currentCase.financialLedger.structuringSummary} Hops Logged: ${currentCase.financialLedger.hops.map((h, i) => ` [Hop ${i+1}] ${h.from} -> ${h.to} | $${h.amountUsd.toLocaleString()} (${h.asset}) | Tag: ${h.riskTag}`).join('\n')} `, 'output'); } else if (mainCmd === 'tco-dispatch') { addLog(`[tco] Initiating EU TCO Regulation (EU) 2021/784 1-Hour takedown order...`, 'system'); await new Promise(r => setTimeout(r, 400)); onUpdateStatus(currentCase.id, 'TCO_DISPATCHED', 'TCO 1-Hour Takedown dispatched from CLI'); addLog(`[tco] 1-Hour Takedown Order broadcast to global edge network. Ref: TCO-${currentCase.id}`, 'success'); } else if (mainCmd === 'freeze-rails') { addLog(`[aml] Freezing settlement queues and wallet addresses...`, 'system'); await new Promise(r => setTimeout(r, 400)); onUpdateStatus(currentCase.id, 'ASSETS_FROZEN', 'Asset Freeze executed via CLI'); addLog(`[aml] Rails frozen for target ${currentCase.entityTarget.primaryAlias}. Assets locked.`, 'success'); } else if (mainCmd === 'sar-generate') { addLog(`[sar] Generating FinCEN Part V Narrative for Docket ${currentCase.id}...`, 'system'); addLog(` FINCEN SAR PART V NARRATIVE: Subject: ${currentCase.entityTarget.primaryAlias} Reason: Structured smurfing & material support under 18 U.S.C. ยง 2339B. Unmasked IP: ${currentCase.networkTelemetry.clientProbes.webrtcCandidateLeak.unmaskedPublicIp} Total Intercepted: $${currentCase.financialLedger.totalVolumeUsd.toLocaleString()} USD Preserved in Evidence Locker. Referral code: SAR-SENTINEL-${currentCase.id} `, 'output'); } else if (mainCmd === 'ai-analyze') { addLog(`[ai-analyst] Calling Sentinel Deep Forensics AI Agent...`, 'system'); const aiResult = await requestAiAnalysis(currentCase, 'CUSTOM', arg || 'Provide a technical risk assessment.'); addLog(aiResult, 'ai'); } else { addLog(`Command not recognized: '${mainCmd}'. Type 'help' for available commands.`, 'error'); } setIsExecuting(false); }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter') { handleExecuteCommand(input); } }; const StatusIcon = status.icon; return (
{/* Chrome Tab Strip */}
FROI.OS ENCLAVE // SENTINEL PTY BRIDGE Termux / Linux PTY Emulation
{status.text}
{/* Active Viewport & Terminal Mount */}
{/* Terminal Header Bar */}
ENCLAVE-ACTIVE // CASE: {currentCase.id} TARGET: {currentCase.networkTelemetry.claimedGeo.ip}
{/* Terminal Output Stream */}
          {logs.map((entry) => (
            
[{entry.timestamp}] {entry.text}
))} {isExecuting && (
> Executing forensic routine...
)}
{/* Terminal Input */}
> setInput(e.target.value)} onKeyDown={handleKeyDown} disabled={isExecuting} placeholder="Enter command (e.g., triangulate, webrtc-stun-probe, crypto-trace, help)..." className="w-full bg-[#0d131f] border border-slate-800 text-white py-2 pr-3 pl-8 rounded font-mono text-xs focus:outline-none focus:border-cyan-500 transition-colors placeholder-slate-600 disabled:opacity-50" autoComplete="off" spellCheck="false" />
); };