Verify Tray.io webhooks

Tray.io doesn't sign these requests, so there's no signature to check and no SDK to verify one. You add a header to the HTTP Client step, take its value from a Tray authentication, and your endpoint compares the whole value in constant time. That authenticates the sender, but it doesn't protect the body or stop a replay.

These pages cover requests a Tray workflow sends to your endpoint. To send data into Tray and start a workflow, see Tray's Webhook Trigger docs. Log streaming, which sends workflow logs to an endpoint, is a separate feature and isn't covered here.

The facts

Signature header
None (unsigned)
What to build
Compare the secret header you chose with your stored value
Key
shared secret

Tray.io webhook secret

Tray issues no secret. You generate a value and store it in a Tray authentication, which the HTTP Client step reads as $.auth.<property>. Keep it in an environment variable, not in source code.

  • Create a Generic Service Authentication on the step's Auth tab, and add a property such as api_key that holds your value
  • Map the header's value from $.auth.api_key, because Tray obscures it in the logs only when it comes from an authentication
  • The header name is your choice, and the value to compare is the whole header, including any Bearer prefix
  • A Generic Service Authentication in an organization workspace is accessible to everyone in the organization
  • Tray lower-cases header names unless the step's Case sensitive headers option is on, so match them case-insensitively
  • Rotate it by changing the authentication and your stored value together

Source: Tray.io docs ↗

Code

express/src/index.js
javascript
// Generated with: tray-io-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');

const app = express();

/**
 * Constant-time comparison. Hashing both sides first gives equal-length
 * buffers, so timingSafeEqual never throws and the secret's length isn't leaked.
 */
function safeEqual(a, b) {
  const ha = crypto.createHash('sha256').update(a).digest();
  const hb = crypto.createHash('sha256').update(b).digest();
  return crypto.timingSafeEqual(ha, hb);
}

/**
 * Tray.io requests are unsigned. The workflow's HTTP Client step adds a secret header
 * (name chosen by the user, value from a Generic Service Authentication). We compare the
 * WHOLE header value, including any "Bearer " prefix, and never strip or parse it.
 * A static credential authenticates the sender, not the body, and gives no replay protection.
 */
function verifyTrayRequest(headers, {
  headerName = process.env.TRAY_IO_WEBHOOK_HEADER || 'Authorization',
  secret = process.env.TRAY_IO_WEBHOOK_SECRET,
} = {}) {
  if (!secret) return false; // never accept when unconfigured
  const received = headers[headerName.toLowerCase()]; // Node lower-cases header names
  if (typeof received !== 'string' || !received) return false;
  return safeEqual(Buffer.from(received, 'latin1'), Buffer.from(secret, 'utf8'));
}

// The "event" field is a convention: Tray defines no event types.
function handleEvent(payload) {
  const { event, data } = payload;

  switch (event) {
    case 'record.created':
      console.log('Record created:', data);
      // Your code: create the record in your system
      break;

    case 'record.updated':
      console.log('Record updated:', data);
      // Your code: update the record in your system
      break;

    case 'record.deleted':
      console.log('Record deleted:', data);
      // Your code: remove the record from your system
      break;

    default:
      console.log(`Unhandled event: ${event}`);
  }
}

function trayHandler(req, res) {
  // Authenticate before parsing the body.
  if (!verifyTrayRequest(req.headers)) {
    return res.status(401).json({ error: 'Invalid or missing credential header' });
  }

  // GET (or any request without a body) leaves req.body undefined.
  const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
  if (raw.trim() === '') {
    return res.status(200).json({ received: true });
  }

  let payload;
  try {
    payload = JSON.parse(raw);
  } catch {
    return res.status(400).json({ error: 'Invalid JSON body' });
  }

  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
    return res.status(400).json({ error: 'Expected a JSON object' });
  }

  try {
    handleEvent(payload);
  } catch (err) {
    console.error('Error handling Tray.io request:', err);
    return res.status(500).json({ error: 'Handler error' });
  }

  res.status(200).json({ received: true });
}

// The method is chosen in the workflow, so accept all of them. The body is read raw for any content type.
for (const method of ['get', 'post', 'put', 'patch', 'delete']) {
  app[method]('/webhooks/tray-io', express.raw({ type: '*/*' }), trayHandler);
}

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = app;
module.exports.verifyTrayRequest = verifyTrayRequest;

if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: http://localhost:${PORT}/webhooks/tray-io (POST, PUT, PATCH, DELETE, GET)`);
  });
}
nextjs/app/webhooks/tray-io/route.ts
typescript
// Generated with: tray-io-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyTrayRequest } from '../../../lib/verify-tray-io';

interface TrayPayload {
  event?: string;
  data?: unknown;
  [key: string]: unknown;
}

