---
title: "Webhooks"
description: "Answer requests a third-party service sends to Forge, and run an extension tool for each event."
---

> Documentation Index
> Fetch the complete documentation index at: https://buildrforge.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Webhooks

A **webhook** lets a third-party service tell an extension that something changed, such as a project in Procore or a payment in Stripe, without the extension polling it.

A webhook has two parts:

- **A request handler** answers each request the service sends to the webhook's URL, while the service waits. It checks the request, using the webhook's secret to verify the service's signature, and decides how to answer: echo a challenge, refuse a forged request, or accept an event.
- **A tool** runs once for each event the request handler accepts, after the service has its answer. Like a trigger, it's an ordinary call of one of the extension's tools, which takes what the request handler accepted as its input.

## Webhook declarations in `index.ts`

Import `webhook` from `@buildr/sdk` and pass your webhooks under `webhooks` in `defineExtension`. This request handler checks an HMAC-SHA256 signature, answers a URL check, and accepts each event:

```ts
import {
  accept,
  defineExtension,
  hmac,
  object,
  webhook,
  respond,
  string,
  timingSafeEqual,
  tool,
} from "@buildr/sdk";

const recordChange = tool(
  {
    description: "Records a project that changed",
    input: object({ project: string() }),
  },
  async (ctx, { project }) => {
    // Update the repo with ctx.forge, as any tool does.
    return null;
  },
);

const projectChanged = webhook(
  {
    instructions: "In the service's settings, add the URL and the secret, and sign each body.",
    handleRequest: async (ctx, request) => {
      const body = await request.text();
      const expected = await hmac({
        hash: "SHA-256",
        key: ctx.secret ?? "",
        message: body,
        encoding: "hex",
      });
      if (!timingSafeEqual(request.headers.get("x-signature") ?? "", expected)) {
        return respond(401);
      }
      const event = JSON.parse(body);
      if (event.type === "url_verification") {
        return respond(200, { body: event.challenge, headers: { "content-type": "text/plain" } });
      }
      return accept({ project: event.project }, { dedupeKey: event.id });
    },
  },
  recordChange,
);

export default defineExtension({}, { tools: { recordChange }, webhooks: { projectChanged } });
```

`webhook` takes these options:

- `handleRequest`: The request handler, described below. Required.
- `secret`: Who makes the webhook's secret. `"forge"`, the default, means Forge makes it, and a member gives it to the service. `"provider"` means the service makes it, as Stripe does, and a member gives it to Forge.
- `instructions`: How to set the webhook up at the service, in at most 4000 characters, which `forge webhooks list-webhooks` shows each member.

### The request handler

`handleRequest(ctx, request)` gets the request exactly as the service sent it, as a standard `Request`: its method, its URL with the query, every header but `cookie` and an `Authorization` that holds a Forge token, and its body. A service's own `Authorization`, such as a bearer secret or a JWT it signed, arrives as sent. `ctx.secret` is the webhook's secret, or `null` until a member sets one. `ctx.receivedAt` is when Forge received the request.

It returns one of these:

- `respond(status, { body, headers })`: Answer the service and run nothing. Use it for a challenge's echo, a refused signature, or an event the extension ignores.
- `accept(payload, { dedupeKey, respond })`: Keep `payload` as a delivery, which runs the webhook's tool after. Forge answers `202 Accepted` with the delivery, or with `respond` when you pass one, such as a `200` that a service insists on. `respond` here is a plain `{ status, body, headers }` object, not a call to `respond()`. A `dedupeKey`, such as the service's event id, makes an event the service sends again the same delivery, which runs once. It's a non-empty string whose `length` is at most 256, so turn a numeric id into a string first.

An answer's status must be from 200 to 599, and its body's `length` at most 65,536. An answer outside those bounds fails the request. `length` counts UTF-16 code units, so a character such as an emoji counts as two.

Requests with `GET`, `HEAD`, `OPTIONS`, `POST`, `PUT`, `PATCH`, or `DELETE` reach the request handler, so check `request.method`. Services check a URL with `GET` or `HEAD`, as Trello does with a `HEAD` it wants a `200` for, and a service that follows the CloudEvents webhook spec, such as Azure Event Grid, sends `OPTIONS` to ask leave to deliver, which the request handler grants with `WebHook-Allowed-Origin` and `WebHook-Allowed-Rate` headers. Answer methods the service never sends with `respond(405)`.

Anyone can open a webhook's URL, so Forge serves the request handler's answer as a document no browser runs, frames, or caches. Of the headers the request handler sets, the answer keeps only `Content-Type`, `WebHook-Allowed-Origin`, `WebHook-Allowed-Rate`, `Retry-After`, and `Allow`, in any case. Webhook URLs answer only on the API's origin, never through the signed-in site.

The request handler runs in a sandbox with no network and no `ctx.forge`, so it can only check and decide, and the tool does the work. A request handler that throws answers the service `500`, which makes most services send again, and leaves a failed delivery that says why. Forge checks that each payload the request handler accepts fits the tool's input, so a mismatch shows up the same way.

