# Anti-Detection Techniques for Chrome Extensions

## Problem
Automated behavior patterns can trigger anti-bot systems, especially when:
- Requests occur at fixed intervals
- Page navigation happens too rapidly
- Content extraction appears robotic
- User interactions lack natural timing

## Solutions

### 1. Random Delays
Replace fixed delays with randomized timing to simulate human behavior.

**Basic Implementation:**
```javascript
function randomSleep(minMs, maxMs) {
  const randomMs = Math.floor(Math.random() * (maxMs - minMs + 1)) + minMs;
  console.log(`[BG] Random delay: ${randomMs}ms (${minMs}-${maxMs}ms range)`);
  return new Promise(resolve => setTimeout(resolve, randomMs));
}
```

**Usage:**
```javascript
// Instead of: await sleep(1500);
// Use:
await randomSleep(2000, 4000); // 2-4 seconds random delay
```

### 2. Configurable Delay Modes
Allow users to adjust delay behavior based on their risk tolerance.

**Delay Configuration:**
```javascript
function getDelayTime(delayConfig) {
  if (!delayConfig) {
    return { minMs: 2000, maxMs: 4000 }; // Default: 2-4 seconds
  }
  const { minDelay, maxDelay } = delayConfig;
  return {
    minMs: minDelay * 1000,
    maxMs: maxDelay * 1000
  };
}
```

**UI Implementation:**
```html
<select id="delay-mode">
  <option value="conservative">Conservative (3-6s)</option>
  <option value="normal" selected>Normal (2-4s)</option>
  <option value="aggressive">Aggressive (1-3s)</option>
  <option value="custom">Custom</option>
</select>
```

**Delay Modes:**
- **Conservative**: 3-6 seconds - Maximum safety, slowest
- **Normal**: 2-4 seconds - Balanced (recommended)
- **Aggressive**: 1-3 seconds - Fastest, higher risk
- **Custom**: User-defined 1-30 seconds - Flexible

### 3. Multi-Layer Delay Strategy
Implement delays at different points to create natural human-like timing.

**Primary Delay (After Navigation):**
```javascript
await chrome.tabs.update(tabId, { url: newUrl });
await waitForPageReady(tabId);
const delayTimes = getDelayTime(delayConfig);
await randomSleep(delayTimes.minMs, delayTimes.maxMs);
```

**Secondary Delay (After Extraction):**
```javascript
const data = await extractContent();

// Add smaller delay before next action
if (i < items.length - 1) { // Don't delay after last item
  const smallDelay = getDelayTime(delayConfig);
  await randomSleep(
    Math.floor(smallDelay.minMs / 2),
    Math.floor(smallDelay.maxDelay / 2)
  );
}
```

**Benefits:**
- Simulates "thinking time" between viewing content
- Reduces robot-like behavior
- Adapts to different operation lengths

### 4. Progressive Speed Adjustment
Start conservative, increase speed gradually based on success.

```javascript
let consecutiveSuccesses = 0;
let currentDelay = { minDelay: 3, maxDelay: 6 }; // Start conservative

function adjustDelay(success) {
  if (success) {
    consecutiveSuccesses++;
    // Gradually speed up after 5 successes
    if (consecutiveSuccesses > 5 && currentDelay.minDelay > 2) {
      currentDelay.minDelay -= 0.5;
      currentDelay.maxDelay -= 0.5;
    }
  } else {
    consecutiveSuccesses = 0;
    // Slow down on failure
    currentDelay = { minDelay: 3, maxDelay: 6 };
  }
  return currentDelay;
}
```

## Implementation Example

### Background Script Pattern
```javascript
async function processItems(items, delayConfig) {
  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    
    // Primary delay after navigation
    await navigateToItem(item);
    const delayTimes = getDelayTime(delayConfig);
    await randomSleep(delayTimes.minMs, delayTimes.maxMs);
    
    // Extract content
    const content = await extractContent(item);
    
    // Secondary delay between items
    if (i < items.length - 1) {
      await randomSleep(
        Math.floor(delayTimes.minMs / 2),
        Math.floor(delayTimes.maxMs / 2)
      );
    }
  }
}
```

