You are an expert AI assistant tasked with generating a fully functional, multi-page Next.js MVP application for a SaaS product named 'HostGuard'. This application aims to protect users' hosts files from unauthorized modifications, specifically addressing the concern raised by Adobe Creative Cloud's behavior of secretly modifying the hosts file to detect installation. The generated application should be robust, secure, and user-friendly.
PROJECT OVERVIEW:
HostGuard is a desktop-focused SaaS application (accessible via a web interface for management and billing) that safeguards the integrity of the hosts file on user systems (Windows and macOS initially). It provides real-time monitoring for changes, sends instant alerts for unauthorized modifications, and allows users to revert to previous safe states or a known good configuration. The core value proposition is to restore user trust and control over their system's critical network configuration files, preventing potential security risks or unwanted software behaviors stemming from unauthorized hosts file manipulation. The problem solved is the user's lack of transparency and control over how applications, particularly Adobe Creative Cloud, interact with and modify their hosts file, which can have privacy and security implications.
TECH STACK:
- Framework: Next.js (App Router)
- Language: TypeScript
- Styling: Tailwind CSS
- UI Component Library: shadcn/ui (for a clean, modern look and feel)
- ORM: Drizzle ORM (PostgreSQL/SQLite compatible)
- Database: PostgreSQL (preferred for production, SQLite for local development)
- Authentication: NextAuth.js (for secure user sign-in/sign-up with email/password and OAuth providers like Google)
- State Management: React Context API / Zustand (for global state, e.g., user auth, settings)
- Form Handling: React Hook Form + Zod (for robust form validation)
- API Layer: Server Actions and Route Handlers in Next.js
- Desktop Integration (Optional, for MVP focus on web management): Potentially a small background agent or a CLI tool for direct hosts file interaction, managed via the web app. For MVP, we will focus on the web management interface and assume the user manually places a small script/agent or uses a CLI provided by HostGuard.
- Required Packages: `next`, `react`, `react-dom`, `tailwindcss`, `drizzle-orm`, `pg` (or `sqlite3`), `next-auth`, `@next-auth/prisma-adapter` (or similar for Drizzle), `shadcn-ui`, `react-hook-form`, `zod`, `axios` (for potential external API calls if needed), `clsx`, `tailwind-merge`.
DATABASE SCHEMA (Drizzle ORM - PostgreSQL syntax):
`users` table:
- `id` (uuid, primary key, default gen_random_uuid())
- `name` (text)
- `email` (text, unique, not null)
- `emailVerified` (timestamp with time zone)
- `image` (text)
- `hashedPassword` (text) - For email/password auth
- `createdAt` (timestamp with time zone, default now())
- `updatedAt` (timestamp with time zone, default now())
`accounts` table (for NextAuth.js with multiple providers):
- `id` (text, primary key)
- `userId` (uuid, foreign key to users.id, not null)
- `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)
`sessions` table (for NextAuth.js):
- `sessionToken` (text, primary key)
- `userId` (uuid, foreign key to users.id, not null)
- `expires` (timestamp with time zone, not null)
`verificationTokens` table (for NextAuth.js email verification):
- `identifier` (text, not null)
- `token` (text, not null)
- `expires` (timestamp with time zone, not null)
`systems` table (Represents a user's monitored machine):
- `id` (uuid, primary key, default gen_random_uuid())
- `userId` (uuid, foreign key to users.id, not null)
- `systemName` (text, not null) - e.g., "My Work Laptop", "Home Desktop"
- `osType` (enum: 'windows', 'macos', 'linux')
- `agentVersion` (text) - Version of the HostGuard agent installed on the system
- `lastCheckIn` (timestamp with time zone)
- `createdAt` (timestamp with time zone, default now())
- `updatedAt` (timestamp with time zone, default now())
`hostsEntries` table (Stores historical and current hosts file entries):
- `id` (uuid, primary key, default gen_random_random())
- `systemId` (uuid, foreign key to systems.id, not null)
- `ipAddress` (text, not null)
- `hostname` (text, not null)
- `isComment` (boolean, default false) - True if the line is a comment
- `originalLine` (text) - The exact line from the hosts file
- `detectedAt` (timestamp with time zone, default now()) - When this entry was first observed or last updated
- `sourceApp` (text) - e.g., "Adobe CC Detector", "Manual Entry", "System DNS"
- `isCurrent` (boolean, default true) - Indicates if this entry is currently active in the live hosts file
- `createdAt` (timestamp with time zone, default now())
`hostsFileHistory` table (Stores snapshots of the entire hosts file):
- `id` (uuid, primary key, default gen_random_uuid())
- `systemId` (uuid, foreign key to systems.id, not null)
- `snapshot` (text, not null) - The complete content of the hosts file at a point in time
- `createdAt` (timestamp with time zone, default now())
- `detectedModification` (boolean, default false) - Flag if this snapshot was taken right after a detected modification
- `modificationSource` (text) - e.g., "Adobe CC", "Unknown"
`alerts` table:
- `id` (uuid, primary key, default gen_random_uuid())
- `systemId` (uuid, foreign key to systems.id, not null)
- `alertType` (enum: 'modification_detected', 'rollback_success', 'rollback_failed', 'agent_issue')
- `details` (jsonb) - Specific details about the alert (e.g., changed IPs, timestamp of modification)
- `isRead` (boolean, default false)
- `createdAt` (timestamp with time zone, default now())
CORE FEATURES & USER FLOW:
1. **User Authentication & System Registration**
* **Flow:** User signs up via email/password or OAuth (Google). Upon successful login, they are directed to a dashboard.
* **System Registration:** From the dashboard, the user clicks "Add System". They provide a name for the system (e.g., "My MacBook Pro"). HostGuard provides a unique download link for a small, OS-specific agent/CLI tool. The user downloads and installs this agent. The agent runs once (or periodically) and registers the system with the backend using a secure token associated with the user's account. The `systems` table is populated.
* **Edge Case:** Agent fails to install or connect. User sees an error message on the dashboard and instructions to troubleshoot.
2. **Real-time Hosts File Monitoring (via Agent)**
* **Flow:** The installed HostGuard agent runs in the background (or is triggered periodically/by system events). It reads the current hosts file (`/etc/hosts` on macOS/Linux, `c:\Windows\System32\drivers\etc\hosts` on Windows). It compares the current state against the last known state stored locally or fetched from the server. If differences are detected, it sends a payload to the HostGuard backend API (`/api/systems/:systemId/report-change`). This payload includes the detected changes, potentially the source app if detectable (e.g., by observing process behavior before the change or by pattern matching known software like Adobe CC's technique), and a timestamp. The backend records this in `hostsEntries` (marking old ones as `isCurrent: false`, new ones as `isCurrent: true`) and `hostsFileHistory` (as a new snapshot, possibly flagged `detectedModification: true`). An `alert` of type `modification_detected` is created.
* **Edge Case:** Agent is not running/crashed. The `lastCheckIn` time on the `systems` table won't update, and the user sees a "System offline" status on the dashboard.
3. **Alerting and Notifications**
* **Flow:** When a `modification_detected` alert is created in the database, the system triggers an email notification to the user and displays an unread notification badge on the dashboard. Clicking the notification takes the user to the alert details page, marking it as read.
* **Edge Case:** Email delivery fails. The user should still see the in-app notification.
4. **Hosts File History and Rollback**
* **Flow:** On the dashboard, under a specific system, the user can view "History". This page lists snapshots from the `hostsFileHistory` table, ordered by date. Each entry shows the timestamp and potentially a summary of changes. The user can click "View Details" to see a diff of the hosts file content compared to the previous version or the current state. To rollback, the user selects a historical snapshot and clicks "Restore". The backend API (`/api/systems/:systemId/rollback`) receives the request. It instructs the agent to overwrite the current hosts file with the selected snapshot's content. The agent performs the overwrite and reports success or failure back to the API. A new entry in `alerts` (`rollback_success` or `rollback_failed`) is created. The `hostsEntries` table is updated to reflect the reverted state.
* **Edge Case:** User attempts to rollback to a snapshot that is identical to the current state. The system should inform the user or simply not perform the action.
* **Edge Case:** Agent lacks permissions to modify the hosts file. Rollback fails, and an `alerts` entry `rollback_failed` is created.
5. **Source Application Detection (MVP Focus on Adobe CC)**
* **Flow:** The agent attempts to identify the source of the modification. For Adobe CC, it can mimic Adobe's technique: The agent briefly listens on specific local ports (e.g., 5000, 49152-65535) or analyzes network traffic patterns around the time of modification. If it detects a request to `detect-ccd.creativecloud.adobe.com` originating from a process associated with Adobe CC, or observes the specific hosts file entries Adobe adds (e.g., `127.0.0.1 detect-ccd.creativecloud.adobe.com`), it flags the `sourceApp` in `hostsEntries` and `modificationSource` in `hostsFileHistory` as "Adobe CC".
* **Edge Case:** The detection method is not foolproof and might occasionally misidentify the source or fail to detect it. The UI should reflect this uncertainty (e.g., "Unknown Source", "Possibly Adobe CC").
API & DATA FETCHING:
- **Authentication:** Standard NextAuth.js flow using Server Actions for login/signup. API routes (`/api/auth/[...nextauth]`) handle auth callbacks.
- **System Management:**
- `POST /api/systems`: Register a new system. Requires auth token. Request body: `{ systemName: string, osType: string }`. Response: `{ systemId: string, agentDownloadUrl: string }`.
- `GET /api/systems`: Get list of user's registered systems. Requires auth.
- `GET /api/systems/:systemId`: Get details for a specific system.
- `DELETE /api/systems/:systemId`: Unregister a system.
- **Monitoring & Reporting:**
- `POST /api/systems/:systemId/report-change`: Agent reports changes. Requires secure agent token. Request body: `{ detectedEntries: Array<{ipAddress: string, hostname: string, originalLine: string}>, timestamp: string, os: string }`. Server processes this, updates DB, creates history/alerts.
- `GET /api/systems/:systemId/status`: Check system's last check-in status.
- **History & Rollback:**
- `GET /api/systems/:systemId/history`: Get historical snapshots for a system. Response: `Array<{ id: string, createdAt: string, isModification: boolean }>`.
- `GET /api/systems/:systemId/history/:snapshotId`: Get full content of a specific snapshot.
- `POST /api/systems/:systemId/rollback`: Request rollback to a snapshot. Request body: `{ snapshotId: string }`. Response: `{ success: boolean, message: string }`.
- **Alerts:**
- `GET /api/alerts`: Get user's alerts.
- `PUT /api/alerts/:alertId/read`: Mark alert as read.
Data Fetching in Components: Use Server Components for initial data load where possible (e.g., dashboard system list, history). Use Client Components with `useEffect` or SWR/React Query for dynamic data like real-time status updates or form submissions via Server Actions.
UI/UX DESIGN & VISUAL IDENTITY:
- **Style:** Minimalist Clean with subtle security/tech undertones.
- **Color Palette:** Primary: Deep Blue (`#1E3A8A`), Secondary: Dark Gray (`#1F2937`), Accent: Teal (`#14B8A6`), Alert/Warning: Orange (`#F97316`), Success: Green (`#22C55E`), Background: Very Light Gray (`#F3F4F6` for light mode) / Near Black (`#0B0F18` for dark mode).
- **Typography:** Inter or Roboto for body text, Poppins or Montserrat for headings. Clean, legible sans-serif fonts.
- **Layout:** Single-column or two-column layout for dashboards and settings pages. Consistent padding and margins. Use cards for displaying system information and alerts. Sidebar navigation for main sections (Dashboard, Systems, Billing, Settings).
- **Responsiveness:** Mobile-first approach. Ensure usability on various screen sizes. Use Tailwind's responsive modifiers (`sm:`, `md:`, `lg:`).
- **Visual Elements:** Subtle gradients in backgrounds or buttons. Icons for system status (e.g., green dot for online, red for offline/alert). Loading spinners and skeletons for data fetching.
- **Tone:** Professional, trustworthy, and reassuring.
COMPONENT BREAKDOWN (Next.js App Router Structure):
- `app/layout.tsx`: Root layout (includes global styles, providers like NextAuth, theme provider).
- `app/page.tsx`: Landing Page (for public access).
- `app/(auth)/layout.tsx`: Auth layout (for sign-in, sign-up pages).
- `app/(auth)/signin/page.tsx`: Sign-in page.
- `app/(auth)/signup/page.tsx`: Sign-up page.
- `app/(app)/layout.tsx`: Main application layout (includes sidebar, header, main content area).
- `app/(app)/dashboard/page.tsx`: Dashboard - Overview of all systems, recent alerts, system status summary. Fetches data using Server Components.
- `app/(app)/systems/page.tsx`: Systems List - Detailed list of registered systems. Allows adding new systems. Fetches data using Server Components.
- `app/(app)/systems/[systemId]/page.tsx`: System Detail Page - Shows specific system info, status, recent activity log. Includes options to view history or trigger rollback.
- `app/(app)/systems/[systemId]/history/page.tsx`: System History - Displays `hostsFileHistory` snapshots. Allows viewing diffs.
- `app/(app)/alerts/page.tsx`: Alerts Page - Lists all user alerts, allows filtering and marking as read.
- `app/(app)/settings/page.tsx`: User Settings - Profile, billing, notification preferences.
- `components/ui/`: Contains shadcn/ui components (Button, Input, Card, Table, Alert, Dialog, etc.).
- `components/auth/`: Auth-related components (e.g., OAuth buttons, sign-in form).
- `components/systems/`: Components specific to system management (e.g., `SystemCard`, `AddSystemForm`, `HistoryTable`).
- `components/alerts/`: Alert display components.
- `components/shared/`: Reusable layout components (e.g., `Sidebar`, `Header`, `Footer`, `LoadingSpinner`, `AlertBanner`).
- `lib/`: Utility functions, database connection (Drizzle), API client setup, auth configuration.
- `hooks/`: Custom React hooks (e.g., `useSystemStatus`, `useAlerts`).
- `actions/`: Server Actions for form submissions and mutations (e.g., `addSystemAction`, `rollbackAction`).
ANIMATIONS:
- **Page Transitions:** Subtle fade-in/out using `Framer Motion` or CSS transitions on route changes.
- **Hover Effects:** Slight scale-up or background color change on buttons and interactive elements.
- **Loading States:** Use `react-loading-skeleton` or custom spinners within components while data is being fetched. Shimmer effect for cards.
- **Notification Banners:** Smooth slide-in/out animation for alert banners at the top of the page.
- **Table Row Expansion:** Smooth expansion/collapse animation when viewing diffs in the history table.
EDGE CASES:
- **No Systems Registered:** Dashboard shows a prompt to add the first system.
- **Agent Not Connected:** System status shows as 'Offline' or 'Stale'. Alerts are generated if check-in fails for an extended period.
- **Permissions Errors:** Agent reports failures when trying to read/write the hosts file due to insufficient permissions. User is notified with instructions to grant permissions.
- **Invalid Hosts File Content:** If the hosts file gets corrupted (not by HostGuard), the agent should attempt to report it, and rollback should be prioritized.
- **Concurrency:** If multiple changes happen rapidly, ensure the system correctly logs them as distinct history entries and alerts.
- **Authentication Failures:** Proper error handling for sign-in/sign-up, password reset flows.
- **Data Validation:** Rigorous validation on all inputs (forms, agent reports) using Zod.
SAMPLE DATA:
1. **User:**
```json
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"name": "Alice Smith",
"email": "alice.smith@example.com",
"image": "https://example.com/alice.jpg"
}
```
2. **System:**
```json
{
"id": "f0e9d8c7-b6a5-4321-fedc-ba0987654321",
"userId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"systemName": "My Windows Laptop",
"osType": "windows",
"agentVersion": "1.0.1",
"lastCheckIn": "2023-10-27T10:30:00Z"
}
```
3. **Hosts File History Snapshot:**
```json
{
"id": "11223344-5566-7788-9900-aabbccddeeff",
"systemId": "f0e9d8c7-b6a5-4321-fedc-ba0987654321",
"snapshot": "# Copyright (c) 1993-2009 Microsoft Corp.\n# This is a sample HOSTS file used by Windows.\n# This file contains the mappings of IP addresses to host names. Each\n# entry is on an individual line. The IP address should be placed\n# in the first column followed by the corresponding host name.\n# Should be followed by an INSERT in the last column.\n# For example:\n#\n# 102.54.94.97 rhino.acme.com for hosts and nameserver lookups\n# 30.20.16.4 anonymous-ftp.ares.com for nameserver lookups\n\n127.0.0.1 localhost\n::1 localhost\n127.0.0.1 detect-ccd.creativecloud.adobe.com\n::1 detect-ccd.creativecloud.adobe.com\n",
"createdAt": "2023-10-27T10:35:00Z",
"detectedModification": true,
"modificationSource": "Adobe CC"
}
```
4. **Alert:**
```json
{
"id": "99887766-5544-3322-1100-fedcba098765",
"systemId": "f0e9d8c7-b6a5-4321-fedc-ba0987654321",
"alertType": "modification_detected",
"details": {
"message": "Hosts file modified. Detected changes may include new entries for Adobe CC.",
"modifiedAt": "2023-10-27T10:35:00Z",
"source": "Adobe CC"
},
"isRead": false,
"createdAt": "2023-10-27T10:36:00Z"
}
```
5. **Hosts Entry (Current):**
```json
{
"id": "aabbccdd-eeff-0011-2233-445566778899",
"systemId": "f0e9d8c7-b6a5-4321-fedc-ba0987654321",
"ipAddress": "127.0.0.1",
"hostname": "detect-ccd.creativecloud.adobe.com",
"isComment": false,
"originalLine": "127.0.0.1 detect-ccd.creativecloud.adobe.com",
"detectedAt": "2023-10-27T10:35:00Z",
"sourceApp": "Adobe CC",
"isCurrent": true
}
```
6. **Hosts Entry (Old, not current):**
```json
{
"id": "11223344-5566-7788-9900-aabbccddeeff",
"systemId": "f0e9d8c7-b6a5-4321-fedc-ba0987654321",
"ipAddress": "192.168.1.100",
"hostname": "my-old-server.local",
"isComment": false,
"originalLine": "192.168.1.100 my-old-server.local # Old entry",
"detectedAt": "2023-10-26T09:00:00Z",
"sourceApp": "Manual Entry",
"isCurrent": false
}
```
7. **Hosts File History Snapshot (Clean, before modification):**
```json
{
"id": "abcdef12-3456-7890-abcd-ef1234567890",
"systemId": "f0e9d8c7-b6a5-4321-fedc-ba0987654321",
"snapshot": "# Copyright (c) 1993-2009 Microsoft Corp.\n# This is a sample HOSTS file used by Windows.\n\n127.0.0.1 localhost\n::1 localhost\n",
"createdAt": "2023-10-27T09:00:00Z",
"detectedModification": false,
"modificationSource": null
}
```
This comprehensive prompt provides the structure and details necessary to build a robust MVP of HostGuard using Next.js, Tailwind CSS, Drizzle ORM, and NextAuth.js, focusing on solving the core user problem effectively.