# Webhooks

ConnectCloud pushes events to your systems as **signed HTTP POST requests**, following the
[Standard Webhooks](https://www.standardwebhooks.com) specification. All outgoing webhooks are sent
by the Comms module, so they share one configuration, one retry policy and one delivery log.

## Set up outgoing webhooks

You need `comms:admin` (or do it in the portal: **Einstellungen › Benachrichtigungen**).

**1. Create a webhook channel**: where events go.

```bash
curl -X POST 'https://api.mbcom.cloud/api/comms/v1/channels' \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  --data '{
    "kind": "webhook",
    "name": "Ticket-Sync",
    "config": { "format": "json_event" },
    "secrets": {
      "url": "https://integration.example.com/connectcloud/events",
      "signingSecret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"
    }
  }'
```

- `format`: `json_event` (the JSON body below) or `teams_card` (a Microsoft Teams Adaptive Card,
  for Teams or Power Automate workflows).
- `url` is stored encrypted (webhook URLs often contain a token) and never returned.
- `signingSecret` is `whsec_` + base64 of at least 24 random bytes. Leave it out and a secret is
  generated for you. Secrets are never returned by the API.
- The URL must be a public address (use HTTPS); internal addresses are refused and redirects are not followed.
- [`POST /channels/{id}/test`](/reference/comms/testChannel) sends a `comms.test` event.

**2. Decide which events are announced: a flow.** Comms has no notification rules of its own (the `/rules` routes are
gone): what happens when an event occurs is a [flow](/guides/flows) with an `event` trigger and, to tell people, a
`mail` node.

```yaml
schemaVersion: 1
key: kritische-tickets-melden
name: Kritische Tickets melden
triggers:
  - { id: neues_ticket, kind: event, event: desk.item.created, filter: "trigger.data.priority in ['hoch', 'kritisch']" }
nodes:
  info:
    kind: mail
    to: ["group:<group id>", "channel:<id of the webhook channel>"]
    subject: "Kritisches Ticket {{ trigger.data.number }}"
    text: "{{ trigger.data.title ?? '' }}"
edges:
  - neues_ticket -> info
```

- **A webhook channel is addressed with `to: ["channel:<id>"]`** – the id of the channel from step 1 (a Microsoft
  Teams channel of comms is addressed the same way). Each channel gets one request per run of the node, without
  recipients; its `type` is `flows.message` (see "A flow's message" below).
- The same `to` list reaches people: employees (`person:<e-mail>` or the bare address, `employee:<id>`), groups
  (`group:<id>`), roles (`role:<id>`) and managers (`manager:<e-mail or employee id>`). A company flow (a tenant flow)
  also mails addresses outside the company; a personal flow reaches employees only.
- `mandatory: true` (people cannot switch the mail off in their notification settings) and `mailChannel: <id>` (the
  e-mail channel the people's mail is sent through instead of the default) are reserved for company flows without
  scope, managed with `tenant:flows:admin`; in a personal or scoped flow the draft reports
  `mail_option_not_allowed` and is not published.
- The events a flow can start on, with their payload schemas, are listed by the flows catalogue
  ([`GET /catalog`](/reference/flows/getFlowsCatalog)); the `filter` is an expression over `trigger.data`.
- People can also subscribe to events for themselves in their own notification settings (personal subscriptions); the
  events offered there and their fields are listed by [`GET /bootstrap`](/reference/comms/getBootstrap) of comms.
  Examples: `desk.item.created`, `desk.item.transitioned`, `desk.item.commented`, `desk.item.handed_off`,
  `forge.item.created`, `forge.item.status_changed`, `hr.absence.requested`, `hr.absence.approved`,
  `hr.travel.submitted`, `hr.application.received`, `hr.interview.confirmed`, `trade.invoice.issued`,
  `dms.document.created`.

## The request you receive

```http
POST /connectcloud/events HTTP/1.1
Content-Type: application/json
User-Agent: ConnectCloud-Comms/1
webhook-id: 0f6b5c1e-4c33-4d1a-a1a5-2cb8e6f9d0a7
webhook-timestamp: 1772443800
webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=
```

```json
{
  "id": "0f6b5c1e-4c33-4d1a-a1a5-2cb8e6f9d0a7",
  "eventId": "0f6b5c1e-4c33-4d1a-a1a5-2cb8e6f9d0a7",
  "type": "desk.item.created",
  "occurredAt": "2026-03-02T09:30:00Z",
  "title": "Neues Ticket #1234: VPN-Verbindung bricht ab",
  "message": "Anna Schmidt hat ein Ticket angelegt.",
  "url": "https://app.mbcom.cloud/desk/tickets/1234",
  "facts": [ { "title": "Priorität", "value": "hoch" } ],
  "data": {
    "itemId": "3f2b8c1e-7d4a-4e9b-9c2a-5b1d6e8f0a12",
    "number": 1234,
    "status": "neu",
    "title": "VPN-Verbindung bricht ab",
    "spaceName": "Support",
    "typeName": "Störung",
    "assignees": [],
    "watchers": [],
    "changes": []
  }
}
```

`data` holds the machine-readable fields of the event; `title`, `message` and `facts` are rendered
for people. Desk item events carry `itemId`, `spaceId`, `typeId`, `number`, `status`, `actor`,
`changes` (`[{field, from, to}]`), `title`, `priority`, `confidential`, `createdBy`, `assignees`,
`watchers`, `customerName`, `spaceName`, `typeName` and `dueAt`. Descriptions and custom field
values are never part of an event: load the item through the API when you need them. Forge item
events (`forge.item.created`, `status_changed`, `assigned`, `commented`, `closed`, `scm_deployed`) carry only
`itemId`, `ref` (`APP-12`), `projectKey`, `typeKey`, `statusKey`, `statusCategory`, `environment` and person
references – never the title. The [handoff](/guides/handoffs) events (`desk.item.handed_off`, `handoff_received`,
`handed_back`, `handback_received`, `converted`; `forge.item.handoff_received`, `handback_received`,
`handoff_notice`, `converted_from`) are item events of the item they happened to. New fields may be added at any
time.

### A flow's message

What a flow's `mail` node posts into a webhook channel (`to: ["channel:<id>"]`) has the same envelope and the type
`flows.message`:

```json
{
  "id": "5b0d6c0e-2f0a-4d0b-9b1c-0e8f6a7d3c21",
  "eventId": "9a1f4c2e-6b7d-4e8f-a0b1-c2d3e4f5a6b7",
  "type": "flows.message",
  "occurredAt": "2026-03-02T09:30:00Z",
  "title": "Kritisches Ticket 1234",
  "message": "VPN-Verbindung bricht ab",
  "facts": [ { "title": "Flow", "value": "Kritische Tickets melden" } ],
  "data": {
    "subject": "Kritisches Ticket 1234",
    "text": "VPN-Verbindung bricht ab",
    "flowName": "Kritische Tickets melden"
  }
}
```

- `id` is the message, `eventId` the **run** of the flow (every message of one run shares it; read the run with
  [`GET /runs/{id}`](/reference/flows/getFlowRun)).
- `title` is the node's rendered `subject`, `message` its rendered `text`; `facts` names the flow; `data` holds the
  same three values (`subject`, `text`, `flowName`). There is no `url` and no `recipient`.
- The message carries only what the node's templates render. To pass fields of the event that started the flow, put
  them into `subject` or `text` (e.g. a JSON line in `text`), or let your endpoint load the record through the API.

## Verify the signature

Always verify before you trust a request. The signature is an HMAC-SHA256 over
`<webhook-id>.<webhook-timestamp>.<raw body>` with the base64-decoded part of the secret after
`whsec_`. The header holds `v1,<base64 signature>` (several, space-separated, during secret
rotation). Also reject timestamps older than five minutes to stop replays.

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

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

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

export function verify(secret: string, h: Record<string, string>, body: Buffer, tolerance = 300): boolean {
  const id = h["webhook-id"], ts = h["webhook-timestamp"], sigs = h["webhook-signature"] ?? "";
  if (Math.abs(Date.now() / 1000 - Number(ts)) > tolerance) return false;
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = createHmac("sha256", key).update(`${id}.${ts}.`).update(body).digest();
  return sigs.split(" ").some((s) => {
    const [v, sig] = s.split(",");
    const got = Buffer.from(sig ?? "", "base64");
    return v === "v1" && got.length === expected.length && timingSafeEqual(got, expected);
  });
}
```

```go
func verify(secret string, h http.Header, body []byte) bool {
	ts, err := strconv.ParseInt(h.Get("webhook-timestamp"), 10, 64)
	if err != nil || math.Abs(float64(time.Now().Unix()-ts)) > 300 {
		return false
	}
	key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
	if err != nil {
		return false
	}
	mac := hmac.New(sha256.New, key)
	fmt.Fprintf(mac, "%s.%d.", h.Get("webhook-id"), ts)
	mac.Write(body)
	expected := mac.Sum(nil)
	for _, s := range strings.Fields(h.Get("webhook-signature")) {
		if v, sig, ok := strings.Cut(s, ","); ok && v == "v1" {
			if got, err := base64.StdEncoding.DecodeString(sig); err == nil && hmac.Equal(got, expected) {
				return true
			}
		}
	}
	return false
}
```

Standard Webhooks libraries for many languages verify this for you
(`pip install standardwebhooks`, `npm i standardwebhooks`, …).

## Answer quickly, process later

- Answer with any `2xx` within a few seconds, then process asynchronously.
- `webhook-id` is unique per delivery: store it and ignore repeats, deliveries are
  **at least once**.
- Events can arrive out of order. Compare `occurredAt`, or load the current state through the API.
- Non-`2xx` answers and timeouts are retried with exponential backoff and jitter; `Retry-After` on a
  `429` or `503` is honoured. Redirects (`3xx`) are not followed and count as failure. A delivery
  that still fails after its last attempt is `dead`; fix the endpoint and retry it from the delivery log.
- Every attempt is visible in the delivery log:
  [`GET /deliveries`](/reference/comms/listDeliveries), retry one with
  [`POST /deliveries/{id}/retry`](/reference/comms/retryDelivery).

## Incoming webhooks

The other direction: let an external system post events *into* ConnectCloud, for example to start
a workflow. Create an endpoint with [`POST /inbound-hooks`](/reference/comms/createInboundHook)
(`comms:admin`); the answer contains its public `url` and, once, its secret.

| Scheme | The sender proves itself with |
|---|---|
| `standard_webhooks` (default) | the three `webhook-*` headers as above |
| `hmac_sha256` | an HMAC-SHA256 of the body in a header you name (`config.signatureHeader`, optional `prefix` like `sha256=`) |
| `token` | a static token in a header you name |

The sender posts to [`POST /api/comms/v1/hooks/{publicId}`](/reference/comms/receiveInboundWebhook)
without any ConnectCloud token. Verified requests are stored (`202`), repeats of the same delivery
id answer `200`, failed checks `401` without details. Received events are listed with
[`GET /inbound-hooks/{id}/events`](/reference/comms/listInboundHookEvents).

To start an automation instead of storing the request, give a flow a webhook trigger: it gets its own address
`POST /api/flows/v1/hooks/{token}` with an optional HMAC signature – see [Flows](/guides/flows).
