# Webhooks & Ed25519 Verification

> OpenGen sends per-request generation lifecycle webhooks to public HTTPS destinations supplied via webhookUrl and webhookEvents on POST /v1/generations or MCP generate. Every delivery is signed with Ed25519 keys published at GET /.well-known/webhook-jwks.json using five X-OpenGen-Webhook-* headers over the raw UTF-8 body, with replay protection and up to eight retry attempts.

## Agent Prompt

```text
Configure and verify OpenGen per-request webhooks using https://opengen.dev/docs/webhooks:
1. Pass webhookUrl (public HTTPS on port 443, no credentials or fragments) and optional webhookEvents (subset of generation.started, generation.completed, generation.failed, generation.cancelled, generation.delivery_ready) on POST https://opengen.dev/v1/generations or MCP generate — remember webhookUrl and webhookEvents are part of the canonical Idempotency-Key request hash.
2. Always verify inbound deliveries using the exact raw UTF-8 body BEFORE JSON parsing: check the 5 X-OpenGen-Webhook-* headers, enforce a replay window (e.g. +/- 300s), fetch/cache public Ed25519 keys from GET https://opengen.dev/.well-known/webhook-jwks.json (refreshing on unknown kid), verify the 128-char lowercase hex signature over `${requestId}\n${workspaceId}\n${timestamp}\n${sha256Hex(rawBody)}`, and deduplicate by body.id.
3. Never expect prompts or signed output URLs inside webhook payloads; fetch GET https://opengen.dev/v1/generations/{jobId} separately to retrieve fresh private media links.
```

## Registering a per-request webhook

OpenGen delivers generation lifecycle events strictly via **per-request ad-hoc webhooks** (legacy workspace webhook subscription CRUD is retired). Supply `webhookUrl` and optional `webhookEvents` directly on `POST /v1/generations` or MCP `generate`:

```bash tab="cURL"
curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/generations" \
  -H "Authorization: Bearer $OPENGEN_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: webhook-demo-001" \
  -d '{
    "modelId": "bytedance/seedance-2.5",
    "operation": "text-to-video",
    "input": {
      "prompt": "Aerial tracking shot along a misty basalt coastline at sunrise",
      "resolution": "720p",
      "duration": 5,
      "aspectRatio": "16:9"
    },
    "billing": "managed",
    "maxCostMicros": 1500000,
    "webhookUrl": "https://hooks.example.com/opengen",
    "webhookEvents": ["generation.completed", "generation.failed", "generation.delivery_ready"]
  }'
```

```ts tab="TypeScript"
const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';

const job = await fetch(`${baseUrl}/v1/generations`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': 'webhook-demo-001',
  },
  body: JSON.stringify({
    modelId: 'bytedance/seedance-2.5',
    operation: 'text-to-video',
    input: {
      prompt: 'Aerial tracking shot along a misty basalt coastline at sunrise',
      resolution: '720p',
      duration: 5,
      aspectRatio: '16:9',
    },
    billing: 'managed',
    maxCostMicros: 1500000,
    webhookUrl: 'https://hooks.example.com/opengen',
    webhookEvents: ['generation.completed', 'generation.failed', 'generation.delivery_ready'],
  }),
}).then((r) => r.json());

console.log(job.id, job.status);
```

```python tab="Python"
import os
import httpx

base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")

response = httpx.post(
    f"{base_url}/v1/generations",
    headers={
        "Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}",
        "Idempotency-Key": "webhook-demo-001",
    },
    json={
        "modelId": "bytedance/seedance-2.5",
        "operation": "text-to-video",
        "input": {
            "prompt": "Aerial tracking shot along a misty basalt coastline at sunrise",
            "resolution": "720p",
            "duration": 5,
            "aspectRatio": "16:9",
        },
        "billing": "managed",
        "maxCostMicros": 1500000,
        "webhookUrl": "https://hooks.example.com/opengen",
        "webhookEvents": [
            "generation.completed",
            "generation.failed",
            "generation.delivery_ready",
        ],
    },
    timeout=30.0,
)
response.raise_for_status()
print(response.json()["id"])
```

