npm package: @mockdetector/widget
Description: Professional mock data detection widget with 85%+ accuracy, AI-powered fixes, and confidence scoring - Built for React/Lovable projects. Smart whitelisting eliminates false positives.
Author: Silver
Latest version: 1.8.9

# 🕵️ MockDetector Widget

**Advanced mock data detection widget for React/Lovable projects**

Detects test data, security issues, and provides AI-powered fix suggestions for your Lovable applications.

Built by **Silver (Anton Fredriksson)** 🇸🇪 with AI assistance 🤖

---

## ✨ Features

- 🔍 **Quick Scan** - Fast DOM-based mock data detection
- 🧠 **Smart Deep Scan** - Source code analysis with file scanning
- 🗄️ **Database Scan** - Supabase database mock data detection
- 📊 **Real-time Progress** - Live scan progress with file counts
- 💳 **Beta Credits System** - Free testing with credit-based scans
- 🎯 **Floating Bubble UI** - Draggable, minimizable widget
- 📈 **Detailed Reports** - Severity levels, auto-fixes, and examples
- 🔄 **Auto Version Check** - Notifies you when new versions are available

---

## 🚀 Quick Start Guide (Recommended for Lovable Developers)

### Step 1: Apply for Beta Access
Visit [MockDetector Beta](https://b7e334d8-37c6-4e20-9ab2-0bccb19039fe.lovableproject.com/mockdetector-beta) and submit your application to get your API key.

### Step 2: Tell Lovable AI to Install
Simply paste this into Lovable AI chat:

```
Install @mockdetector/widget and add it to my app with API key: md_beta_xxxxxxxxxxxxx
```

That's it! Lovable AI will handle everything. 🎉

### Step 3: Test the Widget
- Widget appears in bottom-right corner
- Click to expand and run your first scan
- Drag the widget to move it around

---

## 📦 Manual Installation (Optional)

If you prefer to install manually instead of using Lovable AI:

### Install Package
```bash
npm install @mockdetector/widget
```

### Import at the TOP of App.tsx
```tsx
import { MockDetectorFloatingBubble } from '@mockdetector/widget';
```

### Add Component Inside Your App
```tsx
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <TooltipProvider>
        <Toaster />
        <Sonner />
        <BrowserRouter>
          <Routes>
            {/* Your routes */}
          </Routes>
        </BrowserRouter>
        
        {/* Add MockDetector here */}
        <MockDetectorFloatingBubble apiKey="md_beta_xxxxxxxxxxxxx" />
      </TooltipProvider>
    </QueryClientProvider>
  );
}
```

✅ **Correct placement:** Inside `QueryClientProvider`, `TooltipProvider`, or your main wrapper  
❌ **Wrong:** Outside all providers or at the very top level

---

### Configure Supabase (Optional - for Database Scan)
Make sure you have Supabase configured in your project:
```tsx
import { createClient } from '@supabase/supabase-js';

const supabase = createClient(
  import.meta.env.VITE_SUPABASE_URL,
  import.meta.env.VITE_SUPABASE_ANON_KEY
);
```

---

### Step 5: Test
- Widget appears in bottom-right corner
- Click to expand and run your first scan!
- Drag the widget to move it around (resets on page refresh)

---

## 🔄 Updating MockDetector

### Automatic Update Notification
The widget automatically checks for updates every **15 minutes** and shows a notification when a new version is available.

### One-Click Auto-Update (Recommended!)
When an update notification appears:
1. Click **"🚀 Uppdatera automatiskt"** (Auto-update)
2. Wait 1-2 seconds while the new version downloads from CDN
3. Button turns green with **"✅ Uppdaterad! Ladda om sidan"**
4. Reload your page to activate the new version

**What happens during auto-update:**
- New version is downloaded from jsDelivr CDN
- Widget files are cached in your browser
- Old version continues working until page reload
- No npm install needed!

### Manual Update (Alternative)
If auto-update doesn't work, you can manually update via npm:

```bash
npm update @mockdetector/widget
```

Then reload your page to activate the new version.

### Check Current Version
The widget displays its version in the Settings panel (click the gear icon).

### Update Troubleshooting
If auto-update fails:
- **Check Console**: Look for error messages with the 🔥 emoji
- **Network Issues**: Ensure you have internet connection
- **Fallback**: Use manual update command instead
- **Reload**: Try refreshing the page and updating again

---

## 🔧 Troubleshooting

### Widget Not Visible
1. **Check Access Control**: Widget only shows for moderators/developers by default
2. **Emergency Re-enable**: Press `Ctrl+Shift+M` to force show
3. **Check Console**: Look for MockDetector debug logs

### Database Scan Fails
1. **Verify Supabase Connection**: Make sure Supabase client is configured
2. **Check Credentials**: Ensure `VITE_SUPABASE_URL` and `VITE_SUPABASE_ANON_KEY` are set
3. **RLS Policies**: Database scan requires read access to tables

### Scans Use Too Many Credits
- **Quick Scan**: 1 credit (fast, DOM-based)
- **Smart Deep Scan**: 3 credits (scans source code)
- **Database Scan**: 5 credits (scans Supabase tables)
- **Multi-Route Scan**: 10 credits (scans all routes)

Submit feedback in the Settings panel to get +25 bonus credits!

### Widget Position Resets
Widget position resets to bottom-right on page refresh by design. Drag it during your session to reposition.

---

## 🎓 Advanced Usage

### Custom Hooks
```tsx
import { 
  useMockDetection, 
  useBetaCredits,
  useVersionCheck 
} from '@mockdetector/widget';

function CustomScanner() {
  const { runScan, scanResult } = useMockDetection();
  const { credits, canScan } = useBetaCredits();
  const { shouldShowNotification, getUpdateCommand } = useVersionCheck();
  
  // Build your own UI
}
```

### Disable Permanently
```tsx
import { useMockDetectorControl } from '@mockdetector/widget';

const { disablePermanently } = useMockDetectorControl();

// Disable widget completely
disablePermanently();
```

### Type Definitions
All types are exported for TypeScript users:
```tsx
import type { 
  MockViolation, 
  ScanResult,
  DatabaseScanResult 
} from '@mockdetector/widget';
```

---

## 🐙 Developer Workflow (with GitHub)

### For Widget Developers (Silver's workflow):
1. Make changes in Lovable
2. Push to GitHub (automatic)
3. Clone locally and build:
   ```bash
   git clone https://github.com/YOUR-REPO/mockdetector-widget.git
   cd @mockdetector/widget
   npm install
   npm run build
   npm version patch  # 1.0.0 → 1.0.1
   npm publish
   ```
4. Test platform updates:
   ```bash
   npm update @mockdetector/widget
   ```

### For Widget Users:
1. Install from NPM: `npm install @mockdetector/widget`
2. Update when notified: `npm update @mockdetector/widget`
3. Report bugs on GitHub Issues

---

## 🔒 Privacy & Data Transparency

**We believe in complete transparency about what data MockDetector collects.**

### Production Mode (with API Key)

When you use MockDetector with an API key, the widget sends the following data every 5 minutes via heartbeat:

✅ **What IS sent:**
- `apiKey` - Your API key for validation
- `domain` - Your application's hostname (e.g., `myapp.lovableproject.com`)
- `widgetVersion` - The version of MockDetector you're using (e.g., `1.2.0`)

❌ **What is NOT sent:**
- ❌ Your source code or file contents
- ❌ User data or personal information
- ❌ Scan results or violations found
- ❌ Page content or DOM structure
- ❌ Full URLs or navigation paths
- ❌ Cookies, localStorage, or session data
- ❌ API keys from your application
- ❌ Database credentials or queries

**Purpose:** The heartbeat allows us to:
- Track active widget installations
- Provide usage analytics in your dashboard
- Monitor which widget versions are in use
- Ensure API key validity

### Local Development Mode (without API Key)

When you use MockDetector without an API key:

✅ **What happens:**
- All scans run entirely in your browser
- All results are stored in `localStorage` only
- No data is sent to any server
- You get 50 free daily scans

❌ **No external communication:**
- Zero network requests to MockDetector servers
- No tracking or analytics
- Complete privacy for local development

### GDPR & Compliance

- ✅ **GDPR compliant** - We only collect operational data necessary for service delivery
- ✅ **No personal data** - We don't collect names, emails, or user behavior from your app
- ✅ **Data minimization** - We only collect what's absolutely necessary
- ✅ **Transparent** - This section documents everything we collect

### Opt-out (if needed)

If you want to disable the heartbeat but keep using the API key features:

```tsx
<MockDetectorFloatingBubble 
  apiKey="md_beta_xxxxx" 
  enableHeartbeat={false} 
/>
```

**Note:** Disabling heartbeat may affect analytics and support capabilities.

---

## 🔧 Advanced Configuration

### Admin-Only Visibility

By default, MockDetector is visible to all users. For production apps, you should hide it from regular visitors:

```tsx
<MockDetectorFloatingBubble 
  apiKey="md_beta_xxxxx"
  adminMode={userRole === 'admin' || userRole === 'moderator'}
/>
```

**Example with role check:**
```tsx
function App() {
  const { user, userRole } = useAuth(); // Your auth hook
  
  return (
    <div>
      {/* Your app content */}
      
      {/* Widget only visible to admins */}
      <MockDetectorFloatingBubble 
        apiKey="md_beta_xxxxx"
        adminMode={userRole === 'admin'}
      />
    </div>
  );
}
```

**Benefits:**
- ✅ **Security** - Visitors can't see debug information
- ✅ **UX** - Cleaner interface for end users
- ✅ **Professional** - Production apps look polished
- ✅ **Flexible** - You control who sees the widget

**Note:** When `adminMode={false}`, the widget is completely hidden (not just minimized).

### Custom Backend Endpoints

If you're self-hosting MockDetector's backend or using a staging environment, you can configure custom endpoints:

```tsx
<MockDetectorFloatingBubble 
  apiKey="md_beta_xxxxx"
  validationEndpoint="https://your-project.supabase.co/functions/v1/validate-mockdetector-key"
  heartbeatEndpoint="https://your-project.supabase.co/functions/v1/widget-heartbeat"
/>
```

**Default Production Endpoints:**
- Validation: `https://tzowmzqfbicbyvikhdwy.supabase.co/functions/v1/validate-mockdetector-key`
- Heartbeat: `https://tzowmzqfbicbyvikhdwy.supabase.co/functions/v1/widget-heartbeat`

**Note:** Most users don't need to configure this - the defaults work out of the box! ✨

### Disable Heartbeat

If you want to use API key features without sending heartbeat data:

```tsx
<MockDetectorFloatingBubble 
  apiKey="md_beta_xxxxx" 
  enableHeartbeat={false} 
/>
```

**Note:** Disabling heartbeat may affect usage analytics and support capabilities.

---

## 💡 What Can MockDetector Find?

### 🔥 Critical Security
- Test credit cards (Visa, MasterCard, Amex, Discover + CVV/expiry)
- Hardcoded API keys (AWS, Google, Firebase, OpenAI, GitHub)
- Supabase service_role keys and JWT tokens
- Test credentials (admin/admin, test/test patterns)

### 🔧 Development Artifacts
- Tunneling services (ngrok, localtunnel)
- Staging/dev/test domain names
- Private IP addresses (192.168.x.x, 10.x.x.x)
- Port numbers in URLs (:3000, :8080, :5173)

### 🐛 Debug Code
- Console.log/debug statements
- Debugger statements
- Debug mode flags (DEBUG: true)

### 🖼️ Mock Images
- Avatar generators (avataaars.io, pravatar.cc)
- Placeholder images (placehold.it, via.placeholder)
- Random images (picsum.photos, unsplash.com/random)

### ⚛️ React Patterns
- useState with hardcoded arrays/objects
- Array.map() with inline hardcoded data
- Test emails (test@test.com, user@example.com)
- Lorem Ipsum placeholder text

...and 50+ more patterns!

---

## 🤝 Contributing

See [CONTRIBUTING.md](./CONTRIBUTING.md) for development guidelines.

---

## 📝 License & Copyright

**MockDetector Widget** is proprietary software.

### Copyright Notice
© 2025 Anton Fredriksson (Silver). All rights reserved.

### License
This software is licensed under the MIT License for usage, but the MockDetector name, branding, and concept are protected intellectual property of Anton Fredriksson.

### Intellectual Property
- **Name & Branding**: "MockDetector" is a trademark of Anton Fredriksson
- **Concept & Design**: The mock data detection concept and implementation are original works
- **Usage Rights**: You may use this software under the MIT license terms
- **Attribution**: When using MockDetector, please maintain attribution to the original author

### Author
Built by **Silver (Anton Fredriksson)** 🇸🇪 with AI assistance 🤖

**Contact**: fredrikssonanton01@gmail.com  
**GitHub**: https://github.com/silver/mockdetector-widget  
**NPM**: https://www.npmjs.com/package/@mockdetector/widget

---

*MockDetector™ - Advanced mock data detection for modern web applications*