TrimLynk Docs

TrimLynk Custom Webhook Integration Guide

TrimLynk's Custom Webhook Integration enables teams to stream real-time workspace lifecycle events (clicks, leads, sales, campaigns, links) directly to arbitrary external endpoints, API gateways, serverless handlers (AWS Lambda, Cloudflare Workers), or ingestion backends.


1. Overview & Capabilities

The custom_webhook provider connects TrimLynk's event bus directly to user-defined HTTPS endpoints with production-grade reliability, security controls, and operational observability.

PropertyValue
Provider IDcustom_webhook
Capabilitieswebhook, test, retry
Supported MethodsPOST
Target ProtocolHTTPS required (plain http:// blocked in production)
SSRF MitigationStrict loopback, RFC 1918, link-local, cloud metadata IP blocking
SigningHMAC-SHA256 (v1=<hash>) with timestamp validation
Payload Schemasstandard (nested envelope) or flattened (top-level properties)

2. Configuration & Setup

Creating a Custom Webhook

Custom webhooks can be registered via the TrimLynk UI (Developers → Integrations → Custom Webhook) or programmatically using the REST API:

http
POST /api/v1/integrations
Content-Type: application/json
Authorization: Bearer <API_KEY>

{
  "name": "Production Events Webhook",
  "provider": "custom_webhook",
  "config": {
    "webhookUrl": "https://api.example.com/trimlynk-events",
    "signingSecret": "whsec_live_9b8c7d6e5f4a3b2c1d0e9f8a7b6c5d4e",
    "payloadMode": "standard",
    "customHeaders": {
      "X-Source": "trimlynk",
      "X-Environment": "production"
    }
  },
  "events": [
    "sale.created",
    "lead.created",
    "click.created",
    "link.created"
  ]
}

Configuration Parameters

FieldTypeRequiredDescription
namestringYesHuman-readable identifier for your integration (e.g. Data Warehouse Webhook).
providerstringYesMust be custom_webhook.
config.webhookUrlstringYesPublicly accessible HTTPS URL. Private IP spaces and loopback addresses are blocked.
config.signingSecretstringOptionalShared secret key used for HMAC-SHA256 payload signing. If omitted during creation, TrimLynk generates one securely.
config.payloadModestringOptionalEither standard (default) or flattened.
config.customHeadersobjectOptionalKey-value dictionary of up to 10 custom request headers.
eventsstring[]YesList of event types to subscribe to, or omit/pass empty array to subscribe to all events.

3. Custom Headers & Security Constraints

TrimLynk permits passing up to 10 custom headers for routing, authentication, or tracing. To maintain network security and HTTP RFC compliance, strict guardrails are enforced:

Blocked Protected Headers

The following headers cannot be customized or overridden by user configuration:

  • Authorization
  • Host
  • Content-Length
  • Connection
  • Transfer-Encoding
  • Cookie
  • X-TrimLynk-Signature
  • X-TrimLynk-Event-Id
  • X-TrimLynk-Event-Type
  • X-TrimLynk-Timestamp
  • User-Agent
  • Content-Type

Header Name & Value Validation

  • CRLF Injection Prevention: Header names and header values containing carriage returns (\r) or line feeds (\n) are strictly rejected.
  • Length Bounds: Header names cannot exceed 100 characters; header values cannot exceed 1024 characters.
  • Header Limit: Maximum 10 headers per integration.

4. Payload Modes

TrimLynk supports two distinct JSON payload layouts to match your downstream architecture:

1. Standard Envelope (payloadMode: "standard")

Best for generic event brokers and microservices expecting a consistent event envelope:

json
{
  "id": "evt_01k12abc89def",
  "type": "sale.created",
  "createdAt": "2026-09-24T16:00:00.000Z",
  "workspaceId": "ws_production_01",
  "data": {
    "linkId": "clk_summer2026",
    "shortCode": "summer-sale",
    "revenue": 49.00,
    "currency": "USD",
    "orderId": "ord_987654",
    "customerId": "cust_12345"
  }
}

2. Flattened Payload (payloadMode: "flattened")

Best for direct ingestion into relational databases, flat data lakes, Zapier/Make webhooks, or spreadsheet append workflows:

json
{
  "id": "evt_01k12abc89def",
  "type": "sale.created",
  "createdAt": "2026-09-24T16:00:00.000Z",
  "workspaceId": "ws_production_01",
  "linkId": "clk_summer2026",
  "shortCode": "summer-sale",
  "revenue": 49.00,
  "currency": "USD",
  "orderId": "ord_987654",
  "customerId": "cust_12345"
}

5. Webhook Signature Verification (HMAC-SHA256)

When a signingSecret is configured, TrimLynk signs every outbound webhook delivery with standard HMAC-SHA256 headers:

HeaderDescriptionExample
X-TrimLynk-Event-IdUnique ID of the eventevt_01k12abc89def
X-TrimLynk-Event-TypeTrigger event namesale.created
X-TrimLynk-TimestampUnix epoch in milliseconds1790265600000
X-TrimLynk-SignatureVersioned HMAC-SHA256 signaturev1=a1b2c3d4e5f6...

Signature Algorithm

$$\text{Signature} = \text{HMAC-SHA256}(\text{secret}, \text{timestamp} + \text{"."} + \text{rawBody})$$ The header value is formatted as v1=<hex_digest>.

To prevent replay attacks:

  1. Verify the timestamp is within 5 minutes (300,000 ms) of your server's current time.
  2. Use constant-time comparison when verifying signatures.

Verification Example: Node.js / JavaScript

javascript
const crypto = require('crypto');

function verifyTrimLynkWebhook(rawBody, headers, signingSecret, toleranceMs = 300000) {
  const timestamp = headers['x-trimlynk-timestamp'];
  const signatureHeader = headers['x-trimlynk-signature'];

  if (!timestamp || !signatureHeader) {
    throw new Error('Missing TrimLynk signature headers');
  }

  // 1. Replay attack protection
  const currentTime = Date.now();
  if (Math.abs(currentTime - parseInt(timestamp, 10)) > toleranceMs) {
    throw new Error('Webhook timestamp outside acceptable tolerance window');
  }

  // 2. Compute expected HMAC
  const signedPayload = `${timestamp}.${rawBody}`;
  const expectedHash = crypto
    .createHmac('sha256', signingSecret)
    .update(signedPayload, 'utf8')
    .digest('hex');
  const expectedHeader = `v1=${expectedHash}`;

  // 3. Constant-time comparison
  const isValid = crypto.timingSafeEqual(
    Buffer.from(signatureHeader),
    Buffer.from(expectedHeader)
  );

  if (!isValid) {
    throw new Error('Invalid TrimLynk webhook signature');
  }

  return true;
}

// Example Express middleware:
// app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
//   verifyTrimLynkWebhook(req.body.toString('utf8'), req.headers, process.env.WEBHOOK_SECRET);
//   const payload = JSON.parse(req.body);
//   res.status(200).send('OK');
// });

Verification Example: Python 3

python
import hmac
import hashlib
import time

def verify_trimlynk_webhook(raw_body: str, headers: dict, signing_secret: str, tolerance_seconds: int = 300) -> bool:
    timestamp = headers.get('x-trimlynk-timestamp') or headers.get('X-TrimLynk-Timestamp')
    signature_header = headers.get('x-trimlynk-signature') or headers.get('X-TrimLynk-Signature')

    if not timestamp or not signature_header:
        raise ValueError("Missing TrimLynk signature headers")

    # 1. Replay attack protection
    timestamp_ms = int(timestamp)
    current_time_ms = int(time.time() * 1000)
    if abs(current_time_ms - timestamp_ms) > (tolerance_seconds * 1000):
        raise ValueError("Webhook timestamp outside acceptable tolerance window")

    # 2. Compute expected HMAC
    signed_payload = f"{timestamp}.{raw_body}".encode('utf-8')
    secret_bytes = signing_secret.encode('utf-8')
    expected_hash = hmac.new(secret_bytes, signed_payload, hashlib.sha256).hexdigest()
    expected_header = f"v1={expected_hash}"

    # 3. Constant-time comparison
    if not hmac.compare_digest(signature_header, expected_header):
        raise ValueError("Invalid TrimLynk webhook signature")

    return True

# Example Flask handler:
# @app.route('/webhook', methods=['POST'])
# def handle_webhook():
#     raw_body = request.get_data(as_text=True)
#     verify_trimlynk_webhook(raw_body, request.headers, os.environ['WEBHOOK_SECRET'])
#     payload = request.get_json()
#     return ('OK', 200)

6. Security Guarantees

  1. Secret Encryption at Rest: Webhook signing secrets are encrypted in PostgreSQL using AES-256-GCM with unique initialization vectors (iv:authTag:ciphertext).
  2. One-Time Secret Reveal: The plaintext signing secret is returned only once upon creation. It is permanently masked (whsec_••••••••) in all subsequent API GET responses and masked in UI views.
  3. Zero Secret Leakage in Logs: Request headers and URLs logged in structured telemetry redact Authorization, Cookie, X-TrimLynk-Signature, and credentials.
  4. SSRF Hardening: All destination endpoints are validated prior to execution:
    • Private IPv4 ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) are blocked.
    • Cloud instance metadata endpoints (169.254.169.254) are blocked.
    • Loopback IPs (127.0.0.1, ::1, localhost) are blocked.
    • Protocols other than https:// (e.g. file://, gopher://, ftp://) are rejected.
    • Redirect chains are validated against SSRF targets on every hop.

Ready to test in your workspace?

Manage API keys, live webhooks, and request telemetry in the TrimLynk Developer Console.

Configure Webhooks