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)
| 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 port443(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.
{
"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):
${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:
- Reject any request missing one of the five headers, with a non-numeric timestamp, or outside your replay tolerance (recommended
±300seconds). - Validate that
X-OpenGen-Webhook-Signatureis 128 hex characters (64bytes). - Look up the public Ed25519 JWK matching
X-OpenGen-Webhook-Key-IdfromGET https://opengen.dev/.well-known/webhook-jwks.json— refresh your cached JWKS once if thekidis unknown so key rotations succeed seamlessly. - Verify the Ed25519 signature over
${requestId}\n${workspaceId}\n${timestamp}\n${sha256Hex(rawBody)}. - Parse JSON only after signature verification succeeds, assert
body.id === requestIdandbody.workspaceId === workspaceId, **verify thatbody.workspaceIdmatches your configured trusted workspace (OPENGEN_WORKSPACE_IDor 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 bybody.idtransactionally 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
2xxstatus within10seconds. Receiver response bodies are discarded and bounded to8 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, and24 hours. Each retry preserves the exactidand JSON body while minting a freshX-OpenGen-Webhook-TimestampandX-OpenGen-Webhook-Signature. - Self-hosted key rotation: Self-hosted operators configure
OPENGEN_WEBHOOK_SIGNING_KEYS_JSONas a multi-key JSON array. The first entry withactive: truesigns new deliveries while older verification-only public keys remain published in/.well-known/webhook-jwks.jsonduring the 24-hour+ retry grace window. See Self-Hosting Guide.