Browse all docs & guides
On this page
CORE CONCEPTS

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.

Reviewed 2026-12-02
AGENT PROMPT · PASTE INTO YOUR AGENT OR AUTO-READ
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.
View raw .md ↗

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:

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"]
  }'

Supported webhookEvents (5 events)

EventIncluded by Default?Trigger
generation.startedNoJob transitioned into upstream execution
generation.completedYesJob reached status: "succeeded" (delivery may still be pending)
generation.failedYesJob reached status: "failed"
generation.cancelledYesJob reached status: "cancelled"
generation.delivery_readyNoPrivate 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:

HeaderDescription
X-OpenGen-Webhook-Request-IdUnique delivery UUID (idempotency / deduplication key; matches JSON body.id)
X-OpenGen-Webhook-Workspace-IdOwning workspace ID (matches JSON body.workspaceId)
X-OpenGen-Webhook-TimestampUnix timestamp in whole seconds (used for replay window checks)
X-OpenGen-Webhook-Key-IdActive signing key kid matching an entry in /.well-known/webhook-jwks.json
X-OpenGen-Webhook-Signature128-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):

Example
${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.
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;
}

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.