# Echomark CORS Issue - Troubleshooting & Fix

**Issue**: `Failed to fetch` error when watermarking documents
**Cause**: CORS (Cross-Origin Resource Sharing) configuration needed on Echomark server

---

## The Problem

When the extension tries to watermark a document, it fails with:

```
TypeError: Failed to fetch
    at EchomarkClient._markDocument (echomark-client.js:64)
```

This happens because:
1. Chrome extensions run in a different origin (`chrome-extension://...`)
2. The Echomark server needs to allow requests from this origin
3. CORS headers must be properly configured

---

## Quick Test

The Echomark server **does** return CORS headers, which is good:

```bash
$ curl -I -X POST https://ec2-52-8-108-29.us-west-1.compute.amazonaws.com:5345/echomark/api/v2/document/mark/pdf \
  -H "Authorization: Bearer 79f8eaa8-735d-480c-a594-891a9afe9b89" \
  -H "Origin: chrome-extension://test"

< Access-Control-Allow-Origin: chrome-extension://test
< Access-Control-Expose-Headers: Content-Type
< Access-Control-Allow-Credentials: true
```

✅ **Server supports CORS** - it echoes back the origin

---

## Solution Options

### Option 1: Wildcard CORS for Chrome Extensions (Recommended)

Configure the Echomark server to allow all Chrome extension origins:

**In Echomark Server Configuration**:

```python
# Flask/Waitress configuration
CORS(app, origins=[
    "chrome-extension://*",  # Allow all Chrome extensions
    "moz-extension://*",      # Allow Firefox if needed
])
```

**Or in nginx/reverse proxy**:

```nginx
# If origin starts with chrome-extension://, allow it
if ($http_origin ~* "^chrome-extension://") {
    add_header 'Access-Control-Allow-Origin' $http_origin always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type' always;
    add_header 'Access-Control-Expose-Headers' 'Content-Type' always;
}
```

### Option 2: Specific Extension ID

If you want to restrict to only your extension:

1. Get your extension ID:
   - Go to `chrome://extensions/`
   - Find "Filevine Document Viewer"
   - Copy the ID (e.g., `abcdefghijklmnopqrstuvwxyz123456`)

2. Configure Echomark to allow only that ID:

```python
CORS(app, origins=[
    "chrome-extension://abcdefghijklmnopqrstuvwxyz123456"
])
```

### Option 3: Use Preflight Requests

Ensure the server handles OPTIONS requests properly:

```python
@app.route('/echomark/api/v2/document/mark/pdf', methods=['OPTIONS'])
def preflight_pdf():
    response = make_response()
    response.headers['Access-Control-Allow-Origin'] = request.headers.get('Origin')
    response.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Authorization, Content-Type'
    return response
```

---

## How to Apply the Fix

### SSH into Echomark Server

```bash
# Use the provided SSH key
ssh -i <key>.pem ubuntu@ec2-52-8-108-29.us-west-1.compute.amazonaws.com
```

### Locate Configuration File

```bash
# Find the Echomark configuration
sudo find /opt /etc /var -name "*.py" -o -name "*.conf" 2>/dev/null | grep -i echomark

# Common locations:
# - /opt/echomark/
# - /etc/echomark/
# - /var/www/echomark/
```

### Update CORS Configuration

Look for:
- Flask CORS configuration
- nginx configuration
- Apache configuration

Add the chrome-extension:// origin support.

### Restart Service

```bash
# Find the service
sudo systemctl list-units | grep echomark

# Restart it
sudo systemctl restart echomark
# or
sudo systemctl restart echomark-api
```

---

## Alternative: Use Chrome webRequest API

If you **cannot** modify the Echomark server, we can use Chrome's declarativeNetRequest to bypass CORS:

**Update manifest.json**:

```json
{
  "permissions": [
    "declarativeNetRequest",
    "declarativeNetRequestWithHostAccess"
  ],
  "host_permissions": [
    "https://ec2-52-8-108-29.us-west-1.compute.amazonaws.com:5345/*"
  ],
  "declarative_net_request": {
    "rule_resources": [{
      "id": "echomark_cors",
      "enabled": true,
      "path": "rules.json"
    }]
  }
}
```