```json tab="MCP"
{
  "tool": "generate",
  "arguments": {
    "modelId": "bytedance/seedance-2.5",
    "operation": "text-to-video",
    "input": {
      "prompt": "Aerial tracking shot along a misty basalt coastline at sunrise",
      "resolution": "720p",
      "duration": 5,
      "aspectRatio": "16:9"
    },
    "billing": "managed",
    "maxCostMicros": 1500000,
    "webhookUrl": "https://hooks.example.com/opengen",
    "webhookEvents": ["generation.completed", "generation.failed", "generation.delivery_ready"],
    "idempotencyKey": "webhook-demo-001"
  }
}
```

### Supported `webhookEvents` (5 events)

| Event                       | Included by Default? | Trigger                                                                    |
| --------------------------- | -------------------- | -------------------------------------------------------------------------- |
| `generation.started`        | No                   | Job transitioned into upstream execution                                   |
| `generation.completed`      | **Yes**              | Job reached `status: "succeeded"` (delivery may still be `pending`)        |
| `generation.failed`         | **Yes**              | Job reached `status: "failed"`                                             |
| `generation.cancelled`      | **Yes**              | Job reached `status: "cancelled"`                                          |
| `generation.delivery_ready` | No                   | Private output capture completed and `deliveryStatus` became `"available"` |

When `webhookEvents` is omitted alongside `webhookUrl`, OpenGen defaults to `["generation.completed", "generation.failed", "generation.cancelled"]`. Supplying `webhookEvents` without `webhookUrl` fails validation with `400 invalid_generation` (`field: "webhookEvents"`). Both `webhookUrl` and `webhookEvents` are hashed into `Idempotency-Key` validation — changing either on a replay returns `409 idempotency_conflict`.

### Destination security rules

- Must be a public `https://` URL on port `443` (max 2,048 characters), without embedded credentials (userinfo) or `#fragments`.
- DNS is re-resolved on submission and on every delivery attempt; all resolved answers are validated against local, private, link-local, mapped, transition, and reserved IP ranges, and the TLS connection is pinned to a validated public IP.
- HTTP redirects are never followed and count as failed delivery attempts.

## Payload envelope

OpenGen sends a compact UTF-8 JSON body. Prompts, credentials, signed output URLs, and private supplier cost internals are **never** placed in webhook payloads. Fetch `GET /v1/generations/{jobId}` separately to obtain fresh short-lived signed `/media` links.

```json
{
  "id": "8e31c7f2-6d5c-4c36-9f64-29f2d8d5f210",
  "jobId": "00000000-0000-4000-8000-000000000001",
  "workspaceId": "ws_demo",
  "event": "generation.delivery_ready",
  "createdAt": "2026-12-02T12:00:00.000Z",
  "data": {
    "jobId": "00000000-0000-4000-8000-000000000001",
    "status": "succeeded",
    "deliveryStatus": "available"
  }
}
```

## Public Ed25519 JWKS endpoint & 5 signature headers

OpenGen publishes active and rotated Ed25519 verification keys unauthenticated at **`GET /.well-known/webhook-jwks.json`** (`Cache-Control: public, max-age=3600`, `Access-Control-Allow-Origin: *`) as an RFC 7517 JWK Set (`kty: "OKP"`, `crv: "Ed25519"`, `alg: "EdDSA"`, `use: "sig"`, `kid`, `x`). Private key material (`d`) is never exposed.

Every outbound webhook `POST` includes exactly five verification headers:

