# Audience webhooks

`crm.webhooks` — `/v1/audience/webhooks`

HTTPS endpoints the platform POSTs contact events to.

Three things in this SDK are called a webhook; they are not the same thing:

| | Carries | Signed |
| --- | --- | --- |
| `crm.webhooks` | Contact events: created, updated, deleted | **yes** |
| [`crm.crmTriggers`](crm-triggers.md) | One configured request per rule, when a contact matches | no |
| [`crm.channelWebhooks`](../channels/webhooks.md) | A channel's message traffic | n/a |

**Permissions** — `CRM.WEBHOOK`: `LIST`, `READ`, `CREATE`, `UPDATE`, `DELETE`.
`READ` is a grant rather than a side effect of `LIST` because reading one
reveals the endpoint URL and its secret header.

Distinct from `CRM.CHANNEL.WEBHOOK`, which is where a *provider* delivers
inbound traffic for one channel.
**Scoping** — unlike the rest of the audience module, these rows are scoped by
**tenant** rather than by the calling user.

| Action | Route | Scope |
| --- | --- | --- |
| [`list`](#list) | `GET /v1/audience/webhooks` | `webhooks:read` |
| [`get`](#get) | `GET /v1/audience/webhooks/:id` | `webhooks:read` |
| [`create`](#create) | `POST /v1/audience/webhooks` | `webhooks:write` |
| [`update`](#update) | `PATCH /v1/audience/webhooks/:id` | `webhooks:write` |
| [`delete`](#delete) | `DELETE /v1/audience/webhooks/:id` | `webhooks:write` |


## The webhook object

```ts
interface Webhook {
  id: string;
  url: string;
  events: ('contact.created' | 'contact.updated' | 'contact.deleted')[];
  enabled: boolean;
  failureCount: number;     // consecutive delivery failures
  lastDeliveredAt?: string;
  createdAt: string;
  updatedAt: string;
}
```

## The delivery

Your endpoint receives:

```ts
interface WebhookEnvelope {
  id: string;         // delivery id, stable across retries of the same event
  type: string;       // e.g. 'contact.created'
  tenantId: string;
  createdAt: string;
  data: unknown;      // the contact, or { id } for a deletion
}
```

with two headers:

```
x-crm-timestamp: 1774512000
x-crm-signature: v1=<hex>
```

where the digest is `HMAC-SHA256(secret, "<timestamp>.<raw body>")`. Verify
against the **raw bytes**, before any JSON parsing:

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

const verify = (secret: string, timestamp: string, rawBody: string, header: string) => {
  const digest = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex');
  const expected = Buffer.from(`v1=${digest}`);
  const actual = Buffer.from(header);
  return expected.length === actual.length && timingSafeEqual(expected, actual);
};
```

Reject a timestamp too far from now to stop replays.

---

## list

```ts
crm.webhooks.list(query?: Partial<ListWebhooksQuery>): Promise<Page<Webhook>>
```

`GET /v1/audience/webhooks` · `webhooks:read` · **200**

**Cursor paginated**, not offset.

| Field | Type | Default | Notes |
| --- | --- | --- | --- |
| `limit` | number | `50` | 1–100. |
| `cursor` | string | — | From the previous response's `nextCursor`. |
| `enabled` | boolean | — | Accepted by the contract, but **not yet applied** by the service — the list comes back unfiltered. Filter client-side until that lands. |

---

## get

```ts
crm.webhooks.get(id: string): Promise<Webhook>
```

`GET /v1/audience/webhooks/:id` · `webhooks:read` · **200**

The signing secret is **never** returned here. It is shown once, by `create`.

---

## create

```ts
crm.webhooks.create(input: CreateWebhookInput): Promise<Webhook & { secret: string }>
```

`POST /v1/audience/webhooks` · `webhooks:write` · **201**

### Body

| Field | Type | Required | Default | Notes |
| --- | --- | --- | --- | --- |
| `url` | string | yes | — | Must be a valid absolute URL. |
| `events` | `WebhookEventType[]` | yes | — | At least one of `contact.created`, `contact.updated`, `contact.deleted`. |
| `enabled` | boolean | no | `true` | |

The URL has to be **public https**. A non-https URL, or a hostname resolving to
a loopback, link-local or private address, is rejected with
`422 invalid_webhook_url` — the DNS lookup happens at write time, so a name that
resolves privately is caught here rather than at delivery.

```ts
const hook = await crm.webhooks.create({
  url: 'https://ops.example.com/hooks/crm',
  events: ['contact.created', 'contact.updated'],
});

await vault.store(hook.secret);  // the only response that carries it
```

---

## update

```ts
crm.webhooks.update(id: string, input: UpdateWebhookInput): Promise<Webhook>
```

`PATCH /v1/audience/webhooks/:id` · `webhooks:write` · **200**

Same fields as `create`, all optional. A new `url` is checked the same way.
`events` **replaces** the subscription list rather than adding to it.

The secret does not change and cannot be rotated through this route — create a
second webhook, move over, and delete the first.

---

## delete

```ts
crm.webhooks.delete(id: string): Promise<void>
```

`DELETE /v1/audience/webhooks/:id` · `webhooks:write` · **204**, no body.

Delivery stops immediately; queued attempts are dropped. To pause instead, send
`update(id, { enabled: false })`.
