# Customer Config API - Supabase Edge Function

## Overview

This Edge Function provides customer configuration data to the `@buzztrail-ai/engage` NPM package with server-side domain validation. It enforces domain locking to prevent unauthorized usage and ensures security through server-side checks that cannot be bypassed by client-side code.

## Endpoint

```
GET /functions/v1/get-client-config?client_id={clientId}
```

**Production URL:**
```
https://dwdytxxqcvlrmyemonxz.supabase.co/functions/v1/get-client-config?client_id=buzztrail
```

## Security Model

### Domain Locking (CRITICAL)

**Server-side validation prevents unauthorized usage:**

1. Client makes request with `Origin` or `Referer` header
2. Server extracts hostname from request headers
3. Server queries `buzztrail_clients` table for `allowed_domains`
4. Server validates hostname against `allowed_domains` array
5. If unauthorized: Return `403 Forbidden` with error message
6. If authorized: Return client config WITHOUT `allowed_domains` field

**Why this is secure:**
- Domain check happens on the server (cannot be bypassed by modifying client code)
- `allowed_domains` is never sent to the client (bad actors can't see the whitelist)
- Client receives either full config or 403 error (no partial data leakage)
- Works seamlessly with localhost for development/testing

### What is NOT sent to client

The following fields are NEVER included in the response:
- `allowed_domains` - Domain whitelist (server-side only)
- `id` - Internal UUID (not needed by client)
- Database metadata fields (`created_at`, `updated_at`)

## Request Parameters

### Query Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `client_id` | string | Yes | Human-readable client identifier (e.g., 'buzztrail') |

### Headers

| Header | Type | Required | Description |
|--------|------|----------|-------------|
| `Authorization` | string | Yes | Bearer token with Supabase anon key |
| `Origin` | string | Recommended | Request origin (e.g., 'https://buzztrail.ai') |
| `Referer` | string | Fallback | Request referer URL if Origin not present |

**Authentication:** The Edge Function requires authentication via Supabase anon key (safe to expose publicly):

```bash
-H "Authorization: Bearer YOUR_SUPABASE_ANON_KEY"
```

Get the anon key from: **Supabase Dashboard → Settings → API → Project API keys → anon public**

**Note:** Modern browsers automatically send `Origin` or `Referer` headers. If neither is present, the request will be rejected as unauthorized.

## Response Format

### Success Response (200 OK)

```json
{
  "clientId": "buzztrail",
  "name": "BuzzTrail",
  "status": "active",
  "agent": {
    "agentId": "tom-insurance",
    "agentName": "Tom - Insurance Agent",
    "agentType": "video",
    "capabilities": {
      "video": true,
      "voice": true,
      "text": false,
      "slides": false,
      "screenshare": false
    },
    "providers": [
      {
        "provider": "tavus",
        "personaId": "p527c5d8b826",
        "replicaId": "rca8a38779a8"
      }
    ]
  },
  "ui": {
    "mode": "video-panel",
    "primaryColor": "#a3e635",
    "buttonText": {
      "en": "Talk with Tom"
    },
    "assets": {
      "videoUrl": "https://video.wixstatic.com/video/878890_9ada079151a14e1ca7cfc09930f3177f/1080p/mp4/file.mp4"
    }
  },
  "gating": {
    "enabled": true,
    "collectInfo": ["name", "email", "company"],
    "requiredInfo": ["name", "email"],
    "language": "en",
    "gdprCompliant": true,
    "passToConversation": true,
    "storage": {
      "destination": "supabase",
      "supabaseTable": "buzztrail_leads"
    }
  }
}
```

### Error Responses

#### 400 Bad Request - Missing client_id

```json
{
  "error": "Missing client_id parameter"
}
```

#### 403 Forbidden - Unauthorized Domain

```json
{
  "error": "Unauthorized domain",
  "message": "Domain 'evil.com' is not authorized for this client"
}
```

#### 404 Not Found - Client Not Found

```json
{
  "error": "Client not found"
}
```

#### 500 Internal Server Error

```json
{
  "error": "Internal server error",
  "message": "Detailed error message"
}
```

## Database Schema

The function queries the following tables:

### buzztrail_clients

Primary table storing client configurations:

- `id` (UUID) - Primary key
- `client_id` (VARCHAR) - Human-readable identifier
- `name` (VARCHAR) - Display name
- `status` (VARCHAR) - 'active', 'trial', 'suspended', 'terminated'
- `allowed_domains` (JSONB) - Domain whitelist (NEVER sent to client)
- `ui` (JSONB) - UI configuration
- `gating` (JSONB) - Lead capture settings

### buzztrail_client_agents (Junction Table)

Many-to-many relationship between clients and agents:

- `client_uuid` (UUID FK) - Links to buzztrail_clients.id
- `agent_uuid` (UUID FK) - Links to buzztrail_agents.id
- `is_default` (BOOLEAN) - Whether this is the default agent
- `context` (JSONB) - Additional context for this pairing

### buzztrail_agents

Agent configurations (provider-agnostic):

- `id` (UUID) - Primary key
- `agent_id` (VARCHAR) - Human-readable identifier
- `agent_name` (VARCHAR) - Display name
- `agent_type` (VARCHAR) - 'video', 'voice', 'hybrid'
- `capabilities` (JSONB) - Feature flags
- `providers` (JSONB) - Provider-specific configs

## Local Development

### Prerequisites

- Supabase CLI installed (`brew install supabase/tap/supabase`)
- Supabase project linked (`supabase link --project-ref dwdytxxqcvlrmyemonxz`)
- Environment variables configured

### Start Local Function Server

```bash
# From repository root
pnpm nx run supabase-backend:functions:serve

# Or directly with Supabase CLI
cd apps/supabase-backend
supabase functions serve get-client-config --workdir supabase
```

### Test Local Endpoint

```bash
# Get your anon key from Supabase Dashboard → Settings → API
ANON_KEY="your-supabase-anon-key"

# Test with valid domain (localhost)
curl "http://localhost:54321/functions/v1/get-client-config?client_id=buzztrail" \
  -H "Authorization: Bearer $ANON_KEY" \
  -H "Origin: http://localhost:3000"

# Test with buzztrail.ai domain
curl "http://localhost:54321/functions/v1/get-client-config?client_id=buzztrail" \
  -H "Authorization: Bearer $ANON_KEY" \
  -H "Origin: https://buzztrail.ai"

# Test with unauthorized domain (should return 403)
curl "http://localhost:54321/functions/v1/get-client-config?client_id=buzztrail" \
  -H "Authorization: Bearer $ANON_KEY" \
  -H "Origin: https://evil.com"
```

## Production Deployment

### Deploy Function

```bash
# From repository root (uses Nx target)
pnpm nx run supabase-backend:functions:deploy

# Or directly with Supabase CLI
cd apps/supabase-backend
supabase functions deploy get-client-config --workdir supabase --project-ref dwdytxxqcvlrmyemonxz
```

### Environment Variables

The function requires these environment variables (configured in Supabase Dashboard):

- `SUPABASE_URL` - Auto-populated by Supabase
- `SUPABASE_SERVICE_ROLE_KEY` - Auto-populated by Supabase

**Note:** These are automatically available in Edge Functions. No manual configuration needed.

### Test Production Endpoint

```bash
# Get your anon key from Supabase Dashboard → Settings → API → Project API keys
ANON_KEY="your-supabase-anon-key"

# Test with valid domain
curl "https://dwdytxxqcvlrmyemonxz.supabase.co/functions/v1/get-client-config?client_id=buzztrail" \
  -H "Authorization: Bearer $ANON_KEY" \
  -H "Origin: https://buzztrail.ai"

# Expected: 200 OK with full config

# Test with invalid domain
curl "https://dwdytxxqcvlrmyemonxz.supabase.co/functions/v1/get-client-config?client_id=buzztrail" \
  -H "Authorization: Bearer $ANON_KEY" \
  -H "Origin: https://evil.com"

# Expected: 403 Forbidden with error message

# Interactive test page
# Open apps/supabase-backend/supabase/functions/get-client-config/test.html in browser
```

## Client Integration

### NPM Package Usage

```typescript
// In @buzztrail-ai/engage package
const SUPABASE_ANON_KEY = 'YOUR_SUPABASE_ANON_KEY'; // Safe to expose publicly

async function fetchClientConfig(clientId: string): Promise<ClientConfig> {
  const origin = window.location.hostname;

  const response = await fetch(
    `https://dwdytxxqcvlrmyemonxz.supabase.co/functions/v1/get-client-config?client_id=${clientId}`,
    {
      headers: {
        'Authorization': `Bearer ${SUPABASE_ANON_KEY}`,
        'Content-Type': 'application/json'
      }
    }
  );

  if (response.status === 403) {
    throw new Error(
      `Domain '${origin}' is not authorized. Contact support@buzztrail.ai`
    );
  }

  if (!response.ok) {
    throw new Error(`Failed to load config: ${response.statusText}`);
  }

  return response.json();
}
```

**Note:** The Supabase anon key is safe to expose in client-side code. It's designed to be public and only provides read access to public data. Domain validation provides the actual security.

### CDN Usage

```html
<!-- Load from CDN -->
<script src="https://cdn.jsdelivr.net/npm/@buzztrail-ai/engage@latest/dist/buzztrail.min.js"
        data-client-id="buzztrail">