| Header                           | Description                                                                    |
| -------------------------------- | ------------------------------------------------------------------------------ |
| `X-OpenGen-Webhook-Request-Id`   | Unique delivery UUID (idempotency / deduplication key; matches JSON `body.id`) |
| `X-OpenGen-Webhook-Workspace-Id` | Owning workspace ID (matches JSON `body.workspaceId`)                          |
| `X-OpenGen-Webhook-Timestamp`    | Unix timestamp in whole seconds (used for replay window checks)                |
| `X-OpenGen-Webhook-Key-Id`       | Active signing key `kid` matching an entry in `/.well-known/webhook-jwks.json` |
| `X-OpenGen-Webhook-Signature`    | **128-character lowercase hex** Ed25519 signature (64 raw bytes)               |

### Canonical signing string

Compute the signed UTF-8 message from the **exact raw UTF-8 request body bytes** (before calling `JSON.parse`):

```text
${X-OpenGen-Webhook-Request-Id}\n${X-OpenGen-Webhook-Workspace-Id}\n${X-OpenGen-Webhook-Timestamp}\n${sha256Hex(rawBody)}
```

Where `sha256Hex(rawBody)` is the 64-character lowercase hexadecimal SHA-256 digest of the raw body bytes, and `\n` is a single ASCII line feed (`0x0a`).

## Verifying Ed25519 signatures (Node.js & Python)

Follow these five checks on every inbound webhook request:

1. Reject any request missing one of the five headers, with a non-numeric timestamp, or outside your replay tolerance (recommended `±300` seconds).
2. Validate that `X-OpenGen-Webhook-Signature` is 128 hex characters (`64` bytes).
3. Look up the public Ed25519 JWK matching `X-OpenGen-Webhook-Key-Id` from `GET https://opengen.dev/.well-known/webhook-jwks.json` — refresh your cached JWKS once if the `kid` is unknown so key rotations succeed seamlessly.
4. Verify the Ed25519 signature over `${requestId}\n${workspaceId}\n${timestamp}\n${sha256Hex(rawBody)}`.
5. Parse JSON only after signature verification succeeds, assert `body.id === requestId` and `body.workspaceId === workspaceId`, **verify that `body.workspaceId` matches your configured trusted workspace (`OPENGEN_WORKSPACE_ID` or an explicit authorized-workspace allowlist — never skip this check, because OpenGen signing keys are gateway-wide and another workspace can point callbacks at your URL)**, and deduplicate by `body.id` transactionally with your business side effect.

