# Webhooks

Webhooks push your organization's events to an HTTPS endpoint you control — useful for piping deploy notifications into Slack, paging on agent-fleet anomalies, or feeding a downstream pipeline.

Ampbase delivers events as [CloudEvents v1.0](https://github.com/cloudevents/spec) in HTTP **structured mode**: the request body is a JSON document carrying every CE attribute inline, with `Content-Type: application/cloudevents+json`. You can consume Ampbase events with any off-the-shelf CloudEvents SDK.

## Event types

| Event | When it fires |
|---|---|
| `io.ampbase.agent.connected` | A new agent (by `agent_id`) completes its first OpAMP handshake. |
| `io.ampbase.agent.disconnected` | An agent's heartbeat stops within the timeout window. |
| `io.ampbase.config.deployed` | A configuration version becomes the active deployed version. |
| `io.ampbase.agent.limit.warning` | Your organization's agent count comes within the burst allowance of its agent limit: about 90% of the limit. Sent once, and again only after the count has fallen a further allowance below that, to about 80%. |
| `io.ampbase.agent.limit.exceeded` | An agent is refused because the organization is at its agent limit. Sent once, however many agents are refused, and again only after the count has fallen back below the warning's level. |
| `io.ampbase.intelligence.finding.created` | The intelligence layer first observes a recommendation (a high-cardinality label, a cost hotspot). Also fires when a previously resolved finding regresses — the finding's `state` tells the two apart. |
| `io.ampbase.intelligence.finding.resolved` | A re-analysis no longer reproduces a finding you hadn't dismissed — the thing it flagged is gone. |
| `io.ampbase.rollout.started` | A staged rollout starts. |
| `io.ampbase.rollout.advanced` | A rollout's stage begins, the first stage included. |
| `io.ampbase.rollout.gate_failed` | A stage stops, on a failed gate or on an error it can't recover from, and the rollout halts. |
| `io.ampbase.rollout.rolled_back` | A rollout finishes rolling back. |
| `io.ampbase.rollout.promoted` | A rollout completes: its last stage passed and what it ships is broadcasting. |
| `io.ampbase.track.ready` | A track is marked ready for the next rollout. |
| `io.ampbase.track.shipped` | A track ships: a rollout's last stage, or a Broadcast, makes its heads what its configurations serve. |
| `io.ampbase.track.handed_back` | A rollout or a Broadcast hands a ready track back to open without shipping it, with the reason. Taking a track out of the queue yourself sends no event. |

A webhook subscribes to one or more of these. You'll usually want `io.ampbase.config.deployed` plus `io.ampbase.agent.disconnected` at minimum.

Intelligence findings are channel-scoped, not tied to a single agent, so their deliveries carry no `subject`. Dismissing a finding in the dashboard is an explicit "stop telling me about this" — it fires no webhook.

The two agent-limit events belong to the organization, not to a channel. A webhook limited to some channels still receives them if it subscribes to them, and their deliveries carry no `subject`.

### Agent limit payload

Both agent-limit events carry the same `data`: your limits and the agent count that triggered the event. The count is the agents that have checked in within the last 5 minutes, across every channel. It is read about once a minute, so an event can follow the change that caused it by a minute or so. The `source` is the organization, with no channel.

```json
{
  "specversion": "1.0",
  "id": "01HXJ…",
  "source": "https://ampbase.io/orgs/01HQR…",
  "type": "io.ampbase.agent.limit.warning",
  "time": "2026-05-18T10:30:00Z",
  "datacontenttype": "application/json",
  "data": {
    "agent_limit": 1000,
    "burst_limit": 1100,
    "agent_count": 903,
    "observed_at": "2026-05-18T10:29:41Z"
  }
}
```

`agent_limit` is what your plan and agent packs cover. `burst_limit` is how far past it the organization can go for a short grace period before new agents are refused; the difference between the two is the burst allowance the events' levels are set by. `agent_count` and `observed_at` are the count and the time at which the crossing was seen, not when the event was sent; an event that is delayed carries the values it was queued with, so the count may have moved since. Each event is sent at most once for each time the count crosses its level. An agent that is already connected is never refused; `io.ampbase.agent.limit.exceeded` means a new one was, or one that had been away for more than 10 minutes.

### Finding payload

The `data` block for a finding event carries the derived `analyzer` discriminator plus the full finding as canonical protobuf JSON — the analyzer's report (`cardinality`, `cost`, …) alongside its **evidence packet**: the provenance of the measurement (window, calculation method and whether it's approximate, coverage, and the query reference needed to re-run it).

