# Webhooks and events

> Every event Galerne emits, webhook filters, the payload, the t=…,v1=… signature with verification in TypeScript and Python, retries, and the event stream.

Everything that happens in a project is an event: a document published, a branch promoted, a review requested, an image uploaded. Webhooks send events to your URLs, and the event stream lets a long-running program or agent follow them live.

## Events

| Event | When |
|---|---|
| `doc.created` | A document is created on a branch, or a promotion creates it on `main` |
| `doc.updated` | A document's draft changes |
| `doc.published` | A document is published |
| `doc.unpublished` | A published version is removed |
| `doc.deleted` | A document is deleted |
| `branch.created` | A branch or release is created |
| `branch.promoted` | A branch is merged into `main` |
| `branch.closed` | A branch is closed without promotion |
| `review.requested` | Someone asks for review of a branch |
| `review.approved` | A reviewer approves a branch |
| `review.changes_requested` | A reviewer asks for changes |
| `comment.created` | A comment or task is added |
| `media.uploaded` | A new file is added to the library |
| `media.updated` | A file's details change |
| `media.deleted` | A file is deleted |
| `schema.deployed` | A new schema is deployed |
| `release.published` | A release is promoted and published, by hand or at its time |
| `release.rolled_back` | A promotion is rolled back |
| `source.synced` | A [data source](/docs/sources) run created, changed or removed docs |
| `source.failed` | A data source run failed or stopped on an empty or malformed answer |

## Add a webhook

In the project settings, open **Webhooks** and add a URL. It must use `https`. Galerne shows the signing secret, `whsec_…`, once.

Each webhook can filter what it receives. Empty filters match everything.

| Filter | Example | Matches |
|---|---|---|
| Events | `doc.published`, `doc.unpublished`, `media.*` | Exact names, or every event starting with the prefix before `.*` |
| Types | `post`, `page` | Events about documents of these types |
| Branches | `main` | Events on these branches |

A site that rebuilds on publish usually listens to `doc.published` and `doc.unpublished` on `main`. An agent that writes alt text listens to `media.uploaded`.

The Free plan includes 2 webhooks, Pro 20, and Business no limit.

## The request

Galerne sends a `POST` with a JSON body:

```json
{
  "id": "evt_8KfQ2x…",
  "type": "doc.published",
  "project": "acme",
  "branch": "main",
  "docId": "harbours",
  "docType": "post",
  "actor": { "kind": "human", "id": "acc_…", "name": "Marie" },
  "data": {},
  "tags": ["doc:harbours", "type:post", "all"],
  "at": "2026-10-16T09:22:41.000Z"
}
```

`actor.kind` is `human`, `agent`, `token` or `system`. `data` holds details that depend on the event, such as the source branch of a promotion or the number of changes in a schema deploy. `tags` lists the cache tags the event changes, the same ones [query answers](/docs/query.md#caching) carry: purge them to refresh what the change touched. The [Next.js kit](/docs/nextjs.md) has a ready route for it.

| Header | Value |
|---|---|
| `content-type` | `application/json` |
| `user-agent` | `Galerne-Webhooks/1` |
| `x-galerne-event` | The event type |
| `x-galerne-delivery` | The delivery id, the same across retries |
| `x-galerne-signature` | `t=<unix seconds>,v1=<hex HMAC-SHA256>` |

## Verify the signature

The signature is an HMAC-SHA256, keyed with the webhook secret, of the timestamp, a dot, and the raw request body: `<t>.<body>`. Check it against the raw bytes you received, before parsing the JSON, and reject timestamps more than five minutes old.

With the client:

```ts
import { verifyWebhook } from '@galerne/client'

export async function POST(request: Request) {
  const body = await request.text()
  const ok = await verifyWebhook(process.env.GALERNE_WEBHOOK_SECRET!, body, request.headers.get('x-galerne-signature'))
  if (!ok) return new Response('invalid signature', { status: 401 })
  const event = JSON.parse(body)
  if (event.type === 'doc.published') {
    // revalidate the pages that show event.docId
  }
  return new Response('ok')
}
```

With Node.js and no dependency:

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

export function verify(secret: string, body: string, header: string | null, toleranceSeconds = 300) {
  if (!header) return false
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=') as [string, string]))
  const t = Number(parts.t)
  if (!t || !parts.v1 || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false
  const expected = Buffer.from(createHmac('sha256', secret).update(`${t}.${body}`).digest('hex'), 'hex')
  const given = Buffer.from(parts.v1, 'hex')
  return expected.length === given.length && timingSafeEqual(expected, given)
}
```

With Python:

```python
import hashlib
import hmac
import time

def verify(secret: str, body: bytes, header: str | None, tolerance: int = 300) -> bool:
    if not header:
        return False
    parts = dict(part.split("=", 1) for part in header.split(","))
    try:
        t = int(parts["t"])
    except (KeyError, ValueError):
        return False
    if abs(time.time() - t) > tolerance or "v1" not in parts:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts["v1"])
```

## Retries

A delivery succeeds when your endpoint answers with a `2xx` status within 10 seconds. Redirects are not followed. Otherwise Galerne retries after 30 seconds, 2 minutes, 10 minutes, 1 hour and 6 hours: six attempts over about seven and a half hours, after which the delivery is marked failed.

Deliveries can arrive more than once and out of order. Use `x-galerne-delivery` or the event `id` to skip duplicates, and `at` to order them. The project settings show every delivery with its status and last error, and let you send one again.

## The event stream

The [event stream](/docs/events.md) page has the message format, filters and limits. Programs that run all the time, such as an agent waiting for new uploads, can follow events without a public URL. The event stream is part of Pro and up.

```bash
curl -N https://api.galerne.cloud/p/acme/v1/events/stream?types=media.uploaded,review.* \
  -H "Authorization: Bearer gal_…"
```

It is a Server-Sent Events stream. Each message has the event type as `event`, the event sequence number as `id`, and the event as JSON in `data`. A `ping` comes every 25 seconds when nothing happens. To resume after a disconnect, send the last id in the `Last-Event-ID` header, or pass `?since=<id>`. Without either, the stream starts with new events. The token needs the `read` scope.

`GET /p/<project>/v1/events?limit=50&before=<id>` lists recent events, newest first, on every plan.
