You are a senior full-stack developer tasked with building a robust, multi-page Next.js MVP application using the App Router. The application, 'SecureCode Watch', aims to proactively monitor third-party package security for software development teams. It will scan project dependencies, detect known vulnerabilities (CVEs), identify malicious packages (like RATs or crypto miners), and integrate with CI/CD pipelines to provide real-time security alerts.
PROJECT OVERVIEW:
SecureCode Watch is a SaaS platform designed to mitigate risks associated with compromised npm/yarn packages. It addresses the critical problem of supply chain attacks and malicious code injection in open-source libraries, exemplified by recent incidents like the Axios compromise. The core value proposition is to provide development teams with automated, real-time security scanning of their project dependencies, preventing security breaches, data leaks, and the introduction of malware into their codebase. The MVP will focus on core scanning, detection, alerting, and essential integrations.
TECH STACK:
- **Framework:** Next.js (App Router)
- **UI Library:** shadcn/ui (for clean, accessible, and customizable components)
- **Styling:** Tailwind CSS
- **Database ORM:** Drizzle ORM (with PostgreSQL using `pg` driver)
- **Authentication:** NextAuth.js (for robust email/password and OAuth support)
- **State Management:** React Context API and Server Components state management
- **API Layer:** Next.js API Routes (for backend logic) and Server Actions (for mutations)
- **Deployment:** Vercel
- **Other Libraries:** `zod` (for schema validation), `react-hook-form` (for form management), `clsx` (for conditional class names), `date-fns` (for date manipulation), `react-icons` (for icons), `axios` (for inter-service communication if needed, but not for user projects in this context).
DATABASE SCHEMA (PostgreSQL with Drizzle ORM):
```sql
-- User authentication and profile
users table
id: uuid PRIMARY KEY
name: text
email: text UNIQUE NOT NULL
emailVerified: timestamp
image: text
createdAt: timestamp DEFAULT now()
updatedAt: timestamp DEFAULT now()
accounts table (for NextAuth.js)
id: uuid PRIMARY KEY
userId: uuid REFERENCES users(id) ON DELETE CASCADE
type: text NOT NULL
provider: text NOT NULL
providerAccountId: 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, providerAccountId)
sessions table (for NextAuth.js)
id: uuid PRIMARY KEY
sessionToken: text UNIQUE NOT NULL
userId: uuid REFERENCES users(id) ON DELETE CASCADE
expires: timestamp NOT NULL
verificationTokens table (for NextAuth.js)
identifier: text NOT NULL
token: text NOT NULL
expires: timestamp NOT NULL
UNIQUE(identifier, token)
-- Application specific tables
projects table
id: uuid PRIMARY KEY
userId: uuid REFERENCES users(id) ON DELETE CASCADE
name: text NOT NULL
repoUrl: text UNIQUE NOT NULL -- e.g., GitHub URL
packageManager: text NOT NULL -- 'npm', 'yarn', 'pnpm'
createdAt: timestamp DEFAULT now()
updatedAt: timestamp DEFAULT now()
packages table
id: uuid PRIMARY KEY
projectId: uuid REFERENCES projects(id) ON DELETE CASCADE
name: text NOT NULL
version: text NOT NULL
vulnerabilitySeverity: text -- 'low', 'medium', 'high', 'critical', null
isMalicious: boolean DEFAULT false
detectedAt: timestamp
scanId: uuid REFERENCES scans(id) ON DELETE SET NULL
UNIQUE(projectId, name, version)
scans table
id: uuid PRIMARY KEY
projectId: uuid REFERENCES projects(id) ON DELETE CASCADE
status: text NOT NULL -- 'running', 'completed', 'failed'
startedAt: timestamp DEFAULT now()
completedAt: timestamp
dependenciesScanned: integer DEFAULT 0
vulnerabilitiesFound: integer DEFAULT 0
maliciousPackagesFound: integer DEFAULT 0
severityLevels table
level: text PRIMARY KEY -- 'low', 'medium', 'high', 'critical'
description: text
-- Junction table for many-to-many between users and projects (if needed for team collaboration later)
-- projectMembers table
-- userId: uuid REFERENCES users(id) ON DELETE CASCADE
-- projectId: uuid REFERENCES projects(id) ON DELETE CASCADE
-- role: text -- 'owner', 'member'
-- PRIMARY KEY (userId, projectId)
```
CORE FEATURES & USER FLOW:
1. **User Authentication (Sign Up/Login/OAuth):**
* **Flow:** User lands on the homepage. Clicks 'Sign Up' or 'Login'. Can use email/password or GitHub/Google OAuth.
* **Details:** NextAuth.js will handle the auth logic. Redirect to the dashboard upon successful login. Handle sign-out and session management.
* **Edge Cases:** Invalid credentials, locked accounts (future), OAuth callback errors, email verification pending.
2. **Project Onboarding:**
* **Flow:** Logged-in user navigates to 'Projects' page. Clicks 'Add New Project'. Enters project name, GitHub repository URL, and selects package manager (npm, yarn, pnpm).
* **Details:** Backend validates the URL and initiates a background scan. The repo URL will be used for future CI/CD integration hooks.
* **Edge Cases:** Invalid repository URL, private repositories (initially MVP supports public), unsupported package manager.
3. **Dependency Scanning (Initial & Scheduled):**
* **Flow (Manual):** User clicks 'Scan Now' on a project's detail page. A background job is triggered.
* **Flow (CI/CD):** A GitHub Action workflow (or similar) runs `securecodewatch scan --project <project-id>` during build. This action sends a request to our API.
* **Details:** The backend clones the repository (if not already cached/indexed), reads the `package.json` and `package-lock.json`/`yarn.lock`/`pnpm-lock.yaml`, extracts the dependency list and versions. It then queries internal/external vulnerability databases (like Snyk DB, NVD) and checks against a curated list of known malicious package signatures/heuristics. Scan status (`running`, `completed`, `failed`) is updated in the `scans` table.
* **Edge Cases:** Large projects with many dependencies, network errors during cloning or dependency fetching, API rate limits for external databases, corrupted lock files.
4. **Vulnerability & Malicious Package Detection:**
* **Flow:** As dependencies are scanned, each package is checked against vulnerability databases. If a known CVE exists for a package version, its `vulnerabilitySeverity` is updated in the `packages` table. If a package matches a malicious signature or heuristic (e.g., suspicious postinstall scripts, known RAT droppers), `isMalicious` is set to `true` and `detectedAt` is updated.
* **Details:** This involves maintaining an internal database of malicious package indicators, potentially using heuristics and threat intelligence feeds. For CVEs, integration with public databases (NVD, GitHub Advisory Database) is crucial.
* **Edge Cases:** Zero-day vulnerabilities (cannot be detected without signatures), polymorphic malware, packages with slightly modified malicious code.
5. **Dashboard & Alerting:**
* **Flow:** User logs in and sees the main dashboard. It displays an overview of all projects, recent scan statuses, and a summary of critical/high vulnerabilities and malicious packages found. Clicking on a project shows detailed findings.
* **Details:** The dashboard aggregates data from `scans` and `packages` tables. Alerts can be triggered via email (using a transactional email service like Resend or Nodemailer) or Slack notifications (via webhooks) when new critical issues are detected.
* **Edge Cases:** No projects added, no vulnerabilities found (clean state), high volume of alerts overwhelming the user.
6. **CI/CD Integration (GitHub Actions Example):**
* **Flow:** User adds a `.github/workflows/security.yml` file to their repo. This workflow file uses a pre-built GitHub Action (or a simple `curl` command to our API) that takes the project ID and API token.
* **Details:** The action runs `npm ls --json` (or equivalent), sends the dependency list to SecureCode Watch API endpoint (`/api/scan/external`), which then performs the check and returns a status code/report. The action can be configured to fail the build if critical vulnerabilities or malicious packages are found.
* **Edge Cases:** API token security, action failing due to network issues, parsing errors in dependency output.
API & DATA FETCHING:
- **API Routes (`/app/api/...` or root `/api/...`):**
- `POST /api/auth/signup`: User registration.
- `POST /api/auth/login`: User login.
- `GET /api/projects`: Get all projects for the logged-in user.
- `POST /api/projects`: Add a new project.
- `GET /api/projects/{projectId}`: Get details of a specific project, including recent scans and detected packages.
- `POST /api/projects/{projectId}/scan`: Trigger a manual scan for a project.
- `POST /api/scan/external`: Endpoint for CI/CD tools to initiate scans.
- `GET /api/vulnerabilities`: Fetch vulnerability data (potentially paginated).
- `GET /api/malicious-packages`: Fetch known malicious package indicators.
- `GET /api/dashboard/summary`: Get summary data for the user's dashboard.
- **Server Actions:** Used within components for mutations like adding projects, triggering scans, updating settings.
- **Data Fetching:** Use `fetch` in Server Components for initial data load. Use Client Components with `react-query` or SWR for dynamic data fetching, polling scan status, and handling real-time updates. Use Server Actions for form submissions and mutations.
- **Request/Response Examples:**
- `POST /api/projects`: `{ "name": "MyWebApp", "repoUrl": "https://github.com/user/mywebapp", "packageManager": "npm" }` -> `{ "id": "uuid", "message": "Project added successfully" }`
- `POST /api/scan/external`: `{ "projectId": "uuid", "dependencies": [{"name": "axios", "version": "1.14.1"}, ...] }` -> `{ "scanId": "uuid", "status": "running", "findings": [...] }`
COMPONENT BREAKDOWN (Next.js App Router Structure):
- **`app/layout.tsx`:** Root layout with global styles, providers (NextAuth.js SessionProvider, ThemeProvider), and global elements.
- **`app/page.tsx`:** Landing Page (Marketing content, features overview, call to action).
- **`app/(auth)/layout.tsx`:** Layout for auth pages.
- **`app/(auth)/login/page.tsx`:** Login form component.
- **`app/(auth)/signup/page.tsx`:** Signup form component.
- **`app/(auth)/oauth/callback/[provider]/page.tsx`:** OAuth callback handler.
- **`app/(app)/layout.tsx`:** Main application layout (sidebar, header, main content area).
- **`app/(app)/dashboard/page.tsx`:** Dashboard (Summary of projects, alerts, recent activity).
- `components/Dashboard/ProjectOverview.tsx`: Lists projects and their current security status.
- `components/Dashboard/AlertSummary.tsx`: Shows counts of critical/high vulnerabilities and malicious packages.
- `components/Dashboard/RecentScans.tsx`: Recent scan history.
- **`app/(app)/projects/page.tsx`:** Projects list page.
- `components/Projects/ProjectList.tsx`: Displays a table or list of user's projects.
- `components/Projects/AddProjectForm.tsx`: Form to add a new project (can be a modal or separate page).
- **`app/(app)/projects/[projectId]/page.tsx`:** Project detail page.
- `components/ProjectDetail/ProjectHeader.tsx`: Project name, repo URL, package manager, 'Scan Now' button.
- `components/ProjectDetail/ScanHistory.tsx`: Table of past scans for the project.
- `components/ProjectDetail/DependencyAlerts.tsx`: Detailed list of detected vulnerabilities and malicious packages for the selected project, filterable by severity.
- **`app/(app)/settings/page.tsx`:** User settings (profile, notification preferences, API keys for CI/CD).
- `components/Settings/ProfileForm.tsx`
- `components/Settings/NotificationSettings.tsx`
- `components/Settings/ApiKeys.tsx`
- **`app/api/...`:** API routes (as described above).
- **`lib/`:** Utility functions, database access layer (Drizzle schema and queries), external API clients.
- **`components/ui/`:** Re-exported shadcn/ui components.
- **`components/common/`:** Shared components like Button, Input, Card, Alert, Spinner, DataTable.
UI/UX DESIGN & VISUAL IDENTITY:
- **Design Style:** Modern, clean, and professional with a focus on clarity and data visualization. Subtle dark mode support.
- **Color Palette:**
- Primary (Dark Mode): `#1F2937` (Dark Slate Gray)
- Secondary (Dark Mode): `#374151` (Slate Gray)
- Accent/CTA (Light Mode): `#3B82F6` (Bright Blue)
- Alerts: Red (`#EF4444`) for Critical, Orange (`#F97316`) for High, Yellow (`#EAB308`) for Medium, Gray (`#9CA3AF`) for Low.
- Background (Dark Mode): `#111827` (Very Dark Blue)
- Text (Dark Mode): `#D1D5DB` (Light Gray)
- **Typography:** Inter or Manrope for a modern sans-serif feel. Clear hierarchy for headings, body text, and UI elements.
- **Layout:** Sidebar navigation for authenticated sections. Main content area uses a responsive grid system. Use cards for distinct information blocks (e.g., project summaries, scan results).
- **Responsiveness:** Mobile-first approach. Components should adapt seamlessly from small mobile screens to large desktop monitors. Use Tailwind's responsive modifiers (`sm:`, `md:`, `lg:`).
- **Interactivity:** Subtle hover effects on buttons and list items. Loading spinners for asynchronous operations. Smooth transitions for modal pop-ups and content reveal.
ANIMATIONS:
- **Page Transitions:** Use Next.js's built-in features or a library like `Framer Motion` for subtle fade-in/out transitions between pages, especially for authenticated routes.
- **Loading States:** Implement skeleton loaders or spinners within components (e.g., inside cards or table rows) while data is being fetched.
- **Hover Effects:** Gentle scaling or background color changes on interactive elements (buttons, links, project cards).
- **Micro-interactions:** Animate status indicators (e.g., scan status changing from 'running' to 'completed').
EDGE CASES:
- **Authentication:** Handle expired sessions, invalid tokens, OAuth flow errors gracefully. Implement secure token storage (HTTPOnly cookies).
- **Empty States:** Display informative messages and clear calls to action when there are no projects, no scan history, or no vulnerabilities found. E.g.,