# CORS Fix for Anthropic API

## Problem

When trying to call the Anthropic API from the Chrome extension, we encountered a CORS error:

```
Access to fetch at 'https://api.anthropic.com/v1/messages' has been blocked by CORS policy
```

## Root Cause

The Anthropic API doesn't include `Access-Control-Allow-Origin` headers for browser extension origins. When using `fetch()`, the browser enforces CORS restrictions even in service workers.

## Solution

We fixed this by:

1. **Adding host permissions** to `manifest.json`:
   ```json
   "host_permissions": [
     "https://api.anthropic.com/*"
   ]
   ```

2. **Switching from `fetch()` to `XMLHttpRequest`** in `ai-service.js`:
   - XMLHttpRequest has special privileges in Chrome extensions
   - When combined with host_permissions, it bypasses CORS restrictions
   - This is a documented Chrome extension capability

## Changes Made

### File: `manifest.json`
- Added `"https://api.anthropic.com/*"` to `host_permissions` array

### File: `src/background/ai-service.js`
- Added `makeAnthropicRequest()` method that uses XMLHttpRequest
- Updated `generateFields()` to use the new method instead of fetch
- Properly handles errors and parses JSON responses

## How It Works

```javascript
// Old approach (doesn't work - CORS blocked)
const response = await fetch('https://api.anthropic.com/v1/messages', {
  method: 'POST',
  headers: { /* ... */ }
});

// New approach (works - XMLHttpRequest with host_permissions)
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.anthropic.com/v1/messages');
xhr.setRequestHeader('x-api-key', apiKey);
xhr.send(JSON.stringify(body));
```

## Testing

After reloading the extension:
1. Open the sidebar
2. Go to "Customs Editor" tab
3. Fill in org/project IDs and load sections
4. Enter requirements
5. Click "Generate Fields with AI"
6. Should now successfully call Claude API and create fields

## References

- [Chrome Extension Host Permissions](https://developer.chrome.com/docs/extensions/mv3/match_patterns/)
- [XMLHttpRequest in Service Workers](https://developer.chrome.com/docs/extensions/mv3/service_workers/service-worker-lifecycle/)
- [Anthropic API Documentation](https://docs.anthropic.com/claude/reference/messages_post)
