You are an expert AI assistant tasked with building a fully functional, multi-page MVP of a proactive cybersecurity SaaS application called 'CyberShield AI' using the Next.js App Router. The application will focus on analyzing threat intelligence related to ransomware groups like GandCrab and REvil, predicting potential attacks, and providing actionable defense recommendations to businesses.
PROJECT OVERVIEW:
CyberShield AI aims to empower businesses to proactively defend against sophisticated cyber threats, particularly ransomware. By leveraging AI to analyze threat intelligence, it identifies emerging attack vectors, assesses organizational risk, and delivers tailored, actionable defense strategies. The core value proposition is shifting cybersecurity from reactive defense to proactive threat mitigation, saving businesses from costly data breaches and operational disruptions caused by ransomware like GandCrab and REvil.
TECH STACK:
- Framework: Next.js (App Router)
- Language: TypeScript
- Styling: Tailwind CSS
- UI Components: shadcn/ui
- ORM: Drizzle ORM (PostgreSQL compatible)
- Database: PostgreSQL (using Vercel Postgres or similar)
- Authentication: NextAuth.js (Credentials & Google Provider)
- State Management: React Context API / Zustand (for global state)
- Data Fetching: Server Components, Route Handlers (API Routes)
- Libraries: `zod` for validation, `date-fns` for date manipulation, `chart.js` or `recharts` for charts, `clsx` for conditional class names, `react-hook-form` for forms.
DATABASE SCHEMA:
1. **`users` Table:**
* `id` (UUID, primary key)
* `name` (VARCHAR)
* `email` (VARCHAR, unique)
* `emailVerified` (TIMESTAMP)
* `image` (TEXT, nullable)
* `passwordHash` (VARCHAR, nullable - for credentials provider)
* `createdAt` (TIMESTAMP, default NOW())
* `updatedAt` (TIMESTAMP, default NOW())
2. **`accounts` Table (for NextAuth.js):**
* `id` (UUID, primary key)
* `userId` (UUID, foreign key to users.id)
* `type` (VARCHAR - 'oauth' or 'credentials')
* `provider` (VARCHAR)
* `providerAccountId` (VARCHAR)
* `refresh_token` (TEXT, nullable)
* `access_token` (TEXT, nullable)
* `expires_at` (BIGINT, nullable)
* `token_type` (VARCHAR, nullable)
* `scope` (VARCHAR, nullable)
* `id_token` (TEXT, nullable)
* `session_token` (TEXT, unique)
3. **`sessions` Table (for NextAuth.js):**
* `id` (UUID, primary key)
* `userId` (UUID, foreign key to users.id)
* `expires` (TIMESTAMP)
* `sessionToken` (TEXT, unique)
4. **`verificationTokens` Table (for NextAuth.js):**
* `identifier` (TEXT)
* `token` (TEXT, unique)
* `expires` (TIMESTAMP)
5. **`threat_intel_sources` Table:**
* `id` (UUID, primary key)
* `name` (VARCHAR, unique) - e.g., 'BKA Advisory', 'US DOJ Filing', 'Security Blog X'
* `type` (VARCHAR) - e.g., 'Government Report', 'News Article', 'Forum Post'
* `url` (TEXT, nullable)
* `lastChecked` (TIMESTAMP)
6. **`threat_reports` Table:**
* `id` (UUID, primary key)
* `sourceId` (UUID, foreign key to threat_intel_sources.id)
* `title` (VARCHAR)
* `summary` (TEXT)
* `reportDate` (DATE)
* `tags` (TEXT[]) - e.g., ['ransomware', 'GandCrab', 'REvil', 'exploitation']
* `rawData` (JSONB, nullable) - Original unstructured data if available
* `processedAt` (TIMESTAMP, default NOW())
7. **`analyzed_threats` Table:**
* `id` (UUID, primary key)
* `reportId` (UUID, foreign key to threat_reports.id)
* `threatName` (VARCHAR) - e.g., 'GandCrab v5 TTPs', 'REvil Double Extortion'
* `description` (TEXT)
* `attackerGroup` (VARCHAR) - e.g., 'GandCrab', 'REvil', 'UNKN'
* `attackVector` (VARCHAR) - e.g., 'Phishing', 'Exploited Vulnerability', 'RDP'
* `victimology` (TEXT)
* `monetaryDamage` (BIGINT, nullable)
* `estimatedIoC` (TEXT[], nullable) - Indicators of Compromise
* `analysisDate` (TIMESTAMP, default NOW())
8. **`risk_assessments` Table:**
* `id` (UUID, primary key)
* `userId` (UUID, foreign key to users.id)
* `organizationName` (VARCHAR)
* `assessmentDate` (TIMESTAMP, default NOW())
* `overallRiskScore` (INTEGER) - 1-100
* `primaryThreats` (TEXT[]) - Linked to `analyzed_threats.threatName` or similar identifier
9. **`defense_recommendations` Table:**
* `id` (UUID, primary key)
* `riskAssessmentId` (UUID, foreign key to risk_assessments.id)
* `recommendationText` (TEXT)
* `recommendationType` (VARCHAR) - e.g., 'Technical', 'Policy', 'Training'
* `priority` (VARCHAR) - e.g., 'High', 'Medium', 'Low'
* `status` (VARCHAR, default 'Pending') - e.g., 'Pending', 'In Progress', 'Completed'
* `assignedTo` (UUID, foreign key to users.id, nullable)
* `createdAt` (TIMESTAMP, default NOW())
CORE FEATURES & USER FLOW:
1. **Authentication Flow:**
* User lands on the homepage.
* Option to 'Sign Up' or 'Log In'.
* Sign Up: Requires name, email, password. Uses `zod` for validation. Creates a user in the `users` table and potentially an account entry.
* Log In: Uses NextAuth.js. Supports email/password (Credentials Provider) and Google OAuth.
* After successful login, user is redirected to the Dashboard.
* Protected Routes: All pages except `/` and `/auth/*` require authentication. Redirect unauthenticated users to `/auth/login`.
2. **Threat Intelligence Ingestion & Analysis (Admin/Internal Process):**
* A scheduled script or internal tool (not directly part of MVP user flow but essential for backend) fetches data from defined `threat_intel_sources`.
* Parses reports (potentially using NLP for basic summarization and keyword extraction). Stores raw and processed data in `threat_reports`.
* Analyzes reports to identify key threat details (attacker group, vector, damage, IoCs) and populates the `analyzed_threats` table.
* Focus on extracting details relevant to GandCrab, REvil, UNKN, double extortion, and German victimology.
3. **Dashboard:**
* **Page:** `/dashboard` (Protected Route)
* **Functionality:** Displays a summary of the current threat landscape and the organization's risk.
* **Components:**
* `ThreatSummaryCard`: Shows count of recent critical reports, primary threat groups active.
* `RiskScoreChart`: Displays the organization's current `risk_assessments.overallRiskScore` (e.g., line or gauge chart).
* `RecentThreatsTable`: Lists the latest entries from `analyzed_threats` relevant to the user's context (filtered if possible based on subscription/organization profile).
* `ActionableInsightsWidget`: Highlights the top 3-5 `defense_recommendations` based on priority and status for the user's organization.
* **Data Fetching:** Server Component fetches data from `analyzed_threats`, `risk_assessments`, and `defense_recommendations` tables (potentially joining or filtering).
4. **Risk Assessment Creation:**
* **Page:** `/dashboard/assessments/new` (Protected Route)
* **Functionality:** Allows users to initiate a new risk assessment or provides automated assessment based on existing data if applicable.
* **Components:**
* `AssessmentForm`: Collects organization details (name, industry - for future enhancements). Might include questions to refine the initial assessment score.
* **User Flow:** User fills form -> Clicks 'Assess' -> Backend generates a `risk_assessments` record -> A corresponding `risk_assessments.id` is created.
* **Backend:** A service calculates the `overallRiskScore` based on factors like industry, user inputs, and recent relevant threats from `analyzed_threats`. It also generates initial `defense_recommendations` linked to this assessment.
5. **View Risk Assessment Details:**
* **Page:** `/dashboard/assessments/[assessmentId]` (Protected Route)
* **Functionality:** Displays detailed information about a specific assessment.
* **Components:**
* `AssessmentOverview`: Shows `organizationName`, `assessmentDate`, `overallRiskScore`.
* `PrimaryThreatsList`: Lists the `primaryThreats` identified.
* `RecommendationsTable`: Displays all `defense_recommendations` for this assessment, with options to update status.
* **Data Fetching:** Server Component fetches data using `assessmentId` from `risk_assessments` and `defense_recommendations` tables.
6. **Threat Intelligence Library:**
* **Page:** `/threat-intel` (Protected Route)
* **Functionality:** Browse and search the processed threat intelligence reports.
* **Components:**
* `IntelSearchBar`: Filter by keywords, tags, date range, threat group.
* `IntelReportList`: Displays summaries of `analyzed_threats` entries.
* `IntelReportDetailModal`: On clicking a report, opens a modal showing `title`, `description`, `attackerGroup`, `attackVector`, `victimology`, `tags`, etc. from `analyzed_threats`.
* **Data Fetching:** Client or Server Component fetches data from `analyzed_threats` with filtering capabilities.
API & DATA FETCHING:
- Utilize Next.js Route Handlers (`app/api/.../route.ts`) for API endpoints.
- Server Components will fetch data directly from the database using Drizzle ORM within `async` functions, ensuring data is fetched server-side where possible for security and performance.
- API Routes will handle mutations (POST, PUT, DELETE) for actions like updating recommendation status, creating assessments.
- Use `zod` for validating incoming request bodies in API routes.
- Example API Route (`PUT /api/recommendations/[recommendationId]/status`):
* Request Body Schema (zod):
```typescript
const updateStatusSchema = z.object({
status: z.enum(['Pending', 'In Progress', 'Completed'])
});
```
* Logic: Authenticate user, validate request body, find recommendation by ID, update status in the database.
- Example Server Component Fetch (`/dashboard/page.tsx`):
```typescript
// Hypothetical Drizzle query
const recentThreats = await db.query.analyzedThreats.findMany({
orderBy: desc(tables.analyzedThreats.analysisDate),
limit: 10,
// Add filters based on user context if available
});
```
COMPONENT BREAKDOWN (Next.js App Router Structure):
- **`app/`**
* **`(auth)` Group:**
* `login/page.tsx`: Login form component.
* `signup/page.tsx`: Signup form component.
* **`(app)` Group (Protected Routes):**
* `layout.tsx`: Main application layout, includes sidebar navigation, header.
* **`dashboard/`:**
* `page.tsx`: Main dashboard view. Fetches and displays summary cards, charts, recent threats, and actionable insights.
* `layout.tsx`: Dashboard specific layout if needed.
* **`assessments/`:**
* `page.tsx`: List of past assessments.
* `new/page.tsx`: Form for creating a new assessment.
* `[assessmentId]/page.tsx`: Detailed view of a single assessment.
* **`threat-intel/`:**
* `page.tsx`: Browseable list of analyzed threats, includes search/filter components.
* **`api/`:**
* `auth/[...nextauth]/route.ts`: NextAuth.js handler.
* `recommendations/[recommendationId]/status/route.ts`: API route for updating recommendation status.
* `assessments/route.ts`: API route for creating new assessments.
* `layout.tsx`: Root layout (html, body, providers).
* `page.tsx`: Public homepage.
- **`components/ui/`:** Reusable UI elements from shadcn/ui (Button, Input, Card, Table, Sheet, Dialog, etc.).
- **`components/`:** Custom components.
* `AuthButton.tsx`: Handles login/logout logic and display.
* `Sidebar.tsx`: Navigation menu.
* `Header.tsx`: Top bar with user info, etc.
* `DashboardWidgets/`: Components specific to the dashboard (e.g., `ThreatSummaryCard.tsx`, `RiskScoreChart.tsx`, `RecentThreatsTable.tsx`, `ActionableInsightsWidget.tsx`).
* `Assessments/`: Components related to assessments (e.g., `AssessmentForm.tsx`, `AssessmentDetailView.tsx`, `RecommendationsTable.tsx`).
* `ThreatIntel/`: Components for the threat intel page (e.g., `IntelSearchBar.tsx`, `IntelReportList.tsx`, `IntelReportDetailModal.tsx`).
* `Common/`: General purpose components (e.g., `DataTable.tsx`, `LoadingSpinner.tsx`, `AlertMessage.tsx`).
UI/UX DESIGN & VISUAL IDENTITY:
- **Design Style:** Modern, Clean, Professional with a hint of futuristic security.
- **Color Palette:**
* Primary: Dark Blue (`#0A192F`)
* Secondary: Deep Teal (`#235D5C`)
* Accent: Bright Cyan (`#61DAFB`)
* Neutral Dark: Off-Black (`#111827`)
* Neutral Light: Light Gray (`#F3F4F6`)
* Alerts: Orange (`#F97316`), Red (`#EF4444`)
- **Typography:**
* Headings: Inter (Bold)
* Body: Inter (Regular)
- **Layout:** Utilize a consistent sidebar navigation. Content areas should be well-spaced with clear visual hierarchy. Use cards for modular content display. Maintain a 16:9 aspect ratio for charts where applicable.
- **Responsiveness:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows gracefully. Use Tailwind's responsive prefixes (`sm:`, `md:`, `lg:`).
ANIMATIONS:
- **Page Transitions:** Subtle fade-in/out using Next.js's `useRouter` and a layout wrapper (e.g., `framer-motion`).
- **Hover Effects:** Slight scale or shadow lift on interactive elements like buttons and cards.
- **Loading States:** Use `Suspense` boundaries in Next.js App Router with `LoadingSpinner.tsx` components for data fetching. Skeleton loaders for tables and cards before data arrives.
- **Chart Animations:** Animate data loading into charts (`recharts` or `chart.js` support this).
- **Button Transitions:** Smooth color/transform changes on hover/active states.
EDGE CASES:
- **Authentication:** Handle expired sessions, invalid credentials, Google OAuth callback errors.
- **Data Fetching:** Implement error handling for API calls and server component fetches. Display user-friendly error messages (`AlertMessage.tsx`). Handle empty states gracefully (e.g., 'No threats found', 'No assessments yet').
- **Validation:** Use `zod` for all form and API input validation. Provide clear feedback to the user on validation errors.
- **Authorization:** Ensure users can only access/modify their own data (e.g., `risk_assessments` belonging to their `userId`).
- **Rate Limiting:** Implement basic rate limiting on API routes to prevent abuse.
- **Database Errors:** Gracefully handle potential database connection issues or query errors.
SAMPLE DATA (for `analyzed_threats` table):
1. `{ threatName: 'GandCrab V5 Double Extortion', description: 'GandCrab group uses RDP compromise for initial access, exfiltrates data before encryption.', attackerGroup: 'GandCrab', attackVector: 'RDP Compromise', victimology: 'Multiple German SMEs in manufacturing sector', monetaryDamage: 500000, estimatedIoC: ['192.168.1.100', '*.gandcrab.onion'], reportId: 'uuid-report-1' }`
2. `{ threatName: 'REvil Supply Chain Attack', description: 'REvil exploited a vulnerability in a popular accounting software update to compromise numerous businesses.', attackerGroup: 'REvil', attackVector: 'Software Vulnerability', victimology: 'Users of AcctSoft Suite', monetaryDamage: 2000000, estimatedIoC: ['malicious.update.server.com', 'revil-domain.xyz'], reportId: 'uuid-report-2' }`
3. `{ threatName: 'UNKN Phishing Campaign', description: 'Targeted phishing emails with malicious attachments impersonating German tax authorities.', attackerGroup: 'UNKN', attackVector: 'Phishing', victimology: 'German Taxpaying Individuals & Businesses', monetaryDamage: 150000, estimatedIoC: ['tax-gov-malware.doc', 'secure-portal-login.com'], reportId: 'uuid-report-3' }`
4. `{ threatName: 'GandCrab Credential Stuffing', description: 'Leveraged previously leaked credentials to gain access to corporate networks.', attackerGroup: 'GandCrab', attackVector: 'Credential Stuffing', victimology: 'Various businesses with weak password policies', monetaryDamage: 300000, estimatedIoC: ['leaked_creds_list_xyz.txt'], reportId: 'uuid-report-4' }`
5. `{ threatName: 'REvil Ransomware Deployment via Cobalt Strike', description: 'Post-exploitation using Cobalt Strike for lateral movement and data exfiltration before encrypting systems.', attackerGroup: 'REvil', attackVector: 'Exploited Vulnerability (Initial) + Cobalt Strike', victimology: 'Large enterprise in the logistics sector', monetaryDamage: 1500000, estimatedIoC: ['cobaltstrike-beacon.dll', 'evil.command.center:443'], reportId: 'uuid-report-5' }`
6. `{ threatName: 'GandCrab Network Propagation', description: 'Utilized SMB vulnerabilities to spread rapidly across internal networks after initial compromise.', attackerGroup: 'GandCrab', attackVector: 'SMB Vulnerability Exploit', victimology: 'Medium-sized organizations with unpatched systems', monetaryDamage: 400000, estimatedIoC: ['ms17-010-exploit'], reportId: 'uuid-report-6' }`
7. `{ threatName: 'German Police Identified UNKN Leader', description: 'Report detailing the identification of Daniil Shchukin as the alleged leader of GandCrab/REvil operations.', attackerGroup: 'GandCrab, REvil', attackVector: 'Law Enforcement Action', victimology: 'Global cybercrime landscape', monetaryDamage: null, estimatedIoC: ['Daniil Shchukin', 'Anatoly Kravchuk'], reportId: 'uuid-report-7' }`