PROJECT OVERVIEW: Develop a comprehensive SaaS application called 'Secure Inbox Shield' that automatically detects, mitigates, and cleans up subscription bombing attacks. This application acts as a digital defense system against malicious actors who flood victims' inboxes with excessive sign-up confirmations and notifications, burying crucial emails like password resets and financial alerts. The core value proposition is to provide users with peace of mind, ensuring they don't miss important communications and protecting them from potential identity theft and financial fraud facilitated by subscription bombing. The MVP should be a multi-page web application built with Next.js, offering robust security features and a user-friendly interface.
TECH STACK:
- Frontend: React with Next.js (App Router)
- Styling: Tailwind CSS
- ORM: Drizzle ORM
- Database: PostgreSQL (recommended for Drizzle)
- Authentication: NextAuth.js (or Clerk for a quicker setup)
- UI Components: shadcn/ui
- Email Handling: Nodemailer for sending transactional emails (e.g., password reset, welcome)
- Background Jobs: Resend or similar for reliable email delivery, and a task queue like `node-cron` or a dedicated service for background processing (e.g., email scanning, rule application).
- State Management: React Context API or Zustand for global state.
- Form Handling: React Hook Form with Zod for validation.
- Icons: Lucide React
DATABASE SCHEMA:
Primary Tables:
1. `users`:
- `id` (UUID, PK)
- `name` (VARCHAR)
- `email` (VARCHAR, UNIQUE)
- `emailVerified` (TIMESTAMP)
- `image` (VARCHAR)
- `createdAt` (TIMESTAMP)
- `updatedAt` (TIMESTAMP)
2. `accounts` (for NextAuth.js or similar)
- `id` (BIGSERIAL, PK)
- `userId` (UUID, FK to users)
- `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. `email_providers`:
- `id` (UUID, PK)
- `userId` (UUID, FK to users)
- `email` (VARCHAR)
- `provider_type` (VARCHAR) - e.g., 'gmail', 'outlook', 'custom_imap'
- `imap_host` (VARCHAR)
- `imap_port` (INTEGER)
- `smtp_host` (VARCHAR)
- `smtp_port` (INTEGER)
- `credentials_encrypted` (TEXT) - Encrypted IMAP/SMTP credentials
- `is_verified` (BOOLEAN, default: false)
- `createdAt` (TIMESTAMP)
- `updatedAt` (TIMESTAMP)
4. `attack_detections`:
- `id` (UUID, PK)
- `email_provider_id` (UUID, FK to email_providers)
- `detection_time` (TIMESTAMP)
- `suspicious_signup_count` (INTEGER)
- `analysis_result` (TEXT) - e.g., 'High Probability', 'Possible', 'False Positive'
- `status` (VARCHAR) - e.g., 'Pending', 'Mitigated', 'False Positive'
- `createdAt` (TIMESTAMP)
5. `mitigation_actions`:
- `id` (UUID, PK)
- `attack_detection_id` (UUID, FK to attack_detections)
- `action_type` (VARCHAR) - e.g., 'auto_unsubscribe', 'flag_sender', 'create_filter', 'report_spam'
- `action_details` (TEXT)
- `action_time` (TIMESTAMP)
- `success` (BOOLEAN)
- `createdAt` (TIMESTAMP)
CORE FEATURES & USER FLOW:
1. **User Authentication**:
* **Flow**: User lands on the homepage. Clicks 'Sign Up' or 'Login'. Presented with options: Sign up/Login with Google, or Email/Password.
* **Email/Password**: User enters email and password. If sign-up, a verification email is sent (using Nodemailer). User clicks verification link (handled by a dedicated Next.js API route) to activate account. If login, credentials are validated against the `users` table.
* **Google Auth**: User clicks 'Sign in with Google'. Redirected to Google's OAuth consent screen. Upon approval, redirected back to the app with user data (name, email, image). `accounts` table is updated/created.
* **Edge Cases**: Invalid credentials, email already exists, verification email expired/not received (resend option), OAuth errors.
2. **Email Provider Integration**:
* **Flow**: After authentication, user navigates to 'Settings' -> 'Email Accounts'. Clicks 'Add Email Account'. User selects provider type (Gmail, Outlook, Other IMAP/SMTP).
* **Gmail/Outlook**: OAuth flow for accessing email (requires specific scopes like `readonly` for IMAP or `send` for SMTP if supported). Securely store access/refresh tokens.
* **Other IMAP/SMTP**: User manually enters IMAP host, port, SMTP host, port, and credentials. Credentials MUST be encrypted before storing in `email_providers.credentials_encrypted` using a robust encryption library (e.g., `crypto` with AES-256).
* **Verification**: An initial connection test (IMAP and SMTP if provided) is performed to ensure credentials and server details are correct and the account is accessible. `is_verified` flag is set to true upon successful connection.
* **Edge Cases**: Incorrect credentials, incorrect server details, network errors, authentication failures (e.g., 2FA issues requiring app-specific passwords), unsupported providers.
3. **Subscription Bombing Detection**:
* **Flow**: A background job runs periodically (e.g., hourly or daily, configurable) for each verified `email_provider`.
* **Process**: The job connects to the user's email using IMAP. It scans incoming emails, looking for patterns indicative of subscription bombing:
* High volume of 'welcome', 'verify your email', 'confirm subscription' emails within a short timeframe.
* Unusual sender domains (often temporary or automatically generated).
* Randomly generated or nonsensical email addresses in the 'To' or 'From' fields for these types of emails.
* Emails from newly created or obscure services.
* **Analysis**: Based on predefined rules and potentially a simple ML model (future enhancement), the system assigns a risk score and determines if an attack is likely. A record is created in the `attack_detections` table.
* **User Notification**: If a high probability of attack is detected, the user receives an in-app notification and optionally an email alert (to a *different*, trusted email address if configured).
* **Edge Cases**: High volume of legitimate emails (e.g., during a marketing campaign), emails with similar subjects but benign intent, server timeouts during IMAP scan.
4. **Automated Mitigation & Cleanup**:
* **Flow**: Triggered automatically after a high-confidence detection in `attack_detections` or manually by the user via the dashboard.
* **Actions**: The system attempts to:
* **Auto-Unsubscribe**: Find 'unsubscribe' links within detected emails and programmatically click them (requires careful HTML parsing and potentially headless browser interaction or using a service like `unroll.me` API if available).
* **Create Filters**: Automatically create email filters/rules within the user's email client (via Gmail API, Outlook API, or IMAP commands if supported) to move detected spam sign-up emails to a specific folder or trash.
* **Flag Senders**: Mark suspicious senders as spam.
* **Report Spam**: Use email client APIs or protocols to report suspicious emails as spam.
* **Logging**: Each action taken is logged in the `mitigation_actions` table with its success status.
* **User Confirmation**: For potentially destructive actions (like mass deletion or unsubscribing from everything), an optional user confirmation step might be implemented via the dashboard.
* **Edge Cases**: Unsubscribe links not working or being malicious, email provider API rate limits, inability to create filters, emails not having standard unsubscribe options.
5. **Security Dashboard**:
* **Flow**: Accessible to all logged-in users.
* **Components**: Displays:
* **Overview**: Summary of recent detections and mitigations.
* **Detections**: List of detected potential attacks (`attack_detections` table) with details (time, count, status).
* **Mitigation Log**: History of actions taken (`mitigation_actions` table) with success/failure status.
* **Connected Accounts**: Manage connected email providers.
* **Security Settings**: Configure alert preferences, detection sensitivity, and potentially API keys for advanced integrations.
* **Recommendations**: Tips for further securing their inbox.
* **Interactivity**: Users can manually trigger mitigation actions, mark detections as false positives, or mark emails/senders as spam from the dashboard.
* **Edge Cases**: Empty states (no detections yet), long lists requiring pagination and filtering/sorting, permission issues.
API & DATA FETCHING:
- **API Routes (Next.js App Router)**:
- `/api/auth/*`: Handled by NextAuth.js (or Clerk).
- `/api/email-providers`: CRUD operations for managing connected email accounts (POST to add, GET to list, DELETE to remove).
- `/api/email-providers/[id]/verify`: POST request to test connection and verify credentials.
- `/api/detections`: GET request to fetch detection history (with pagination, filtering).
- `/api/mitigations`: GET request to fetch mitigation log (with pagination, filtering).
- `/api/settings`: GET/PUT for user settings.
- `/api/dashboard/summary`: GET for dashboard overview data.
- **Data Fetching**: Server Components will fetch data directly from the database using Drizzle ORM where possible for SEO and initial load performance. Client Components will use API routes via `fetch` or a library like SWR/React Query for dynamic data, mutations, and real-time updates. Use `fetch` with appropriate caching strategies.
- **Request/Response Bodies**: Standard JSON. Example for adding email provider:
- POST `/api/email-providers`:
- Request Body: `{ email: string, provider_type: string, imap_host?: string, imap_port?: number, smtp_host?: string, smtp_port?: number, username?: string, password?: string }` (Note: credentials should ideally be handled securely, perhaps via OAuth or a separate secure input flow)
- Response Body (Success): `201 Created`, `{ id: string, ... }`
- Response Body (Error): `400 Bad Request`, `401 Unauthorized`, `500 Internal Server Error` with error messages.
UI/UX DESIGN & VISUAL IDENTITY:
- **Style**: Minimalist Clean with a touch of secure, professional aesthetic.
- **Color Palette**:
- Primary: `#4A90E2` (Trustworthy Blue)
- Secondary: `#50E3C2` (Active Green/Teal)
- Accent: `#F5A623` (Warning/Attention Orange)
- Neutral Dark: `#2D3748` (Dark Gray for text/backgrounds)
- Neutral Light: `#F7FAFC` (Off-white for backgrounds)
- Alert/Error: `#E53E3E` (Red)
- **Typography**: Sans-serif font like Inter or Poppins for readability. Use varying weights for hierarchy.
- **Layout**: Clean, card-based layout for dashboard widgets. Clear navigation sidebar (collapsible). Responsive design using Tailwind's breakpoints (sm, md, lg, xl).
- **Sections**:
- Public: Homepage (explaining the problem and solution), Features, Pricing.
- Authenticated: Dashboard, Settings, Email Accounts Management.
- **Animations**: Subtle fade-ins for new content, smooth transitions on sidebar collapse/expand, loading spinners (e.g., using `react-loader-spinner` or shadcn/ui's skeleton loader) for data fetching. Button hover effects.
COMPONENT BREAKDOWN (Next.js App Router Structure):
- **`app/` directory**:
- `(public)/` folder for public pages:
- `page.tsx`: Homepage (Marketing content, value proposition).
- `features/page.tsx`: Detailed features page.
- `pricing/page.tsx`: Pricing tiers.
- `layout.tsx`: Public layout (navbar, footer).
- `(authenticated)/` folder for protected pages:
- `dashboard/page.tsx`: Main dashboard view (summary, recent activity).
- `settings/page.tsx`: User profile and account settings.
- `email-accounts/page.tsx`: Manage connected email providers.
- `layout.tsx`: Authenticated layout (sidebar navigation, header).
- `api/` folder for API routes:
- `auth/[...nextauth]/route.ts`: NextAuth.js configuration.
- `email-providers/route.ts`: CRUD for email providers.
- `email-providers/[id]/verify/route.ts`: Verify email provider connection.
- `detections/route.ts`: Get detection logs.
- `mitigations/route.ts`: Get mitigation logs.
- `settings/route.ts`: User settings API.
- `layout.tsx`: Root layout (html, body, providers).
- `page.tsx`: (Optional) Root catch-all or redirect.
- **`components/` directory**:
- `ui/`: Re-exported shadcn/ui components (Button, Card, Input, Sidebar, etc.).
- `auth/`: Auth-related components (LoginForm, SignupForm, GoogleSignInButton).
- `dashboard/`: Components specific to the dashboard (OverviewCard, DetectionList, MitigationLogTable).
- `email/`: Email account management components (EmailProviderForm, EmailAccountListItem).
- `common/`: Shared components (Navbar, Footer, Spinner, ErrorMessage, EmptyState).
- `charts/`: Charting components (e.g., using Recharts or Chart.js).
- **State Management**: Use Server Components for initial data loads. For dynamic updates in Client Components, utilize `useState`, `useReducer`, or a global state manager like Zustand. Pass necessary data via props from Server to Client Components.
ANIMATIONS:
- **Page Transitions**: Use `Framer Motion` for smooth `AnimatePresence` transitions between pages or sections.
- **Element Entry**: Apply `fadeIn` and `slideIn` effects on elements as they enter the viewport using Intersection Observer API or Framer Motion.
- **Button Hovers**: Subtle scale or background color change on button hover states.
- **Loading States**: Use shadcn/ui's Skeleton component or custom spinners during data fetching. Indicate background job progress where applicable.
- **Sidebar Toggle**: Smooth slide animation for the sidebar.
EDGE CASES:
- **Authentication**: Handle expired tokens, refresh token failures, multiple device logins.
- **Email Integration**: Robust error handling for IMAP/SMTP connection issues, authentication failures (especially 2FA), API rate limits. Implement retry mechanisms with exponential backoff.
- **Detection Logic**: Avoid false positives by implementing confidence thresholds. Allow users to mark detections as 'False Positive'. Consider seasonal legitimate email spikes.
- **Mitigation Actions**: Handle cases where unsubscribe links fail, filters cannot be created, or APIs are unresponsive. Provide manual fallback options for users.
- **Empty States**: Design clear and informative empty states for the dashboard, detection logs, and mitigation history when no data is available. Include calls to action (e.g., 'Connect your first email account').
- **Validation**: Implement client-side and server-side validation for all user inputs (forms, settings) using libraries like Zod and React Hook Form.
- **Security**: Encrypt sensitive credentials (IMAP/SMTP passwords) at rest. Use secure protocols (HTTPS, secure database connections). Sanitize all user inputs to prevent XSS attacks.
SAMPLE DATA:
1. **User**: `{ id: 'uuid-user-1', name: 'Alice Wonderland', email: 'alice@example.com', image: 'url/to/alice.jpg' }`
2. **Email Provider (OAuth)**: `{ id: 'uuid-ep-1', userId: 'uuid-user-1', email: 'alice.primary@gmail.com', provider_type: 'gmail', is_verified: true }`
3. **Email Provider (IMAP/SMTP)**: `{ id: 'uuid-ep-2', userId: 'uuid-user-1', email: 'alice.secondary@domain.com', provider_type: 'custom_imap', imap_host: 'mail.domain.com', imap_port: 993, smtp_host: 'smtp.domain.com', smtp_port: 587, is_verified: true }` (credentials stored encrypted)
4. **Attack Detection (High Risk)**: `{ id: 'uuid-ad-1', email_provider_id: 'uuid-ep-1', detection_time: '2023-10-27T10:00:00Z', suspicious_signup_count: 150, analysis_result: 'High Probability of Subscription Bombing', status: 'Pending' }`
5. **Attack Detection (Low Risk)**: `{ id: 'uuid-ad-2', email_provider_id: 'uuid-ep-1', detection_time: '2023-10-26T15:30:00Z', suspicious_signup_count: 25, analysis_result: 'Possible anomaly, low confidence', status: 'False Positive' }`
6. **Mitigation Action**: `{ id: 'uuid-ma-1', attack_detection_id: 'uuid-ad-1', action_type: 'auto_unsubscribe', action_details: 'Clicked unsubscribe link for sender: bot@example.net', action_time: '2023-10-27T10:15:00Z', success: true }`
7. **Mitigation Action (Filter)**: `{ id: 'uuid-ma-2', attack_detection_id: 'uuid-ad-1', action_type: 'create_filter', action_details: 'Created filter to move emails from *@spammer.xyz to Trash', action_time: '2023-10-27T10:16:00Z', success: true }`
8. **User Settings**: `{ notification_preference: 'in_app_and_email', sensitivity: 'high' }`
9. **Dashboard Summary**: `{ recent_detections: 2, total_mitigations: 5, avg_signups_per_attack: 120 }`
10. **Email Example (for scanning)**: Subject: "Welcome to FakeService!", From: "noreply@random-domain-gen.com", Body: "...<a href='http://random-domain-gen.com/unsubscribe?id=xyz'>Unsubscribe</a>..."