# Webhook 回调

> 在任务进入终态时接收主动推送，并按 Standard Webhooks 规范校验 HMAC-SHA256 签名。

## 事件类型与请求体

当任务进入终态时，Kerox 会向该任务的 `webhook_url`（任务没带时用你在[控制台 → API → Webhook](/console/webhooks)里设置的默认接收地址）发送 `POST` 请求，`Content-Type: application/json`。接收地址只接受 `https://`。`data` 是完整的任务对象，和 `GET /v1/tasks/{id}` 返回的一样：

- `task.succeeded`
- `task.failed`
- `task.canceled`

```json
{
  "type": "task.succeeded",
  "created_at": "2026-11-20T08:01:10Z",
  "data": {
    "id": "task_01JD8X9B4Q2M7T8N3K5P6R1S0V",
    "object": "task",
    "model": "bytedance/seedream-5.5",
    "status": "succeeded",
    "source": "api",
    "format": "native",
    "input": {
      "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
      "size": "2K"
    },
    "output": {
      "images": [
        {
          "url": "https://cdn.kerox.ai/t/task_01JD8X9B4Q2M7T8N3K5P6R1S0V/5f2b8c1e9d3a4f6b8a7c0d1e2f3a4b5c/0.png",
          "content_type": "image/png",
          "width": 2048,
          "height": 2048
        }
      ]
    },
    "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"
  }
}
```

## 签名校验（Standard Webhooks）

每次投递都按 [Standard Webhooks](https://www.standardwebhooks.com/) 规范签名，并附带三个请求头。验签是可选的，但推荐做：它能确认推送来自 Kerox。

| 请求头 | 说明 |
| --- | --- |
| `webhook-id` | 投递唯一 ID（`msg_...`），重试时保持不变，可直接用于幂等去重 |
| `webhook-timestamp` | 签发时的 Unix 秒级时间戳 |
| `webhook-signature` | 一个或多个以空格分隔的 `v1,<base64>` 签名（轮换密钥后的 24 小时重叠期内会同时携带两个） |

签名原文为 `{webhook-id}.{webhook-timestamp}.{raw_body}`，使用 **HMAC-SHA256** 计算，密钥是你的签名密钥（在[控制台 → API → Webhook](/console/webhooks)里查看）去掉 `whsec_` 前缀后 base64 解码得到的字节。

> **对原始请求体验签**
>
> 务必使用收到的原始 UTF-8 请求体字符串参与签名计算，不要先 JSON 解析再重新序列化。同时校验 `webhook-timestamp` 与当前时间的差值不超过 5 分钟，防止重放攻击。

### 使用 Standard Webhooks 官方库验签

```javascript

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

export async function handleKeroxWebhook(rawBody, headers) {
  // 签名无效或时间戳超出 5 分钟窗口时会自动抛出异常
  const event = wh.verify(rawBody, {
    'webhook-id': headers['webhook-id'],
    'webhook-timestamp': headers['webhook-timestamp'],
    'webhook-signature': headers['webhook-signature'],
  });
  console.log(event.type, event.data.id, event.data.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]):
    event = wh.verify(raw_body, headers)
    print(event["type"], event["data"]["id"], event["data"]["status"])
```

### 使用标准库手动验签

```javascript

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")
```

## 重试策略、密钥轮换与建议

- **成功判定**：**10 秒**内返回任意 `2xx` 状态码视为投递成功，其他状态码或超时均计为失败。
- **退避重试**：依次间隔 `1 分、5 分、15 分、30 分、1 时、2 时、3 时、4 时、4 时、4 时、4 时`，最多 **12 次**（约 24 小时）。投递记录保留 7 天，失败的投递可以在[控制台 → API → Webhook](/console/webhooks)里重新发送。
- **密钥轮换**：在控制台轮换签名密钥后，旧密钥会继续有效 **24 小时**，期间 `webhook-signature` 会以空格分隔同时附带新旧两个 `v1,...` 签名。
- **工程建议**：按 `webhook-id` 做幂等去重；收到后尽快返回 `200`，再异步下载结果文件；即使偶发漏收，也可以随时通过 `GET /v1/tasks/{id}` 兜底查询。
