# Webhooks

Webhooks allow you to receive real-time notifications when events occur in the
Veritas platform.

## Overview

Instead of polling the API for changes, configure webhooks to receive HTTP POST
requests when:

- New articles match your alert criteria
- Entities you're tracking are mentioned
- New fact-checks are published
- Breaking news occurs

## Setting Up Webhooks

### 1. Create an Alert Subscription

```javascript
const subscription = await client.alerts.create({
  name: 'Breaking Politics News',
  alertType: 'breaking_news',
  filters: {
    categories: ['politics'],
    languages: ['en'],
  },
  webhookUrl: 'https://your-server.com/webhooks/veritas',
  frequency: 'instant',
});
```

### 2. Configure Your Endpoint

Your webhook endpoint must:

- Accept HTTP POST requests
- Respond with 2xx status within 30 seconds
- Handle duplicate deliveries idempotently
- Verify webhook signatures (recommended)

**Example Express.js Handler:**

```javascript
const express = require('express');
const crypto = require('crypto');

const app = express();
app.use(express.raw({ type: 'application/json' }));

app.post('/webhooks/veritas', (req, res) => {
  // Verify signature
  const signature = req.headers['x-veritas-signature'];
  const timestamp = req.headers['x-veritas-timestamp'];

  if (!verifySignature(req.body, signature, timestamp)) {
    return res.status(401).send('Invalid signature');
  }

  // Parse payload
  const payload = JSON.parse(req.body);

  // Process the webhook
  console.log('Received webhook:', payload.notificationType);
  console.log('Article:', payload.article?.headline);

  // Acknowledge receipt
  res.status(200).send('OK');

  // Process asynchronously
  processWebhook(payload);
});

function verifySignature(body, signature, timestamp) {
  const secret = process.env.VERITAS_WEBHOOK_SECRET;
  const payload = `${timestamp}.${body}`;
  const expected = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(`sha256=${expected}`)
  );
}
```

## Webhook Payload

All webhook payloads follow this structure:

```json
{
  "id": "notif_abc123",
  "subscriptionId": "sub_xyz789",
  "notificationType": "keyword",
  "title": "New article matches your keywords",
  "summary": "Article about election results matches 'election, voting'",
  "payload": {
    "articleId": "article_001",
    "headline": "Election Results Announced",
    "publishedAt": "2024-01-15T14:30:00Z",
    "matchedKeywords": ["election", "voting"],
    "source": {
      "name": "Global News Network",
      "domain": "gnn.com"
    }
  },
  "createdAt": "2024-01-15T14:30:05Z"
}
```

### Payload Fields

| Field              | Type   | Description                                   |
| ------------------ | ------ | --------------------------------------------- |
| `id`               | string | Unique notification ID                        |
| `subscriptionId`   | string | Alert subscription that triggered this        |
| `notificationType` | string | Type of alert (keyword, entity_mention, etc.) |
| `title`            | string | Human-readable notification title             |
| `summary`          | string | Brief description                             |
| `payload`          | object | Event-specific data                           |
| `createdAt`        | string | When the notification was created             |

### Payload by Notification Type

**Keyword Alert:**

```json
{
  "notificationType": "keyword",
  "payload": {
    "articleId": "article_001",
    "headline": "Article headline",
    "publishedAt": "2024-01-15T14:30:00Z",
    "matchedKeywords": ["keyword1", "keyword2"],
    "source": { "name": "Source Name", "domain": "source.com" }
  }
}
```

**Entity Mention:**

```json
{
  "notificationType": "entity_mention",
  "payload": {
    "articleId": "article_001",
    "headline": "Article headline",
    "publishedAt": "2024-01-15T14:30:00Z",
    "entityId": "ent_001",
    "entityName": "Entity Name",
    "entityType": "person",
    "mentionCount": 5,
    "sentiment": 0.3
  }
}
```

**Breaking News:**

```json
{
  "notificationType": "breaking_news",
  "payload": {
    "articleId": "article_001",
    "headline": "Breaking: Major Event Occurs",
    "publishedAt": "2024-01-15T14:30:00Z",
    "category": "politics",
    "source": { "name": "Source Name", "domain": "source.com" }
  }
}
```

**Fact Check:**

```json
{
  "notificationType": "fact_check",
  "payload": {
    "claimId": "claim_001",
    "claimText": "Claim being fact-checked",
    "verdict": "false",
    "confidence": 0.98,
    "publishedAt": "2024-01-15T14:30:00Z"
  }
}
```

## Webhook Headers

Each webhook request includes these headers:

| Header                  | Description                     |
| ----------------------- | ------------------------------- |
| `Content-Type`          | `application/json`              |
| `X-Veritas-Signature`   | HMAC signature for verification |
| `X-Veritas-Timestamp`   | Request timestamp (Unix epoch)  |
| `X-Veritas-Delivery-Id` | Unique delivery attempt ID      |
| `X-Veritas-Event-Type`  | Notification type               |
| `User-Agent`            | `Veritas-Webhook/1.0`           |