```ts tab="TypeScript"
import { createHash, createPublicKey, verify, type JsonWebKey } from 'node:crypto';

interface WebhookPublicJwk {
  kty: 'OKP';
  crv: 'Ed25519';
  alg: 'EdDSA';
  use: 'sig';
  kid: string;
  x: string;
}

const JWKS_URL = 'https://opengen.dev/.well-known/webhook-jwks.json';
const JWKS_TTL_MS = 5 * 60 * 1000;
let cachedJwks: { fetchedAt: number; keys: Map<string, WebhookPublicJwk> } | null = null;

async function loadKey(kid: string): Promise<WebhookPublicJwk | undefined> {
  const now = Date.now();
  const isFresh = cachedJwks !== null && now - cachedJwks.fetchedAt < JWKS_TTL_MS;
  if (isFresh && cachedJwks!.keys.has(kid)) {
    return cachedJwks!.keys.get(kid);
  }
  // Refresh when the TTL has expired (evicting removed/revoked keys) or on an unknown kid during rotation.
  const res = await fetch(JWKS_URL, { cache: 'no-store' });
  if (!res.ok) throw new Error(`Failed to fetch JWKS (${res.status})`);
  const jwks = (await res.json()) as { keys: WebhookPublicJwk[] };
  const nextKeys = new Map<string, WebhookPublicJwk>();
  for (const key of jwks.keys) {
    if (key.kty === 'OKP' && key.crv === 'Ed25519' && key.kid) {
      nextKeys.set(key.kid, key);
    }
  }
  cachedJwks = { fetchedAt: now, keys: nextKeys };
  return nextKeys.get(kid);
}

export async function verifyOpenGenWebhook(
  headers: Record<string, string | undefined>,
  rawBody: string | Uint8Array,
  expectedWorkspaceId: string = process.env.OPENGEN_WORKSPACE_ID?.trim() ?? '',
  maxSkewSeconds = 300,
): Promise<{ id: string; jobId: string; workspaceId: string; event: string; data: unknown }> {
  const trustedWorkspaceId = expectedWorkspaceId.trim();
  if (!trustedWorkspaceId) {
    throw new Error('OPENGEN_WORKSPACE_ID must be configured before accepting webhooks.');
  }
  const lowered = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
  const get = (name: string) => lowered[name.toLowerCase()];

  const requestId = get('X-OpenGen-Webhook-Request-Id');
  const workspaceId = get('X-OpenGen-Webhook-Workspace-Id');
  const timestamp = get('X-OpenGen-Webhook-Timestamp');
  const keyId = get('X-OpenGen-Webhook-Key-Id');
  const signatureHex = get('X-OpenGen-Webhook-Signature');

  if (!requestId || !workspaceId || !timestamp || !keyId || !signatureHex) {
    throw new Error('Missing required OpenGen webhook headers.');
  }
  if (!/^\d{1,15}$/.test(timestamp)) {
    throw new Error('Invalid webhook timestamp.');
  }
  const nowSeconds = Math.floor(Date.now() / 1000);
  if (Math.abs(nowSeconds - Number(timestamp)) > maxSkewSeconds) {
    throw new Error('Webhook timestamp outside replay window.');
  }
  if (!/^[0-9a-f]{128}$/.test(signatureHex)) {
    throw new Error('Invalid Ed25519 signature format.');
  }

  const jwk = await loadKey(keyId);
  if (!jwk || jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519') {
    throw new Error(`Unknown webhook signing key id: ${keyId}`);
  }

  const bodyHash = createHash('sha256').update(rawBody).digest('hex');
  const message = Buffer.from(`${requestId}\n${workspaceId}\n${timestamp}\n${bodyHash}`, 'utf8');
  const publicKey = createPublicKey({
    key: { kty: 'OKP', crv: 'Ed25519', x: jwk.x } as JsonWebKey,
    format: 'jwk',
  });
  const ok = verify(null, message, publicKey, Buffer.from(signatureHex, 'hex'));
  if (!ok) {
    throw new Error('Invalid OpenGen webhook signature.');
  }

  const payload = JSON.parse(
    typeof rawBody === 'string' ? rawBody : Buffer.from(rawBody).toString('utf8'),
  );
  if (payload.id !== requestId || payload.workspaceId !== workspaceId) {
    throw new Error('Webhook header and payload identity mismatch.');
  }
  if (payload.workspaceId !== trustedWorkspaceId) {
    throw new Error('Webhook workspaceId does not match the configured trusted workspace.');
  }
  return payload;
}
```

