You are an expert AI assistant tasked with building a robust, fully functional MVP of 'Network Sentinel (Linux Firewall)' using Next.js (App Router). The application should provide users with real-time visibility and control over their Linux system's network connections. Focus on creating a secure, user-friendly, and visually appealing application that can be directly used for development.
**1. PROJECT OVERVIEW:**
Network Sentinel aims to solve the problem of opaque network activity on Linux systems. Currently, applications can establish connections to external servers without the user's explicit knowledge or consent, posing security and privacy risks. Network Sentinel provides a clear, real-time view of all network connections initiated by applications, allowing users to identify, monitor, and block unwanted or suspicious traffic. The core value proposition is empowering Linux users with granular control over their system's network communications, enhancing security and privacy through transparency.
**2. TECH STACK:**
- **Framework:** Next.js (App Router)
- **Language:** TypeScript
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM (PostgreSQL as the database)
- **UI Library:** shadcn/ui (for accessible and customizable components)
- **Authentication:** NextAuth.js (for robust user authentication, e.g., email/password, GitHub)
- **Database Client:** `pg` for PostgreSQL
- **Real-time Data:** WebSockets (e.g., using `socket.io` or built-in Next.js features) for live connection updates.
- **Charting:** `chart.js` or `recharts` for traffic data visualization.
- **State Management:** React Context API and Server Components for efficient data handling.
- **Deployment:** Vercel or similar platform.
**3. DATABASE SCHEMA (PostgreSQL with Drizzle ORM):**
```typescript
// schema.ts (Drizzle ORM schema definition)
import { pgTable, uuid, varchar, timestamp, integer, boolean, text } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
// Users table for authentication
export const users = pgTable('users', {
id: uuid('id').primaryKey(),
name: varchar('name'),
email: varchar('email').unique().notNull(),
emailVerified: timestamp('emailVerified', { mode: 'date' }),
image: varchar('image'),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
// Table to store network connection rules defined by the user
export const rules = pgTable('rules', {
id: uuid('id').primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
applicationName: varchar('applicationName'), // e.g., 'firefox', 'curl'
domain: varchar('domain'), // e.g., 'google.com'
port: integer('port'), // e.g., 80, 443
protocol: varchar('protocol'), // e.g., 'TCP', 'UDP'
action: varchar('action').notNull(), // 'allow' or 'block'
description: text('description'),
createdAt: timestamp('createdAt').defaultNow(),
updatedAt: timestamp('updatedAt').defaultNow(),
});
// Table to log network connection events (can become very large, consider partitioning or separate logging service for production)
export const connectionLogs = pgTable('connection_logs', {
id: uuid('id').primaryKey(),
userId: uuid('userId').notNull().references(() => users.id, { onDelete: 'cascade' }),
applicationName: varchar('applicationName').notNull(),
domain: varchar('domain').notNull(),
port: integer('port').notNull(),
protocol: varchar('protocol'),
ipAddress: varchar('ipAddress'),
timestamp: timestamp('timestamp').defaultNow(),
dataVolumeSent: integer('dataVolumeSent'), // in bytes
dataVolumeReceived: integer('dataVolumeReceived'), // in bytes
actionTaken: varchar('actionTaken'), // 'allowed', 'blocked', 'unknown'
});
// Relations (Example)
export const usersRelations = relations(users, ({ many }) => ({
rules: many(rules),
connectionLogs: many(connectionLogs),
}));
export const rulesRelations = relations(rules, ({ one }) => ({
user: one(users, {
fields: [rules.userId],
references: [users.id],
}),
}));
export const connectionLogsRelations = relations(connectionLogs, ({ one }) => ({
user: one(users, {
fields: [connectionLogs.userId],
references: [users.id],
}),
}));
```
**4. CORE FEATURES & USER FLOW:**
* **User Authentication:**
* **Flow:** User visits the app -> Clicks "Sign In/Sign Up" -> Presented with options (e.g., Email/Password, GitHub) -> Enters credentials/uses OAuth provider -> Authenticated user is redirected to the dashboard.
* **Edge Cases:** Invalid credentials, email verification (if applicable), password reset, OAuth callback handling.
* **Real-time Connection Monitoring:**
* **Flow:** Upon successful login, the dashboard loads. A background process (potentially initiated via a system agent or IPC mechanism on Linux, sending data via WebSockets to the Next.js backend) streams active network connections. The UI updates dynamically via WebSockets.
* **Data Display:** Each connection shows Application Name, Target Domain/IP, Port, Protocol, Data Sent/Received, Timestamp. Connections are sortable and filterable.
* **Underlying Mechanism:** A Linux-native agent (e.g., written in C/Rust or using eBPF) will be responsible for capturing network packets/socket events. This agent sends data to the Next.js backend via WebSockets. The backend then broadcasts this data to connected clients (the web UI).
* **Edge Cases:** No connections active (empty state), agent not running/connected, high volume of connections overloading the WebSocket stream.
* **Connection Blocking:**
* **Flow:** User sees an active connection they want to block -> Clicks a "Block" button next to the connection entry -> A confirmation modal appears -> User confirms -> The connection is immediately blocked (backend sends a command to the Linux agent) AND a rule is automatically generated (or user is prompted to create one) to permanently block this connection pattern (App + Domain + Port). The connection list visually reflects the blocked status.
* **Edge Cases:** Block command fails, rule creation fails, user accidentally blocks a critical system process.
* **Rule Management:**
* **Flow:** User navigates to the "Rules" page -> Sees a list of all created rules (Application, Domain, Port, Action: Allow/Block, Description) -> Can add new rules via a form (specifying all parameters) or edit/delete existing rules.
* **Edge Cases:** Invalid rule input, conflicting rules, deleting essential rules.
* **Traffic History & Visualization:**
* **Flow:** User navigates to the "History" or "Dashboard" page -> Sees a chart displaying data volume (Sent/Received) over time, broken down by application or domain -> Can select time ranges to zoom in -> Data is fetched from the `connectionLogs` table via API calls.
* **Edge Cases:** No historical data, chart rendering issues, large datasets impacting performance.
**5. API & DATA FETCHING:**
* **Real-time Updates:** WebSocket endpoint (`/api/ws/connections`) for the Linux agent to push connection data and for the frontend to subscribe.
* **Authentication:** Handled by NextAuth.js (`/api/auth/...`).
* **Rule Management API:**
* `GET /api/rules`: Fetch all user rules.
* `POST /api/rules`: Create a new rule.
* `PUT /api/rules/[id]`: Update an existing rule.
* `DELETE /api/rules/[id]`: Delete a rule.
* **Connection Log API:**
* `GET /api/logs`: Fetch connection logs (with pagination, filtering, sorting parameters).
* **Data Fetching (Client-side):** Use `fetch` API or libraries like SWR/React Query within client components to interact with the backend APIs. Server Components will fetch initial data directly.
* **Data Structure (Example - WebSocket message):**
```json
{
"type": "CONNECTION_UPDATE",
"payload": {
"id": "unique_connection_id",
"appName": "firefox",
"domain": "example.com",
"port": 443,
"protocol": "TCP",
"ipAddress": "93.184.216.34",
"timestamp": "2023-10-27T10:30:00Z",
"dataSent": 1024,
"dataReceived": 2048,
"status": "active" // 'active', 'closed'
}
}
```
**6. COMPONENT BREAKDOWN (Next.js App Router Structure):**
* **(app)/layout.tsx:** Root layout (HTML, Head, Body, global providers, Tailwind CSS setup).
* **(app)/page.tsx:** Landing page (Marketing content, value proposition, CTA).
* **(auth)/layout.tsx:** Authentication layout.
* **(auth)/signin/page.tsx:** Sign-in form.
* **(auth)/signup/page.tsx:** Sign-up form.
* **(dashboard)/layout.tsx:** Main application layout (includes sidebar/navbar).
* **(dashboard)/page.tsx:** Dashboard - Overview, real-time connections list, summary charts.
* `components/Dashboard/ConnectionList.tsx`: Displays live connections, includes search/filter/sort. Fetches data via WebSocket.
* `components/Dashboard/TrafficChart.tsx`: Displays historical traffic data.
* `components/Dashboard/ConnectionListItem.tsx`: Individual row for a connection.
* **(dashboard)/rules/page.tsx:** Rule management page.
* `components/Rules/RuleList.tsx`: Displays current rules.
* `components/Rules/RuleForm.tsx`: Form to add/edit rules.
* **(dashboard)/history/page.tsx:** Detailed connection history log view.
* `components/History/LogTable.tsx`: Paginated, sortable, filterable table of connection logs.
* **(dashboard)/settings/page.tsx:** User settings page.
* **(dashboard)/components/ui/Sidebar.tsx`: Navigation sidebar.
* **(dashboard)/components/ui/Navbar.tsx`: Top navigation bar.
* **(dashboard)/components/ui/DataTable.tsx`: Generic data table component (used for rules and logs).
* **(dashboard)/components/ui/Card.tsx`, `Button.tsx`, `Input.tsx`, etc. (from shadcn/ui).
**State Management:** Utilize Server Components for static data and initial fetches. Client Components will manage dynamic UI state, real-time data (via WebSocket subscriptions), and form states. Context API can be used for global state like authentication status or theme.
**7. UI/UX DESIGN & VISUAL IDENTITY:**
* **Style:** "Minimalist Clean" with subtle "Modern Gradient" accents.
* **Color Palette:**
* Primary: `#007AFF` (Vibrant Blue)
* Secondary: `#34C759` (Vibrant Green)
* Accent/Gradient: Linear gradient from `#5E3CF4` to `#007AFF`.
* Background: `#FFFFFF` (Light Mode) / `#1A1A1A` (Dark Mode).
* Text: `#1C1C1E` (Dark Mode) / `#F2F2F7` (Light Mode).
* Muted: `#8E8E93`
* **Typography:** System fonts for clean readability (e.g., `-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif`). Use a clear hierarchy with distinct heading sizes.
* **Layout:** Main content area with a fixed sidebar for navigation. Use cards and clean tables for data presentation. Responsive design for seamless use on various screen sizes.
* **Animations:** Subtle transitions on hover effects, smooth loading spinners/skeletons, fade-in animations for new data on the connection list. Avoid overly flashy animations.
* **Responsive Rules:** Sidebar collapses into a hamburger menu on smaller screens. Data tables should adapt gracefully, potentially stacking columns or allowing horizontal scrolling.
**8. SAMPLE/MOCK DATA:**
* **Connection List Item:**
```json
{
"id": "conn-1",
"appName": "firefox",
"domain": "mozilla.org",
"port": 443,
"protocol": "TCP",
"ipAddress": "104.18.32.131",
"timestamp": "2023-10-27T11:00:00Z",
"dataSent": 1536,
"dataReceived": 3072,
"status": "active"
}
```
* **Connection List Item (Blocked Example):**
```json
{
"id": "conn-2",
"appName": "curl",
"domain": "malicious-tracker.com",
"port": 80,
"protocol": "TCP",
"ipAddress": "192.0.2.1",
"timestamp": "2023-10-27T11:05:00Z",
"dataSent": 0,
"dataReceived": 0,
"status": "blocked"
}
```
* **Rule Item:**
```json
{
"id": "rule-1",
"userId": "user-abc",
"applicationName": "discord",
"domain": "*.discordapp.com",
"port": 443,
"protocol": "TCP",
"action": "block",
"description": "Block Discord access during work hours"
}
```
* **Connection Log Item:**
```json
{
"id": "log-1",
"userId": "user-abc",
"applicationName": "systemd",
"domain": "0.0.0.0",
"port": 68,
"protocol": "UDP",
"ipAddress": "192.168.1.1",
"timestamp": "2023-10-27T09:15:00Z",
"dataVolumeSent": 512,
"dataVolumeReceived": 1024,
"actionTaken": "allowed"
}
```
* **Empty State (Connections):**
`"No active network connections detected."`
* **Empty State (Rules):**
`"You haven't created any network rules yet. Start by blocking a connection or adding a new rule."`
**9. TURKISH TRANSLATIONS:**
* **App Title:** Ağ Gözcüsü
* **Sign In:** Giriş Yap
* **Sign Up:** Kayıt Ol
* **Dashboard:** Kontrol Paneli
* **Connections:** Bağlantılar
* **Rules:** Kurallar
* **History:** Geçmiş
* **Settings:** Ayarlar
* **Block:** Engelle
* **Allow:** İzin Ver
* **Add Rule:** Kural Ekle
* **Application:** Uygulama
* **Domain:** Alan Adı
* **Port:** Port
* **Protocol:** Protokol
* **Action:** Eylem
* **Description:** Açıklama
* **Data Sent:** Gönderilen Veri
* **Data Received:** Alınan Veri
* **Timestamp:** Zaman Damgası
* **Block Connection:** Bağlantıyı Engelle
* **Are you sure?** Emin misiniz?
* **Create Rule:** Kural Oluştur
* **No active connections:** Aktif ağ bağlantısı yok.
* **No rules found:** Kural bulunamadı.
**10. ANIMATIONS:**
* **Hover Effects:** Subtle background color change or slight scaling on interactive elements (buttons, table rows).
* **Transitions:** Smooth fades for modal popups, smooth transitions between page states.
* **Loading:** Use shadcn/ui's `Card` or `Skeleton` components with subtle shimmer effects for content loading placeholders. Implement a clear loading indicator (spinner) for data fetches and WebSocket connection status.
* **Real-time Updates:** New connection entries should fade in smoothly. Data volume updates can have a subtle highlight or counter animation.
**11. EDGE CASES & VALIDATIONS:**
* **Authentication:** Handle expired tokens, unauthorized access attempts gracefully (redirect to login).
* **Data Input Validation:** Ensure domain names, ports, IP addresses, and protocols are in valid formats using frontend and backend validation.
* **Agent Communication:** Implement retry mechanisms and clear error messages if the Linux agent is unresponsive.
* **Empty States:** Provide informative messages and clear calls to action when lists (connections, rules, logs) are empty.
* **Error Handling:** Implement global error handling (e.g., using a toast notification system) for API failures or unexpected issues.
* **Permissions:** Ensure the Linux agent runs with appropriate (but not excessive) privileges to monitor network activity.
* **Performance:** For high-traffic systems, consider optimizing WebSocket message frequency, implementing data aggregation on the backend, and using efficient database queries. Backend should handle potential backpressure from the agent.
This detailed prompt provides a comprehensive guide for generating the Network Sentinel MVP application, ensuring all critical aspects from backend to frontend, including security, user experience, and specific Next.js App Router patterns, are covered.