You are an expert full-stack developer and AI architect tasked with building a comprehensive MVP for 'AI Exploit Guard'. This application aims to proactively identify and mitigate security vulnerabilities introduced by AI coding agents. The goal is to generate a fully functional, multi-page Next.js application, not just a landing page.
**1. PROJECT OVERVIEW:**
AI Exploit Guard is a SaaS platform designed to combat the rising tide of security vulnerabilities caused by the proliferation of AI coding agents. The problem stems from the increasing tendency for AI to generate code that may contain subtle, novel, or complex security flaws, making traditional security scanning insufficient. AI Exploit Guard addresses this by specifically analyzing codebases for AI-introduced vulnerabilities, providing detailed explanations, suggesting automated patches, and simulating exploit scenarios. Its core value proposition is to enhance software security in the age of AI-assisted development, reduce the risk of breaches originating from AI-generated code, and empower security teams with specialized tools to combat these new threats.
**2. TECH STACK:**
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM (PostgreSQL compatible)
- **Database:** PostgreSQL (or Supabase/Neon.tech for ease of use)
- **Authentication:** NextAuth.js (Credentials Provider for email/password, Google Provider)
- **UI Components:** shadcn/ui (for accessible and customizable components)
- **State Management:** React Context API / Zustand (for global state)
- **API Layer:** Server Actions & Route Handlers (Next.js App Router)
- **Form Handling:** React Hook Form + Zod for validation
- **Charting:** Recharts or Chart.js for dashboard visualizations
- **Deployment:** Vercel
- **Other:** Axios (for potential external API calls), clsx (for conditional class names)
**3. DATABASE SCHEMA (PostgreSQL/Drizzle ORM):**
```sql
-- Users Table
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255),
email VARCHAR(255) UNIQUE NOT NULL,
email_verified TIMESTAMP WITH TIME ZONE,
image TEXT, -- URL to profile picture
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Accounts Table (for NextAuth.js)
CREATE TABLE accounts (
id SERIAL PRIMARY KEY,
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
type VARCHAR(255) NOT NULL,
provider VARCHAR(255) NOT NULL,
provider_account_id TEXT NOT NULL,
refresh_token TEXT,
access_token TEXT,
expires_at BIGINT,
token_type TEXT,
scope TEXT,
id_token TEXT,
session_state TEXT,
UNIQUE (provider, provider_account_id)
);
-- Sessions Table (for NextAuth.js)
CREATE TABLE sessions (
id SERIAL PRIMARY KEY,
session_token TEXT UNIQUE NOT NULL,
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
expires TIMESTAMP WITH TIME ZONE NOT NULL
);
-- Verification Tokens Table (for NextAuth.js)
CREATE TABLE verification_tokens (
identifier TEXT NOT NULL,
token TEXT NOT NULL,
expires TIMESTAMP WITH TIME ZONE NOT NULL,
PRIMARY KEY (identifier, token)
);
-- Projects Table
CREATE TABLE projects (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
repository_url TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Scans Table (Represents a single analysis run)
CREATE TABLE scans (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
project_id UUID REFERENCES projects(id) ON DELETE CASCADE,
scan_status VARCHAR(50) NOT NULL DEFAULT 'pending', -- pending, running, completed, failed
scan_type VARCHAR(100) NOT NULL, -- e.g., 'code-analysis', 'exploit-simulation'
started_at TIMESTAMP WITH TIME ZONE,
completed_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Vulnerabilities Table
CREATE TABLE vulnerabilities (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
scan_id UUID REFERENCES scans(id) ON DELETE CASCADE,
project_id UUID REFERENCES projects(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
severity VARCHAR(50) NOT NULL, -- e.g., 'low', 'medium', 'high', 'critical'
file_path TEXT,
line_number INTEGER,
code_snippet TEXT,
ai_generated_potential BOOLEAN DEFAULT FALSE,
exploit_simulation_possible BOOLEAN DEFAULT FALSE,
status VARCHAR(50) DEFAULT 'open', -- open, in-progress, resolved, false-positive
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Patches Table (Suggested or applied fixes)
CREATE TABLE patches (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
vulnerability_id UUID REFERENCES vulnerabilities(id) ON DELETE CASCADE,
patch_code TEXT NOT NULL,
is_auto_generated BOOLEAN DEFAULT FALSE,
applied BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
```
*Note: Drizzle schema will be defined in `drizzle.config.ts` and models generated.*
**4. CORE FEATURES & USER FLOW:**
* **Authentication (User Signup/Login):**
1. User lands on the landing page.
2. Clicks 'Sign Up' or 'Login'.
3. Can sign up/in using Email/Password or Google OAuth.
4. Upon successful login, redirected to the Dashboard.
5. JWT tokens are managed securely (e.g., via HttpOnly cookies).
* **Project Management:**
1. User logs in and sees the Dashboard.
2. Navigates to 'Projects' section.
3. Clicks 'Add New Project'.
4. Enters Project Name and GitHub Repository URL.
5. Submits the form. A new entry is created in the `projects` table.
6. User can view a list of their projects on the Projects page.
* **AI-Vulnerability Scan (MVP Core Feature):**
1. From the 'Projects' list, user clicks 'Scan' for a specific project.
2. A new entry is created in the `scans` table with `status: 'pending'` and `scan_type: 'code-analysis'`.
3. A background job (e.g., using a queue system or serverless function) is triggered.
4. The job clones the repository from the provided URL.
5. It runs a sophisticated static analysis tool enhanced with AI-specific vulnerability patterns (e.g., looking for insecure use of AI-generated functions, potential prompt injection points in user inputs handled by AI-generated logic, etc.). This is the core AI analysis step.
6. Identified potential vulnerabilities are parsed and saved into the `vulnerabilities` table, linked to the `scan_id` and `project_id`. The `ai_generated_potential` flag is set to `true`.
7. The `scans` status is updated to `completed`.
8. The user is notified (e.g., via a toast or an update on the dashboard).
* **Vulnerability Review & Details:**
1. User navigates to the 'Vulnerabilities' tab for a project or views the main vulnerability list.
2. A paginated, sortable, and filterable list of vulnerabilities is displayed.
3. User clicks on a specific vulnerability.
4. A detailed view page/modal opens, showing description, severity, file path, line number, code snippet, and status.
5. User can update the status (e.g., 'in-progress', 'resolved', 'false-positive').
* **Automated Patch Suggestion (Basic MVP):**
1. On the vulnerability detail view, if `ai_generated_potential` is true, a button 'Suggest Patch' is available.
2. Clicking this button triggers a request to an internal/external AI model (or a set of predefined heuristics for common AI-introduced flaws).
3. The AI attempts to generate a code snippet to fix the vulnerability.
4. The suggested patch is displayed to the user in a code editor view, linked to the vulnerability, and saved in the `patches` table with `is_auto_generated: true`.
5. User can manually copy or potentially apply the patch (apply functionality might be out of MVP scope but the suggestion is key).
**5. API & DATA FETCHING:**
- **NextAuth.js:** Handles `/api/auth/[...nextauth]` for authentication flows.
- **Server Actions:** Used for mutations like creating projects, triggering scans, updating vulnerability status. Example: `await createProject({ name: '...', repoUrl: '...' })`.
- **Route Handlers (API Routes):** Used for backend tasks not directly tied to form submissions, or for external API integrations (e.g., fetching repo data). Example: `/api/scan/trigger/{projectId}`.
- **Data Fetching in Components:** Use `fetch` within Server Components for direct data retrieval based on route params (e.g., fetching project details or vulnerabilities for a specific project ID). Use `useEffect` with Axios or `fetch` in Client Components for client-side data fetching or mutations.
- **Expected Response Format:** JSON for all API interactions.
- **Example Scan Trigger API (Route Handler):**
`POST /api/scan/trigger/{projectId}`
*Request Body:* `{ "scanType": "code-analysis" }`
*Response (Success):* `202 Accepted`, `{ "message": "Scan initiated successfully", "scanId": "uuid" }`
*Response (Error):* `400 Bad Request`, `{ "error": "Invalid project ID" }` or `500 Internal Server Error`.
**6. COMPONENT BREAKDOWN (Next.js App Router):**
- **`app/layout.tsx`:** Root layout (html, body, global providers, Tailwind CSS setup).
- **`app/page.tsx`:** Landing Page (Hero section, Features overview, Call to Action).
- **`app/(auth)/layout.tsx`:** Auth layout (shared structure for login/signup).
- **`app/(auth)/login/page.tsx`:** Login form component.
- **`app/(auth)/signup/page.tsx`:** Signup form component.
- **`app/(marketing)/layout.tsx`:** Marketing pages layout.
- **`app/(marketing)/about/page.tsx`:** About Us page.
- **`app/(marketing)/pricing/page.tsx`:** Pricing page.
- **`app/(app)/layout.tsx`:** Main application layout (with sidebar/header, protected routes).
- **`app/(app)/dashboard/page.tsx`:** Dashboard (overview of projects, recent scans, vulnerability stats - uses Chart.js/Recharts).
- **`app/(app)/projects/page.tsx`:** Projects List page (Table of projects, 'Add Project' button).
- **`app/(app)/projects/[projectId]/page.tsx`:** Project Detail page (Overview, Scan History, Vulnerabilities list for the project).
- **`app/(app)/projects/[projectId]/vulnerabilities/page.tsx`:** Project Vulnerabilities page (Paginated, filterable list).
- **`app/(app)/vulnerabilities/[vulnerabilityId]/page.tsx`:** Vulnerability Detail page (Shows all details, status update, patch suggestion/view).
- **`app/(app)/settings/page.tsx`:** User Settings page (Profile info, API keys, notification settings).
- **`app/(app)/settings/billing/page.tsx`:** Billing page (Subscription management - Placeholder for MVP).
- **Reusable UI Components (in `components/ui/` via shadcn/ui):** `Button`, `Input`, `Card`, `Table`, `Dialog`, `Form`, `Alert`, `Spinner`, `Tabs`, `Select`, `CodeBlock`, `Notification`.
- **Custom Components (in `components/`):** `Sidebar`, `Header`, `ProjectForm`, `ScanTriggerButton`, `VulnerabilityList`, `VulnerabilityDetailView`, `PatchSuggestionView`, `DashboardCharts`.
- **State Management:** Primarily use Server Components for data loading. Zustand or Context API for managing UI state in Client Components (e.g., modal open/close states, form states, notification queues).
**7. UI/UX DESIGN & VISUAL IDENTITY:**
- **Style:** Modern, Clean, Professional, with a hint of futuristic/techy aesthetic.
- **Color Palette:**
- Primary: Dark Blue (`#1A237E`)
- Secondary: Teal (`#00ACC1`)
- Accent/Highlight: Bright Cyan (`#29B6F6`)
- Background: Very Dark Gray (`#121212`)
- Card/Element Background: Slightly Lighter Dark Gray (`#1E1E1E`)
- Text (Primary): White (`#FFFFFF`)
- Text (Secondary): Light Gray (`#B0BEC5`)
- Success: Green (`#4CAF50`)
- Warning: Orange (`#FF9800`)
- Danger: Red (`#F44336`)
- **Typography:**
- Headings: Inter (Bold, Semi-bold)
- Body Text: Inter (Regular)
- **Layout:** Sidebar navigation on the left for authenticated users. Main content area takes the rest of the screen. Clean cards and tables for data display. Responsive design using Tailwind CSS breakpoints.
- **Key Visual Elements:** Subtle background gradients, glowing accent elements on hover/focus, clean code block formatting, clear visual hierarchy.
**8. SAMPLE/MOCK DATA:**
* **User:**
```json
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"name": "Alice Smith",
"email": "alice.smith@example.com"
}
```
* **Project:**
```json
{
"id": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"userId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"name": "AI-Powered CMS",
"repositoryUrl": "https://github.com/user/ai-cms",
"createdAt": "2024-03-15T10:00:00Z"
}
```
* **Scan:**
```json
{
"id": "1a2b3c4d-5e6f-7890-abcd-ef1234567890",
"projectId": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"scanStatus": "completed",
"scanType": "code-analysis",
"completedAt": "2024-03-15T10:35:00Z"
}
```
* **Vulnerability (Critical):**
```json
{
"id": "98765432-10fe-dcba-9876-543210fedcba",
"scanId": "1a2b3c4d-5e6f-7890-abcd-ef1234567890",
"projectId": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"title": "Insecure Deserialization via AI-generated Input Handler",
"description": "The AI-generated input handling function in UserProfileManager.java does not properly validate serialized data, potentially allowing arbitrary code execution.",
"severity": "critical",
"filePath": "src/main/java/com/example/UserProfileManager.java",
"lineNumber": 152,
"codeSnippet": "ObjectInputStream ois = new ObjectInputStream(inputStream); return ois.readObject(); // Vulnerable line",
"aiGeneratedPotential": true,
"exploitSimulationPossible": true,
"status": "open",
"createdAt": "2024-03-15T10:35:00Z"
}
```
* **Vulnerability (Medium):**
```json
{
"id": "abcdef12-3456-7890-abcd-ef1234567890",
"scanId": "1a2b3c4d-5e6f-7890-abcd-ef1234567890",
"projectId": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"title": "Potential Prompt Injection in AI Assistant Logic",
"description": "The AI assistant's response generation logic might be susceptible to prompt injection attacks if user input is not sufficiently sanitized before being passed to the LLM prompt.",
"severity": "medium",
"filePath": "src/utils/aiAssistant.js",
"lineNumber": 78,
"codeSnippet": "const prompt = `User query: ${userInput}\nRespond based on the context."; // Vulnerable if userInput is not sanitized",
"aiGeneratedPotential": true,
"exploitSimulationPossible": false,
"status": "open",
"createdAt": "2024-03-15T10:35:00Z"
}
```
* **Patch:**
```json
{
"id": "c1d2e3f4-a5b6-7890-1234-567890abcdef",
"vulnerabilityId": "98765432-10fe-dcba-9876-543210fedcba",
"patchCode": "// Secure deserialization block\ntry (InputStream sanitizedStream = new SanitizedInputStreamWrapper(inputStream)) {\n ObjectInputStream ois = new ObjectInputStream(sanitizedStream);\n return ois.readObject();\n} catch (IOException | ClassNotFoundException e) {\n // Handle exception\n}",
"isAutoGenerated": true,
"applied": false
}
```
**9. TURKISH TRANSLATIONS:**
- **App Title:** AI Exploit Guard
- **Navigation:** Kontrol Paneli (Dashboard), Projeler (Projects), Güvenlik Açıkları (Vulnerabilities), Ayarlar (Settings), Faturalandırma (Billing)
- **Buttons:** Yeni Proje Ekle (Add New Project), Tara (Scan), Yamayı Öner (Suggest Patch), Güncelle (Update), Kaydet (Save), Giriş Yap (Login), Kayıt Ol (Sign Up)
- **Labels:** Proje Adı (Project Name), Depo URL (Repository URL), Durum (Status), Ciddiyet (Severity), Dosya Yolu (File Path), Satır Numarası (Line Number)
- **Headings:** Genel Bakış (Overview), Tarama Geçmişi (Scan History), Tespit Edilen Açıklar (Detected Vulnerabilities)
- **Placeholders/Messages:** Depo URL'sini girin (Enter repository URL), Taramayı başlatmak için buraya tıklayın (Click here to start scan), Güvenlik açığı bulunamadı (No vulnerabilities found), Lütfen bir proje seçin (Please select a project).
**10. ANIMATIONS:**
- **Page Transitions:** Subtle fade-in/fade-out animations between pages using Next.js `transition` directives or a library like Framer Motion.
- **Hover Effects:** Slight scale-up or background color change on interactive elements (buttons, links, cards).
- **Loading States:** Use skeleton loaders (shadcn/ui `Skeleton` component) for data tables and charts while fetching. Display spinners (`@/components/ui/spinner`) for ongoing operations like scans.
- **Subtle Parallax:** Optionally, a very subtle parallax effect on the landing page hero background.
**11. EDGE CASES & VALIDATION:**
- **Auth:** Implement robust auth state management. Protect all `/app/*` routes. Handle expired tokens/sessions gracefully (redirect to login).
- **Repository Access:** Handle cases where the provided GitHub URL is invalid, private (requiring token setup), or inaccessible. Provide clear error messages.
- **Scan Failures:** If a scan fails (e.g., network error, build failure), mark the scan as 'failed' and provide debugging information if possible.
- **Empty States:** Design informative empty states for Projects, Scans, and Vulnerabilities lists (e.g., "You haven't added any projects yet. Click 'Add New Project' to start.").
- **Form Validation:** Use Zod with React Hook Form for all form inputs (Project name, URL, Login/Signup credentials) ensuring client-side and server-side validation.
- **API Errors:** Implement global error handling for API responses. Display user-friendly error messages.
- **Rate Limiting:** Consider basic rate limiting on API endpoints, especially the scan trigger.
- **Security:** Sanitize all user inputs. Use environment variables for secrets (API keys, DB credentials). Ensure proper authorization checks on all relevant API routes/Server Actions (e.g., user can only access their own projects).