Webhooks

Real-time event notifications for your AI governance pipeline

Overview

Webhooks allow you to receive real-time HTTP notifications when events occur in your Tork AI Governance pipeline. Instead of polling the API, your server receives POST requests with event data whenever something important happens.

Real-time

Instant notifications when events occur

Secure

HMAC-SHA256 signature verification

Reliable

Automatic retries with exponential backoff

Webhook Events

Subscribe to the events that matter to your workflow. Each webhook can listen to multiple event types.

Governance Events

policy.violation

Triggered when content violates a configured policy rule. Includes policy details, violation type, and severity.

pii.detected

Triggered when personally identifiable information is detected in content. Includes detected entity types and confidence scores.

agent.blocked

Triggered when an AI agent action is blocked by governance rules. Includes the blocked action and reason.

Human-in-the-Loop Events

hitl.pending

Triggered when a request requires human review before proceeding.

hitl.approved

Triggered when a human reviewer approves a pending request.

hitl.rejected

Triggered when a human reviewer rejects a pending request.

System Events

circuit_breaker.triggered

Triggered when a circuit breaker opens due to repeated failures, temporarily blocking requests.

rate_limit.exceeded

Triggered when rate limits are exceeded for an API key or IP address.

security.alert

Triggered for security-related events such as suspicious activity or authentication anomalies.

Setting Up Webhooks

1. Create a Webhook Endpoint

bash
curl -X POST https://api.tork.network/v1/webhooks \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production Alerts",
    "url": "https://your-server.com/webhook",
    "events": [
      "policy.violation",
      "pii.detected",
      "security.alert"
    ]
  }'

2. Store the Secret Securely

The response includes a secret that you must store securely. This secret is only shown once and is used to verify webhook signatures.

json
{
  "id": "wh_abc123",
  "name": "Production Alerts",
  "url": "https://your-server.com/webhook",
  "events": ["policy.violation", "pii.detected", "security.alert"],
  "secret": "whsec_a1b2c3d4e5f6...",
  "is_active": true,
  "created_at": "2026-01-21T12:00:00Z",
  "message": "Webhook created. Save the secret - it will not be shown again."
}
Important

Store your webhook secret in a secure environment variable. Never commit it to source control or expose it in client-side code.

Webhook Payload

All webhook payloads follow a consistent structure with event metadata and event-specific data:

json
{
  "id": "evt_xyz789",
  "event": "policy.violation",
  "timestamp": "2026-01-21T12:30:45Z",
  "organization_id": "org_abc123",
  "data": {
    "policy_id": "pol_001",
    "policy_name": "PII Protection Policy",
    "violation_type": "pii_detected",
    "severity": "high",
    "content_preview": "The user's SSN is...",
    "agent_id": "agent_456",
    "request_id": "req_789",
    "metadata": {
      "detected_entities": ["ssn", "phone_number"],
      "confidence": 0.95
    }
  }
}

HTTP Headers

HeaderDescription
X-Tork-SignatureHMAC-SHA256 signature for verification
X-Tork-EventThe event type (e.g., policy.violation)
X-Tork-Delivery-IDUnique ID for this delivery attempt
X-Tork-TimestampISO 8601 timestamp of the event

Signature Verification

Always verify webhook signatures to ensure requests are from Tork. The signature uses HMAC-SHA256 with your webhook secret.

javascript
const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret, tolerance = 300) {
  const parts = signature.split(',');
  const timestamp = parseInt(parts.find(p => p.startsWith('t='))?.replace('t=', '') || '0');
  const sig = parts.find(p => p.startsWith('v1='))?.replace('v1=', '') || '';

  // Check timestamp tolerance (default 5 minutes)
  const now = Math.floor(Date.now() / 1000);
  if (Math.abs(now - timestamp) > tolerance) {
    throw new Error('Webhook timestamp too old');
  }

  // Compute expected signature
  const signedPayload = `${timestamp}.${payload}`;
  const expectedSig = crypto
    .createHmac('sha256', secret)
    .update(signedPayload)
    .digest('hex');

  // Constant-time comparison
  if (!crypto.timingSafeEqual(Buffer.from(sig, 'hex'), Buffer.from(expectedSig, 'hex'))) {
    throw new Error('Invalid webhook signature');
  }

  return true;
}

// Express.js example
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
  const signature = req.headers['x-tork-signature'];
  const payload = req.body.toString();

  try {
    verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET);
    const event = JSON.parse(payload);

    // Handle the event
    switch (event.event) {
      case 'policy.violation':
        handlePolicyViolation(event.data);
        break;
      case 'pii.detected':
        handlePiiDetected(event.data);
        break;
      // ... handle other events
    }

    res.status(200).json({ received: true });
  } catch (err) {
    console.error('Webhook error:', err.message);
    res.status(400).json({ error: err.message });
  }
});

Retry Policy

Tork automatically retries failed webhook deliveries with exponential backoff:

AttemptDelayRetry Condition
1st retry1 second5xx error or timeout
2nd retry5 seconds5xx error or timeout
3rd retry30 seconds5xx error or timeout

4xx errors are not retried as they indicate a client-side issue. Ensure your endpoint returns a 2xx status code to acknowledge receipt.

Best Practices

  • Always verify signatures - Never process webhooks without verifying the HMAC signature
  • Respond quickly - Return a 2xx response within 10 seconds; process asynchronously if needed
  • Handle duplicates - Use the delivery ID to deduplicate; webhooks may be sent more than once
  • Use HTTPS - Webhook URLs must use HTTPS in production for security
  • Rotate secrets periodically - Use the API to rotate your webhook secret regularly
  • Monitor delivery logs - Check the deliveries endpoint to track webhook health
  • Implement idempotency - Design handlers to safely process the same event multiple times

API Reference

Endpoints

MethodEndpointDescription
GET/v1/webhooksList all webhooks
POST/v1/webhooksCreate a webhook
GET/v1/webhooks/:idGet webhook details
PATCH/v1/webhooks/:idUpdate a webhook
DELETE/v1/webhooks/:idDelete a webhook
POST/v1/webhooks/:id/testSend a test webhook
GET/v1/webhooks/:id/deliveriesGet delivery history

Documentation

Learn to integrate TORK

Upgrade Plan

Current: free

Support

Get help from our team