// The "event" field is a convention: Tray defines no event types.
function handleEvent(payload: TrayPayload): void {
  const { event, data } = payload;

  switch (event) {
    case 'record.created':
      console.log('Record created:', data);
      // Your code: create the record in your system
      break;

    case 'record.updated':
      console.log('Record updated:', data);
      // Your code: update the record in your system
      break;

    case 'record.deleted':
      console.log('Record deleted:', data);
      // Your code: remove the record from your system
      break;

    default:
      console.log(`Unhandled event: ${event}`);
  }
}

async function handle(request: NextRequest) {
  // Authenticate before reading or parsing the body.
  if (!verifyTrayRequest(request.headers)) {
    return NextResponse.json({ error: 'Invalid or missing credential header' }, { status: 401 });
  }

  // Read as text so any content type is accepted; GET has an empty body.
  const raw = await request.text();
  if (raw.trim() === '') {
    return NextResponse.json({ received: true });
  }

  let payload: unknown;
  try {
    payload = JSON.parse(raw);
  } catch {
    return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
  }

  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
    return NextResponse.json({ error: 'Expected a JSON object' }, { status: 400 });
  }

  try {
    handleEvent(payload as TrayPayload);
  } catch (err) {
    console.error('Error handling Tray.io request:', err);
    return NextResponse.json({ error: 'Handler error' }, { status: 500 });
  }

  return NextResponse.json({ received: true });
}

// The method is chosen in the workflow, so accept all of them.
export const GET = handle;
export const POST = handle;
export const PUT = handle;
export const PATCH = handle;
export const DELETE = handle;
fastapi/main.py
python
# Generated with: tray-io-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hmac
import json
import os

from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()


def verify_tray_request(headers, header_name=None, secret=None) -> bool:
    """Tray.io requests are unsigned. The workflow's HTTP Client step adds a secret header
    (name chosen by the user, value from a Generic Service Authentication). We compare the
    WHOLE header value, including any "Bearer " prefix, and never strip or parse it.
    A static credential authenticates the sender, not the body, and gives no replay protection.
    """
    header_name = header_name or os.environ.get("TRAY_IO_WEBHOOK_HEADER") or "Authorization"
    secret = secret if secret is not None else os.environ.get("TRAY_IO_WEBHOOK_SECRET")
    if not secret:
        return False  # never accept when unconfigured
    received = headers.get(header_name)  # Starlette headers are case-insensitive
    if not received:
        return False
    # compare_digest raises TypeError on non-ASCII str, so compare bytes. Starlette decodes
    # header bytes as latin-1, so re-encoding as latin-1 recovers what was sent.
    return hmac.compare_digest(received.encode("latin-1"), secret.encode("utf-8"))


async def require_tray_credential(request: Request) -> None:
    """FastAPI dependency: reject the request before the body is read or parsed."""
    if not verify_tray_request(request.headers):
        raise HTTPException(status_code=401, detail="Invalid or missing credential header")


# The "event" field is a convention: Tray defines no event types.
def handle_event(payload: dict) -> None:
    event = payload.get("event")
    data = payload.get("data")

    if event == "record.created":
        print(f"Record created: {data}")
        # Your code: create the record in your system

    elif event == "record.updated":
        print(f"Record updated: {data}")
        # Your code: update the record in your system

    elif event == "record.deleted":
        print(f"Record deleted: {data}")
        # Your code: remove the record from your system

    else:
        print(f"Unhandled event: {event}")


# The method is chosen in the workflow, so accept all of them.
@app.api_route(
    "/webhooks/tray-io",
    methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
    dependencies=[Depends(require_tray_credential)],
)
async def tray_webhook(request: Request):
    # Read the raw body so any content type is accepted; GET has an empty body.
    raw_body = await request.body()
    if not raw_body.strip():
        return {"received": True}

    try:
        payload = json.loads(raw_body)
    except (json.JSONDecodeError, UnicodeDecodeError):
        raise HTTPException(status_code=400, detail="Invalid JSON body")

    if not isinstance(payload, dict):
        raise HTTPException(status_code=400, detail="Expected a JSON object")

    try:
        handle_event(payload)
    except Exception as err:  # noqa: BLE001
        print(f"Error handling Tray.io request: {err}")
        raise HTTPException(status_code=500, detail="Handler error")

    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

From hookdeck/webhook-skills ↗

Or install the Tray.io webhooks skill:

npx skills add hookdeck/webhook-skills --skill tray-io-webhooks

Common failures

Prefix left out of the comparison

Compare the whole header value. If the step sends Bearer abc, the value to compare is Bearer abc, not abc.

Header name mismatch

Your endpoint has to read the header the step adds. Tray lower-cases header names unless Case sensitive headers is on, so match them case-insensitively.

Authentication changed on one side

After a rotation, the Tray authentication and your stored value have to match. Change them together.

Authentication not selected on the step

$.auth reads from the authentication selected on the step, so selecting a different one sends a different value.

From Hookdeck's Tray.io guide

Let Event Gateway check your Tray.io header.

Enter the same header name and value on a Hookdeck source with the Tray.io type. Event Gateway checks the header on each request before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with Tray.io. Facts are compiled from public sources and linked inline.