### Popup Configuration
```javascript
function getDelayConfig() {
  const mode = document.getElementById('delay-mode').value;
  let minDelay = 2;
  let maxDelay = 4;

  switch(mode) {
    case 'conservative':
      minDelay = 3; maxDelay = 6;
      break;
    case 'normal':
      minDelay = 2; maxDelay = 4;
      break;
    case 'aggressive':
      minDelay = 1; maxDelay = 3;
      break;
    case 'custom':
      const customDelay = parseInt(document.getElementById('custom-delay').value) || 2;
      minDelay = Math.max(1, customDelay - 1);
      maxDelay = Math.min(30, customDelay + 1);
      break;
  }
  return { minDelay, maxDelay, mode };
}
```

## Testing Strategy

### 1. Start Conservative
- Use Conservative mode for initial testing
- Export small batches (5-10 items)
- Monitor for detection/blocking

### 2. Scale Gradually
- If no issues, try Normal mode
- Increase batch sizes incrementally
- Monitor success/failure rates

### 3. Error Handling
- Implement retry logic with increasing delays
- Add exponential backoff for failures
- Notify users of detection events

## Advanced Techniques

### 1. User Interaction Simulation
```javascript
// Simulate mouse movements
function simulateMouseMove(element) {
  const rect = element.getBoundingClientRect();
  const x = rect.left + Math.random() * rect.width;
  const y = rect.top + Math.random() * rect.height;
  element.dispatchEvent(new MouseEvent('mousemove', { clientX: x, clientY: y }));
}
```

### 2. Scroll Behavior
```javascript
// Natural scrolling with random pauses
async function naturalScroll() {
  const scrollSteps = 10;
  for (let i = 0; i < scrollSteps; i++) {
    window.scrollBy(0, window.innerHeight / scrollSteps);
    await randomSleep(200, 500);
  }
}
```

### 3. Timing Jitter
```javascript
// Add small random variations to all timing
function withJitter(delay) {
  const jitter = delay * 0.1; // 10% jitter
  return delay + (Math.random() - 0.5) * jitter;
}
```

## Platform-Specific Considerations

### ChatGPT
- Strict rate limiting
- Consider using longer delays (3-6s)
- Implement backoff on errors

### Claude
- More lenient than ChatGPT
- Normal delays (2-4s) usually work
- Monitor for CAPTCHA prompts

### Grok
- Similar to ChatGPT in strictness
- Conservative approach recommended
- Watch for blocking messages

### Gemini
- More relaxed detection
- Normal to aggressive delays often work
- Still monitor for rate limiting

## Best Practices

1. **Always Default to Safety**: Start with Conservative mode
2. **Provide User Control**: Let users adjust based on experience
3. **Monitor and Adapt**: Track success rates and adjust automatically
4. **Clear Feedback**: Show users what's happening and why
5. **Graceful Degradation**: Slow down instead of failing completely

## Common Mistakes

### Fixed Delays
```javascript
// ❌ BAD: Fixed delay triggers detection
await sleep(1500);

// ✅ GOOD: Random delay mimics human behavior
await randomSleep(2000, 4000);
```

### Insufficient Randomization
```javascript
// ❌ BAD: Too predictable
await sleep(Math.random() * 1000 + 2000);

// ✅ GOOD: Wider range, more unpredictable
await randomSleep(2000, 4000);
```

### Missing Context Delays
```javascript
// ❌ BAD: No delay after heavy operations
await extractLargeContent();
processContent();

// ✅ GOOD: Delay after operations
await extractLargeContent();
await randomSleep(1000, 2000);
processContent();
```

## References
- Chrome Extension Documentation: https://developer.chrome.com/docs/extensions/
- Anti-Bot Evasion: Pattern recognition and timing analysis
- Human Behavior Studies: Natural interaction timing patterns