The SDK has helpers for checking signatures:

- `hmac({ hash, key, message, encoding })`: The HMAC of `message`, hex or base64 encoded, with SHA-1, SHA-256, or SHA-512.
- `timingSafeEqual(a, b)`: Compares a signature the service sent with one the request handler computed, in time that doesn't reveal where they differ.
- `bearerSecret`: A ready-made request handler for a service that sends the secret as `Authorization: Bearer <secret>` and signs nothing. It accepts each request that carries the secret as a `webhookDelivery`: the headers, without `authorization`, the body's text, and `receivedAt`. Its tool takes `webhookDelivery` as its input.

### Webhook validation rules

Publishing an extension checks every entry in `webhooks`, and a webhook that breaks a rule fails the publication with `DeclarationFailed`:

- **Webhook name**: Each key in `webhooks` must be a valid JavaScript identifier (`/^[A-Za-z_][A-Za-z0-9_]*$/`) of at most 128 characters.
- **Handler**: `handleRequest` must be a function.
- **Target tool**: The tool passed to `webhook` must also be in the extension's `tools` tree.
- **Secret and instructions**: `secret` is `"forge"` or `"provider"`, and `instructions` is text of at most 4000 characters.

## Connecting a service to a webhook

Each repo that runs the extension subscribes to each webhook on its own, which gives the webhook a URL in that repo and a secret:

```sh
forge webhooks list-webhooks --repo "$REPO"
forge webhooks create-webhook-subscription --repo "$REPO" --extension integrations.procore --webhook projectChanged
forge webhooks update-webhook-secret --repo "$REPO" --extension integrations.stripe --webhook paymentSucceeded --data-file secret.json
```

- **A secret Forge makes**: `create-webhook-subscription` answers the URL and the webhook's first secret. Give both to the service. Forge never shows the secret again. `update-webhook-secret` with no body makes a new one, replacing the old one at once.
- **A secret the service makes**: `create-webhook-subscription` answers only the URL. Give it to the service, then pass the secret the service shows to `update-webhook-secret` as `{"secret":"…"}`.

Forge keeps each secret sealed with your organization's key, and only the webhook's request handler reads it. A webhook's URL stays the same when its secret changes. Subscribing and setting a secret take `manage` on the installation, which the default Editor policy doesn't allow. Any member who can read the repo can list its webhooks, and `read` on the installation lists their deliveries. See the [Action reference](https://buildrforge.com/docs/permissions/actions/#installations).

A `POST`, `PUT`, `PATCH`, or `DELETE` request can carry a body of any content type, of at most 1 MiB. A `GET`, `HEAD`, or `OPTIONS` request reaches the handler with no body, as some services use to check a URL with a challenge in its query. The handler gets the body's bytes exactly as sent, byte-order mark included, so `new Uint8Array(await request.arrayBuffer())` is what the service signed, and `hmac` takes it as its `message`.

## Where webhooks run

A repo's `main` decides which webhooks run in that repo, as it does for triggers:

| Repo | Version whose webhooks run |
| --- | --- |
| A repo that installed the extension | The release that `main`'s head commit pins |
| The repo that defines the extension | The version that `main`'s head commit publishes, prereleases included |

Its tool's `ctx.branch` is [the run's own branch](https://buildrforge.com/docs/extensions/tools/#where-a-background-run-writes), which merges into `main`. These rules decide how a request runs:

- **The request handler answers, the tool runs after**: The service has its answer as soon as the request handler decides, so a slow tool never makes it send again.
- **At the version `main` runs**: The request handler runs the version `main` runs when the request arrives, and each delivery's tool the version `main` runs when it starts.
- **Side by side**: Deliveries of one webhook can run at the same time, oldest first. At most 8 deliveries run at once in a repo, and the rest wait their turn. Services don't promise an order, so don't rely on one.
- **Archived repos**: An archived repo takes no writes, so it refuses requests with `RepoArchived` (409), and deliveries already queued wait until someone with `update` on the repo unarchives it.
- **While publishing**: In the repo that defines the extension, a request while the version that `main`'s head publishes is still publishing gets `503`, so the service sends again, and queued deliveries wait for that version. Deliveries fail without running once `main` no longer runs the extension.

Forge doesn't keep what a webhook's tool returns, and it never retries a delivery that failed or was interrupted. Each webhook keeps its latest 100 finished deliveries, and remembers their dedupe keys while it does. List them, and how each one went, with `forge webhooks list-webhook-deliveries`.

## Execution identity and connections

A webhook's tool has no interactive caller. Its `ctx.forge` calls act as [the extension itself](https://buildrforge.com/docs/permissions/#who-a-run-acts-as), under the policies that name it. Like a trigger run, it holds only the repo's bound `org` connections, and reading `ctx.user.connections.<name>` throws.

A webhook's tool can start a [workflow](https://buildrforge.com/docs/extensions/workflows/) with `ctx.workflows.start` for work that takes longer than one tool call.

Source: https://buildrforge.com/docs/extensions/webhooks/index.mdx