## Signature Verification

All webhooks are signed using HMAC-SHA256. Verify signatures to ensure
authenticity.

### Signature Format

```
X-Veritas-Signature: sha256=<hex_digest>
```

### Verification Algorithm

```python
import hmac
import hashlib

def verify_signature(payload: bytes, signature: str, timestamp: str, secret: str) -> bool:
    """Verify webhook signature."""
    # Construct the signed payload
    signed_payload = f"{timestamp}.{payload.decode('utf-8')}"

    # Calculate expected signature
    expected = hmac.new(
        secret.encode('utf-8'),
        signed_payload.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()

    # Compare signatures
    expected_sig = f"sha256={expected}"
    return hmac.compare_digest(signature, expected_sig)
```

### Timestamp Validation

Reject webhooks with timestamps older than 5 minutes to prevent replay attacks:

```javascript
function isTimestampValid(timestamp) {
  const now = Math.floor(Date.now() / 1000);
  const webhookTime = parseInt(timestamp, 10);
  const fiveMinutes = 5 * 60;
  return Math.abs(now - webhookTime) <= fiveMinutes;
}
```

## Delivery & Retries

### Delivery Guarantees

- **At-least-once delivery** - Webhooks may be delivered multiple times
- **Order not guaranteed** - Events may arrive out of order

### Retry Policy

If your endpoint fails to respond with 2xx, we retry with exponential backoff:

| Attempt | Delay      |
| ------- | ---------- |
| 1       | Immediate  |
| 2       | 1 minute   |
| 3       | 5 minutes  |
| 4       | 30 minutes |
| 5       | 2 hours    |
| 6       | 12 hours   |

After 6 failed attempts, the notification is marked as undeliverable.

### Handling Duplicates

Use the notification `id` for idempotency:

```javascript
const processedIds = new Set();

function handleWebhook(payload) {
  if (processedIds.has(payload.id)) {
    console.log('Duplicate webhook, skipping');
    return;
  }

  processedIds.add(payload.id);
  // Process the webhook...
}
```

## Testing Webhooks

### Using the Sandbox

Test webhooks using sandbox (test) API keys:

```javascript
// Create a test subscription
const client = new VeritasClient({ apiKey: 'sk_test_...' });

await client.alerts.create({
  name: 'Test Alert',
  alertType: 'keyword',
  filters: { keywords: ['test'] },
  webhookUrl: 'https://your-test-endpoint.com/webhook',
});
```

### Local Development

Use tools like ngrok to expose local endpoints:

```bash
# Start ngrok tunnel
ngrok http 3000

# Use the ngrok URL for webhook testing
# https://abc123.ngrok.io/webhooks/veritas
```

### Manual Trigger

Trigger a test webhook via the sandbox API:

```javascript
// Force a notification (sandbox only)
await client.sandbox.forceWebhook({
  subscriptionId: 'sub_001',
  notificationType: 'keyword',
  payload: {
    articleId: 'test_article',
    headline: 'Test Article',
    matchedKeywords: ['test'],
  },
});
```

## Webhook Security Best Practices

1. **Always verify signatures** - Reject unsigned or invalid webhooks
2. **Validate timestamps** - Prevent replay attacks
3. **Use HTTPS** - Never expose webhook endpoints over HTTP
4. **Implement idempotency** - Handle duplicate deliveries
5. **Respond quickly** - Return 200 immediately, process async
6. **Keep secrets secure** - Store webhook secrets in environment variables
7. **Monitor failures** - Alert on repeated delivery failures
8. **Log webhook data** - Maintain audit trail for debugging

## Managing Webhook URLs

### Update Webhook URL

```javascript
await client.alerts.update(subscriptionId, {
  webhookUrl: 'https://new-endpoint.com/webhook',
});
```

### Disable Webhooks (Use Email Instead)

```javascript
await client.alerts.update(subscriptionId, {
  webhookUrl: null,
  email: 'alerts@example.com',
});
```

### View Delivery History

```javascript
// Get recent notifications with delivery status
const notifications = await client.alerts.notifications({
  subscriptionId: 'sub_001',
  delivered: false, // Show failed deliveries
});
```

## Troubleshooting

### Webhook Not Received

1. Check subscription is active: `await client.alerts.get(subscriptionId)`
2. Verify webhook URL is accessible from the internet
3. Check your server logs for incoming requests
4. Review notification history for delivery attempts

### Invalid Signature

1. Ensure you're using the raw request body (not parsed JSON)
2. Verify your webhook secret is correct
3. Check timestamp is being included in signature calculation

### Duplicate Deliveries

1. Implement idempotency using notification ID
2. Check for multiple active subscriptions with same filters
3. Review retry logs for failed initial delivery

## Support

For webhook issues, contact api-support@veritas.news with:

- Subscription ID
- Notification IDs (if available)
- Webhook endpoint URL
- Error messages or response codes
- Timestamps of issues
