# Webhook connectors

The delivery contract itself — headers, envelope, retries, the event catalog — is [WEBHOOKS.md](webhooks.md).
This is the other half: **the code**. `docs/webhooks/connectors/` holds a verifier per language and
two n8n templates to import, and this page says which one you want and what each platform can
actually do.

The short version: an Otobiz delivery is a plain signed HTTP `POST`, so **no connection is required
for any of these tools to receive it.** n8n's Webhook trigger, Zapier's Catch Raw Hook and Make's
custom webhook each mint a URL and accept it as-is. What differs between them is only whether they
can hand your automation the **raw bytes** — and without those you cannot check a signature.

## The standard format every snippet follows

One shape, so a translation can be read against the original line by line:

| | |
|---|---|
| **Input** | the raw body bytes, the request headers (any casing), the endpoint secret, optionally "now" |
| **Output** | one of four verdicts and a human `detail` |
| **Order** | `webhook-*` headers present → timestamp numeric → **freshness, before any hashing** → `v1,` signature → constant-time compare against each space-separated value |
| **Dependencies** | none beyond each language's standard library |

The verdicts are the same four words in every file here — and in the test receiver
`apps/scripts/webhook-receiver.mjs`, so one word means one thing wherever you read it:

| Verdict | Meaning | What to do |
|---|---|---|
| `valid` | signed, fresh, a `v1,` signature matches | dedupe on the event id, then process |
| `unsigned` | no `webhook-*` headers — the endpoint has no secret set, or a proxy stripped them | if you configured a secret, treat this as a rejection |
| `STALE` | timestamp outside ±300s | refuse — a replay, or a badly wrong clock |
| `INVALID` | one of the three headers missing, non-numeric timestamp, or no signature matches | refuse without parsing the body |

Two rules break more connections than signatures do, so they are restated in every file:
**answer 2xx within 5 seconds** (acknowledge, then work — never work, then acknowledge), and
**dedupe on the event id** (`webhook-id` and `X-Otobiz-Event-Id`, identical to `payload.id`; delivery is at-least-once).

## Which file you want

| You are using | Can it give you the raw body? | Verification | Start from |
|---|---|---|---|
| **n8n** (Cloud or self-hosted) | yes — Webhook node → Options → **Raw Body** | full, no code needed | `docs/webhooks/connectors/n8n-verify-webhook.json` |
| **n8n**, and you can set env vars | yes | full, in one Code node | `docs/webhooks/connectors/n8n-code-node.js` |
| **Zapier** | yes — trigger must be **Catch Raw Hook**, not Catch Hook | full, in a Code step | `docs/webhooks/connectors/zapier-code-step.js` |
| **Make** | not reliably — see below | best-effort only | this page, the Make section |
| **Your own service** | yes | full | `verify.mjs` · `verify.py` · `verify.php` · `verify.go` |

`docs/webhooks/connectors/event-samples.json` sits beside them: one canonical delivery body **per
catalog event**, in the envelope it arrives in (`type`, `data.object`), generated from `apps/src/api/screen-reads/webhooks/samples.ts` by `pnpm --filter apps api:spec`. That is the file to map fields from when you are
building a Zap, an n8n location or a connector node — the payload field names per event exist nowhere
else in one place.

## n8n

### The no-code chain (works on n8n Cloud)

Import `docs/webhooks/connectors/n8n-verify-webhook.json`. Four nodes, and each one is load-bearing:

1. **Webhook** — POST, Respond **Immediately**, Options → **Raw Body** on. n8n then keeps the
   unparsed bytes in `binary.data` (base64) beside the parsed `json.body`. The digest is over those
   bytes; hashing a re-serialised object gives a different digest for a body nobody touched.
2. **Extract From File** (operation *Move File to Text*) — turns the binary into `rawBody` text,
   with **Keep Source = JSON**. That option is not cosmetic: the node starts its output item at an
   empty `json`, so without it the headers the next two nodes read are gone. Encoding is pinned to
   `utf8` rather than auto-detected.
3. **Crypto** — HMAC, SHA256, base64, over
   `{{$json.headers['webhook-id']+'.'+$json.headers['webhook-timestamp']+'.'+$json.rawBody}}`.
   On Crypto v2 the secret lives in a **Crypto credential** (HMAC secret), so it never enters the
   automation JSON; on older installs with Crypto v1 it is an inline node field. The node keys the HMAC
   with the secret's text, so set your own secret on the endpoint (any text not starting `whsec_`);
   a `whsec_` secret is keyed by its base64-decoded bytes, which only the Code node version handles.