**Create rules.json**:

```json
[
  {
    "id": 1,
    "priority": 1,
    "action": {
      "type": "modifyHeaders",
      "requestHeaders": [
        {
          "header": "Origin",
          "operation": "set",
          "value": "https://filevineapp.com"
        }
      ]
    },
    "condition": {
      "urlFilter": "ec2-52-8-108-29.us-west-1.compute.amazonaws.com:5345",
      "resourceTypes": ["xmlhttprequest"]
    }
  }
]
```

---

## Verification Steps

After applying the fix:

### 1. Test with curl

```bash
# Get your extension ID
EXTENSION_ID="your-extension-id-here"

# Test CORS
curl -I -X POST https://ec2-52-8-108-29.us-west-1.compute.amazonaws.com:5345/echomark/api/v2/document/mark/pdf \
  -H "Authorization: Bearer 79f8eaa8-735d-480c-a594-891a9afe9b89" \
  -H "Origin: chrome-extension://$EXTENSION_ID"

# Should see:
# Access-Control-Allow-Origin: chrome-extension://your-extension-id
```

### 2. Test in Extension

1. Reload extension in Chrome
2. Open background console: `chrome://extensions/` → Service worker
3. Try watermarking a document
4. Check console logs (now with better logging)

**Expected logs**:
```
[Echomark] Marking document: { ... }
[Echomark] Making request to: https://ec2-52-8-108-29...
[Echomark] Headers: { Authorization: "Bearer ..." }
[Echomark] Response status: 200
[Echomark] Response headers: [ ... ]
[Echomark] Document marked successfully
```

**If still failing**:
```
[Echomark] Failed to mark document: TypeError: Failed to fetch
[Echomark] Error name: TypeError
[Echomark] Error message: Failed to fetch
```

This means CORS is still not configured correctly.

---

## Python Example (for Echomark server)

If the Echomark server uses Flask:

```python
from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)

# Allow all chrome-extension origins
def is_chrome_extension(origin):
    return origin.startswith('chrome-extension://') or origin.startswith('moz-extension://')

CORS(app,
     origins=is_chrome_extension,
     supports_credentials=True,
     expose_headers=['Content-Type'])

@app.route('/echomark/api/v2/document/mark/pdf', methods=['POST', 'OPTIONS'])
def mark_pdf():
    if request.method == 'OPTIONS':
        # Preflight request
        return '', 204

    # Your existing watermarking logic here
    # ...
```

---

## What We Changed in the Extension

Added better error logging and explicit CORS mode:

**File**: [src/lib/echomark-client.js:75-81](src/lib/echomark-client.js#L75-L81)

```javascript
const response = await fetch(url, {
  method: 'POST',
  headers: headers,
  body: formData,
  mode: 'cors',         // Explicitly request CORS
  credentials: 'omit'   // Don't send cookies
});
```

This helps diagnose the issue but doesn't fix it - **server configuration is required**.

---

## Contact Echomark Support

If you're not comfortable making these changes:

1. Contact Echomark support
2. Explain: "Chrome extension needs CORS support for `chrome-extension://` origins"
3. Share this document
4. Ask them to enable wildcard CORS for chrome-extension:// origins

---

## Summary

**Root Cause**: Echomark server needs to allow `chrome-extension://` origins in CORS

**Fix Required**: Server-side configuration update

**Options**:
1. ✅ **Best**: Allow `chrome-extension://*` wildcard in CORS
2. ⚠️ **Okay**: Allow specific extension ID
3. ⚠️ **Workaround**: Use declarativeNetRequest (complex)

**Who Can Fix**:
- Echomark server administrator
- OR Echomark support team
- OR you (if you have SSH access)

---

**Next Steps**: SSH into the server and update CORS configuration, or contact Echomark support.
