import{r as u,j as l}from"./index-XAQEFxR0.js";const J=({taskId:G,challengeConfig:s,onComplete:w})=>{const[k,x]=u.useState(["Welcome to InfoSec Labs Terminal v1.0","Type 'help' for available commands.","------------------------------------"]),[N,$]=u.useState(""),S=t=>{var p;const e=a=>{if(a===null||typeof a!="object")return a;if(Array.isArray(a))return a.map(e);const d={};for(const h in a)d[h]=e(a[h]);return d},r={"/":{type:"dir",children:{}},"/home":{type:"dir",children:{}},"/home/user":{type:"dir",children:{}},"/var":{type:"dir",children:{}},"/var/log":{type:"dir",children:{}},"/tmp":{type:"dir",children:{}}};if(!t)return console.log("[TerminalChallenge] No inputFs provided"),r;const n=(a,d)=>{if(!a||!a.children)return;const h=e(a.children);r[d]={type:"dir",children:h},Object.entries(h).forEach(([y,P])=>{if(P&&P.type==="dir"){const H=d==="/"?`/${y}`:`${d}/${y}`;n(P,H)}})};return Object.entries(t).forEach(([a,d])=>{n(d,a)}),Object.keys(r).sort((a,d)=>a.length-d.length).forEach(a=>{if(a==="/")return;const d=a.split("/").filter(Boolean),h=d[d.length-1],y=d.length===1?"/":"/"+d.slice(0,-1).join("/");r[y]&&!r[y].children[h]&&(r[y].children[h]=r[a])}),console.log("[TerminalChallenge] Flattened FS paths:",Object.keys(r)),console.log("[TerminalChallenge] /home/user children:",Object.keys(((p=r["/home/user"])==null?void 0:p.children)||{})),r};u.useMemo(()=>S(s==null?void 0:s.initialFileSystem),[s==null?void 0:s.initialFileSystem]);const[m,b]=u.useState(()=>S(s==null?void 0:s.initialFileSystem));u.useEffect(()=>{if(s!=null&&s.initialFileSystem){const t=S(s.initialFileSystem);b(t),f("/home/user"),E(!1),x(["Welcome to InfoSecLabs Terminal v1.0","Type 'help' for available commands.","------------------------------------","",`>>> MISSION OBJECTIVE: ${s.title||"Challenge"}`,s.description||"","",`Goal: ${s.objective||"Complete the challenge"}`,""])}},[s==null?void 0:s.id]);const j=()=>s.osType==="windows"?c==="/home/user"?"C:\\Users\\User>":c==="/"?"C:\\>":`${c.replace(/^\/home\/user/,"C:\\Users\\User").replace(/\//g,"\\")}>`:s.osType==="cloud"?`cloud-user@aws-cli:~${c==="/home/user"?"":c}$`:s.osType==="container"?`root@k8s-pod-x92:${c==="/home/user"?"~":c}#`:s.osType==="network"?`analyst@wireshark-box:~${c==="/home/user"?"":c}$`:s.osType==="memory"?`forensics@volatility-workstation:~${c==="/home/user"?"":c}$`:`user@infoseclabs:${c}$`,[c,f]=u.useState("/home/user"),[I,E]=u.useState(!1),v=u.useRef(null),T=u.useRef(null);u.useEffect(()=>{T.current&&T.current.scrollIntoView({behavior:"smooth"})},[k]),u.useEffect(()=>{!I&&s.checkCondition&&s.checkCondition("",null,m,k)&&(E(!0),setTimeout(()=>{o("🎉 MISSION ACCOMPLISHED: "+s.successMessage),w&&w()},500))},[k,I,s,m,w]);const F=()=>{v.current&&v.current.focus()},D=t=>{t.key==="Enter"&&(O(N),$(""))},o=(t,e=!1)=>{x(r=>[...r,e?`${j()} ${t}`:t])},O=t=>{if(!t)return;const e=t.trim();if(!e)return;o(e,!0),e.includes("|");const r=e.split(/\s+/);let n=r[0].toLowerCase();const i=r.slice(1);if(s.osType==="windows"&&(n==="dir"&&(n="ls"),n==="type"&&(n="cat"),n==="cls"&&(n="clear"),n==="md"&&(n="mkdir"),n==="copy"&&(n="touch")),s.customCommands){if(s.customCommands[e]){const p=s.customCommands[e];o(p);return}if(s.customCommands[n]&&typeof s.customCommands[n]=="string"){o(s.customCommands[n]);return}if(typeof s.customCommands[n]=="function"&&s.customCommands[n](i,o,{fs:m,setFs:b,currentPath:c,setCurrentPath:f}))return}switch(n){case"help":o(s.osType==="windows"?"Available commands: dir, cd, type, cls, ipconfig, whoami, help, tasklist, netstat, systeminfo":"Available commands: ls, cd, pwd, cat, touch, mkdir, clear, whoami, date, chmod, grep, find, sed, awk, head, tail, wc");break;case"clear":x([]);break;case"whoami":o(s.osType==="windows"?"infoseclabs\\user":"user");break;case"ipconfig":s.osType==="windows"?o(`Windows IP Configuration

Ethernet adapter Ethernet:
   IPv4 Address. . . . . . . . . . . : 192.168.1.105
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1`):o("bash: ipconfig: command not found");break;case"tasklist":s.osType==="windows"&&o(`Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0          8 K
System                           4 Services                   0      3,100 K
svchost.exe                    932 Services                   0     12,210 K
notepad.exe                   1337 Console                    1     15,420 K`);break;case"systeminfo":s.osType==="windows"&&o(`Host Name:                 DESKTOP-ABC1234
OS Name:                   Microsoft Windows 10 Pro
OS Version:                10.0.19045 N/A Build 19045
System Type:               x64-based PC`);break;case"hostname":o("DESKTOP-ABC1234");break;case"ping":o(`
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=24ms TTL=115
Reply from 8.8.8.8: bytes=32 time=21ms TTL=115

Ping statistics for 8.8.8.8:
    Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),`);break;case"netstat":o(`
Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    192.168.1.105:49666    20.190.160.8:443       ESTABLISHED
  TCP    192.168.1.105:49667    52.123.123.1:443       TIME_WAIT`);break;case"taskkill":i.length>0?o(`SUCCESS: The process with PID ${i[0].replace("/PID","").trim()} has been terminated.`):o("Usage: taskkill /PID [ProcessID]");break;case"date":o(new Date().toString());break;case"pwd":o(c);break;case"ls":A(i);break;case"cd":L(i);break;case"touch":M(i);break;case"mkdir":B(i);break;case"chmod":K(i);break;case"grep":U(i);break;case"find":W(i);break;case"sed":handleSed(i);break;case"awk":handleAwk(i);break;case"head":handleHead(i);break;case"tail":handleTail(i);break;case"wc":handleWc(i);break;case"kill":i.length>0?o(`Process ${i[0]} terminated.`):o("Usage: kill [PID]");break;case"sudo":i[0]==="apt"?(o("Reading package lists... Done"),o("Building dependency tree... Done"),o("The following NEW packages will be installed: "+(i[2]||"package")),o("0 upgraded, 1 newly installed, 0 to remove.")):O(r.slice(1).join(" "));break;case"apt":o("Permission denied. Try 'sudo apt'.");break;case"cat":R(i);break;default:e.includes("|")||o(`bash: ${n}: command not found`)}},A=t=>{console.log("[handleLs] currentPath:",c),console.log("[handleLs] fs[currentPath]:",m[c]),console.log("[handleLs] fs keys:",Object.keys(m));const e=t[0]||c,r=e.replace(/^-\w+$/,"")||c;if(m[r]){const i=Object.keys(m[r].children||{}).join("  ");console.log("[handleLs] Found files:",i),o(i||"(empty directory)");return}const n=m[c];if(n&&n.children){const i=Object.keys(n.children).join("  ");console.log("[handleLs] Fallback files:",i),o(i||"(empty directory)")}else console.log("[handleLs] No curr or children"),o(`ls: cannot access '${e}': No such file or directory`)},L=t=>{const e=t[0];if(!e||e==="~"){f("/home/user");return}if(e===".")return;if(e===".."){if(c==="/")return;const i=c.split("/");i.pop();const p=i.join("/")||"/";f(p);return}if(e.startsWith("/")&&m[e]){f(e);return}const r=c==="/"?`/${e}`:`${c}/${e}`;if(m[r]){f(r);return}const n=m[c];n&&n.children[e]&&n.children[e].type==="dir"?(f(r),m[r]||b(i=>({...i,[r]:n.children[e]}))):o(`bash: cd: ${e}: No such file or directory`)},M=t=>{if(!t[0]){o("touch: missing file operand");return}const e=t[0];b(r=>{const n={...r};return n[c].children||(n[c].children={}),n[c].children[e]={type:"file",content:""},n})},B=t=>{if(!t[0])return;const e=t[0];b(r=>{const n={...r};n[c].children[e]={type:"dir",children:{}};const i=c==="/"?`/${e}`:`${c}/${e}`;return n[i]={type:"dir",children:{}},n})},K=t=>{if(t.length<2){o("chmod: missing operand");return}t[0];const e=t[1],r=m[c];r&&r.children[e]||o(`chmod: cannot access '${e}': No such file or directory`)},R=t=>{if(!t[0])return;const e=t[0],r=m[c];r&&r.children[e]?r.children[e].type==="dir"?o(`cat: ${e}: Is a directory`):o(r.children[e].content||""):o(`cat: ${e}: No such file or directory`)},U=t=>{if(t.length<2){o("grep: usage: grep [pattern] [file]");return}const e=t[0].replace(/['"]/g,""),r=t[t.length-1],n=m[c];n&&n.children[r]?(n.children[r].content||"").split(`
`).filter(d=>d.includes(e)).forEach(d=>o(d)):o(`grep: ${r}: No such file or directory`)},W=t=>{const e=t.indexOf("-name");(e!==-1&&t[e+1]?t[e+1].replace(/['"]/g,""):t[2]?t[2].replace(/['"]/g,""):"something")==="config.php"&&o("/var/www/html/config.php")};return l.jsx("div",{className:"my-8 animate-fadeIn",children:l.jsxs("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl border border-gray-700 overflow-hidden font-mono text-sm w-full max-w-4xl mx-auto",children:[l.jsxs("div",{className:"bg-[#2d2d2d] px-4 py-2 flex items-center justify-between border-b border-black",children:[l.jsxs("div",{className:"flex gap-2",children:[l.jsx("div",{className:"w-3 h-3 rounded-full bg-red-500"}),l.jsx("div",{className:"w-3 h-3 rounded-full bg-yellow-500"}),l.jsx("div",{className:"w-3 h-3 rounded-full bg-green-500"})]}),l.jsx("div",{className:"text-gray-400 text-xs text-center flex-1",children:s.osType==="windows"?"Administrator: Command Prompt":"user@infoseclabs:~"})]}),l.jsxs("div",{className:"p-4 h-[400px] overflow-y-auto cursor-text text-gray-200",onClick:F,children:[l.jsxs("div",{className:"mb-4 border-b border-gray-700 pb-2",children:[l.jsxs("div",{className:"text-green-400 font-bold",children:[">>>"," MISSION OBJECTIVE: ",s.title]}),l.jsx("div",{className:"text-gray-400",children:s.description}),l.jsxs("div",{className:"text-blue-400 mt-1",children:["Goal: ",s.objective]})]}),k.map((t,e)=>l.jsx("div",{className:"whitespace-pre-wrap mb-1",children:t},e)),l.jsxs("div",{className:"flex items-center",children:[l.jsx("span",{className:"text-green-500 mr-2",children:j()}),l.jsx("input",{ref:v,type:"text",value:N,onChange:t=>$(t.target.value),onKeyDown:D,className:"bg-transparent border-none outline-none flex-1 text-gray-200 focus:ring-0 p-0",autoComplete:"off",autoFocus:!0})]}),l.jsx("div",{ref:T})]})]})})};export{J as T};
