# Yemaya Webhooks Documentation

Webhooks allow your application to receive real-time notifications about events that occur in the Yemaya platform. Instead of polling the API for changes, you can configure webhook endpoints to receive HTTP POST requests when specific events occur.

## Table of Contents

- [Overview](#overview)
- [Setting Up Webhooks](#setting-up-webhooks)
- [Webhook Events](#webhook-events)
- [Payload Format](#payload-format)
- [Signature Verification](#signature-verification)
- [Retry Policy](#retry-policy)
- [Best Practices](#best-practices)

## Overview

When an event occurs in Yemaya (such as a project being created, an asset being uploaded, or an AI generation completing), we can send an HTTP POST request to a URL you specify. This allows your application to:

- React to changes in real-time
- Synchronize data with external systems
- Trigger automated workflows
- Send notifications to users

## Setting Up Webhooks

### Creating a Webhook Endpoint

```bash
curl -X POST https://api.yemaya.io/v1/webhooks \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-app.com/webhooks/yemaya",
    "events": ["project.created", "asset.uploaded", "generation.completed"],
    "secret": "your_webhook_secret"
  }'
```

### Response

```json
{
  "success": true,
  "data": {
    "id": "whk_abc123",
    "url": "https://your-app.com/webhooks/yemaya",
    "events": ["project.created", "asset.uploaded", "generation.completed"],
    "active": true,
    "createdAt": "2024-01-15T10:30:00Z"
  }
}
```

### Managing Webhooks

#### List Webhooks

```bash
GET /v1/webhooks
```

#### Get Webhook Details

```bash
GET /v1/webhooks/{webhookId}
```

#### Update Webhook

```bash
PATCH /v1/webhooks/{webhookId}
```

#### Delete Webhook

```bash
DELETE /v1/webhooks/{webhookId}
```

#### Test Webhook

```bash
POST /v1/webhooks/{webhookId}/test
```

## Webhook Events

### Project Events

| Event | Description |
|-------|-------------|
| `project.created` | A new project was created |
| `project.updated` | A project was updated |
| `project.deleted` | A project was deleted |
| `project.archived` | A project was archived |
| `project.restored` | An archived project was restored |
| `project.member.added` | A member was added to a project |
| `project.member.removed` | A member was removed from a project |
| `project.member.role_changed` | A member's role was changed |

### Asset Events

| Event | Description |
|-------|-------------|
| `asset.created` | A new asset was created |
| `asset.uploaded` | An asset file was uploaded |
| `asset.updated` | An asset was updated |
| `asset.deleted` | An asset was deleted |
| `asset.processing.started` | Asset processing started |
| `asset.processing.completed` | Asset processing completed |
| `asset.processing.failed` | Asset processing failed |
| `asset.version.created` | A new asset version was created |

### Scene Events

| Event | Description |
|-------|-------------|
| `scene.created` | A new scene was created |
| `scene.updated` | A scene was updated |
| `scene.deleted` | A scene was deleted |
| `scene.object.added` | An object was added to a scene |
| `scene.object.removed` | An object was removed from a scene |

### Character Events

| Event | Description |
|-------|-------------|
| `character.created` | A new character was created |
| `character.updated` | A character was updated |
| `character.deleted` | A character was deleted |

### AI Generation Events

| Event | Description |
|-------|-------------|
| `generation.started` | An AI generation started |
| `generation.completed` | An AI generation completed successfully |
| `generation.failed` | An AI generation failed |
| `generation.cancelled` | An AI generation was cancelled |

### Organization Events

| Event | Description |
|-------|-------------|
| `organization.created` | An organization was created |
| `organization.updated` | An organization was updated |
| `organization.member.invited` | A member was invited to an organization |
| `organization.member.joined` | A member joined an organization |
| `organization.member.removed` | A member was removed from an organization |

### User Events

| Event | Description |
|-------|-------------|
| `user.created` | A new user account was created |
| `user.updated` | A user profile was updated |
| `user.deleted` | A user account was deleted |

## Payload Format

All webhook payloads follow a consistent structure:

```json
{
  "id": "evt_abc123xyz",
  "type": "project.created",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "apiVersion": "2024-01-01",
  "data": {
    "object": {
      // The full object that was affected
    },
    "previousAttributes": {
      // For update events, the previous values of changed fields
    }
  },
  "metadata": {
    "userId": "usr_abc123",
    "organizationId": "org_xyz789",
    "projectId": "prj_def456",
    "requestId": "req_123abc"
  }
}
```

### Example Payloads

#### project.created

```json
{
  "id": "evt_proj123",
  "type": "project.created",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "apiVersion": "2024-01-01",
  "data": {
    "object": {
      "id": "prj_abc123",
      "name": "My New Game",
      "type": "game",
      "status": "active",
      "ownerId": "usr_xyz789",
      "createdAt": "2024-01-15T10:30:00.000Z",
      "updatedAt": "2024-01-15T10:30:00.000Z"
    }
  },
  "metadata": {
    "userId": "usr_xyz789",
    "requestId": "req_abc123"
  }
}
```

#### generation.completed

```json
{
  "id": "evt_gen456",
  "type": "generation.completed",
  "timestamp": "2024-01-15T10:35:00.000Z",
  "apiVersion": "2024-01-01",
  "data": {
    "object": {
      "id": "gen_xyz789",
      "type": "image",
      "status": "completed",
      "prompt": "A mystical forest at sunset",
      "model": "dalle-3",
      "result": "https://assets.yemaya.io/generated/img_abc123.png",
      "metadata": {
        "width": 1024,
        "height": 1024,
        "format": "png"
      },
      "createdAt": "2024-01-15T10:30:00.000Z",
      "completedAt": "2024-01-15T10:35:00.000Z"
    }
  },
  "metadata": {
    "userId": "usr_xyz789",
    "projectId": "prj_abc123",
    "requestId": "req_def456"
  }
}
```

## Signature Verification

All webhook requests include a signature in the `X-Yemaya-Signature` header. You should verify this signature to ensure the request came from Yemaya.

### Signature Format

The signature is a HMAC-SHA256 hash of the request body, using your webhook secret as the key.

```
X-Yemaya-Signature: sha256=abc123def456...
```

### Verification Examples

#### Node.js

```javascript
import crypto from 'crypto';

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload, 'utf8')
    .digest('hex');

  const providedSignature = signature.replace('sha256=', '');

  return crypto.timingSafeEqual(
    Buffer.from(expectedSignature, 'hex'),
    Buffer.from(providedSignature, 'hex')
  );
}

// Express.js example
app.post('/webhooks/yemaya', express.raw({ type: 'application/json' }), (req, res) => {
  const signature = req.headers['x-yemaya-signature'];
  const payload = req.body.toString();

  if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }

  const event = JSON.parse(payload);
  // Handle the event...

  res.status(200).send('OK');
});
```

#### Python

```python
import hmac
import hashlib

def verify_webhook_signature(payload: bytes, signature: str, secret: str) -> bool:
    expected = hmac.new(
        secret.encode('utf-8'),
        payload,
        hashlib.sha256
    ).hexdigest()

    provided = signature.replace('sha256=', '')

    return hmac.compare_digest(expected, provided)

# Flask example
from flask import Flask, request

@app.route('/webhooks/yemaya', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-Yemaya-Signature')
    payload = request.get_data()

    if not verify_webhook_signature(payload, signature, WEBHOOK_SECRET):
        return 'Invalid signature', 401

    event = request.get_json()
    # Handle the event...

    return 'OK', 200
```

#### Go

```go
package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "io"
    "net/http"
    "strings"
)

func verifyWebhookSignature(payload []byte, signature, secret string) bool {
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write(payload)
    expected := hex.EncodeToString(mac.Sum(nil))

    provided := strings.TrimPrefix(signature, "sha256=")

    return hmac.Equal([]byte(expected), []byte(provided))
}

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    signature := r.Header.Get("X-Yemaya-Signature")
    payload, _ := io.ReadAll(r.Body)

    if !verifyWebhookSignature(payload, signature, webhookSecret) {
        http.Error(w, "Invalid signature", http.StatusUnauthorized)
        return
    }

    // Handle the event...

    w.WriteHeader(http.StatusOK)
}
```

## Retry Policy

If your endpoint returns a non-2xx status code or times out, we will retry the delivery:

| Attempt | Delay |
|---------|-------|
| 1 | Immediate |
| 2 | 1 minute |
| 3 | 5 minutes |
| 4 | 30 minutes |
| 5 | 2 hours |
| 6 | 8 hours |
| 7 | 24 hours |

After 7 failed attempts, the webhook delivery is marked as failed and will not be retried.

### Timeout

Webhook requests have a 30-second timeout. If your endpoint doesn't respond within 30 seconds, the request is considered failed.

### Delivery Headers

Each webhook request includes these headers:

| Header | Description |
|--------|-------------|
| `Content-Type` | `application/json` |
| `X-Yemaya-Signature` | HMAC-SHA256 signature |
| `X-Yemaya-Event` | Event type (e.g., `project.created`) |
| `X-Yemaya-Delivery` | Unique delivery ID |
| `X-Yemaya-Timestamp` | Unix timestamp of the delivery |
| `User-Agent` | `Yemaya-Webhooks/1.0` |

## Best Practices

### 1. Respond Quickly

Return a 2xx response as quickly as possible. Process the webhook payload asynchronously:

```javascript
app.post('/webhooks/yemaya', async (req, res) => {
  // Verify signature first
  if (!verifySignature(req)) {
    return res.status(401).send('Invalid signature');
  }

  // Respond immediately
  res.status(200).send('OK');

  // Process asynchronously
  processWebhookAsync(req.body).catch(console.error);
});
```

### 2. Handle Duplicate Events

Webhooks may be delivered more than once. Use the `id` field to deduplicate:

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

async function handleWebhook(event) {
  if (processedEvents.has(event.id)) {
    return; // Already processed
  }

  processedEvents.add(event.id);
  // Process the event...
}
```

### 3. Verify Signatures

Always verify the webhook signature before processing. Never process unsigned requests.

### 4. Use HTTPS

Always use HTTPS for your webhook endpoint. We will not deliver webhooks to HTTP endpoints.

### 5. Handle All Event Types

Gracefully handle unknown event types:

```javascript
function handleWebhook(event) {
  switch (event.type) {
    case 'project.created':
      handleProjectCreated(event);
      break;
    case 'generation.completed':
      handleGenerationCompleted(event);
      break;
    default:
      console.log(`Unhandled event type: ${event.type}`);
  }
}
```

### 6. Monitor Webhook Deliveries

Use the webhook delivery logs in the Yemaya dashboard to monitor:
- Successful deliveries
- Failed deliveries and error messages
- Response times

### 7. Rotate Secrets Periodically

Rotate your webhook secrets periodically for security:

```bash
# Generate a new secret
PATCH /v1/webhooks/{webhookId}
{
  "secret": "new_secret_value"
}
```

## Testing Webhooks

### Test Endpoint

Send a test event to your webhook:

```bash
POST /v1/webhooks/{webhookId}/test
{
  "eventType": "project.created"
}
```

### Local Development

For local development, use a tunneling service like ngrok:

```bash
ngrok http 3000
```

Then use the ngrok URL as your webhook endpoint:

```bash
POST /v1/webhooks
{
  "url": "https://abc123.ngrok.io/webhooks/yemaya",
  "events": ["*"]
}
```

### Webhook Logs

View recent webhook deliveries:

```bash
GET /v1/webhooks/{webhookId}/deliveries
```

Response:

```json
{
  "data": [
    {
      "id": "dlv_abc123",
      "eventId": "evt_xyz789",
      "eventType": "project.created",
      "status": "success",
      "statusCode": 200,
      "responseTime": 150,
      "createdAt": "2024-01-15T10:30:00Z"
    }
  ],
  "meta": {
    "page": 1,
    "limit": 20,
    "total": 100
  }
}
```

## Webhook IP Addresses

Webhook requests originate from these IP addresses. You may want to allowlist them:

- `52.1.2.3`
- `52.1.2.4`
- `52.1.2.5`

Note: These IPs may change. Subscribe to our status page for updates.