```http
POST https://your-endpoint.example.com/ HTTP/1.1
Content-Type: application/cloudevents+json
X-Ampbase-Timestamp: 1700000200
X-Ampbase-Signature: sha256=...

{
  "specversion": "1.0",
  "id": "01HXK...",
  "source": "https://ampbase.io/orgs/01HQR…/channels/01HXY…",
  "type": "io.ampbase.intelligence.finding.created",
  "time": "2026-07-19T10:30:00Z",
  "datacontenttype": "application/json",
  "data": {
    "analyzer": "cardinality",
    "finding": {
      "fingerprint": "9f2c…",
      "org_id": "01HQR…",
      "channel_id": "01HXY…",
      "source": { "kind": "SOURCE_KIND_RULE_BASED" },
      "state": "FINDING_STATE_OPEN",
      "first_seen": "2026-07-19T10:30:00Z",
      "last_seen": "2026-07-19T10:30:00Z",
      "cardinality": {
        "channel_id": "01HXY…",
        "metric_name": "http_requests_total",
        "attribute_key": "user_id",
        "cardinality": "50000"
      },
      "evidence": {
        "as_of": "2026-07-19T10:30:00Z",
        "window": { "start": "2026-07-12T10:30:00Z", "end": "2026-07-19T10:30:00Z" },
        "calculation": { "method": "HLL++ sketch merge estimate", "approximate": true },
        "coverage": { "rows_observed": "20", "truncated": true },
        "query": { "analyzer_version": "cardinality/v1", "params": { "window_days": "7" } }
      }
    }
  }
}
```

Route on `analyzer` to pick a handler, and on the finding's `state` to distinguish a brand-new `FINDING_STATE_OPEN` from a `FINDING_STATE_REGRESSED` re-occurrence. Enum fields use their protobuf constant names; numbers arrive as JSON strings, per protobuf-JSON convention.

### Rollout payload

A rollout event's `subject` is `rollout/{rollout_id}`, and its `data` is the rollout's full record at the moment of the event, as canonical protobuf JSON: its state, its plan and current stage, what it ships, and its last verdict, whose `sentence` says what the stage's gate found. Ids arrive as their text.

### Track payload

A track event's `subject` is `track/{track_id}`, and its `data` is the track exactly as `GetTrack` answers it, at the moment it changed state: its state, its configurations with each one's `base` and `head`, and the field that says what happened. Ids arrive as their text. The examples below are abridged: fields not shown are omitted.

`io.ampbase.track.ready` carries the track in `TRACK_STATE_READY`, with `ready_at` set:

```json
{
  "track_id": "trk-01JBQ2A2B3C4D5E6F7G8H9J0K1",
  "note": "batch 800",
  "state": "TRACK_STATE_READY",
  "targets": [
    { "config_id": "cfg-01JBQ0Z5M6V3T8K2R4N7P9W1XC", "base": "01JBQ1A2B3C4D5E6F7G8H9J0K1", "head": "01JBQ3A2B3C4D5E6F7G8H9J0K1" }
  ],
  "ready_at": "2026-11-24T10:30:00Z",
  "updated_at": "2026-11-24T10:30:00Z"
}
```

`io.ampbase.track.shipped` carries it in `TRACK_STATE_SHIPPED`, with `shipped` saying what shipped it: `rollout_id` for a rollout, `move_id` for a Broadcast, and `versions`, the version each configuration now serves:

