> ## Documentation Index
> Fetch the complete documentation index at: https://docs.octen.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Monitor Webhooks API Reference

> The payload Octen sends to a monitor's webhook URL after a run, and how to verify and acknowledge it.

After each run that generates events, Octen sends one HTTPS POST to the monitor's `webhook.url` with all of that run's events in `items`. Runs with no events send nothing.

## Request Headers

| Header | Description |
| - | - |
| `X-Octen-Event` | Always `monitor.run.completed`. |
| `X-Octen-Delivery` | The delivery id, such as `dlv_01JD…`. One per run, unchanged across retries; use it to deduplicate. |
| `X-Octen-Timestamp` | When this request was sent, in Unix seconds. Regenerated on each retry. |
| `X-Octen-Signature` | `sha256=` followed by 64 lowercase hex characters. Recomputed on each retry. See [Verify the Signature](#verify-the-signature). |
| `Content-Type` | `application/json`, UTF-8 encoded |
| `User-Agent` | `Octen-Webhook/1.0` |

## Payload

| Field | Type | Description |
| - | - | - |
| `event_type` | string | Always `monitor.run.completed`. |
| `monitor_id` | string | The monitor id. |
| `run_id` | string | The run that generated these events. |
| `items` | array | The events generated by this run. Notified items only. |
| `items[].event_type` | string | `monitor.new` for a new `topic` result, or `monitor.change` for a `page` change. |
| `items[].run_id` | string | Same as the top-level `run_id`. |
| `items[].detected_at` | string (date-time) | When the event was detected, in ISO 8601. Usually within 1 second of the top-level `detected_at`. |
| `items[].event_id` | string | The event id. |
| `items[].url` | string | The URL of the result or page. |
| `items[].title` | string | The title of the page. Returned only when available. |
| `items[].change_status` | string | `new`, `changed`, or `baseline` (the first run). |
| `items[].fields` | object | Values extracted with `output_schema`, keyed by `field_name`. Returned only when `output_schema` is set. |
| `items[].changed` | object | Previous and current values of each `output_schema` field, and whether it changed, keyed by `field_name`. `page` monitors only. |
| `items[].changed.<field_name>.previous` | string / number / boolean | The value before the change: the value at the last notification, or the first run's value if there hasn't been one. |
| `items[].changed.<field_name>.current` | string / number / boolean | The value after the change. |
| `items[].changed.<field_name>.changed` | boolean | Whether the field changed. |
| `items[].changed.<field_name>.delta` | number | The amount of change. Number fields only. |
| `items[].changed.<field_name>.pct` | number | The relative change, such as `-0.5` for a 50% drop. Number fields only. |
| `items[].previous_detected_at` | string (date-time) | When the previous value was recorded, in ISO 8601. `page` monitors only. |
| `items[].full_content` | string | Full raw page content. Always returned for `page` monitors; returned for `topic` monitors only if `full_content.enable` is true. |
| `items[].full_content_truncated` | boolean | If true, `full_content` was shortened. Returned only when shortened. |
| `items[].highlight` | string | Query-relevant highlight snippets. `topic` monitors only. |
| `items[].highlight_truncated` | boolean | If true, `highlight` was shortened. Returned only when shortened. |
| `items[].authors` | string | Website name or author. `topic` monitors only. |
| `items[].time_published` | string (date-time) | Publish time in ISO 8601. `topic` monitors only. |
| `items[].images` | array | Images on the result page. Returned only when `topic.include_images` is true. |
| `items[].images[].url` | string | The image URL. |
| `items[].images[].description` | string | Text description of the image. Returned only when available. |
| `items[].judgment` | object | The judgment result. |
| `items[].judgment.meaningful` | boolean | Whether the change was judged worth notifying. |
| `items[].judgment.confidence` | enum: `high`, `medium`, `low` | Confidence of the judgment. |
| `items[].judgment.reason` | string | Why the event was sent, such as `price: 51.77 → 45 (-13.1%) (price < 50)`. The format may change; to read field values, use `changed` or `fields`. Not returned on the first run of a monitor with no condition. |
| `metadata` | object | The monitor's `metadata`. Returned only when set. |
| `detected_at` | string (date-time) | When this run detected the changes, in ISO 8601. |

The body is limited to 1 MB. Above that, Octen shortens every item's `full_content` and `highlight` by the same ratio and sets `full_content_truncated` or `highlight_truncated`. Get the full content from [Get Monitor Run](https://docs.octen.ai/api-reference/get-monitor-run.md).

`metadata` and `webhook.url` use the monitor's configuration at the time of delivery.

Example for a `page` monitor with `output_schema`:

```json theme={null}
{
  "event_type": "monitor.run.completed",
  "monitor_id": "mon_123",
  "run_id": "run_789",
  "detected_at": "2026-11-16T14:00:07.123Z",
  "metadata": {
    "team": "pricing"
  },
  "items": [
    {
      "event_type": "monitor.change",
      "run_id": "run_789",
      "detected_at": "2026-11-16T14:00:07.120Z",
      "event_id": "evt_1",
      "url": "https://shop.example.com/products/widget-pro",
      "title": "Widget Pro – Example Shop",
      "change_status": "changed",
      "fields": {
        "price": 849
      },
      "judgment": {
        "meaningful": true,
        "confidence": "high",
        "reason": "price: 999 → 849 (-15.0%) (price change < -10%)"
      },
      "changed": {
        "price": {
          "previous": 999,
          "current": 849,
          "delta": -150,
          "pct": -0.1502,
          "changed": true
        }
      },
      "previous_detected_at": "2026-11-16T13:00:05.002Z",
      "full_content": "Widget Pro\nPrice: $849.00\nIn stock"
    }
  ]
}
```

The actual body is one line of JSON, and `<`, `>`, and `&` are escaped as `\u003c`, `\u003e`, and `\u0026`. Verify the signature against the raw bytes you receive.

## Verify the Signature

Every request is signed with the monitor's `webhook.secret`. Verify the signature before processing the payload.

### Signature Algorithm

`X-Octen-Signature` = `sha256=` + hex(HMAC-SHA256(key, signed payload)), in lowercase hex.

* **Signed payload**: the value of `X-Octen-Timestamp`, then `.`, then the raw request body, such as `1794873600.{"event_type":…}`.
* **Key**: the 32 bytes decoded from `webhook.secret`, not the string itself. Strip the `octen_whsec_` prefix and decode the remaining 52 characters as base32hex (RFC 4648, alphabet `0-9A-V`, uppercase, no `=` padding).

### Verification Steps

1. Read the raw request body bytes. Don't parse the JSON and serialize it again, or the bytes change and the signature won't match.
2. Reject the request if `X-Octen-Timestamp` is more than 300 seconds from your server's time in either direction. This prevents replay attacks; keep your clock synced with NTP.
3. Compute the expected signature and compare it with `X-Octen-Signature` in constant time (such as `hmac.compare_digest` in Python, `crypto.timingSafeEqual` in Node.js, or `hmac.Equal` in Go), not with `==`.
4. If verification fails, return `401` and don't process the body. Once it passes, deduplicate with `X-Octen-Delivery`, then return `2xx` as soon as possible and do slow work after you respond.

### Secret Management

* `webhook.secret` is returned only once, in one of three responses: [Create Monitor](https://docs.octen.ai/api-reference/post-monitor.md) with a webhook, [Update Monitor](https://docs.octen.ai/api-reference/patch-monitor.md) adding a webhook, or Update Monitor with `"webhook": {"rotate_secret": true}`. Save it right away.
* If the secret is lost or leaked, rotate it with `rotate_secret: true`; the response returns the new secret. Rotation takes effect immediately with no overlap: later deliveries and pending retries are signed with the new secret, so switch your receiver right away.
* Changing only `webhook.url` keeps the secret. Removing the webhook with `"webhook": null` and adding it again generates a new secret.

### Test Data

Use the test secret and body below to check your implementation. The body is the example payload above on one line, with no trailing newline. With the current time within 300 seconds of `1794873600`, verification passes.

```text theme={null}
secret     octen_whsec_000G40O40K30E209185GO38E1S8124GJ2GAHC5OO34D1M70T3OFG
key (hex)  000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
timestamp  1794873600
signature  sha256=9309edb5b4a823db5b205c61bfdc2eac893de3a02917780efc3b11a34d3966c5
```

```json theme={null}
{"event_type":"monitor.run.completed","monitor_id":"mon_123","run_id":"run_789","detected_at":"2026-11-16T14:00:07.123Z","metadata":{"team":"pricing"},"items":[{"event_type":"monitor.change","run_id":"run_789","detected_at":"2026-11-16T14:00:07.120Z","event_id":"evt_1","url":"https://shop.example.com/products/widget-pro","title":"Widget Pro – Example Shop","change_status":"changed","fields":{"price":849},"judgment":{"meaningful":true,"confidence":"high","reason":"price: 999 → 849 (-15.0%) (price change \u003c -10%)"},"changed":{"price":{"previous":999,"current":849,"delta":-150,"pct":-0.1502,"changed":true}},"previous_detected_at":"2026-11-16T13:00:05.002Z","full_content":"Widget Pro\nPrice: $849.00\nIn stock"}]}
```

### Example: Python

Standard library only, Python 3.8+. To use `decode_secret` and `verify` in a framework, read the raw request body, such as `request.get_data()` in Flask.

```python theme={null}
import base64
import hashlib
import hmac
import os
import time
from http.server import BaseHTTPRequestHandler, HTTPServer

PREFIX = "octen_whsec_"
TOLERANCE = 300  # seconds; matches Octen: 5 minutes either way

# base32hex (0-9A-V) -> standard base32 (A-Z2-7), decoded with the standard library; works before Python 3.10
_B32HEX = "0123456789ABCDEFGHIJKLMNOPQRSTUV"
_B32STD = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
_TO_STD = str.maketrans(_B32HEX, _B32STD)


def decode_secret(secret: str) -> bytes:
    """octen_whsec_<unpadded base32hex> -> 32-byte HMAC key."""
    if not secret.startswith(PREFIX):
        raise ValueError("secret must start with octen_whsec_")
    s = secret[len(PREFIX):]
    if any(c not in _B32HEX for c in s):
        raise ValueError("secret is not base32hex (0-9A-V, uppercase)")
    key = base64.b32decode(s.translate(_TO_STD) + "=" * (-len(s) % 8))
    if len(key) != 32:
        raise ValueError("decoded secret must be 32 bytes")
    return key


def verify(key: bytes, timestamp: str, signature: str, body: bytes, now=None) -> bool:
    """body must be the raw bytes received; don't parse and re-serialize it."""
    try:
        ts = int(timestamp)
    except (TypeError, ValueError):
        return False
    now = time.time() if now is None else now
    if abs(now - ts) > TOLERANCE:
        return False
    mac = hmac.new(key, f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(("sha256=" + mac).encode(), (signature or "").encode())


KEY = decode_secret(os.environ["OCTEN_WEBHOOK_SECRET"]) if "OCTEN_WEBHOOK_SECRET" in os.environ else None
seen = set()  # In-memory dedup for this example; in production, record X-Octen-Delivery in a database or Redis


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        if not verify(KEY, self.headers.get("X-Octen-Timestamp"), self.headers.get("X-Octen-Signature"), body):
            self.send_response(401)
            self.end_headers()
            return
        delivery_id = self.headers.get("X-Octen-Delivery")
        if delivery_id not in seen:
            seen.add(delivery_id)
            # Queue the body for async processing and return 2xx right away (Octen times out each request after 5 seconds)
        self.send_response(204)
        self.end_headers()


if __name__ == "__main__":
    HTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8000"))), Handler).serve_forever()
```

Run: `OCTEN_WEBHOOK_SECRET='octen_whsec_…' PORT=8000 python3 verify.py`

### Example: Node.js

Standard library only, Node.js 18+. With Express, read the raw body with `express.raw({ type: "application/json" })`, not `express.json()`.

```javascript theme={null}
const crypto = require("node:crypto");
const http = require("node:http");

const PREFIX = "octen_whsec_";
const TOLERANCE = 300; // seconds; matches Octen: 5 minutes either way
const B32HEX = "0123456789ABCDEFGHIJKLMNOPQRSTUV";

// octen_whsec_<unpadded base32hex> -> 32-byte HMAC key
function decodeSecret(secret) {
  if (!secret.startsWith(PREFIX)) throw new Error("secret must start with octen_whsec_");
  let bits = 0, value = 0;
  const out = [];
  for (const c of secret.slice(PREFIX.length)) {
    const v = B32HEX.indexOf(c);
    if (v < 0) throw new Error("secret is not base32hex (0-9A-V, uppercase)");
    value = (value << 5) | v;
    bits += 5;
    if (bits >= 8) {
      bits -= 8;
      out.push((value >>> bits) & 0xff);
    }
  }
  const key = Buffer.from(out);
  if (key.length !== 32) throw new Error("decoded secret must be 32 bytes");
  return key;
}

// body must be the raw bytes received (a Buffer); don't JSON.parse and re-serialize it
function verify(key, timestamp, signature, body, now = Date.now() / 1000) {
  if (!/^\d+$/.test(timestamp || "")) return false;
  const ts = Number(timestamp);
  if (Math.abs(now - ts) > TOLERANCE) return false;
  const expected = Buffer.from(
    "sha256=" + crypto.createHmac("sha256", key).update(`${ts}.`).update(body).digest("hex"),
  );
  const got = Buffer.from(signature || "");
  return got.length === expected.length && crypto.timingSafeEqual(got, expected);
}

module.exports = { decodeSecret, verify };

if (require.main === module) {
  const key = decodeSecret(process.env.OCTEN_WEBHOOK_SECRET);
  const seen = new Set(); // In-memory dedup for this example; in production, record X-Octen-Delivery in a database or Redis
  http
    .createServer((req, res) => {
      const chunks = [];
      req.on("data", (c) => chunks.push(c));
      req.on("end", () => {
        const body = Buffer.concat(chunks);
        if (!verify(key, req.headers["x-octen-timestamp"], req.headers["x-octen-signature"], body)) {
          res.writeHead(401).end();
          return;
        }
        const deliveryId = req.headers["x-octen-delivery"];
        if (!seen.has(deliveryId)) {
          seen.add(deliveryId);
          // Queue the body for async processing and return 2xx right away (Octen times out each request after 5 seconds)
        }
        res.writeHead(204).end();
      });
    })
    .listen(Number(process.env.PORT || 8000));
}
```

Run: `OCTEN_WEBHOOK_SECRET='octen_whsec_…' PORT=8000 node verify.js`

### Example: Go

Standard library only, Go 1.20+.

```go theme={null}
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base32"
	"encoding/hex"
	"errors"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"
)

const (
	prefix    = "octen_whsec_"
	tolerance = 5 * time.Minute // matches Octen: 5 minutes either way
)

// decodeSecret: octen_whsec_<unpadded base32hex> -> 32-byte HMAC key.
func decodeSecret(secret string) ([]byte, error) {
	if !strings.HasPrefix(secret, prefix) {
		return nil, errors.New("secret must start with octen_whsec_")
	}
	key, err := base32.HexEncoding.WithPadding(base32.NoPadding).DecodeString(strings.TrimPrefix(secret, prefix))
	if err != nil {
		return nil, err
	}
	if len(key) != 32 {
		return nil, errors.New("decoded secret must be 32 bytes")
	}
	return key, nil
}

// verify: body must be the raw bytes received; don't parse and re-serialize it.
func verify(key []byte, timestamp, signature string, body []byte, now time.Time) bool {
	ts, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil {
		return false
	}
	if d := now.Sub(time.Unix(ts, 0)); d > tolerance || d < -tolerance {
		return false
	}
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(strconv.FormatInt(ts, 10) + "."))
	mac.Write(body)
	expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(expected), []byte(signature))
}

func main() {
	key, err := decodeSecret(os.Getenv("OCTEN_WEBHOOK_SECRET"))
	if err != nil {
		log.Fatal(err)
	}
	var seen sync.Map // In-memory dedup for this example; in production, record X-Octen-Delivery in a database or Redis
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(io.LimitReader(r.Body, 8<<20))
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		if !verify(key, r.Header.Get("X-Octen-Timestamp"), r.Header.Get("X-Octen-Signature"), body, time.Now()) {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		if _, dup := seen.LoadOrStore(r.Header.Get("X-Octen-Delivery"), true); !dup {
			// Queue the body for async processing and return 2xx right away (Octen times out each request after 5 seconds)
		}
		w.WriteHeader(http.StatusNoContent)
	})
	port := os.Getenv("PORT")
	if port == "" {
		port = "8000"
	}
	log.Fatal(http.ListenAndServe(":"+port, nil))
}
```

Run: `OCTEN_WEBHOOK_SECRET='octen_whsec_…' PORT=8000 go run main.go`

## Respond and Retry

* Return any `2xx` to acknowledge. The response body is ignored. Each request times out after 5 seconds, so do slow work after you respond.
* Redirects aren't followed: a `3xx` counts as a failure.
* Return `410` to stop retrying this delivery.
* Any other status code, a timeout, or a connection failure is retried with backoff: each delivery is attempted up to 4 times, with retries about 30 seconds, 2 minutes, and 10 minutes after the first failure.
* After 4 failed attempts or a `410`, the delivery isn't resent. The webhook stays configured, the monitor keeps running, and later runs deliver as usual. Octen also emails the account owner (the organization owner for organization accounts), at most once per monitor every 24 hours.
* Undelivered events can still be fetched with [List Monitor Events](https://docs.octen.ai/api-reference/get-monitor-events.md), where `delivered` is `false` (or `true` if that run's email was sent). Events, runs, and delivery records are kept for 30 days.
* Deduplicate retries with `X-Octen-Delivery`. If you also pull events, skip ones you've already processed by `items[].event_id`.

## Email Notifications

With `email` set, each run that generates events sends one digest to each recipient, listing up to 10 items. For `page` monitors, the digest shows the changed fields with previous and current values; without `output_schema`, it shows a content excerpt and, after the first run, a short summary of the change. For `topic` monitors, it shows the new results with highlights.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.