4. **If** — `webhook-signature` contains `v1,` + that digest (two values during a 24 h secret
   rotation; either counts) **and** `webhook-timestamp` is within 300 s. Both conditions, not just
   the first: the freshness half is what makes a captured delivery worthless.

Because the response mode is *Immediately*, n8n has already answered `200` before the check runs —
so a forged delivery is discarded on the false path rather than refused with a 401. That is the
right trade here: our contract treats any 2xx as "received", and waiting for the automation to decide
risks the 5-second window (an automation that answers only at the end fails while looking healthy on
its own side). If you would rather reply 401, set the Webhook node to *Using Respond to Webhook
node* and keep everything before the reply under 5 seconds.

**Then route.** Add a **Switch** node after the true path keyed on
`{{ $json.headers['x-otobiz-event'] }}` — one output per event you handle plus a fallback, which is
also the honest way to notice a new catalog event arriving. And put a **Remove Duplicates** node
keyed on `{{ $json.headers['webhook-id'] }}` before anything with side effects: a retry, a
**Re-run** from our delivery log, and a rare provider redelivery all carry the same id.

### The one-Code-node version

`docs/webhooks/connectors/n8n-code-node.js` does the whole check in a single Code node — freshness,
digest, timing-safe compare — and returns the verdict plus the parsed payload.

**It cannot run on n8n Cloud.** The Code node only requires built-in modules the instance allows, so
the environment needs `NODE_FUNCTION_ALLOW_BUILTIN=crypto`; there is no default list, and without it
`require("crypto")` throws. n8n 3.x runs Code on task runners: set it on the n8n container (internal
mode) or on the `n8nio/runners` container (external mode). n8n blocks `$env` in nodes by default, so
paste the secret into the node. Raw bytes come from `this.helpers.getBinaryDataBuffer` — n8n stores
binary data, so `binary.data.data` is a reference, not the body. Self-hosted only, and worth it if you
would rather read one file than four nodes.

### Registering the endpoint from inside n8n

`docs/webhooks/connectors/n8n-register-endpoint.json` is the other direction: HTTP Request nodes that
`POST /api/v1/webhooks/settings` to register a receiver, list endpoints with the event catalog, resume a
paused one and delete it. The key rides an n8n **Header Auth** credential (`Authorization: Bearer
otb_…`) and needs the `webhooks:write` scope; `Idempotency-Key` is set from `$execution.id`, so a
re-run after a timeout returns the endpoint the first attempt made instead of registering a second.

The key-authenticated public API answers on every deploy. Register your endpoint at **Developer → Webhooks** in the dashboard
and use the verify template above, which needs no API access at all.

## Zapier

Trigger: **Webhooks by Zapier → Catch Raw Hook**. Not Catch Hook — only the raw variant hands over
the unparsed body together with the headers (Zapier caps it at 2 MB). Then a **Code by Zapier**
(JavaScript) step with `docs/webhooks/connectors/zapier-code-step.js`.

Map four fields into that step's **Input Data** — `rawBody`, `webhookId`, `timestamp`, `signature` —
pointing at the raw body and the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers from
the trigger. The snippet reads those names on
purpose rather than guessing at Zapier's own field labels, which have moved between versions of the
Webhooks app: look at what your trigger actually produced in the editor and map it once.

For dedupe, use `payload.id` as the Zap's deduplication key — it equals `webhook-id` and `X-Otobiz-Event-Id`, and
without it a retry runs your Zap twice.

## Make

Make is the one platform where **signature verification is best-effort**, and you should know why
before you rely on it. A custom webhook parses the request; the body you can map is a parsed
structure, and reconstructing the bytes from it (`{{ createJSON(body) }}`) is a *re-serialisation* —
key order, spacing and non-ASCII characters can all come out differently from what we signed, and
then a perfectly good delivery fails the digest. Enabling header capture also folds the headers into
the bundle, so keep in mind which part you are hashing.

Make does have the primitive: the built-in **sha256** function takes an HMAC key plus key and output
encodings, so `"v1," + sha256("{webhook-id}.{webhook-timestamp}.{body}"; base64; secret)` is expressible. It is the input
you cannot guarantee, not the hash.

So on Make, prefer an authentication that does not depend on byte-exact bodies:

