# Webhook

> 완료된 작업 결과를 서버에서 바로 받을 수 있습니다. 제출 시 webhook_url을 전달하면 POST 요청을 한 번 받게 되며, 2xx로 응답하면 됩니다. 서명은 Standard Webhooks를 따릅니다.

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

## 3단계로 설정하기
> **Webhook URL은 콘솔이 아니라 요청에 지정합니다**
>
> 주소는 작업마다 `POST /v1/tasks`의 본문에 `webhook_url`로 지정합니다. 콘솔에서 설정하는 Webhook URL은 없습니다. [Console → API → Webhook](https://kerox.ai/ko/console/webhooks)에는 서명 시크릿과 최근 전송 내역만 보관됩니다.

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

### 1. 공개 HTTPS URL 준비하기
Kerox는 인터넷에서 접근할 수 있는 `https://` 주소로만 전송합니다(`localhost` 또는 사설 IP는 불가). 프로덕션 환경에서는 `https://your-app.example.com/webhooks/kerox`처럼 서버에서 요청을 받는 경로를 사용합니다. 로컬 컴퓨터에서 시험해 보려면 [webhook.site](https://webhook.site) 같은 임시 검사 도구로 수신 내용을 확인하거나, 터널(Cloudflare Tunnel, ngrok)을 사용해 3단계의 수신기에 연결하면 됩니다.

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

### 2. 제출 시 `webhook_url` 전달하기
제출 전에 `KEROX_WEBHOOK_URL`를 1단계에서 준비한 공개 HTTPS URL로 설정합니다(셸 예제에는 jq도 필요합니다). 반환된 작업 ID는 저장해 둡니다. 콜백이 늦어지면 해당 ID로 `GET /v1/tasks/{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. 수신하고 2xx로 응답하기
작업이 `succeeded` 또는 `failed` 상태로 끝나면 Kerox는 `Content-Type: application/json`와 함께 해당 URL로 `POST`를 한 번 전송합니다. 엔드포인트는 다음을 수행합니다.

1. 원본 요청 본문을 읽습니다.
2. 서명을 검증합니다(선택 사항, [아래 참조](#verification)).
3. 완료된 작업인지 확인하고(`status`가 `succeeded`이면서 `outputs`가 있거나, `failed`이면서 `error`가 있는 경우), 그 밖의 요청에는 `400`로 응답하여 잘못된 요청 하나로 인해 중단되지 않도록 합니다.
4. 이미 처리한 `webhook-id`는 건너뜁니다(재시도 시 동일한 값이 전달됩니다).
5. `2xx` 응답은 10초 이내에 반환하고, 시간이 오래 걸리는 작업(파일 다운로드)은 그 이후에 처리합니다.

그 외의 응답이나 10초 이내에 응답이 없으면 실패로 간주되어 재시도됩니다([재시도](#retries)). 다음은 `PORT`에 지정된 포트(기본 포트 8787)에서 수신 대기하며 `/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>

## 전송 내용
본문은 작업 객체 자체이며, `GET /v1/tasks/{id}`이 반환하는 것과 정확히 동일합니다([필드](https://kerox.ai/ko/docs/tasks.md#submit-response)). 성공과 실패는 `status`로 구분합니다. 성공 시 파일은 `outputs`에 있으며, 실패 시 사유는 `error`에 있고 보류 금액은 환불됩니다(`cost.status: "refunded"`). 두 가지 최종 상태만 각각 한 번씩 전송되며, `webhook_url` 없이 제출된 작업은 전송되지 않습니다.


```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
}
```


각 전송에는 아래에 설명된 `webhook-id`, `webhook-timestamp`, `webhook-signature` 헤더도 포함됩니다.

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

## 서명 검증(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}`이며, `whsec_` 접두사를 제거한 서명 시크릿([Console → API → Webhook](https://kerox.ai/ko/console/webhooks)에서 확인)을 base64로 디코딩한 바이트를 사용하여 **HMAC-SHA256**으로 서명합니다.

> **원본 요청 본문 검증**
>
> JSON을 파싱하거나 다시 직렬화하기 전에, 수신한 그대로의 UTF-8 바이트로 HMAC을 계산합니다. 재생 공격을 방지하기 위해 현재 시각과 5분 넘게 차이 나는 타임스탬프는 거부합니다.

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

### Standard Webhooks SDK로 검증하기
```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>

### 내장 crypto 모듈로 직접 검증하기
```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>

## 재시도, 키 교체 및 모범 사례
- **성공 기준**: **10초** 이내에 HTTP `2xx` 응답을 반환해야 합니다. 2xx가 아닌 응답이나 시간 초과는 실패로 처리됩니다.
- **재시도 일정**: `1m, 5m, 15m, 30m, 1h, 2h, 3h, 4h, 4h, 4h, 4h` 간격의 백오프로 약 24시간 동안 최대 **12회** 시도합니다. 전송 기록은 7일간 보관되며, 실패한 전송은 [Console → API → Webhook](https://kerox.ai/ko/console/webhooks)에서 다시 보낼 수 있습니다.
- **시크릿 교체**: 콘솔에서 서명 시크릿을 교체하면 이전 시크릿이 **24시간** 동안 유효하게 유지되며, 이 기간에는 `webhook-signature`에 두 개의 `v1,...` 서명이 공백으로 구분되어 포함됩니다.
- **멱등성**: `webhook-id` 기준으로 중복을 제거하고, `200`로 신속하게 응답한 뒤 다운로드는 비동기로 처리합니다. 언제든지 `GET /v1/tasks/{id}`로 대체할 수 있습니다.
