Skip to content

Webhooks

A webhook endpoint is an HTTPS URL on your server that receives an event each time a generation reaches a final status. Events are signed with Standard Webhooks, so any Standard Webhooks library can verify them.

create-endpoint.sh
# Registers your HTTPS endpoint for final generation events. The response holds the signing secret, once.
set -euo pipefail
API="${HL_API_BASE:-https://api.halationlab.ai/v1}"
curl -sS --fail-with-body "$API/webhook_endpoints" \
-H "Authorization: Bearer $HALATIONLAB_API_KEY" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d "{ \"url\": \"$HL_WEBHOOK_URL\", \"events\": [\"generation.completed\", \"generation.failed\", \"generation.canceled\"] }"
  • url must be a public HTTPS URL on port 443.
  • events defaults to the three final events: generation.completed, generation.failed and generation.canceled. generation.updated fires on every status change.
  • projects limits events to some projects. By default the endpoint receives events from every project the credential can see.

The response holds the signing secret (whsec_…) once. Store it with your other secrets; it is not shown again. An endpoint belongs to the credential that created it: an API key, or an OAuth app’s connection to one user. List endpoints with GET /v1/webhook_endpoints and remove one with DELETE /v1/webhook_endpoints/{id}.

Each delivery is a POST of the event object:

{
"id": "evt_01JD3Y5RJ6M3XW6J8K2N4P7Q9T",
"object": "event",
"type": "generation.completed",
"created_at": "2026-11-28T10:41:12Z",
"data": { "id": "gen_01JD3Y5RJ6M3XW6J8K2N4P7Q9T", "object": "generation", "status": "completed", "outputs": ["…"], "cost": { "quoted_max": 380, "charged": 372, "final": true } }
}

data is the whole generation, as GET /v1/generations/{id} returned it at the time, so no follow-up call is needed. Its output URLs expire after an hour like any other.

With these headers:

Header Value
webhook-id The event ID. The same on every retry of this event.
webhook-timestamp Unix seconds when this attempt was signed.
webhook-signature v1,<base64>. During a secret rotation, several space-separated signatures.

The signature is the base64 HMAC-SHA256 of ${webhook-id}.${webhook-timestamp}.${raw body}, keyed with the base64-decoded part of the secret after whsec_. Accept the delivery if any v1 signature matches, and reject timestamps more than 5 minutes from now.

TypeScript, with node:crypto only:

verify.ts
// Verifies a HalationLab.ai webhook (Standard Webhooks) with node:crypto only. Run it to check it against a signed
// test event: `node verify.ts` (Node 22.18+) or `npx tsx verify.ts`.
import { createHmac, timingSafeEqual } from 'node:crypto';
const TOLERANCE_SECONDS = 5 * 60;
/** Returns the event if the signature is valid and fresh; throws otherwise. `rawBody` must be the exact bytes received. */
export function verifyWebhook(rawBody: string, headers: Record<string, string | undefined>, secret: string, nowSeconds = Date.now() / 1000) {
const id = headers['webhook-id'];
const timestamp = headers['webhook-timestamp'];
const signatures = headers['webhook-signature'];
if (!id || !timestamp || !signatures) throw new Error('Missing webhook-id, webhook-timestamp or webhook-signature.');
if (Math.abs(nowSeconds - Number(timestamp)) > TOLERANCE_SECONDS) throw new Error('Timestamp is more than 5 minutes from now.');
// The key is the base64-decoded part of the secret after `whsec_`.
const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
const expected = createHmac('sha256', key).update(`${id}.${timestamp}.${rawBody}`).digest();
// During a secret rotation the header carries several space-separated `v1,<base64>` signatures.
const valid = signatures.split(' ').some(entry => {
const [version, signature] = entry.split(',');
if (version !== 'v1' || !signature) return false;
const received = Buffer.from(signature, 'base64');
return received.length === expected.length && timingSafeEqual(received, expected);
});
if (!valid) throw new Error('No valid signature.');
return JSON.parse(rawBody) as { id: string; type: string; created_at: string; data: Record<string, unknown> };
}
// Self-check with a test secret: a correctly signed event passes, a tampered body fails.
if (import.meta.url === new URL(`file://${process.argv[1]}`).href) {
const secret = `whsec_${Buffer.from('test-secret-for-the-docs-sample').toString('base64')}`;
const body = JSON.stringify({ id: 'evt_01JD3Y5RJ6M3XW6J8K2N4P7Q9T', object: 'event', type: 'generation.completed', created_at: '2026-11-28T10:41:12Z', data: {} });
const timestamp = String(Math.floor(Date.now() / 1000));
const key = Buffer.from(secret.slice('whsec_'.length), 'base64');
const signature = createHmac('sha256', key).update(`evt_01JD3Y5RJ6M3XW6J8K2N4P7Q9T.${timestamp}.${body}`).digest('base64');
const headers = { 'webhook-id': 'evt_01JD3Y5RJ6M3XW6J8K2N4P7Q9T', 'webhook-timestamp': timestamp, 'webhook-signature': `v1,${signature}` };
console.log('valid event:', verifyWebhook(body, headers, secret).type);
try { verifyWebhook(body.replace('completed', 'failed'), headers, secret); throw new Error('tampered body was accepted'); }
catch (e) { if ((e as Error).message !== 'No valid signature.') throw e; console.log('tampered body rejected'); }
}

Python, with the standard library only:

