Generate a fully functional, multi-page Next.js MVP application for 'SecureLib Watch', a SaaS platform designed to proactively monitor open-source libraries for security vulnerabilities and malicious code injections, inspired by the recent Litellm incident.
PROJECT OVERVIEW:
SecureLib Watch aims to solve the critical problem of supply chain attacks targeting open-source software dependencies. Developers often integrate numerous libraries without full awareness of their security posture. This app will provide developers and teams with real-time security monitoring for their project dependencies. It will scan libraries (initially focusing on PyPI and npm) against known vulnerability databases and detect suspicious code patterns or unexpected behavior (like the Litellm incident's base64 encoded blobs). The core value proposition is to provide peace of mind and prevent costly security breaches by offering early warnings and actionable insights for dependency security.
TECH STACK:
- Frontend: React (Next.js 14 with App Router)
- Styling: Tailwind CSS
- UI Components: shadcn/ui (for accessible, reusable components)
- State Management: React Context API for global state, local component state for UI interactions.
- ORM: Drizzle ORM with PostgreSQL (using Vercel Postgres or Supabase for easy integration)
- Authentication: NextAuth.js (for robust email/password and OAuth - GitHub/Google)
- Database: PostgreSQL
- API Layer: Next.js API Routes (for backend logic and DB interaction)
- Other Libraries: zod (for schema validation), react-hook-form (for forms), axios (for external API calls if needed for vulnerability data), clsx (for conditional class names).
DATABASE SCHEMA:
We will use PostgreSQL with Drizzle ORM.
1. `users` table:
- `id` (UUID, Primary Key)
- `name` (VARCHAR)
- `email` (VARCHAR, Unique)
- `emailVerified` (TIMESTAMP)
- `image` (VARCHAR)
- `createdAt` (TIMESTAMP)
- `updatedAt` (TIMESTAMP)
2. `accounts` table (for NextAuth.js):
- `id` (VARCHAR, Primary Key)
- `userId` (UUID, Foreign Key to `users.id`)
- `type` (VARCHAR)
- `provider` (VARCHAR)
- `providerAccountId` (VARCHAR)
- `refresh_token` (TEXT)
- `access_token` (TEXT)
- `expires_at` (BIGINT)
- `token_type` (VARCHAR)
- `scope` (VARCHAR)
- `id_token` (TEXT)
- `session_state` (VARCHAR)
3. `sessions` table (for NextAuth.js):
- `sessionToken` (VARCHAR, Primary Key)
- `userId` (UUID, Foreign Key to `users.id`)
- `expires` (TIMESTAMP)
4. `verificationTokens` table (for NextAuth.js):
- `identifier` (VARCHAR)
- `token` (VARCHAR)
- `expires` (TIMESTAMP)
5. `projects` table:
- `id` (UUID, Primary Key)
- `userId` (UUID, Foreign Key to `users.id`)
- `name` (VARCHAR, Not Null)
- `description` (TEXT)
- `createdAt` (TIMESTAMP)
- `updatedAt` (TIMESTAMP)
6. `dependencies` table:
- `id` (UUID, Primary Key)
- `projectId` (UUID, Foreign Key to `projects.id`)
- `name` (VARCHAR, Not Null) // e.g., 'litellm', 'react'
- `version` (VARCHAR, Not Null) // e.g., '1.82.7'
- `registry` (VARCHAR, Not Null) // e.g., 'pypi', 'npm'
- `addedManually` (BOOLEAN, Default: false)
- `lastScannedAt` (TIMESTAMP)
- `createdAt` (TIMESTAMP)
- `updatedAt` (TIMESTAMP)
7. `vulnerabilities` table:
- `id` (UUID, Primary Key)
- `dependencyId` (UUID, Foreign Key to `dependencies.id`)
- `vulnerabilityId` (VARCHAR, Not Null) // e.g., CVE ID
- `title` (TEXT, Not Null)
- `description` (TEXT)
- `severity` (VARCHAR, Not Null) // e.g., 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'UNKNOWN'
- `source` (VARCHAR) // e.g., 'NVD', 'GitHub Advisory DB'
- `cvssScore` (DECIMAL(3,1))
- `detectedAt` (TIMESTAMP, Default: now())
- `isMaliciousCode` (BOOLEAN, Default: false) // Flag for suspicious code like Litellm example
- `createdAt` (TIMESTAMP)
8. `alerts` table:
- `id` (UUID, Primary Key)
- `userId` (UUID, Foreign Key to `users.id`)
- `dependencyId` (UUID, Foreign Key to `dependencies.id`)
- `alertType` (VARCHAR, Not Null) // e.g., 'VULNERABILITY_FOUND', 'MALICIOUS_CODE_DETECTED', 'VERSION_DEPRECATED'
- `message` (TEXT, Not Null)
- `severity` (VARCHAR)
- `status` (VARCHAR, Default: 'NEW') // e.g., 'NEW', 'ACKNOWLEDGED', 'RESOLVED'
- `triggeredAt` (TIMESTAMP, Default: now())
- `createdAt` (TIMESTAMP)
CORE FEATURES & USER FLOW:
1. **Authentication Flow:**
- User visits the landing page.
- Clicks 'Sign Up' or 'Sign In'.
- Presented with email/password form and OAuth options (Google, GitHub).
- Upon successful sign-up/sign-in, user is redirected to the dashboard.
- `next-auth` handles session management securely.
2. **Project Creation:**
- Authenticated user navigates to the 'Projects' page.
- Clicks 'Add New Project'.
- A modal or form appears asking for Project Name and optional Description.
- User submits the form. A new record is created in the `projects` table, linked to the user.
- User is redirected to the project's detail page.
3. **Dependency Management:**
- On the Project Detail page, user clicks 'Add Dependency'.
- A modal/form appears requesting:
- Dependency Name (e.g., 'litellm')
- Registry ('pypi', 'npm')
- Version (e.g., '1.82.8')
- User submits the form. A new record is created in the `dependencies` table, linked to the current project.
- For `addedManually=false` dependencies, a background job/API call is triggered to scan the dependency.
- **Scan Process (Backend - API Route `/api/scan-dependency`):**
- Receives dependency name, version, registry.
- Queries external vulnerability databases (e.g., OSV.dev, GitHub Advisory DB API) for known CVEs.
- **Malicious Code Detection:** Implements heuristics/AI analysis (future enhancement) or pattern matching for suspicious elements (like large base64 blobs in source files, unexpected network calls, excessive memory usage patterns) by fetching the library's source code from the registry.
- Stores any found vulnerabilities in the `vulnerabilities` table.
- Flags `isMaliciousCode=true` if suspicious patterns are detected.
- Creates an alert in the `alerts` table if a vulnerability or malicious code is found.
- Updates `lastScannedAt` in the `dependencies` table.
- **User Feedback:** The UI will show a 'Scanning...' state, then update with vulnerability information or a 'Clean' status.
4. **Dashboard Overview:**
- Displays a summary of all projects and their overall security status.
- Shows the total number of vulnerabilities across all projects, categorized by severity.
- Highlights projects with critical vulnerabilities.
- Displays recent alerts.
5. **Alerts & Notifications:**
- Users receive in-app notifications and optionally email alerts for new critical vulnerabilities or detected malicious code.
- The 'Alerts' page lists all triggered alerts, filterable by project, severity, and status (New, Acknowledged, Resolved).
- Users can acknowledge or resolve alerts from this page.
API & DATA FETCHING:
- **Next.js API Routes:** Primarily used for backend logic.
- `POST /api/auth/*`: Handled by NextAuth.js.
- `POST /api/projects`: Create a new project. Request Body: `{ name: string, description?: string }`. Response: `{ success: true, project: Project }`.
- `GET /api/projects`: Get all projects for the logged-in user. Response: `Project[]`.
- `POST /api/projects/[projectId]/dependencies`: Add a dependency. Request Body: `{ name: string, version: string, registry: 'pypi' | 'npm' }`. Response: `{ success: true, dependency: Dependency }`.
- `GET /api/projects/[projectId]/dependencies`: Get dependencies for a project. Response: `Dependency[]`.
- `GET /api/dependencies/[dependencyId]/vulnerabilities`: Get vulnerabilities for a specific dependency. Response: `Vulnerability[]`.
- `GET /api/alerts`: Get alerts for the logged-in user. Response: `Alert[]`.
- `POST /api/alerts/[alertId]/acknowledge`: Acknowledge an alert. Response: `{ success: true }`.
- `POST /api/scan-dependency`: (Internal or triggered by background job) Initiates the scanning process. Request Body: `{ dependencyId: string }`. Response: `{ success: true, scanResult: ScanResult }`.
- **Data Fetching in Components:**
- Server Components will fetch data directly from the database using Drizzle ORM.
- Client Components will use `fetch` or libraries like `swr` to call API routes, passing relevant IDs (projectId, dependencyId) as needed.
- Example `useEffect` in a Client Component:
```javascript
const [dependencies, setDependencies] = useState([]);
useEffect(() => {
fetch(`/api/projects/${projectId}/dependencies`)
.then(res => res.json())
.then(data => setDependencies(data));
}, [projectId]);
```
COMPONENT BREAKDOWN (Next.js App Router):
- **`app/` (Root Directory)**
- **`layout.tsx`**: Root layout (includes `<html>`, `<body>`, global providers, Navbar, Footer, Tailwind CSS setup).
- **`page.tsx`**: Landing Page (Public facing, marketing copy, call to action).
- **`auth/`**: Authentication pages.
- `layout.tsx`: Auth layout (centralized forms).
- `sign-in/page.tsx`: Sign-in form component.
- `sign-up/page.tsx`: Sign-up form component.
- `reset-password/page.tsx`: Password reset form.
- **`dashboard/`**: Authenticated User Dashboard.
- `page.tsx`: Main dashboard view (summary cards, recent alerts).
- `components/`:
- `ProjectSummaryCard.tsx`: Displays a single project's stats.
- `VulnerabilityChart.tsx`: Chart showing vulnerability distribution by severity.
- `RecentAlertsList.tsx`: List of the latest alerts.
- **`projects/`**: Project Management.
- `page.tsx`: Lists all user projects.
- `[projectId]/`:
- `page.tsx`: Project Detail page (shows dependencies, add dependency form/button).
- `components/`:
- `DependencyList.tsx`: Table or list of dependencies for the project.
- `DependencyItem.tsx`: Renders a single dependency row.
- `AddDependencyForm.tsx`: Modal/Form to add new dependencies.
- `VulnerabilityList.tsx`: Lists vulnerabilities for a selected dependency.
- `VulnerabilityItem.tsx`: Renders a single vulnerability row.
- `ScanStatusIndicator.tsx`: Shows scanning progress/status.
- **`alerts/`**: Alert Management.
- `page.tsx`: Main alerts page (filterable list of all alerts).
- `components/`:
- `AlertList.tsx`: Table displaying alerts.
- `AlertItem.tsx`: Renders a single alert row with actions (Acknowledge, Resolve).
- `AlertFilter.tsx`: Controls for filtering alerts.
- **`settings/`**: User Settings.
- `page.tsx`: User profile, notification preferences, connected accounts.
- **`loading.tsx`**: Global loading state indicator.
- **`error.tsx`**: Global error boundary.
- **`components/` (Shared UI Components)**
- **`ui/`**: Components from shadcn/ui (Button, Card, Input, Form, Dialog, Table, Alert, Avatar, etc.).
- **`Navbar.tsx`**: Top navigation bar (logo, links, user profile dropdown).
- **`Footer.tsx`**: Footer section.
- **`Sidebar.tsx`**: (Optional, if needed for complex navigation) Left-hand sidebar.
- **`AuthButton.tsx`**: Button to trigger sign-in/sign-out.
- **`Spinner.tsx`**: Loading spinner component.
- **`lib/`**: Utility functions, API clients, database connection setup (Drizzle).
- **`hooks/`**: Custom React hooks (e.g., `useAuth`, `useProjects`).
- **`contexts/`**: React Context providers (e.g., `AuthContext`).
UI/UX DESIGN & VISUAL IDENTITY:
- **Design Style:** Modern, Clean, and Professional.
- **Color Palette:**
- Primary: `#4F46E5` (Indigo-500)
- Secondary: `#6366F1` (Indigo-600)
- Accent: `#2563EB` (Blue-600) for CTAs and important actions.
- Background: `#F9FAFB` (Light Gray) for light mode, `#111827` (Dark Gray-900) for dark mode.
- Text: `#1F2937` (Dark Gray-800) for light mode, `#E5E7EB` (Light Gray-200) for dark mode.
- Alerts: `RED` (#EF4444) for Critical, `ORANGE` (#F97316) for High, `YELLOW` (#EAB308) for Medium, `BLUE` (#3B82F6) for Low/Info.
- **Typography:** Inter font family (or similar sans-serif like Manrope). Use semantic HTML tags and appropriate font weights for hierarchy.
- Headings: Bold, larger sizes.
- Body Text: Regular weight, readable size.
- **Layout:** Use a consistent grid system (e.g., 12-column). Max-width container for content. Clear separation of sections using cards and spacing.
- **Responsiveness:** Mobile-first approach. Ensure usability on all screen sizes (phones, tablets, desktops). Use Tailwind's responsive modifiers (`sm:`, `md:`, `lg:`).
- **Interactions:** Subtle hover effects on buttons and links. Smooth transitions for modal pop-ups and menu reveals.
ANIMATIONS:
- **Page Transitions:** Subtle fade-in/fade-out effect between pages using Next.js's `Suspense` boundary and potentially a library like `Framer Motion` for more advanced transitions if needed.
- **Loading States:** Use `SkeletonLoaders` (e.g., `react-loading-skeleton` or custom shadcn/ui implementations) or spinners (`Spinner.tsx` component) while data is fetching.
- **Hover Effects:** Gentle scaling or background color changes on interactive elements (buttons, links, cards).
- **Form Feedback:** Subtle animations for input validation errors (e.g., slight shake or border color change).
EDGE CASES:
- **Authentication:** Handle expired sessions, incorrect credentials, locked accounts, OAuth errors.
- **Empty States:** Design clear and helpful empty states for Projects, Dependencies, and Alerts lists (e.g., 'You haven't added any projects yet. Click here to add one!').
- **Error Handling:** Implement robust error handling for API calls (display user-friendly messages), form submissions (validation errors), and unexpected backend issues. Use Next.js `error.tsx` for boundary errors.
- **Validation:** Use `zod` and `react-hook-form` for client-side and server-side (API routes) validation of all user inputs (project names, dependency details, etc.).
- **Rate Limiting:** Implement rate limiting on API routes, especially those that trigger external scans, to prevent abuse.
- **Dependency Not Found:** Gracefully handle cases where a dependency version is not found in the registry or vulnerability database.
- **Permissions:** Ensure users can only access and manage their own projects and data.
SAMPLE/MOCK DATA:
1. **User:**
```json
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"name": "Alice Developer",
"email": "alice@example.com",
"image": "https://example.com/avatar.jpg"
}
```
2. **Project:**
```json
{
"id": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"userId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"name": "Awesome API",
"description": "My main backend service.",
"createdAt": "2023-10-27T10:00:00Z"
}
```
3. **Dependency (Clean):**
```json
{
"id": "1a2b3c4d-5e6f-7890-abcd-ef0123456789",
"projectId": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"name": "fastapi",
"version": "0.101.1",
"registry": "pypi",
"lastScannedAt": "2023-10-27T11:00:00Z",
"createdAt": "2023-10-27T09:00:00Z"
}
```
4. **Dependency (With Vulnerability):**
```json
{
"id": "98765432-10fe-dcba-9876-543210fedcba",
"projectId": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"name": "django",
"version": "4.2.5",
"registry": "pypi",
"lastScannedAt": "2023-10-27T11:05:00Z",
"createdAt": "2023-10-27T09:05:00Z"
}
```
5. **Vulnerability (CVE):**
```json
{
"id": "vuln-12345",
"dependencyId": "98765432-10fe-dcba-9876-543210fedcba",
"vulnerabilityId": "CVE-2023-12345",
"title": "Remote Code Execution in Django Admin",
"description": "A vulnerability exists in the Django admin interface that allows remote attackers to execute code.",
"severity": "HIGH",
"source": "NVD",
"cvssScore": 7.5,
"detectedAt": "2023-10-27T11:05:00Z",
"isMaliciousCode": false
}
```
6. **Vulnerability (Malicious Code Pattern - Litellm example):**
```json
{
"id": "vuln-abcde",
"dependencyId": "some-dependency-id", // hypothetical ID
"vulnerabilityId": "SECURELIB-MALCODE-001",
"title": "Suspicious Base64 Encoded Payload Detected",
"description": "The library contains obfuscated code (base64 blob) attempting to download and execute external scripts.",
"severity": "CRITICAL",
"source": "SecureLib Internal Analysis",
"cvssScore": 9.8,
"detectedAt": "2023-10-26T15:00:00Z",
"isMaliciousCode": true
}
```
7. **Alert (Vulnerability Found):**
```json
{
"id": "alert-xyz789",
"userId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"dependencyId": "98765432-10fe-dcba-9876-543210fedcba",
"alertType": "VULNERABILITY_FOUND",
"message": "High severity vulnerability CVE-2023-12345 found in django v4.2.5. Consider upgrading or patching.",
"severity": "HIGH",
"status": "NEW",
"triggeredAt": "2023-10-27T11:06:00Z"
}
```
8. **Alert (Malicious Code):**
```json
{
"id": "alert-mal001",
"userId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"dependencyId": "some-dependency-id",
"alertType": "MALICIOUS_CODE_DETECTED",
"message": "Critical security risk: Malicious code detected in dependency. Immediate investigation required.",
"severity": "CRITICAL",
"status": "NEW",
"triggeredAt": "2023-10-26T15:01:00Z"
}
```
9. **Dependency (NPM Example):**
```json
{
"id": "npm-dep-1",
"projectId": "project-npm-1",
"name": "lodash",
"version": "4.17.21",
"registry": "npm",
"lastScannedAt": "2023-10-27T12:00:00Z",
"createdAt": "2023-10-27T10:00:00Z"
}
```
10. **Vulnerability (NPM Example):**
```json
{
"id": "vuln-npm-001",
"dependencyId": "npm-dep-1",
"vulnerabilityId": "SNYK-JS-LODASH-1018905",
"title": "Denial of Service (DoS) via crafted input",
"description": "The `deRefUniqueStrings` function in lodash is vulnerable to Regular Expression Denial of Service (ReDoS).",
"severity": "MEDIUM",
"source": "Snyk",
"cvssScore": 6.5,
"detectedAt": "2023-10-27T12:00:00Z",
"isMaliciousCode": false
}
```
This prompt is designed to generate a robust, multi-feature MVP application that directly addresses the security concerns highlighted by the Litellm incident, providing significant value to developers managing open-source dependencies.