# Webhooks

> Webhooks from Naruska CRM: event types, what arrives, how to verify the signature, retries and limits.

Naruska CRM sends an HTTPS `POST` to your server when something changes in your company's data. This page is for developers who receive those requests: what arrives, how to check it is really from us, and what we do when your server fails.

Webhooks follow the [Standard Webhooks](https://www.standardwebhooks.com) signing scheme, so most existing verification libraries work unchanged.

## What to know first

- **Delivery is at least once.** The same event can arrive more than once (a retry after a timeout, a redelivery). **Deduplicate on `webhook-id`.**
- **There is no ordering guarantee.** Use `timestamp` (when the change happened), not the arrival order.
- **Payloads carry changes only.** `data.changes` lists the fields that changed, not the whole record. **Re-fetch the record** from the API (`GET /v1/contacts/{id}` and so on) when you need its current state.
- **Child changes do not fire events yet.** Emails, phones, addresses, tags and affiliations of a contact or account are not events in this version; changing only those sends nothing.
- Respond with any `2xx` within **10 seconds**. Do the real work after you have answered.

## Set up an endpoint

Only admins manage endpoints, through the API or through an AI tool over MCP (`manage_webhooks`). There is no screen for it in the web app yet.

```
POST /v1/webhook-endpoints
{ "url": "https://hooks.example.com/naruska", "event_types": ["contact.created", "opportunity.won"],
  "description": "Billing sync" }
```

The response contains the signing secret (`whsec_…`) **once**. Store it now. A replay of the same request (same `Idempotency-Key`) returns `secret: null`; to get a new secret, rotate it.

The token needs the `webhooks:manage` scope. Every route is in the [Webhooks API reference](/api/reference/webhooks.md).

### URL rules

- `https` only, port 443 (or none), no user name or password in the URL.
- The host must be a public DNS name: no IP addresses, `localhost`, `.local` or `.internal`, and not `naruskacrm.com` or its subdomains.
- The name must resolve to public addresses only (no private, loopback, link-local or reserved ranges). We check this when you save the endpoint **and at every delivery**.
- Redirects are never followed. A `3xx` answer counts as a failed attempt (`error_code: redirect`). Give us the final URL.

A refused URL returns `422 invalid_webhook_url` with a `reason`: `url_scheme`, `url_port`, `url_userinfo`, `url_host`, `url_invalid` or `url_unresolvable`.

DNS can change between our check and our connection; we cannot pin the resolved address, so keep your receiver behind your own authentication (the signature below).

## Event types

`GET /v1/webhook-event-types` lists them. An endpoint subscribes to a subset.

| Type                                                                            | Fires when                                                                                                                                                                                           |
| ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `contact.created`, `account.created`, `opportunity.created`, `note.created`     | A record is created. Later updates in the same change are folded into `changes`.                                                                                                                     |
| `contact.updated`, `account.updated`, `opportunity.updated`                     | Fields changed. One event per change, with the first old and last new value of each field. Fields that end up unchanged are dropped.                                                                 |
| `contact.deleted`, `account.deleted`, `opportunity.deleted`                     | A record was soft-deleted.                                                                                                                                                                           |
| `contact.restored`, `account.restored`, `opportunity.restored`                  | A deleted record was restored.                                                                                                                                                                       |
| `contact.merged`, `account.merged`                                              | A duplicate was merged into another record (`data.merged_into_id`).                                                                                                                                  |
| `activity.created`, `activity.updated`, `activity.deleted`, `activity.restored` | The same as for other records, for tasks, meetings and calls.                                                                                                                                        |
| `activity.completed`                                                            | An activity was marked done (`done_at` went from empty to a time). Fires **in addition to** `activity.updated`, or to `activity.created` when the activity was logged as already done.               |
| `opportunity.stage_changed`                                                     | A deal moved to another stage. Always fires on a stage change.                                                                                                                                       |
| `opportunity.won`, `opportunity.lost`                                           | A deal moved into a won or lost stage. Fires **in addition to** `stage_changed`.                                                                                                                     |
| `quote.created`, `quote.updated`, `quote.deleted`, `quote.restored`             | The same as for other records, for quotes. Versions and lines fire nothing of their own.                                                                                                             |
| `quote.status_changed`                                                          | A quote's status changed. Always fires on a status change.                                                                                                                                           |
| `quote.sent`                                                                    | A quote was sent: its latest version was frozen and its PDF created. Fires **in addition to** `status_changed`.                                                                                      |
| `quote.accepted`                                                                | A quote was accepted. Fires **in addition to** `status_changed`. The deal moves to won in the same change, so `opportunity.stage_changed` and `opportunity.won` arrive too if you subscribe to them. |
| `document.created`                                                              | A file was uploaded, a link added or a quote PDF stored (`data.links` lists the linked record ids).                                                                                                  |
| `document.deleted`                                                              | A document was soft-deleted.                                                                                                                                                                         |
| `case.created`, `case.updated`, `case.deleted`, `case.restored`                 | The same as for other records, for cases.                                                                                                                                                            |
| `case.status_changed`                                                           | A case's status changed. Always fires on a status change.                                                                                                                                            |
| `case.closed`                                                                   | A case was closed: its status category became closed. Fires **in addition to** `status_changed`, once per close.                                                                                     |
| `campaign.created`, `campaign.updated`, `campaign.deleted`, `campaign.restored` | The same as for other records, for campaigns.                                                                                                                                                        |
| `campaign_member.added`                                                         | A contact was added to a campaign, or a removed membership came back (undo, or a restored campaign or contact). One event per member.                                                                |
| `campaign_member.updated`                                                       | A member's `member_status` changed.                                                                                                                                                                  |
| `campaign_member.removed`                                                       | A contact was removed from a campaign, or the membership went with a deleted campaign or contact. One event per member.                                                                              |

Rules worth knowing:

- A deal **created directly in any stage, including won or lost, sends only `opportunity.created`**. No `stage_changed`, `won` or `lost`.
- The stage fields (`stage_id`, `closed_at`, `close_rate`, `close_reason`) are not part of `opportunity.updated`; they arrive with the stage events. `opportunity.updated` fires only if other fields changed too.
- Reopening a done activity sends only `activity.updated`. Adding or removing the people on an activity sends nothing.
- Activity events carry the linked record ids (`account_id`, `opportunity_id` and the contact ids) even when the person who made the change can't read those records. An endpoint belongs to the company and is set up by an admin, and it already receives every opportunity event, so the ids are not masked. Names and amounts are never in a payload.
- A permanent delete (purge) and an erasure send nothing.
- The status fields (`status_id`, `accepted_version_id`) are not part of `quote.updated`; they arrive with the status events. A quote created as a draft sends only `quote.created`.
- Document events carry ids only: never the file name, URL, contents or a download link. Fetch the file with `GET /v1/documents/{id}/content` or a signed link.
- The status fields (`status_id`, `resolved_at`) are not part of `case.updated`; they arrive with the status events. A case created as closed sends only `case.created`.
- Adding many members sends one `campaign_member.added` per member: adding 500 contacts is 500 events for each subscribed endpoint, and each counts as a delivery on your plan.
- Like other events, case and campaign events carry the record's own changed fields and the linked records by id only (`contact_id`, `account_id`, `opportunity_id`, `campaign_id`), never a linked record's name. Opportunity events carry `source_campaign_id` and activity events `case_id` the same way.
- `ping` is a test event, sent only when you ask for one (`POST /v1/webhook-endpoints/{id}/test`). It is not subscribable.

## What arrives

```
POST /naruska HTTP/1.1
Content-Type: application/json
User-Agent: Naruska-Webhooks/1.0
webhook-id: evt_01931e5c-7b3a-7c2e-9a41-5d1f0e2b8c33
webhook-timestamp: 1789158000
webhook-signature: v1,K5oZfzN0AqK0c4mU3Gm0wq5u8pQmM3B7y1l3nXk2v8E=
```

```json
{
  "id": "evt_01931e5c-7b3a-7c2e-9a41-5d1f0e2b8c33",
  "type": "contact.updated",
  "timestamp": "2026-11-12T10:20:00.000Z",
  "data": {
    "object": "contact",
    "id": "0193…",
    "changes": { "job_title": ["Buyer", "Head of purchasing"], "custom": { "segment": ["smb", "mid"] } },
    "operation_id": "0193…",
    "via": "web",
    "actor_user_id": "0193…"
  }
}
```

- `id` is the event id, the same in the body and in `webhook-id`. If two of your endpoints subscribe to the same event, both get the same id.
- `timestamp` is when the change happened. It is not the time of the attempt; `webhook-timestamp` (seconds) is, and it is fresh on every attempt.
- `data.changes` maps each changed field to `[old, new]`. Custom fields are under `custom`. A created record lists its initial values with `null` as the old value; delete, restore and merge events have `{}`.
- `data.operation_id` is the change's operation id (the same one an `undo` takes). `data.via` is `web`, `token`, `integration:<name>`, `mcp:<client>` or `undo`. `data.actor_user_id` is the person (or service account) who made the change.
- `opportunity.stage_changed`, `.won` and `.lost` add `data.stage`: `{ "from": {api_key, name, category}, "to": {api_key, name, category} }`.
- `quote.status_changed`, `.sent` and `.accepted` add `data.status` in the same shape.
- `case.status_changed` and `.closed` add `data.status` in the same shape.
- `campaign_member.*` events add `data.campaign_id` and `data.contact_id`.
- `document.created` adds `data.links`: `{ "contact_ids": [], "account_ids": [], "opportunity_ids": [], "quote_ids": [], "case_ids": [] }`.
- `*.merged` adds `data.merged_into_id`.

## Verify the signature

Always verify, and reject anything that fails. The signed text is `webhook-id`, `webhook-timestamp` and the **raw request body**, joined with dots:

```
signed_content = "<webhook-id>.<webhook-timestamp>.<raw body>"
signature      = "v1," + base64( HMAC-SHA256( key, signed_content ) )
```

`key` is the secret **without** the `whsec_` prefix, base64-decoded (32 bytes).

1. Read the raw body before any JSON parsing; re-serialised JSON will not match.
2. Compute the signature with each secret you hold and compare in constant time.
3. `webhook-signature` may hold **two** space-separated signatures (see rotation). Accept if any matches.
4. Reject if `webhook-timestamp` differs from your clock by more than 5 minutes (this stops replays).
5. Deduplicate on `webhook-id`.

With the Standard Webhooks library:

```js
import { Webhook } from "standardwebhooks";

const wh = new Webhook(process.env.NARUSKA_WEBHOOK_SECRET); // the whsec_… value
// headers: webhook-id, webhook-timestamp, webhook-signature; rawBody: the unparsed string
const event = wh.verify(rawBody, headers); // throws if the signature or timestamp is wrong
```

Without a library (Node):

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

function verify(secret, headers, rawBody, toleranceSeconds = 300) {
  const id = headers["webhook-id"],
    ts = headers["webhook-timestamp"];
  if (Math.abs(Date.now() / 1000 - Number(ts)) > toleranceSeconds) return false;
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = "v1," + createHmac("sha256", key).update(`${id}.${ts}.${rawBody}`).digest("base64");
  return headers["webhook-signature"].split(" ").some((s) => {
    const a = Buffer.from(s),
      b = Buffer.from(expected);
    return a.length === b.length && timingSafeEqual(a, b);
  });
}
```

Without a library (Python 3.9 or later):

```python
import base64, hashlib, hmac, time

def verify(secret, headers, raw_body, tolerance=300):
    msg_id, ts = headers["webhook-id"], headers["webhook-timestamp"]
    if abs(time.time() - int(ts)) > tolerance:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{ts}.".encode() + raw_body  # raw_body: the unparsed bytes
    expected = "v1," + base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    return any(hmac.compare_digest(s, expected) for s in headers["webhook-signature"].split(" "))
```

### Rotate the secret without downtime

`POST /v1/webhook-endpoints/{id}/rotate-secret` returns a new secret (shown once). For the next **24 hours** every delivery carries two signatures, one made with the new secret and one with the previous. Deploy the new secret on your side during that window; verification keeps working throughout. After 24 hours only the new secret signs.

Two rotations within 24 hours leave only the latest previous secret valid: the older one stops working at the second rotation. A rotation cannot be undone.

## What counts as success, and retries

An attempt succeeds on any `2xx` answer within 10 seconds. Anything else fails: another status (`http_error`), a redirect (`redirect`), a timeout (`timeout`), a connection error (`network_error`), or a URL that no longer passes the rules above.

A failed event is retried on this schedule, with no jitter:

| Attempt | When                           |
| ------- | ------------------------------ |
| 1       | immediately                    |
| 2       | 1 minute after attempt 1 fails |
| 3       | 5 minutes after attempt 2      |
| 4       | 30 minutes after attempt 3     |
| 5       | 2 hours after attempt 4        |
| 6       | 6 hours after attempt 5        |
| 7       | 12 hours after attempt 6       |
| 8       | 24 hours after attempt 7       |

The times are the earliest an attempt can run. Attempt 1 is sent right after the change is saved. A retry is sent when it is due and our delivery service next runs: right away if another event is sent by then, otherwise at its next scheduled check, which runs **every 5 minutes**. So each retry can come up to 5 minutes later than the table says (attempt 2 between 1 and about 6 minutes after attempt 1 fails). The same 5-minute bound applies to attempt 1 in the rare case that the change didn't trigger an immediate send.

After attempt 8 the event is **dead**. Dead events can be redelivered for 30 days (below).

### Paused endpoints

When an endpoint has had **20 consecutive failed attempts and the failures span more than 24 hours**, we pause it (`status: paused`, `paused_reason: consecutive_failures`). Its queued events become dead (redeliverable), and no new events are queued while it is paused. An admin resumes it with `PATCH /v1/webhook-endpoints/{id}` and `{"status": "active"}`, which resets the counters. A test event does not count towards pausing.

### Redelivery and the delivery log

- `GET /v1/webhook-endpoints/{id}/deliveries` lists attempts with status, response status, a short excerpt of your response, duration and error code. The log is kept 30 days.
- `POST /v1/webhook-endpoints/{id}/deliveries/{delivery_id}/redeliver` sends one dead event again. The event keeps its `webhook-id`.
- `POST /v1/webhook-endpoints/{id}/redeliver` sends every dead event of the endpoint that is still inside the 30-day window; an optional `{since, until}` narrows it. The endpoint must be active.
- `POST /v1/webhook-endpoints/{id}/test` sends a `ping` event, once, with no retries. It is a diagnostic: it is not redeliverable and does not affect pausing.

## Plans and limits

| Plan     | Active endpoints | Delivery attempts per month |
| -------- | ---------------- | --------------------------- |
| Free     | 1                | 1,000                       |
| Team     | 5                | 10,000                      |
| Business | 20               | 30,000                      |

Every attempt counts, retries and test events included; an attempt that is refused by the URL rules or by the quota does not. From 95 % of the monthly quota the usage headers warn; delivery continues up to 105 %, then we stop sending: attempts are recorded as dead with `error_code: quota_exceeded`, nothing is counted against your endpoint, and the events stay redeliverable. Creating or resuming an endpoint beyond the plan's cap returns `429 cap_reached`. A `disabled` endpoint (turned off by an admin) receives nothing and does not count towards the cap.

## Checking a receiver

Send yourself a test event (`POST /v1/webhook-endpoints/{id}/test`), capture the request as it arrived (the three `webhook-` headers and the raw body), and run one of the functions above on it with your secret. To check an older capture, raise the tolerance so the 5-minute clock check doesn't reject it. Keep the secret in an environment variable or a secret store while you test, never in a command line or in code.

## Security notes

- The signing secret is stored encrypted and is never shown again, never listed, never written to logs or the audit log.
- Treat the secret like a password. Put it in your secret store, not in code.
- Endpoint URLs are returned to admins by the API only; MCP result texts show the host, never the full URL.