```python tab="Python"
import base64
import hashlib
import json
import os
import re
import time
from typing import Any, Optional

import httpx
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

JWKS_URL = "https://opengen.dev/.well-known/webhook-jwks.json"
_JWKS_TTL_SECONDS = 300.0
_CACHED_KEYS: dict[str, dict[str, Any]] = {}
_CACHED_AT: float = 0.0


def _b64url_decode(value: str) -> bytes:
    padding = "=" * (-len(value) % 4)
    return base64.urlsafe_b64decode(value + padding)


def _get_jwk(kid: str) -> dict[str, Any]:
    global _CACHED_AT
    now = time.monotonic()
    is_fresh = _CACHED_AT > 0.0 and (now - _CACHED_AT) < _JWKS_TTL_SECONDS
    if not is_fresh or kid not in _CACHED_KEYS:
        response = httpx.get(JWKS_URL, timeout=10.0)
        response.raise_for_status()
        refreshed: dict[str, dict[str, Any]] = {}
        for item in response.json().get("keys", []):
            if item.get("kty") == "OKP" and item.get("crv") == "Ed25519" and item.get("kid"):
                refreshed[item["kid"]] = item
        _CACHED_KEYS.clear()
        _CACHED_KEYS.update(refreshed)
        _CACHED_AT = now
    if kid not in _CACHED_KEYS:
        raise ValueError(f"Unknown webhook signing key id: {kid}")
    return _CACHED_KEYS[kid]


def verify_opengen_webhook(
    headers: dict[str, str],
    raw_body: bytes,
    expected_workspace_id: Optional[str] = None,
    max_skew_seconds: int = 300,
) -> dict[str, Any]:
    trusted_workspace_id = (
        expected_workspace_id
        if expected_workspace_id is not None
        else os.environ.get("OPENGEN_WORKSPACE_ID", "")
    ).strip()
    if not trusted_workspace_id:
        raise ValueError("OPENGEN_WORKSPACE_ID must be configured before accepting webhooks.")

    lowered = {k.lower(): v for k, v in headers.items()}
    request_id = lowered.get("x-opengen-webhook-request-id")
    workspace_id = lowered.get("x-opengen-webhook-workspace-id")
    timestamp = lowered.get("x-opengen-webhook-timestamp")
    key_id = lowered.get("x-opengen-webhook-key-id")
    signature_hex = lowered.get("x-opengen-webhook-signature")

    if not all([request_id, workspace_id, timestamp, key_id, signature_hex]):
        raise ValueError("Missing required OpenGen webhook headers.")
    if not re.fullmatch(r"\d{1,15}", timestamp):
        raise ValueError("Invalid webhook timestamp.")
    if abs(int(time.time()) - int(timestamp)) > max_skew_seconds:
        raise ValueError("Webhook timestamp outside replay window.")
    if not re.fullmatch(r"[0-9a-f]{128}", signature_hex):
        raise ValueError("Invalid Ed25519 signature format.")

    jwk = _get_jwk(key_id)
    public_key = Ed25519PublicKey.from_public_bytes(_b64url_decode(jwk["x"]))
    body_hash = hashlib.sha256(raw_body).hexdigest()
    message = f"{request_id}\n{workspace_id}\n{timestamp}\n{body_hash}".encode("utf-8")

    try:
        public_key.verify(bytes.fromhex(signature_hex), message)
    except InvalidSignature as exc:
        raise ValueError("Invalid OpenGen webhook signature.") from exc

    payload = json.loads(raw_body.decode("utf-8"))
    if payload.get("id") != request_id or payload.get("workspaceId") != workspace_id:
        raise ValueError("Webhook header and payload identity mismatch.")
    if payload.get("workspaceId") != trusted_workspace_id:
        raise ValueError("Webhook workspaceId does not match the configured trusted workspace.")
    return payload
```

> [!TIP]
> Building on Next.js App Router? Grab the complete copy-paste `app/api/webhooks/opengen/route.ts` handler in [Next.js Webhooks Guide](/docs/guides/webhooks-nextjs).

## Delivery semantics, retries, and key rotation

- **At-least-once delivery**: Return any `2xx` status within `10` seconds. Receiver response bodies are discarded and bounded to `8 KiB`.
- **Retry backoff schedule**: Non-2xx responses, redirects, and network errors retry up to **8 total attempts** with delays of `30 seconds`, `2 minutes`, `10 minutes`, `30 minutes`, `2 hours`, `6 hours`, and `24 hours`. Each retry preserves the exact `id` and JSON body while minting a fresh `X-OpenGen-Webhook-Timestamp` and `X-OpenGen-Webhook-Signature`.
- **Self-hosted key rotation**: Self-hosted operators configure `OPENGEN_WEBHOOK_SIGNING_KEYS_JSON` as a multi-key JSON array. The first entry with `active: true` signs new deliveries while older verification-only public keys remain published in `/.well-known/webhook-jwks.json` during the 24-hour+ retry grace window. See [Self-Hosting Guide](/docs/guides/self-hosting).