verify.py
# Verifies a HalationLab.ai webhook (Standard Webhooks) with the standard library only. Run it to check it against a
# signed test event: python3 verify.py
import base64
import hashlib
import hmac
import json
import time
TOLERANCE_SECONDS = 5 * 60
def verify_webhook(raw_body: bytes, headers: dict, secret: str, now: float | None = None) -> dict:
"""Returns the event if the signature is valid and fresh; raises ValueError otherwise.
`raw_body` must be the exact bytes received; `headers` keys are lower case.
"""
msg_id = headers.get("webhook-id")
timestamp = headers.get("webhook-timestamp")
signatures = headers.get("webhook-signature")
if not msg_id or not timestamp or not signatures:
raise ValueError("Missing webhook-id, webhook-timestamp or webhook-signature.")
if abs((now or time.time()) - int(timestamp)) > TOLERANCE_SECONDS:
raise ValueError("Timestamp is more than 5 minutes from now.")
# The key is the base64-decoded part of the secret after `whsec_`.
key = base64.b64decode(secret.removeprefix("whsec_"))
signed = msg_id.encode() + b"." + timestamp.encode() + b"." + raw_body
expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
# During a secret rotation the header carries several space-separated `v1,<base64>` signatures.
for entry in signatures.split(" "):
version, _, signature = entry.partition(",")
if version == "v1" and hmac.compare_digest(signature, expected):
return json.loads(raw_body)
raise ValueError("No valid signature.")
if __name__ == "__main__":
# Self-check with a test secret: a correctly signed event passes, a tampered body fails.
secret = "whsec_" + base64.b64encode(b"test-secret-for-the-docs-sample").decode()
body = json.dumps({"id": "evt_01JD3Y5RJ6M3XW6J8K2N4P7Q9T", "object": "event", "type": "generation.completed",
"created_at": "2026-11-28T10:41:12Z", "data": {}}).encode()
ts = str(int(time.time()))
key = base64.b64decode(secret.removeprefix("whsec_"))
sig = base64.b64encode(hmac.new(key, b"evt_01JD3Y5RJ6M3XW6J8K2N4P7Q9T." + ts.encode() + b"." + body, hashlib.sha256).digest()).decode()
headers = {"webhook-id": "evt_01JD3Y5RJ6M3XW6J8K2N4P7Q9T", "webhook-timestamp": ts, "webhook-signature": f"v1,{sig}"}
print("valid event:", verify_webhook(body, headers, secret)["type"])
try:
verify_webhook(body.replace(b"completed", b"failed"), headers, secret)
raise SystemExit("tampered body was accepted")
except ValueError:
print("tampered body rejected")

With the SDKs:

verify-sdk.ts
// Verifies a webhook with the TypeScript SDK. Pass the raw body exactly as received, not re-serialised JSON.
import { HalationLab } from '@halationlab/sdk';
const hl = new HalationLab({ apiKey: process.env.HALATIONLAB_API_KEY });
export async function handle(rawBody: string, headers: Record<string, string>) {
// Rejects if the signature or timestamp is not valid.
const event = await hl.webhooks.verify(rawBody, headers, process.env.HL_WEBHOOK_SECRET!);
return event;
}
verify-sdk.py
# Verifies a webhook with the Python SDK. Pass the raw body exactly as received, not re-serialised JSON.
import os
import halationlab
def handle(raw_body: bytes, headers: dict) -> dict:
# Raises if the signature or timestamp is not valid.
return halationlab.webhooks.verify(raw_body, headers, os.environ["HL_WEBHOOK_SECRET"])
  • Answer with any 2xx within 10 seconds. Do slow work after answering.
  • Delivery is at least once and unordered. Deduplicate on webhook-id, for example with a unique key in your database.
  • Failed deliveries are retried with backoff for about a day. A delivery never re-runs paid work.
  • After repeated failures the endpoint’s status becomes failing; deliveries continue.

A minimal receiver:

handler.ts
// A minimal webhook receiver with node:http: verify the signature on the raw body, deduplicate on webhook-id,
// answer 2xx quickly, then do the work. Run: HL_WEBHOOK_SECRET=whsec_... node handler.ts
import { createServer } from 'node:http';
import { verifyWebhook } from './verify.ts';
const secret = process.env.HL_WEBHOOK_SECRET!;
// Use a durable store (a database table with a unique key) in production; deliveries are at-least-once.
const seen = new Set<string>();
createServer((req, res) => {
const chunks: Buffer[] = [];
req.on('data', chunk => chunks.push(chunk));
req.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
let event;
try {
event = verifyWebhook(raw, req.headers as Record<string, string>, secret);
} catch {
res.writeHead(400).end();
return;
}
const id = req.headers['webhook-id'] as string;
res.writeHead(204).end(); // Acknowledge within 10 seconds; do slow work afterwards.
if (seen.has(id)) return;
seen.add(id);
if (event.type === 'generation.completed') {
const generation = event.data as { id: string; outputs: { url: string }[] };
console.log('completed', generation.id, generation.outputs.map(o => o.url));
}
});
}).listen(Number(process.env.PORT ?? 8080));

GET /v1/events lists events oldest first, kept for 14 days. Store the last next_cursor and pass it as cursor next time to read only what is new:

list-events.sh
# Reads the event feed, oldest first, to catch up after missed webhooks. Store next_cursor and pass it as cursor next time.
set -euo pipefail
API="${HL_API_BASE:-https://api.halationlab.ai/v1}"
CURSOR="${HL_EVENTS_CURSOR:-}"
curl -sS --fail-with-body "$API/events?limit=50${CURSOR:+&cursor=$CURSOR}" \
-H "Authorization: Bearer $HALATIONLAB_API_KEY"