# Webhooks, Redirects & Operations

> Send signed outbound webhooks on content changes, handle automatic 301 SEO redirects when slugs change, and inspect idempotency operation receipts.

Under **Webhooks & Logs** in the Admin UI, OvertCMS gives you the operational tools needed to connect your CMS to external deploy pipelines, preserve SEO links, and audit automated writes.

## 1. Outbound Webhooks

Whenever content, schemas, or media change, OvertCMS records an event inside the **same atomic database transaction** as the change itself (`outbox_events`), and the background Worker Plane delivers signed HTTP `POST` notifications asynchronously. This guarantees you never lose an event even if your server restarts mid-request.

<Tip>
  **Testing webhooks locally:** By default, OvertCMS blocks webhooks targeting `localhost` or private IPs as SSRF protection. The fastest way to test locally is to paste a free temporary HTTPS URL from [webhook.site](https://webhook.site) into **Webhooks & Logs → Webhooks → Add Webhook**, edit/publish a post, and wait ~5 seconds for the worker tick. If you want to target a local server on `127.0.0.1`, set `OVERTCMS_WEBHOOK_ALLOW_PRIVATE_IPS=true` in your `.env.local`.
</Tip>

### Transactional Outbox Pipeline

```mermaid
flowchart LR
    Mut["Entry / Schema / Media\nMutation"] -->|"Single Atomic DB Tx"| DB[("Primary Tables +\noutbox_events")]
    DB -->|"worker:outbox_fanout\n(leased every 5s)"| Fanout["Outbox Processor"]
    Fanout --> Cache["Invalidate L2 Cache\n(Memory or Redis/Valkey)"]
    Fanout --> CDN["Optional CDN Purge\nWebhook (Surrogate-Key)"]
    Fanout --> Enq["Enqueue Matching\nwebhook_deliveries"]
    Enq -->|"worker:webhook_delivery\n(leased every 5s)"| Deliver["SSRF-Safe HTTP POST\n+ HMAC-SHA-256 Signature"]
    Deliver -->|"2xx"| Done["status: delivered"]
    Deliver -->|"Non-2xx / Network Error\n(attempt < 5)"| Retry["status: failed\nExponential Backoff"]
    Deliver -->|"Attempt 5 failed"| DLQ["status: dead_letter\n(Manual Admin Replay)"]
```

---

## Supported Webhook Events

Subscribe a webhook to `["*"]` (all events) or any subset of the **11 canonical domain events**:

| Event Name | Trigger |
| :--- | :--- |
| `entry.created` | A new `draft` entry is created. |
| `entry.updated` | An entry's `draftData` is modified (or a failed scheduled entry is demoted to draft). |
| `entry.published` | An entry is published (on create, manual publish, or scheduled auto-publish). |
| `entry.unpublished` | A published entry is unpublished back to `draft` (manual or scheduled `unpublishAt`). |
| `entry.scheduled` | An entry is created as or transitioned to `scheduled`. |
| `entry.archived` | An entry is archived. |
| `entry.trashed` | An entry is soft-deleted into `trashed`. |
| `entry.purged` | A trashed entry is permanently purged. |
| `schema.updated` | A site's Components or PostTypes schema changes. |
| `media.created` | A media asset finishes uploading, sideloading, or completing an upload intent. |
| `media.deleted` | A media asset is deleted. |

### Payload Envelope

Every webhook HTTP `POST` body uses a consistent JSON envelope:

```json
{
  "event": "entry.published",
  "siteId": "0193a8b0-0000-7000-8000-000000000001",
  "resourceType": "entry",
  "resourceId": "0193a8b2-1c4f-7e20-9a11-000000000099",
  "timestamp": "2026-11-25T15:30:00.123456789Z",
  "data": {
    "postType": "posts",
    "slug": "hello-overtcms",
    "locale": "en",
    "status": "published",
    "version": 2,
    "publicUrl": "https://acme.example.com/blog/hello-overtcms"
  }
}
```

---

## Outbound Request Headers

Every webhook delivery sets these HTTP headers:

| Header | Example / Value | Purpose |
| :--- | :--- | :--- |
| `Content-Type` | `application/json` | Canonical JSON payload. |
| `User-Agent` | `OvertCMS-Webhook/1.0` | Identifies OvertCMS Core (CDN purges use `OvertCMS-CDNPurge/1.0`). |
| `X-OvertCMS-Event` | `entry.published` | Event type name. |
| `X-OvertCMS-Delivery-ID` | `0193a8b5-...` | Unique UUIDv7 delivery ID (use for receiver-side idempotency!). |
| `X-OvertCMS-Timestamp` | `1764084600` | UTC Unix epoch seconds when the request was signed. |
| `X-OvertCMS-Signature` | `sha256=9f86d081...` | Hex-encoded HMAC-SHA-256 signature binding timestamp and raw body. |

---

## Managing Webhooks & Signing Secrets

Webhooks are managed on the Admin Plane (requires `site:manage` capability and fresh Step-Up MFA if enrolled):

- `POST /admin-api/v1/sites/{siteSlug}/webhooks` — Creates a webhook and returns `signingSecret` (`whsec_<64-hex>`) **once**. The secret is encrypted at rest with AES-256-GCM and never returned on `GET`.
- `PATCH /admin-api/v1/sites/{siteSlug}/webhooks/{id}` — Updates `name`, `url`, `events`, `enabled`, or rotates the secret by passing `"rotateSecret": true` (returns the new `signingSecret` once).
- `DELETE /admin-api/v1/sites/{siteSlug}/webhooks/{id}` — Deletes the webhook and cascades its delivery history.
- `GET /admin-api/v1/sites/{siteSlug}/webhooks/{id}/deliveries` — Keyset-paginated delivery log filterable by `status` (`pending`, `delivered`, `failed`, `dead_letter`).
- `POST /admin-api/v1/sites/{siteSlug}/webhooks/{id}/deliveries/{deliveryId}/replay` — Resets a `failed` or `dead_letter` delivery back to `pending` (`attempts: 0`) for immediate redelivery.

---

## Verifying Webhook Signatures (Replay-Safe)

OvertCMS Core computes `X-OvertCMS-Signature` over the concatenated string **`<timestamp>.<rawBody>`**:

```text
signature = "sha256=" + hex(HMAC_SHA256(secret, X-OvertCMS-Timestamp + "." + rawRequestBody))
```

Always verify:
1. `X-OvertCMS-Timestamp` is a strict base-10 Unix integer within your replay tolerance window (for example, `±5 minutes`).
2. The computed HMAC matches `X-OvertCMS-Signature` using a **constant-time comparison**.
3. You hash the **exact raw request bytes** before parsing JSON.

<Tabs>
  <Tab title="Go">
    ```go
    package webhookverify

    import (
    	"crypto/hmac"
    	"crypto/sha256"
    	"crypto/subtle"
    	"encoding/hex"
    	"io"
    	"net/http"
    	"strconv"
    	"strings"
    	"time"
    )

    func VerifyRequest(r *http.Request, secret string, maxAge time.Duration) ([]byte, bool) {
    	ts := strings.TrimSpace(r.Header.Get("X-OvertCMS-Timestamp"))
    	sig := strings.TrimSpace(r.Header.Get("X-OvertCMS-Signature"))
    	if secret == "" || ts == "" || sig == "" {
    		return nil, false
    	}

    	sec, err := strconv.ParseInt(ts, 10, 64)
    	if err != nil {
    		return nil, false
    	}
    	diff := time.Since(time.Unix(sec, 0).UTC())
    	if diff < 0 {
    		diff = -diff
    	}
    	if diff > maxAge {
    		return nil, false
    	}

    	body, err := io.ReadAll(io.LimitReader(r.Body, 2<<20))
    	if err != nil {
    		return nil, false
    	}

    	mac := hmac.New(sha256.New, []byte(secret))
    	mac.Write([]byte(ts))
    	mac.Write([]byte("."))
    	mac.Write(body)
    	expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))

    	if subtle.ConstantTimeCompare([]byte(expected), []byte(sig)) != 1 {
    		return nil, false
    	}
    	return body, true
    }
    ```
  </Tab>

  <Tab title="TypeScript (Node.js)">
    ```ts
    import crypto from "node:crypto";

    export function verifyOvertCMSWebhook(params: {
      secret: string;
      timestampHeader: string | undefined;
      signatureHeader: string | undefined;
      rawBody: Buffer | string;
      maxAgeSeconds?: number;
    }): boolean {
      const {
        secret,
        timestampHeader,
        signatureHeader,
        rawBody,
        maxAgeSeconds = 300,
      } = params;

      const ts = timestampHeader?.trim() ?? "";
      const sig = signatureHeader?.trim() ?? "";
      if (!secret || !/^\d+$/.test(ts) || !sig.startsWith("sha256=")) {
        return false;
      }

      const nowSec = Math.floor(Date.now() / 1000);
      if (Math.abs(nowSec - Number(ts)) > maxAgeSeconds) {
        return false;
      }

      const bodyBuf = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, "utf8");
      const mac = crypto.createHmac("sha256", secret);
      mac.update(ts);
      mac.update(".");
      mac.update(bodyBuf);
      const expected = `sha256=${mac.digest("hex")}`;

      const expectedBuf = Buffer.from(expected, "utf8");
      const providedBuf = Buffer.from(sig, "utf8");
      if (expectedBuf.length !== providedBuf.length) {
        return false;
      }
      return crypto.timingSafeEqual(expectedBuf, providedBuf);
    }
    ```
  </Tab>
</Tabs>

---

## Delivery Guarantees, Retries, DLQ & SSRF Defense

- **HTTP timeout & redirects**: Each delivery attempt has a **15-second** timeout (`defaultWebhookHTTPTimeout`). Redirects are **not followed** (`http.ErrUseLastResponse`) to prevent open-redirect SSRF pivots; any non-`2xx` status code is treated as a failure.
- **Retry backoff schedule** (`DefaultWebhookMaxAttempts = 5`):
  - After attempt 1 fails -> retry in **15 seconds**
  - After attempt 2 fails -> retry in **1 minute**
  - After attempt 3 fails -> retry in **5 minutes**
  - After attempt 4 fails -> retry in **15 minutes**
  - After attempt 5 fails -> transitions permanently to `dead_letter` (operators can inspect `httpStatus` and `lastError` and click **Replay** once the receiver is fixed).
- **SSRF protection**: Both at webhook creation/update time and at dial time in the Worker Plane, every DNS-resolved IP is checked with `media.IsPublicIP` (blocking localhost, RFC 1918 private networks, link-local/cloud metadata `169.254.0.0/16`, CGNAT, and IPv6 ULA). For local development against `localhost` receivers, explicitly set `OVERTCMS_WEBHOOK_ALLOW_PRIVATE_IPS=true`.

---

## 2. Automatic 301 Redirects

Whenever you change the **slug** of an already-published entry and re-publish it, OvertCMS automatically creates a **301 permanent redirect** from the old `publicUrl` path to the new one (and collapses multi-hop chains so `A → B → C` stays a single hop `A → C`).

- **View in Admin**: Open **Webhooks & Logs → Redirects** to see every active 301 mapping.
- **Consume in your client / edge proxy**: Fetch `GET /delivery/v1/redirects` during builds or edge middleware to serve 301 responses automatically without broken links.

---

## 3. Idempotency Operation Receipts

When an AI agent, script, or Admin UI sends a write request with an `Idempotency-Key` header, OvertCMS stores an operation receipt (`completed`, `in_progress`, or `failed`) with the HTTP status, request fingerprint, actor, and cached JSON response for 24 hours.

- **Inspect in Admin**: Open **Webhooks & Logs → Operations** and paste any `Idempotency-Key` (from your agent logs, **Audit Log → Details**, or an entry's **Idempotency-Key override** field) to verify exactly what happened.
- **Inspect via API**: `GET /admin-api/v1/sites/{siteSlug}/operations/{idempotencyKey}` (or `GET /agent/v1/operations/{idempotencyKey}` for the key's own writes).
