# Hooks, callbacks and events

> Receive calls from other systems with signed inbound hooks, and get a signed callback when a workflow run finishes.

Source: https://docs.ligament.ai/developers/webhooks/

Two things connect your workspace to other systems over plain HTTP:

-   **Inbound hooks** give another system a URL to call. A script in your workspace handles each call, after Ligament has checked the caller’s signature or API key and filtered out duplicate deliveries.
-   **Run callbacks** let your code start a workflow and get a signed `POST` back when the run completes or fails.

Ligament doesn’t send general-purpose outbound webhooks for record changes. To react to a change, use an automation that starts on the record event, and call out from it.

## Inbound hooks

Any script can be exposed as an HTTP endpoint at:

```plaintext
https://app.ligament.ai/api/hook/<token>
```

The token is long and random, and it’s the only thing in the URL that identifies your workspace. It accepts `GET`, `POST`, `PUT`, `PATCH` and `DELETE`. The script receives the request as `input` (`{ method, query, headers, body }`) and whatever it returns becomes the response: return `{ status, headers, body }` to control the status code, or any other value to answer `200` with that value as JSON. Bodies over 256 KB are refused with `413`.

### Expose a script

1.  Open **Build › Extensions** and select the script (or create one with **New**).
2.  Open the script settings (the icon at the top right of the editor) and turn on **Expose as HTTP endpoint**.
3.  The **Endpoint** section shows the URL, with buttons to copy it and to issue a new token. A new token stops the old URL working.
4.  Choose how callers authenticate under **Auth** (below).