- register the endpoint with a **custom header** carrying a long random token (`customHeaders` on
  create, or the dashboard's header rows) and have the scenario compare that header before doing
  anything;
- keep the webhook URL itself secret, over HTTPS only.

That is bearer-token-grade: it proves the request came from someone holding the token, and unlike the
signature it does **not** prove the body was not altered in transit or that the delivery is recent.
If you need the stronger property on Make, put a small receiver in front — `verify.mjs` or
`verify.py` in a function-as-a-service — and have it forward verified deliveries to Make.

## Four ways a connection looks healthy on its side and failed on ours

Every value here was read out of the delivery engine, not remembered.

**1 · Respond immediately, or you will see failures you cannot explain.** Success is a `2xx` inside
**5 seconds** (`webhook_ack` in `base/knobs/timeouts.ts` `DEADLINES_MS`) — we abort the attempt at
that point and record a failure, while the tool's own execution finishes a minute later looking
perfectly green. So in n8n set the Webhook node's Respond to **Immediately**, never *When Last Node
Finishes*; in Zapier and Make the catch step already answers before your actions run. This is the
most likely "it works but Otobiz says it failed" report you will ever file.

**2 · Any `3xx` is a failure, and that is deliberate.** The sender uses `redirect: "manual"`
(`apps/src/features/webhooks/deliver.ts`) and treats a redirect as a refused attempt rather than
following it — following one would reopen the SSRF door that the URL guard exists to close, since a
public URL could then bounce a signed POST at a private address.

The practical consequence: **a Google Apps Script Web App cannot be a webhook target at all.** It
always answers `302` to `script.googleusercontent.com`, so every attempt fails and the delivery
stops after seven tries. This is not a bug to be fixed on either side — put something in front
(an n8n Webhook node, a small serverless function, `verify.mjs` on a small host) and have that call Apps
Script.

**3 · Do not subscribe with `["*"]` from an API key.** `requiredScopesForEvents` expands the
wildcard to the union of **every** group's read scope, so a key holding `webhooks:read` +
`webhooks:write` is refused with `403 insufficient_scope` naming `conversations:read`,
`contacts:read` and `commerce:read`. List the events you handle explicitly — which is better
practice anyway, and is what both n8n templates do.

> Unresolved, and worth knowing before you design around it: `WEBHOOKS.md` describes `["*"]` as
> "every event including ones added later", and fan-out re-checks scopes per event at delivery time
> — so the create-time union may be stricter than it needs to be. Whether it loosens is an owner
> decision, not a bug anyone should route around. The dashboard lane is unaffected: a wildcard
> endpoint registered at **Developer → Webhooks** works today.

**4 · If you read the delivery log over a key, send `limit` explicitly.** `GET /webhooks/logs`
on the key lane answered `400 "expected number, received NaN"`
to a request that omitted it. Fixed in the repo (`bc26373`) but not yet deployed, so send
`?limit=25` until it is. The dashboard lane always defaulted correctly.

## Sending events back the other way

None of the above lets an automation make Otobiz *send a message*, and that is deliberate: your
automation tells us something happened (`POST /api/v1/events`, scope `events:write`), and an automation
you published in Otobiz decides whether a message goes out — because that path is where consent,
suppression, idempotency and the 24-hour window live. A connector that could send directly would be
a way around all four.

## Published connector packages

`n8n-nodes-otobiz`, a Zapier Platform app and a Make custom app are **separate repositories** and
none exists yet (`todos/mcp.md` AT-1–AT-3). They would wrap exactly what this
page describes by hand: the `/webhooks` registry calls as a *Webhooks* resource, `/events` as an
action, and the catalog from `GET /api/v1/webhooks/settings` as the event picker's options. The Zapier one is key-authenticated rather than OAuth by owner decision
(2026-09-03), since there is no authorization server to be an OAuth app against.

Until one ships, this folder *is* the connector: the templates import in a minute and the verifier is
a copy-paste.

## What keeps this page honest

The snippets must verify against the repo's own signer (`apps/src/features/webhooks/standard-webhooks.ts`)
— valid, tampered, wrong secret, stale, forged timestamp, unsigned, a rotation pair. The Python, PHP and Go
files must keep the window, the key rule, the `{webhook-id}.{webhook-timestamp}.` construction, the `v1,`
base64 form and a constant-time compare against each value; both n8n templates must keep the
settings the scheme depends on; and `event-samples.json` must cover the event catalog exactly — a new event
ships with a sample and a removed one leaves none behind. Held by review.

The snippets re-state the scheme by hand instead of importing it, and that is on purpose: a shared
constant would let our sender and our documentation drift together silently. The test is what makes
the duplication safe.
