Processing webhook events
Check each event's X-Truto-Signature, then process it. This page shows the event body, the header, and verification code.
Skip the reading — fast path for coding agents
truto webhooks list -o json
/skill truto
Webhook event payload structure
The webhook event is a JSON object with the following properties. When a sync job sends file contents as sync_job_run:record records, the same fields arrive as multipart/form-data instead. Each field is a part named like payload[sync_job_run_id], with nested keys in brackets and list items as [0]. The file is the payload[records] part. true and false arrive as 1 and 0, and null fields are left out.
Body
ididentifies this event's delivery to this webhook. Retries and resends keep it, so use it to drop duplicates.eventis the name of the event. E.g,integrated_account:created. It's in the formattruto_entity:action, wheretruto_entitycan be a resource in Truto andactioncan becreated,updated,deleted, etc.payloadis the data associated with the action. In most cases, it will be updated resource. Forrecord:*events it holdsresource,records,integrated_account_id,raw_event_type, andraw_payload(the event as the integration sent it).environment_idis the environment this webhook event is associated with.created_atis the time when this webhook event was generated.webhook_idis the ID of the webhook associated with this event.
An example webhook event sent when a new integrated account is connected is shown below,
{
"id": "3a0da6ba-b2d1-473f-957c-51f6825e3623",
"event": "integrated_account:created",
"payload": {
"id": "79a39d69-e27e-49cb-b9a9-79f5eea7aa26",
"tenant_id": "acme-1",
"environment_integration_id": "27a8c0ff-0c2e-4383-b651-0772b3515921",
"context": {},
"unified_model_override": {},
"integration_override": {},
"created_at": "2023-06-16T09:21:21.000Z",
"updated_at": "2023-06-16T09:21:21.000Z",
"authentication_method": "oauth2",
"status": "connecting",
"last_error": null,
"last_forbidden_error": null,
"last_action_run_result": {},
"features": {},
"region": "wnam",
"environment_id": "ac15abdc-b38e-47d0-97a2-69194017c177",
"integration": {
"id": "1fa47bf3-5f1f-4b65-bcd0-8d07ab455e15",
"name": "helpscout",
"config": {
"label": "Help Scout"
}
},
"environment_integration": {
"id": "27a8c0ff-0c2e-4383-b651-0772b3515921",
"integration_id": "1fa47bf3-5f1f-4b65-bcd0-8d07ab455e15",
"environment_id": "ac15abdc-b38e-47d0-97a2-69194017c177",
"show_in_catalog": true,
"is_enabled": true,
"created_at": "2023-02-16T09:27:16.000Z",
"updated_at": "2023-02-16T09:27:16.000Z"
}
},
"environment_id": "ac15abdc-b38e-47d0-97a2-69194017c177",
"created_at": "2023-06-16T09:21:22.369Z",
"webhook_id": "077ec306-5756-43fa-9a06-0cc0da4eabe0"
}Help Scout runs post-install steps, so a new Help Scout account starts connecting. An account of an integration without post-install or validation steps starts active.
Header
For security, Truto adds a X-Truto-Signature header which contains the URL-safe Base64 encoded SHA256 HMAC of the raw request body, without = padding. Truto signs the exact bytes it sends: one line of JSON, not the pretty-printed form above.
To test your verifier, use this test vector. With the secret 6e17561c-a20c-44ce-b8b5-caff0bf786fe and this exact body (one line, as Truto sends it):
{"id":"3a0da6ba-b2d1-473f-957c-51f6825e3623","event":"integrated_account:created","payload":{"id":"79a39d69-e27e-49cb-b9a9-79f5eea7aa26"},"environment_id":"ac15abdc-b38e-47d0-97a2-69194017c177","created_at":"2023-06-16T09:21:22.369Z","webhook_id":"077ec306-5756-43fa-9a06-0cc0da4eabe0"}the header is:
X-Truto-Signature: format=sha256,v=8dOQt0Y4aRvpRxnMh8qeHHNl_fPp1q-SnbKKXTWaWykVerification of the webhook event
You can get the SHA256 HMAC in the v part of the header value and do the following steps to make sure the webhook event is legit and sent from Truto,
- Store the
vvalue sent as part ofX-Truto-Signatureheader.8dOQt0Y4aRvpRxnMh8qeHHNl_fPp1q-SnbKKXTWaWykin the test vector above. - Calculate the SHA256 HMAC of the request body using the
secretattribute returned to you when you had created the webhook. IMPORTANT: Please use the raw bytes received as the body and not the JSON parsed version of it that most frameworks return you in the middleware function. Formultipart/form-datadeliveries, sign the raw multipart body exactly as received. - Calculate the Base64 encoded version of the data calculated in step 2. Make sure that the Base64 encoding is URL safe (
-and_in place of+and/) and has no=padding. - Compare the value obtained in step 3 with the value stored in step 1. They should be equal. If they are not, then the payload has been tampered with and the webhook event is not generated by Truto.
// Express route handler
import crypto from "node:crypto";
import express from "express";
const app = express();
const secret = process.env.TRUTO_WEBHOOK_SECRET ?? "";
function verifyWebhook(
headerValue: string | undefined,
secret: string,
body: Buffer
): boolean {
// Reject requests without a signature header
if (typeof headerValue !== "string" || !headerValue.includes("v=")) {
return false;
}
// Get HMAC from header
const hmacFromHeader = Buffer.from(headerValue.split("v=")[1]);
// Calculate the SHA256 HMAC of the request body, URL-safe Base64 without padding
const calculatedHmac = Buffer.from(
crypto.createHmac("sha256", secret).update(body).digest("base64url")
);
// timingSafeEqual throws when lengths differ
if (hmacFromHeader.length !== calculatedHmac.length) {
return false;
}
return crypto.timingSafeEqual(hmacFromHeader, calculatedHmac);
}
// Pass the raw request bytes to verifyWebhook, not the parsed body.
// express.raw keeps the body as a Buffer for both JSON and multipart/form-data deliveries.
app.post("/webhook", express.raw({ type: "*/*" }), (req, res) => {
const isVerified = verifyWebhook(
req.get("X-Truto-Signature"),
secret,
req.body
);
if (!isVerified) {
return res.sendStatus(401);
}
// Parse the event only after the signature checks out.
// multipart/form-data deliveries need a multipart parser instead.
if (req.is("application/json")) {
const event = JSON.parse(req.body.toString("utf8"));
console.log("Webhook verified", event.event);
}
// Respond with a 2xx quickly so Truto doesn't retry the delivery
return res.sendStatus(200);
});# Flask route handler
import base64, hashlib, hmac, os
from flask import Flask, request
app = Flask(__name__)
SECRET = os.environ["TRUTO_WEBHOOK_SECRET"]
def verify_webhook(header_value, secret, body: bytes) -> bool:
# Reject requests without a signature header
if not header_value or "v=" not in header_value:
return False
received = header_value.split("v=", 1)[1]
# SHA256 HMAC of the raw body, URL-safe Base64 without padding
digest = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).digest()
expected = base64.urlsafe_b64encode(digest).rstrip(b"=")
return hmac.compare_digest(received.encode("utf-8"), expected)
@app.post("/webhook")
def webhook():
# request.get_data() is the raw body, for JSON and multipart/form-data deliveries
if not verify_webhook(request.headers.get("X-Truto-Signature"), SECRET, request.get_data()):
return "", 401
# Respond with a 2xx quickly so Truto doesn't retry the delivery
return "", 200// ASP.NET Core controller
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Mvc;
public class TrutoWebhookController : ControllerBase
{
[HttpPost("/webhook")]
public async Task<IActionResult> Receive()
{
// Read the raw request body bytes, not a re-encoded string, so multipart deliveries verify too
using var ms = new MemoryStream();
await Request.Body.CopyToAsync(ms);
var body = ms.ToArray();
var secret = Environment.GetEnvironmentVariable("TRUTO_WEBHOOK_SECRET") ?? "";
if (!VerifyWebhook(Request.Headers["X-Truto-Signature"], secret, body))
{
return Unauthorized();
}
// Respond with a 2xx quickly so Truto doesn't retry the delivery
return Ok();
}
public static bool VerifyWebhook(string? headerValue, string secret, byte[] body)
{
// Reject requests without a signature header
if (string.IsNullOrEmpty(headerValue) || !headerValue.Contains("v="))
{
return false;
}
// Get HMAC from header
var hmacFromHeader = Encoding.UTF8.GetBytes(headerValue.Split("v=", 2)[1]);
var secretBytes = Encoding.UTF8.GetBytes(secret);
// Calculate the SHA256 HMAC of the request body, URL-safe Base64 without padding
using var hmac = new HMACSHA256(secretBytes);
var calculatedHmac = hmac.ComputeHash(body);
var urlSafeBase64String = Convert.ToBase64String(calculatedHmac)
.Replace('+', '-').Replace('/', '_').TrimEnd('=');
var generatedBytes = Encoding.UTF8.GetBytes(urlSafeBase64String);
return CryptographicOperations.FixedTimeEquals(hmacFromHeader, generatedBytes);
}
}Handle duplicates and order
Events can arrive out of order and more than once. Drop an event whose id you've already processed. Don't assume events about one account or record arrive in the order they happened: compare the payload's updated_at, or fetch the current record, before you overwrite newer data. Answer 2xx as soon as you've stored the event, and process it afterwards.
Next
See Event types for what each event means, and Find and resend failed events to recover events your endpoint missed.