Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Webhooks

Start an Action for each request another system sends, with an http trigger.

Another system, such as Stripe, GitHub, or Slack, sends its events as HTTP requests to a URL. An Action with an HTTP trigger has that URL. Each request starts the Action with the request as a standard Request, and the sender gets the standard Response the Action returns. The Action checks the request’s signature with its Secrets, and then does anything an Action does.

Declaring an HTTP trigger

Give an unbound Action trigger: http(). The request is its input and a Response its output, so it doesn’t declare either.

import { action, http, secret } from "@tractorbeam/sdk";
import * as Schema from "effect/Schema";

export const stripeSigning = secret("stripe-signing", { schema: Schema.String });

export const handleStripe = action("handle-stripe", {
  trigger: http(),
  capabilities: { secrets: [stripeSigning] },
  run: async (request, { secrets }) => {
    // Check the signature, then act on the event.
    return new Response(null, { status: 204 });
  },
});

Its body holds the exact bytes the sender signed. In the Action’s context, trigger is { kind: "http", receivedAt }, with the RFC 3339 time Tractorbeam received the request.

Each run acts as the Workspace’s default service user, or as the one http({ serviceUser }) gives by its client ID, as a scheduled Action’s does. That service user needs actions:invoke. Because a service user has no connection of its own, an HTTP trigger’s Action lists only Workspace Connectors; see Connectors.

The URL

An Action’s HTTP trigger is at its Workspace’s hooks host, followed by the Action’s name:

https://<workspace>-hooks.tractorbeam.run/<action>

Give the sender this URL. Any method works, because a handshake can be a GET (Meta’s hub.challenge is one), and the sender doesn’t need a Tractorbeam credential. The request is the Action’s input, so a body up to about 23 MiB fits, as for any Action’s input.

The sender gets the Response the Action returns, with the status, headers, and body the Action gives it. That Response is the Action’s output, so like any Action’s output it’s at most 1 MiB, its body in base64. An Action whose request or Response is past those limits fails, and its Invocation says why. When the Action has no Response for it in time, or never reaches it, Tractorbeam answers instead:

Status When
404 Neither the Branch nor an Action with an HTTP trigger has the name.
408 The request’s body didn’t arrive in 10 seconds.
413 The request’s body is too large for any Action’s input.
429 The hooks host got more than 3,000 requests this minute, or this sender more than 600. Retry after retry-after seconds.
500 The Action failed, or its service user can’t run it.
503 Tractorbeam is unavailable or busy. Try again after the retry-after seconds.
504 The Action hasn’t returned in 8 seconds. It keeps running.

Tractorbeam leaves out the response headers it owns: connection, keep-alive, te, trailer, transfer-encoding, upgrade, and the proxy- ones; content-length and content-encoding; and set-cookie, strict-transport-security, content-security-policy, and alt-svc.

Checking a signature

The Action checks the signature with WebCrypto’s crypto.subtle, under its Secret. Stripe signs <t>.<body> with HMAC-SHA256, using the whole secret string as the key, and sends t=<t>,v1=<hex> in stripe-signature:

const hex = (bytes: ArrayBuffer) =>
  [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");

run: async (request, { secrets, trigger }) => {
  const parts = new Map(
    (request.headers.get("stripe-signature") ?? "").split(",").map((part) => part.split("=")),
  );
  const timestamp = parts.get("t") ?? "";
  const key = await crypto.subtle.importKey(
    "raw",
    new TextEncoder().encode(secrets["stripe-signing"]),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign"],
  );
  const body = await request.text();
  const signature = hex(
    await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${timestamp}.${body}`)),
  );
  const age = Date.parse(trigger.receivedAt) / 1000 - Number(timestamp);

  if (parts.get("v1") !== signature || Math.abs(age) > 300) {
    return new Response(null, { status: 401 });
  }

  const event = JSON.parse(body);
  // Act on the event.
  return new Response(null, { status: 204 });
},

Each sender following Standard Webhooks signs <webhook-id>.<webhook-timestamp>.<body>. Its key is the base64 after the secret’s whsec_ prefix, and webhook-signature lists v1,<base64> signatures:

const fromBase64 = (text: string) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0));

const key = await crypto.subtle.importKey(
  "raw",
  fromBase64(secrets["events-signing"].replace(/^whsec_/, "")),
  { name: "HMAC", hash: "SHA-256" },
  false,
  ["verify"],
);
const id = request.headers.get("webhook-id");
const timestamp = request.headers.get("webhook-timestamp");
const signed = new TextEncoder().encode(`${id}.${timestamp}.${await request.text()}`);
let genuine = false;

for (const signature of (request.headers.get("webhook-signature") ?? "").split(" ")) {
  const [version, value] = signature.split(",");
  genuine ||=
    version === "v1" && (await crypto.subtle.verify("HMAC", key, fromBase64(value), signed));
}

// A signature over an old timestamp may be a captured request sent again.
const age = Date.parse(trigger.receivedAt) / 1000 - Number(timestamp);

if (!genuine || !(Math.abs(age) <= 300)) {
  return new Response(null, { status: 401 });
}

A sender whose signature needs the network, such as an AWS SNS message’s signing certificate, is checked the same way: the Action calls the sender’s origin, listed in its egress.

Answering a handshake

The Action’s Response answers a handshake, such as Slack’s url_verification challenge or Meta’s GET with hub.challenge, as it answers any request:

export const slack = action("slack", {
  trigger: http(),
  capabilities: { secrets: [slackSigning] },
  run: async (request) => {
    // Check the signature first.
    const body = (await request.json()) as { readonly type: string; readonly challenge?: string };

    return body.type === "url_verification"
      ? new Response(body.challenge, { headers: { "content-type": "text/plain" } })
      : new Response(null, { status: 200 });
  },
});

A response can also come from data: the Action calls a Query and returns what it reads.

Deliveries

Each request starts an Invocation of its own. A sender’s retry starts another. To act on each delivery once, record its ID, such as Stripe’s event ID or webhook-id, in a Table with a unique index on it. Insert it from a Mutation the Action invokes first. A second insert of the same ID fails, and the Action stops there:

export const deliveries = table("deliveries", {
  schema: { deliveryId: Schema.String },
  indexes: { byDeliveryId: { on: ["deliveryId"], unique: true } },
});

export const recordDelivery = mutation("record-delivery", {
  input: Schema.Struct({ deliveryId: Schema.String }),
  run: async ({ deliveryId }) => {
    await deliveries.insert({ deliveryId });
  },
});

For work longer than the sender waits, record the event and schedule the work, then return. A Mutation the HTTP trigger’s Action invokes inserts the event into a Table and schedules another Action with .schedule(). That Action reads the event. When that Action finishes, it can send its result to Slack’s response_url or Discord’s interaction webhook.

Branches

The URL’s branch parameter sends a request to another Branch’s Action, such as the Personal Branch tractorbeam dev applies to:

https://<workspace>-hooks.tractorbeam.run/<action>?branch=<branch>

That Branch’s Action and Secret values serve the request, and the Invocation starts on that Branch. Point a provider’s test mode at it to try an Action before you apply it to the default Branch. The Action gets the whole URL, branch parameter included, because a sender such as Twilio signs the exact URL.

Last updated on