Scripts that ship in an app declare the same settings in the [app manifest](https://docs.ligament.ai/reference/app-manifest/index.md) (`exposed`, `endpointAuth`, `endpointHmac`, `endpointIdempotency` on a script).

### How callers authenticate

| Auth | The caller sends | Use it for |
| --- | --- | --- |
| Public | Nothing but the URL. The script runs read-only | Low-risk lookups, where the token is enough |
| API key | `Authorization: Bearer <key>` with `endpoints:invoke`, from a key in the same workspace. The script runs as the key’s creator, at most with member rights | Your own services |
| Signed (HMAC) | A signature header computed with a shared secret | Webhooks from SaaS providers (payments, carriers, identity checks) |

The app’s **Auth** menu offers Public and API key. Signed endpoints are set up through the app manifest or the API (`POST /api/scripts` with `endpointAuth: "hmac"` and `endpointHmac`), and then show as **Signed (HMAC)** in the script settings.

### Signed endpoints

A signed endpoint verifies the raw request body against a workspace secret before your script runs. The secret lives in your workspace’s secrets (**Build › Secrets**), and the script never sees it. Two signature formats are supported:

| `scheme` | Header value | Signed text |
| --- | --- | --- |
| `timestamped` | `t=<unix seconds>,v1=<hex>` (several `v1=` allowed, so you can rotate secrets) | `<t>.<raw body>` |
| `hex` | `<hex>`, optionally prefixed `sha256=` | the raw body |

Both use HMAC-SHA256 with a hex digest. With `timestamped`, a timestamp further than `toleranceSeconds` from now (default 300, at most 3600) is refused, which stops replays of old deliveries.

This is the configuration of a carrier status hook in an example workspace:

```json
{
  "key": "carrier_status_webhook",
  "name": "Carrier status webhook",
  "exposed": true,
  "endpointAuth": "hmac",
  "endpointHmac": { "secret": "CARRIER_WEBHOOK_SECRET", "header": "X-Carrier-Signature", "scheme": "timestamped", "toleranceSeconds": 300 },
  "endpointIdempotency": { "header": "Idempotency-Key" }
}
```

and its script:

```js
// Carrier status updates (signed by the carrier)
var b = input.body || {};
return { status: 202, body: { accepted: true, shipment: b.shipment_id, status: b.status } };
```

A delivery, signed the way the carrier would sign it:

```sh
BODY='{"shipment_id":"SHP-20931","status":"delivered"}'
T=$(date +%s)
SIG=$(printf '%s.%s' "$T" "$BODY" | openssl dgst -sha256 -hmac "$CARRIER_WEBHOOK_SECRET" -hex | awk '{print $2}')

curl -i -X POST "https://app.ligament.ai/api/hook/<token>" \
  -H "Content-Type: application/json" \
  -H "X-Carrier-Signature: t=$T,v1=$SIG" \
  -H "Idempotency-Key: evt_7f3a91" \
  -d "$BODY"
```

```plaintext
HTTP/1.1 202 Accepted
{"accepted":true,"shipment":"SHP-20931","status":"delivered"}
```

A missing, malformed, wrong or stale signature gets the same answer, so a caller can’t probe which part was wrong:

```plaintext
HTTP/1.1 401 Unauthorized
{"error":"invalid_signature"}
```

### Duplicate deliveries

Providers retry, and sometimes deliver the same event twice. Set `endpointIdempotency.header` to the header that carries the provider’s event id. The first successful (`2xx`) response for each id is stored; a repeat delivery with the same id gets the stored response back without running the script again, marked with a header:

```plaintext
HTTP/1.1 202 Accepted
Idempotent-Replayed: true
{"status":"delivered","accepted":true,"shipment":"SHP-20931"}
```

If the first delivery is still running when the repeat arrives, the repeat gets `409 {"error":"in_progress"}` and the provider retries later. Add `serializeBy: { "bodyPath": "account.id" }` to run deliveries for the same body value one at a time; a value still busy after 10 seconds gets `409 {"error":"busy"}`.

### Other answers

| Situation | Response |
| --- | --- |
| Unknown token, or the script is disabled or no longer exposed | `404 {"error":"endpoint not found"}` |
| Body over 256 KB | `413 {"error":"payload_too_large"}` |
| Idempotency key longer than allowed | `400 {"error":"invalid_idempotency_key"}` |
| The script throws | `500 {"error":"<message>"}` |

## Run callbacks

When you start a workflow run through the API, you can ask for a callback when it finishes:

```sh
curl -s -X POST "https://app.ligament.ai/api/workflows/trigger" \
  -H "Authorization: Bearer $LIGAMENT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "workflowId": "fulfill-request",
    "input": { "requestId": "REQ0001042" },
    "webhook": {
      "onComplete": "https://orders.example.com/hooks/run-complete",
      "onFailed": "https://orders.example.com/hooks/run-failed"
    }
  }'
```

The key needs `workflows:run`. The call answers `202` with `{ "runId": "…", "status": "running" }`. Both URLs are optional.

The callback URLs are checked when you start the run: they must be `http` or `https`, can’t contain a user name or password, and must resolve to a public address. A URL that fails the check is refused before the run starts:

```plaintext
HTTP/1.1 422 Unprocessable Entity
{"error":"blocked address: 10.0.0.5"}
```

An unknown `workflowId` is `404 {"error":"Workflow not found"}`, and starting runs is rate-limited per workspace (`429` with `Retry-After`).

### The callback

When the run completes (or fails), Ligament sends a `POST` to the matching URL with a JSON body of this shape:

```json
{
  "runId": "<run id>",
  "workflowId": "fulfill-request",
  "status": "complete",
  "output": { "…": "the run's output" },
  "completedAt": "<ISO 8601 timestamp>"
}
```

A failed run has `"status": "failed"`, and an `error` with the reason. These headers come with it:

| Header | Value |
| --- | --- |
| `X-Ligament-Signature` | `sha256=<hex>`: HMAC-SHA256 of the raw body with your workspace’s webhook signing secret |
| `X-Ligament-RunId` | The run id |
| `X-Ligament-Event` | `run.complete` or `run.failed` |

Answer with any `2xx` status. If the delivery fails or times out (10 seconds), it’s retried twice, about 2 and 4 seconds later. Redirects aren’t followed.

### Verify the signature

Compute the HMAC over the exact bytes you received, before parsing the JSON, and compare in constant time. In Node.js:

```js
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verifyRunCallback(rawBody, signatureHeader, secret) {
  const expected = 'sha256=' + createHmac('sha256', secret).update(rawBody).digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(signatureHeader ?? '');
  return a.length === b.length && timingSafeEqual(a, b);
}
```

### The signing secret

Each workspace has one webhook signing secret, starting `whsec_`. There’s no screen for it in the app; read and rotate it through the API:

| Call | Needs |
| --- | --- |
| `GET /api/settings/webhook` returns `{"secret":"whsec_…"}` | `settings:write` (an admin scope), from a key created by an admin or owner |
| `POST /api/settings/webhook` issues a new secret and returns it | `settings:write` (an admin scope) |

Reading the secret needs the same scope as rotating it, because anyone who holds it can sign a callback your system will trust. A `*` or `settings:read` key gets `403 insufficient_scope`. Make a separate key with `settings:write` for the setup step that fetches the secret, and keep it out of everyday clients.

Callbacks are signed with whichever secret is current when they’re sent, so a callback already queued when you rotate will fail verification on your side. Rotate when few runs are in flight.

## Events that start workflows

Inside the workspace, an automation can start on a record being created, updated or moved to a state, or on a named event. Live chat emits `chat.started`, `chat.message_left` and `chat.closed`, and an embedded form capture emits `form.captured` (or the event name the form sends). These events stay inside your workspace: to tell another system about them, add a step to the automation that calls it.
