# Webhooks

> The request a webhook alert channel receives - headers, body fields, event types, retries - and how to verify its signature, with code in JavaScript, Python and Go.

A [webhook channel](https://docs.monitorly.cloud/alerts/webhook.md) sends each alert as one `POST` with a JSON body to your endpoint. Answer with any 2xx status within 10 seconds.

## Request

```http
POST /monitorly HTTP/1.1
Content-Type: application/json
User-Agent: Monitorly-Notifier/<version>
Monitorly-Event-Id: <delivery id>
Monitorly-Event-Type: check.down
Monitorly-Signature: t=1794232920,v1=<hex>

{"id":"<delivery id>","type":"check.down","occurredAt":"2026-11-10T14:02:00Z", …}
```

| Header                 | Value                                                                                 |
| ---------------------- | ------------------------------------------------------------------------------------- |
| `Monitorly-Event-Id`   | The delivery id: the same on every retry of one message. Use it to discard duplicates |
| `Monitorly-Event-Type` | The same as `type` in the body                                                        |
| `Monitorly-Signature`  | `t=<unix seconds>,v1=<hex HMAC-SHA256>`, see [below](#verify-the-signature)           |

## Body

| Field                        | Value                                                                                                                                                 |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                         | The delivery id, as `Monitorly-Event-Id`                                                                                                              |
| `type`                       | The event type, below                                                                                                                                 |
| `occurredAt`                 | When the event happened, RFC 3339 in UTC                                                                                                              |
| `sentAt`                     | When this attempt was sent                                                                                                                            |
| `lateMinutes`                | Minutes late when delivery is more than 5 minutes late, otherwise `null`                                                                              |
| `attempt`                    | Attempt number, from 1                                                                                                                                |
| `text`                       | The message as people read it in email and Telegram                                                                                                   |
| `workspaceId`, `projectId`   | Where it comes from; `projectId` is `null` for workspace notifications                                                                                |
| `check`                      | `{id, name}` or `null`                                                                                                                                |
| `incident`                   | `{id, openedAt, closedAt}` or `null`                                                                                                                  |
| `outage`                     | `{from, to, minutes}` on recovery, otherwise `null`                                                                                                   |
| `escalation`                 | `{level, round}` on `check.down` and `check.escalation` (round 2 is the first repeat), otherwise `null`                                               |
| `ackUrl`                     | The incident's acknowledge link while it is open and not acknowledged, otherwise `null`. It opens the dashboard; a request to it acknowledges nothing |
| `node`                       | `{id, lastSeenAt}` on `node.offline`, otherwise `null`                                                                                                |
| `expiresAt`, `thresholdDays` | On `certificate.expiring` and `domain.expiring`                                                                                                       |

## Event types

| `type`                               | When                                                                         |
| ------------------------------------ | ---------------------------------------------------------------------------- |
| `check.down`                         | A check is DOWN: an incident opened                                          |
| `check.escalation`                   | A later level or a repeat of the incident's escalation policy                |
| `check.recovered`                    | The check is UP again; `outage` has the downtime                             |
| `check.down_recovered`               | The incident closed before its DOWN could be delivered: one message for both |
| `check.still_down_after_maintenance` | A maintenance window ended and the target is still down                      |
| `certificate.expiring`               | An SSL certificate crosses a warning threshold                               |
| `domain.expiring`                    | A domain registration crosses a warning threshold                            |
| `node.offline`                       | A private node has been offline for more than 5 minutes                      |
| `test`                               | **Send test** in the dashboard                                               |

Accept and ignore types you do not know: new ones are added over time.

## Retries

| Your answer                                                                  | What happens                                                                                                         |
| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| 2xx                                                                          | Delivered                                                                                                            |
| 429                                                                          | Retried after `Retry-After`; every pending message of the channel waits as long                                      |
| 408, 425, 5xx, a timeout or a network error                                  | Retried with backoff from 5 seconds, doubling up to 30 minutes, for 24 hours; then the channel is **Not delivering** |
| 401, 403, 404, 410, a redirect other than 307 or 308, or an internal address | The channel is **Not delivering** at once                                                                            |
| Any other 4xx                                                                | This message is dropped; the channel stays active                                                                    |

307 and 308 redirects are followed up to 3 hops, each address checked again. Messages of one incident arrive in order: the next one waits until the previous one is delivered.

## Verify the signature

Every request is signed with the channel's secret, the `whsec_…` value shown once when the channel was created. To check a request:

1. Read `t` and `v1` from `Monitorly-Signature`.
2. Compute HMAC-SHA256 keyed with the whole secret, `whsec_` included, over `<t>.<raw body>`: the timestamp, a dot, and the body bytes exactly as received, before any JSON parsing.
3. Compare its hex form with `v1` in constant time.
4. Reject the request when `t` is more than 5 minutes away from your clock. Each retry is signed again with a new `t`.

To test your code: the secret `whsec_test`, `t = 1794232920` and the body `{"type":"test"}` give

```text
Monitorly-Signature: t=1794232920,v1=7c186512197c7ca0d4dd36b0d00f1de256bbd01f984c02c237bee266db1157b8
```

```js title="verify.mjs"
import { createHmac, timingSafeEqual } from "node:crypto";

// rawBody: the request body as received (a string or a Buffer), not re-serialized JSON.
export function verified(secret, header, rawBody, now = Date.now() / 1000) {
  const parts = Object.fromEntries(header.split(",").map((part) => part.split("=", 2)));
  const t = Number(parts.t);
  if (!Number.isFinite(t) || Math.abs(now - t) > 300 || typeof parts.v1 !== "string") return false;
  const expected = createHmac("sha256", secret).update(`${parts.t}.`).update(rawBody).digest("hex");
  return parts.v1.length === expected.length && timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected));
}
```

```python title="verify.py"
import hashlib
import hmac
import time


def verified(secret: str, header: str, raw_body: bytes, now: float | None = None) -> bool:
    """raw_body: the request body bytes as received, not re-serialized JSON."""
    parts = dict(part.split("=", 1) for part in header.split(",") if "=" in part)
    try:
        t = int(parts["t"])
        v1 = parts["v1"]
    except (KeyError, ValueError):
        return False
    if abs((time.time() if now is None else now) - t) > 300:
        return False
    expected = hmac.new(secret.encode(), f"{parts['t']}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(v1, expected)
```

```go title="verify.go"
package webhook

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"time"
)

// Verified reports whether header signs rawBody, the request body bytes as received.
func Verified(secret, header string, rawBody []byte, now time.Time) bool {
	var t, v1 string
	for _, part := range strings.Split(header, ",") {
		key, value, _ := strings.Cut(part, "=")
		switch key {
		case "t":
			t = value
		case "v1":
			v1 = value
		}
	}
	unix, err := strconv.ParseInt(t, 10, 64)
	if err != nil || now.Sub(time.Unix(unix, 0)).Abs() > 5*time.Minute {
		return false
	}
	got, err := hex.DecodeString(v1)
	if err != nil {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(t + "."))
	mac.Write(rawBody)
	return hmac.Equal(got, mac.Sum(nil))
}
```

## Good practice

- Answer quickly with 2xx and do the work afterwards; a slow endpoint risks the 10-second timeout and a retry.
- Store `Monitorly-Event-Id` for a day and skip ids you have already handled.
- Keep the secret out of source control. If it leaks, remove the channel and add it again: the new channel gets a new secret.