</script>

<!-- Package automatically calls Edge Function on load -->
<!-- Domain validation happens server-side -->
<!-- If unauthorized, widget shows error message -->
```

## Monitoring & Debugging

### View Function Logs

```bash
# Tail production logs
supabase functions logs get-client-config --project-ref dwdytxxqcvlrmyemonxz --follow

# View recent logs
supabase functions logs get-client-config --project-ref dwdytxxqcvlrmyemonxz --tail 100
```

### Common Issues

**403 Unauthorized Domain:**
- Verify domain is in `allowed_domains` array
- Check that `Origin` or `Referer` header is being sent
- Ensure localhost is included for local testing

**404 Client Not Found:**
- Verify `client_id` exists in `buzztrail_clients` table
- Check spelling and case sensitivity

**500 Internal Server Error:**
- Check function logs for detailed error messages
- Verify database connection and permissions
- Ensure default agent is configured

## Security Best Practices

### Do's

✅ Always include localhost in `allowed_domains` for testing
✅ Use exact domain matches (e.g., 'buzztrail.ai' and 'www.buzztrail.ai' are different)
✅ Monitor function logs for unauthorized access attempts
✅ Keep `allowed_domains` minimal (only production domains)
✅ Use client status ('active', 'trial') to control access

### Don'ts

❌ Never send `allowed_domains` to the client
❌ Don't use wildcard domain matching (*.example.com)
❌ Don't disable domain validation for "convenience"
❌ Don't store API keys or secrets in client config
❌ Don't trust client-side domain validation

## Related Documentation

- **PRD**: `.claude/prds/universal-npm-package-cdn-distribution.md` (lines 230-306)
- **Database Schema**: `apps/supabase-backend/supabase/migrations/20251024000000_add_customer_registry.sql`
- **Task Spec**: `.claude/epics/universal-npm-package-cdn-distribution/175.md`
- **Analysis**: `.claude/epics/universal-npm-package-cdn-distribution/174-analysis.md`

## Changelog

### 2025-10-24 - Initial Implementation

- Created Edge Function with server-side domain validation
- Implemented CORS support for CDN access
- Added comprehensive error handling and logging
- Deployed to production Supabase project
