# Webhooks

> Recibe la tarea terminada en tu servidor: pasa webhook_url al enviar la tarea, recibe un único POST y responde con 2xx. Las firmas siguen Standard Webhooks.

<a id="setup"></a>

## Configúralo en tres pasos
> **La URL del Webhook va en la solicitud, no en la consola**
>
> Defines la dirección para cada tarea, como `webhook_url` en el cuerpo de `POST /v1/tasks`. No hay ninguna URL de Webhook que configurar en la consola: [Consola → API → Webhook](https://kerox.ai/es/console/webhooks) solo guarda tu secreto de firma y las entregas recientes.

<a id="url"></a>

### 1. Obtén una URL HTTPS pública
Kerox solo envía a direcciones `https://` accesibles desde internet (no a `localhost` ni a una IP privada). En producción, es una ruta de tu servidor, como `https://your-app.example.com/webhooks/kerox`. Para probar la recepción del Webhook desde tu propio equipo, usa un inspector temporal como [webhook.site](https://webhook.site) para ver lo que llega, o un túnel (Cloudflare Tunnel, ngrok) hacia el receptor del paso 3.

<a id="submit"></a>

### 2. Pasa `webhook_url` al enviar la tarea
Asigna a `KEROX_WEBHOOK_URL` el receptor HTTPS público del paso 1 antes de enviar una tarea (el ejemplo de shell también necesita jq). Guarda el ID de tarea que se devuelve. Si el Webhook tarda en llegar, consulta `GET /v1/tasks/{id}` con ese ID.


```bash
API_ORIGIN=${KEROX_API_ORIGIN:-https://api.kerox.ai}
set -euo pipefail
case "${KEROX_WEBHOOK_URL:-}" in
  https://?*) ;;
  *) echo "Set KEROX_WEBHOOK_URL to your public HTTPS receiver" >&2; exit 1 ;;
esac
curl -fsS -X POST "$API_ORIGIN/v1/tasks" \
  -H "Authorization: Bearer $KEROX_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg url "$KEROX_WEBHOOK_URL" '{
    "model": "bytedance/seedream-5.5",
    "input": {
      "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
      "resolution": "2K"
    },
    "webhook_url": $url,
    "metadata": { "order_id": "A1001" }
  }')"
```
```python
import os
import requests

api = os.environ.get("KEROX_API_ORIGIN", "https://api.kerox.ai")

url = os.environ.get("KEROX_WEBHOOK_URL", "")
if not url.startswith("https://") or not url[8:]:
    raise SystemExit("Set KEROX_WEBHOOK_URL to your public HTTPS receiver")
resp = requests.post(
    f"{api}/v1/tasks",
    headers={
        "Authorization": f"Bearer {os.environ['KEROX_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "model": "bytedance/seedream-5.5",
        "input": {
            "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
            "resolution": "2K",
        },
        "webhook_url": url,
        "metadata": {"order_id": "A1001"},
    },
    timeout=60,
)
resp.raise_for_status()
print(resp.json()["id"])
```
```javascript
const api = process.env.KEROX_API_ORIGIN || 'https://api.kerox.ai';
const url = process.env.KEROX_WEBHOOK_URL;
if (!url || new URL(url).protocol !== 'https:') {
  throw new Error('Set KEROX_WEBHOOK_URL to your public HTTPS receiver');
}
const res = await fetch(`${api}/v1/tasks`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.KEROX_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'bytedance/seedream-5.5',
    input: {
      prompt: 'editorial portrait of a ceramicist in morning sunlight, 35mm film',
      resolution: '2K',
    },
    webhook_url: url,
    metadata: { order_id: 'A1001' },
  }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const task = await res.json();
console.log(task.id);
```


<a id="receive"></a>

### 3. Recíbelo y responde con 2xx
Cuando la tarea alcanza el estado `succeeded` o `failed`, Kerox envía un único `POST` a la URL indicada en `Content-Type: application/json`. Tu endpoint:

1. lee el cuerpo sin procesar de la solicitud;
2. verifica la firma (opcional, [ver más abajo](#verification));
3. comprueba que se trata de una tarea finalizada (`status` es `succeeded` con `outputs`, o `failed` con `error`) y responde `400` a cualquier solicitud que no cumpla estas condiciones, para que una sola solicitud malformada no lo haga fallar;
4. omite un `webhook-id` que ya haya procesado (cada reintento conserva el mismo valor);
5. devuelve cualquier `2xx` en un plazo máximo de 10 segundos y deja para después los procesos que tardan más (como descargar los archivos).

Cualquier otra respuesta, o la falta de respuesta en 10 segundos, se considera un fallo y se reintenta ([Reintentos](#retries)). Un receptor mínimo, que escucha en el puerto indicado por `PORT` (8787 por defecto) y en la ruta `/webhooks/kerox`:


```javascript
// npm install standardwebhooks
import http from 'node:http';
import { Webhook } from 'standardwebhooks';

// Optional: verify signatures with the secret from Console → API → Webhook.
const secret = process.env.KEROX_WEBHOOK_SECRET;
const wh = secret ? new Webhook(secret) : null;
const handled = new Set(); // use your database in production

const server = http.createServer(async (req, res) => {
  if (req.method !== 'POST' || req.url !== '/webhooks/kerox') {
    res.writeHead(404).end();
    return;
  }
  // 1. The raw body, exactly as received.
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  const rawBody = Buffer.concat(chunks).toString('utf8');

  // 2. Verify the signature (optional).
  let task;
  try {
    task = wh ? wh.verify(rawBody, req.headers) : JSON.parse(rawBody);
  } catch {
    res.writeHead(400).end();
    return;
  }

  // 3. Only a finished task with a delivery ID: anything else gets 400.
  const id = req.headers['webhook-id'];
  const finished =
    (task?.status === 'succeeded' && Array.isArray(task.outputs)) ||
    (task?.status === 'failed' && typeof task.error?.code === 'string');
  if (!id || !finished) {
    res.writeHead(400).end();
    return;
  }

  // 4. A retry has the same webhook-id: handle each one once.
  if (!handled.has(id)) {
    if (task.status === 'succeeded') {
      console.log(task.id, 'succeeded', task.outputs[0]?.url);
    } else {
      console.log(task.id, 'failed', task.error.code);
    }
    handled.add(id);
  }

  // 5. Answer 2xx within 10 seconds.
  res.writeHead(200).end();
});

server.listen(Number(process.env.PORT ?? 8787));
```
```python
# pip install standardwebhooks
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

from standardwebhooks.webhooks import Webhook

# Optional: verify signatures with the secret from Console → API → Webhook.
secret = os.environ.get("KEROX_WEBHOOK_SECRET")
wh = Webhook(secret) if secret else None
handled = set()  # use your database in production


class KeroxWebhook(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path != "/webhooks/kerox":
            self.send_response(404)
            self.end_headers()
            return
        # 1. The raw body, exactly as received.
        raw_body = self.rfile.read(int(self.headers.get("Content-Length", 0)))

        # 2. Verify the signature (optional).
        try:
            task = wh.verify(raw_body, dict(self.headers)) if wh else json.loads(raw_body)
        except Exception:
            self.send_response(400)
            self.end_headers()
            return

        # 3. Only a finished task with a delivery ID: anything else gets 400.
        msg_id = self.headers.get("webhook-id")
        status = task.get("status") if isinstance(task, dict) else None
        outputs = task.get("outputs") if status == "succeeded" else None
        finished = (
            isinstance(outputs, list) and all(isinstance(item, dict) for item in outputs)
        ) or (status == "failed" and isinstance(task.get("error"), dict))
        if not (msg_id and finished):
            self.send_response(400)
            self.end_headers()
            return

        # 4. A retry has the same webhook-id: handle each one once.
        if msg_id not in handled:
            if status == "succeeded":
                urls = [item.get("url") for item in task["outputs"]]
                print(task.get("id"), "succeeded", urls, flush=True)
            else:
                print(task.get("id"), "failed", task["error"].get("code"), flush=True)
            handled.add(msg_id)

        # 5. Answer 2xx within 10 seconds.
        self.send_response(200)
        self.end_headers()


HTTPServer(("", int(os.environ.get("PORT", "8787"))), KeroxWebhook).serve_forever()
```


<a id="events"></a>

## Qué enviamos
El cuerpo es el propio objeto de la tarea, exactamente lo que devuelve `GET /v1/tasks/{id}` ([campos](https://kerox.ai/es/docs/tasks.md#submit-response)). Distingue el éxito del fallo mediante `status`: si tiene éxito, los archivos están en `outputs`; si falla, el motivo está en `error` y se liberan los créditos retenidos (`cost.status: "refunded"`). Solo se notifican los dos estados finales, y cada uno se notifica una sola vez; si la tarea se creó sin `webhook_url`, no se entrega ningún Webhook.


```json
{
  "id": "task_01JD8X9B4Q2M7T8N3K5P6R1S0V",
  "object": "task",
  "model": "bytedance/seedream-5.5",
  "status": "succeeded",
  "source": "api",
  "format": "unified",
  "input": {
    "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
    "size": "2K"
  },
  "outputs": [
    {
      "type": "image",
      "url": "https://cdn.kerox.ai/t/task_01JD8X9B4Q2M7T8N3K5P6R1S0V/5f2b8c1e9d3a4f6b8a7c0d1e2f3a4b5c/0.png",
      "content_type": "image/png",
      "width": 2048,
      "height": 2048
    }
  ],
  "outputs_deleted": false,
  "error": null,
  "cost": { "amount": "0.0280", "currency": "USD", "status": "settled" },
  "metadata": { "order_id": "A1001" },
  "warnings": [],
  "created_at": "2026-11-20T08:01:02Z",
  "started_at": "2026-11-20T08:01:02Z",
  "completed_at": "2026-11-20T08:01:10Z",
  "expires_at": "2026-11-27T08:01:10Z"
}
```
```json
{
  "id": "task_01JD8XC7M2N4P6Q8R0S2T4V6W8",
  "object": "task",
  "model": "bytedance/seedream-5.5",
  "status": "failed",
  "source": "api",
  "format": "unified",
  "input": {
    "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
    "size": "2K"
  },
  "outputs": [],
  "outputs_deleted": false,
  "error": {
    "code": "content_violation",
    "message": "The prompt, an input file or the result did not pass content moderation. Change the content and try again."
  },
  "cost": { "amount": "0.0000", "currency": "USD", "status": "refunded" },
  "metadata": { "order_id": "A1001" },
  "warnings": [],
  "created_at": "2026-11-20T08:02:15Z",
  "started_at": "2026-11-20T08:02:15Z",
  "completed_at": "2026-11-20T08:02:19Z",
  "expires_at": null
}
```


Cada entrega también incluye los encabezados `webhook-id`, `webhook-timestamp` y `webhook-signature`, que se describen a continuación.

<a id="verification"></a>

## Verificación de firma (Standard Webhooks)
Cada entrega se firma según la especificación [Standard Webhooks](https://www.standardwebhooks.com/) e incluye tres encabezados. Verificar la firma es opcional, pero recomendable: demuestra que la entrega procede de Kerox.

| Encabezado | Valor |
| --- | --- |
| `webhook-id` | ID único de entrega (`msg_...`), que no cambia entre reintentos; úsalo para la deduplicación |
| `webhook-timestamp` | Marca de tiempo Unix (en segundos) que indica cuándo se generó la firma |
| `webhook-signature` | Una o más firmas con formato `v1,<base64>`, separadas por espacios (aparecen dos durante las 24 h posteriores a una rotación de claves, en las que la clave anterior y la nueva están activas a la vez) |

La cadena que se firma es `{webhook-id}.{webhook-timestamp}.{raw_body}`. Se firma con **HMAC-SHA256** usando como clave tu secreto de firma (disponible en [Consola → API → Webhook](https://kerox.ai/es/console/webhooks)): primero elimina el prefijo `whsec_` y luego decodifica en base64 el resto para obtener los bytes de la clave.

> **Verifica el cuerpo sin procesar de la solicitud**
>
> Calcula el HMAC sobre los bytes UTF-8 exactos del cuerpo, tal como llegaron, antes de analizar o volver a serializar el JSON. Rechaza las marcas de tiempo que difieran en más de 5 minutos de la hora actual para evitar ataques de repetición.

<a id="sdk-verify"></a>

### Verificar con el SDK de Standard Webhooks
```javascript
import { Webhook } from 'standardwebhooks';

const wh = new Webhook(process.env.KEROX_WEBHOOK_SECRET);

export async function handleKeroxWebhook(rawBody, headers) {
  // Throws if the signature is invalid or the timestamp is outside the 5-minute window.
  const task = wh.verify(rawBody, {
    'webhook-id': headers['webhook-id'],
    'webhook-timestamp': headers['webhook-timestamp'],
    'webhook-signature': headers['webhook-signature'],
  });
  console.log(task.id, task.status);
}
```
```python
import os
from standardwebhooks.webhooks import Webhook

wh = Webhook(os.environ["KEROX_WEBHOOK_SECRET"])

def handle_kerox_webhook(raw_body: bytes, headers: dict[str, str]):
    task = wh.verify(raw_body, headers)
    print(task["id"], task["status"])
```


<a id="manual-verify"></a>

### Verificar manualmente con el módulo crypto integrado
```javascript
import crypto from 'node:crypto';

export function verifyKeroxSignature(rawBody, headers, secret) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signatureHeader = headers['webhook-signature'];
  if (!id || !timestamp || !signatureHeader) {
    throw new Error('Missing webhook signature headers');
  }

  const ageSeconds = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
  if (!Number.isFinite(ageSeconds) || ageSeconds > 300) {
    throw new Error('Webhook timestamp outside tolerance');
  }

  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = crypto
    .createHmac('sha256', key)
    .update(`${id}.${timestamp}.${rawBody}`)
    .digest();

  const valid = signatureHeader.split(' ').some((entry) => {
    const [version, sig] = entry.split(',');
    if (version !== 'v1' || !sig) return false;
    const actual = Buffer.from(sig, 'base64');
    return actual.length === expected.length && crypto.timingSafeEqual(actual, expected);
  });

  if (!valid) throw new Error('Invalid webhook signature');
  return JSON.parse(rawBody);
}
```
```python
import base64
import hashlib
import hmac
import json
import time

def verify_kerox_signature(raw_body: str, headers: dict[str, str], secret: str):
    msg_id = headers.get("webhook-id", "")
    timestamp = headers.get("webhook-timestamp", "")
    sig_header = headers.get("webhook-signature", "")
    if not (msg_id and timestamp and sig_header):
        raise ValueError("Missing webhook signature headers")

    if abs(int(time.time()) - int(timestamp)) > 300:
        raise ValueError("Webhook timestamp outside tolerance")

    key = base64.b64decode(secret.removeprefix("whsec_"))
    expected = hmac.new(
        key,
        f"{msg_id}.{timestamp}.{raw_body}".encode("utf-8"),
        hashlib.sha256,
    ).digest()

    for entry in sig_header.split(" "):
        parts = entry.split(",", 1)
        if len(parts) != 2 or parts[0] != "v1":
            continue
        if hmac.compare_digest(base64.b64decode(parts[1]), expected):
            return json.loads(raw_body)

    raise ValueError("Invalid webhook signature")
```


<a id="retries"></a>

## Reintentos, rotación y buenas prácticas
- **Criterios de éxito**: Devuelve cualquier respuesta HTTP `2xx` en un plazo de **10 segundos**. Cualquier respuesta con un código distinto de 2xx, o cualquier caso en que se agote el tiempo de espera, se considera fallida.
- **Calendario de reintentos**: Intervalos de espera que aumentan progresivamente entre reintentos: `1m, 5m, 15m, 30m, 1h, 2h, 3h, 4h, 4h, 4h, 4h`, con hasta **12 intentos** durante unas 24 horas. Las entregas se conservan durante 7 días, y una entrega fallida se puede reenviar desde [Consola → API → Webhook](https://kerox.ai/es/console/webhooks).
- **Rotación del secreto**: Al rotar tu secreto de firma en la consola, el secreto anterior sigue siendo válido durante **24 horas**, periodo en el que `webhook-signature` incluye ambas `v1,...` firmas separadas por un espacio.
- **Idempotencia**: Usa `webhook-id` para reconocer las entregas duplicadas y evitar procesarlas más de una vez, confirma rápidamente con `200` y procesa las descargas de forma asíncrona. Siempre puedes recurrir a `GET /v1/tasks/{id}`.