```json
{
  "track_id": "trk-01JBQ2A2B3C4D5E6F7G8H9J0K1",
  "state": "TRACK_STATE_SHIPPED",
  "shipped": {
    "move_id": "01JBQ6M2B3C4D5E6F7G8H9J0K1",
    "at": "2026-11-24T11:02:00Z",
    "versions": [
      { "config_id": "cfg-01JBQ0Z5M6V3T8K2R4N7P9W1XC", "version": "01JBQ3A2B3C4D5E6F7G8H9J0K1" }
    ]
  }
}
```

`io.ampbase.track.handed_back` carries it back in `TRACK_STATE_OPEN`, with `handed_back`:

```json
{
  "track_id": "trk-01JBQ2A2B3C4D5E6F7G8H9J0K1",
  "state": "TRACK_STATE_OPEN",
  "handed_back": {
    "reason": "TRACK_HAND_BACK_REASON_STALE",
    "rollout_id": "rol-01JBQ7A2B3C4D5E6F7G8H9J0K1",
    "rebase_onto": "01JBQ5A2B3C4D5E6F7G8H9J0K1",
    "config_id": "cfg-01JBQ0Z5M6V3T8K2R4N7P9W1XC",
    "at": "2026-11-24T11:02:00Z"
  }
}
```

The hand-back's fields:

- `reason`: `TRACK_HAND_BACK_REASON_STALE` (the track's base was no longer what is broadcasting), `_ROLLED_BACK` (the rollout carrying it was rolled back), `_STRANDED` (its base was a version of another track handed back at the same time), `_OVERLAPS` (on one configuration, its head and the head of another track being shipped diverge), or `_CONFIG_DELETED` (a configuration it changes was deleted; there is nothing to rebase onto).
- `rollout_id`: the rollout that handed it back; absent when a Broadcast did.
- `rebase_onto`: the version to save the track's next version on, naming it as the save's parent, before marking it ready again; absent when the track need not rebase.
- `config_id`: the configuration the reason is about; absent for a rollback.
- `other_track_id`: the other track the reason names, present for `_STRANDED` and `_OVERLAPS`.

A track event can arrive more than once, or not at all (see [Retries and status lifecycle](#retries-and-status-lifecycle)): for the track's current state, read it with `GetTrack`.

## Setup

1. **Webhooks → New webhook**.
2. Enter your HTTPS endpoint URL and select event types.
3. Save. The webhook starts in **PENDING_VERIFICATION** state.

An organization can have up to 50 webhooks. Delete one to free a slot.

## Endpoint verification

Before any real event fires, Ampbase needs proof that you control the URL. It POSTs a one-shot verification challenge using the same CloudEvents envelope as real deliveries — so your endpoint only needs one `Content-Type` parser:

```http
POST https://your-endpoint.example.com/ HTTP/1.1
Content-Type: application/cloudevents+json
X-Ampbase-Event: io.ampbase.webhook.verification
X-Ampbase-Webhook-ID: wh_01HXJ...
X-Ampbase-Verification-Challenge: 8f2c4a7e9b1d3a5f7e2c4a7e9b1d3a5f
X-Ampbase-Timestamp: 1700000000
X-Ampbase-Signature: sha256=...

{
  "specversion": "1.0",
  "id": "01HXJ...",
  "source": "https://ampbase.io/webhooks/wh_01HXJ...",
  "type": "io.ampbase.webhook.verification",
  "subject": "webhook/wh_01HXJ...",
  "time": "2026-05-18T10:30:00Z",
  "datacontenttype": "application/json",
  "data": {
    "webhook_id": "wh_01HXJ...",
    "challenge": "8f2c4a7e9b1d3a5f7e2c4a7e9b1d3a5f"
  }
}
```

`X-Ampbase-Event`, `X-Ampbase-Webhook-ID`, and `X-Ampbase-Verification-Challenge` are convenience headers for this one POST so endpoints can echo the challenge without parsing the body. They are **only set on the verification handshake** — never on regular deliveries — and like all headers they're outside the HMAC, so the signed body remains the authoritative source.

Your endpoint must reply with **HTTP 200** and the challenge value somewhere in the response body — echoing it back as JSON (`{"challenge":"…"}`) is fine, as is returning it as a plain string. Once verified, the webhook flips to **ACTIVE** and starts receiving real events. Re-run verification any time from the UI.

## Delivery and HMAC signing

Each event delivery POSTs a CloudEvent and includes two signature headers:

```http
POST https://your-endpoint.example.com/ HTTP/1.1
Content-Type: application/cloudevents+json
X-Ampbase-Timestamp: 1700000123
X-Ampbase-Signature: sha256=a1b2c3...

{
  "specversion": "1.0",
  "id": "01HXJ...",
  "source": "https://ampbase.io/orgs/01HQR…/channels/01HXY…",
  "type": "io.ampbase.config.deployed",
  "subject": "agent/01HVZ8...",
  "time": "2026-05-18T10:30:00Z",
  "datacontenttype": "application/json",
  "data": { "config_id": "01ARZ3NDFV", "version_ulid": "01ARZ3...", "agent_id": "01HVZ8..." }
}
```

The signature is `HMAC-SHA256(secret, timestamp + "." + raw_body)` hex-encoded, prefixed with `sha256=`. Binding the timestamp into the MAC prevents replay of an old delivery with a fresh `X-Ampbase-Timestamp`. The secret itself is prefixed `whsec_` and is shown once on webhook creation — store it like an API key.

Verify on your side **before** trusting any field of the payload — including the event type:

```js
import crypto from "crypto";

function verify(req) {
  const ts        = req.headers["x-ampbase-timestamp"];
  const signature = req.headers["x-ampbase-signature"]; // "sha256=…"
  if (!ts || !signature) return false;

  // Reject anything more than 5 minutes off — replay window.
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;

  const expected = "sha256=" + crypto
    .createHmac("sha256", process.env.AMPBASE_WEBHOOK_SECRET)
    .update(ts + "." + req.rawBody)
    .digest("hex");

  return crypto.timingSafeEqual(
    Buffer.from(expected),
    Buffer.from(signature),
  );
}
```

After `verify()` returns true, parse the body and route on the CloudEvents `type` field — it's the only field guaranteed to reflect what Ampbase actually sent:

```js
const event = JSON.parse(req.rawBody); // already verified above
switch (event.type) {
  case "io.ampbase.config.deployed":
    /* … */ break;
  case "io.ampbase.agent.disconnected":
    /* … */ break;
}
```

## Retries and status lifecycle

Deliveries that don't return 2xx are retried with exponential backoff. After repeated failures the webhook progresses through degraded states:

```
ACTIVE  →  DEGRADED   (one or more recent failures, still retrying)
        →  DISABLED   (10 consecutive failures — no more deliveries until you re-verify)
```

A disabled webhook stays in the UI with the reason recorded. Fix the endpoint, re-run verification, and it returns to ACTIVE.

An event can arrive more than once, and it can fail to arrive at all, at two different points:

- **More than once.** Once Ampbase has queued an event for your webhook, it retries until your endpoint answers 2xx or the webhook is disabled, so the same event can reach you more than once. Every CloudEvent carries a unique `id`: dedupe on it.
- **Not at all.** An event raised while Ampbase's delivery service is briefly unavailable is not queued, and never reaches you. Don't treat webhooks as the record of what happened: for a track's or a rollout's current state, read it with `GetTrack` or `GetRollout`.

Retries keep the `id`, which is what makes it safe to dedupe on. One case needs a different key: for `io.ampbase.intelligence.finding.created`, two analysis runs racing the same brand-new finding can each emit it with a *different* `id`. Those duplicates share the same `finding.fingerprint` and `finding.first_seen`, so dedupe findings on that pair.

## Operational tips

- Respond fast (under 5 seconds) — long-running side effects should be deferred to a worker on your side.
- Be idempotent: retries mean the same event may arrive more than once.
- Always verify the signature before reading the body. **Don't route on request headers** — they're not covered by the HMAC. The signed `type` attribute inside the body is authoritative.
