# Webhooks

Source: https://tiltas.openpanel.sh/docs/partner/webhooks

> Receive signed events when Devices join, go online or offline, leave, when a Service's health changes and when a sign-in is approved.

One endpoint per Partner key receives the events of every Network the key created. Deliveries follow
[Standard Webhooks](https://www.standardwebhooks.com/): signed, retried, with the same id on every attempt.

## Set the endpoint

```sh
curl -sS -X PUT "$TILTAS/partner/webhook" -H "$AUTH" \
  -H 'Content-Type: application/json' -d '{"url":"https://openpanel.sh/api/tiltas/events"}'
```

```json
{ "url": "https://openpanel.sh/api/tiltas/events", "secret": "whsec_…", "created_at": "2026-12-01T10:00:00Z" }
```

- **`secret` is in this answer only**, the first time. Store it with your other secrets. Calling `PUT` again changes
  the URL and keeps the secret.
- The URL is `https` with a public name. Plain `http` works only to a container name that Tiltas has listed for a
  Docker network shared with you alone. Addresses, users, passwords and `#fragments` are refused.
- `GET /partner/webhook` shows the URL; `DELETE /partner/webhook` removes the endpoint with its undelivered events.

## What arrives

```http
POST /api/tiltas/events HTTP/1.1
Content-Type: application/json
webhook-id: msg_2b7kq9xw4mz8rt3vjh5c
webhook-timestamp: 1764583443
webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=

{"type":"device.online","timestamp":"2026-12-01T10:04:03Z","data":{"account_id":"acc_x4tq9mzr2e","network_external_id":"org_123","device_id":"dev_n3w8kzq5cb","name":"hel-box-1","address":"100.64.0.3","last_seen_at":"2026-12-01T10:04:03Z"}}
```

Every `data` carries `account_id` and `network_external_id` (your organisation id), plus:

| `type` | When | `data` adds |
|---|---|---|
| `device.joined` | A Device registered for the first time and has its address | `device`: the Device object |
| `device.online` | The Device came online | `device_id`, `name`, `address`, `last_seen_at` |
| `device.offline` | The Device went offline | `device_id`, `name`, `address`, `last_seen_at` |
| `device.removed` | A Device left the Network | `device_id`, `name`, `kind`, `owner_external_id` (people's Devices), `reason`: `removed`, `signed_out` or `person_removed` |
| `service.health` | A Service's health check flipped | `service_id`, `name`, `device_id`, `health`: `{ ok, error, checked_at }` |
| `sign_in.approved` | A sign-in into the Network was approved | `user_code`, `device_id`, `device_name`, `person_external_id`, `same_network` |

New types may appear: ignore the ones you do not know. No events are sent for deleting a whole Network.

## Verify every delivery

Check the signature on the **raw** body, before parsing it, and refuse timestamps more than 5 minutes from now. The
signature is HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the base64-decoded part of the
secret after `whsec_`. During a secret rotation two signatures arrive, space-separated; accept the message if either
matches.

The [`standardwebhooks`](https://www.npmjs.com/package/standardwebhooks) package does all of this in Node:

```ts
import express from "express";
import { Webhook } from "standardwebhooks";

const wh = new Webhook(process.env.TILTAS_WEBHOOK_SECRET!); // "whsec_…"
const app = express();

app.post("/api/tiltas/events", express.raw({ type: "application/json" }), (req, res) => {
  let event: { type: string; timestamp: string; data: Record<string, unknown> };
  try {
    event = wh.verify(req.body, req.headers as Record<string, string>) as typeof event;
  } catch {
    return res.sendStatus(400);
  }
  // Deduplicate by req.headers["webhook-id"], then hand the event to a queue.
  res.sendStatus(204);
});
```

In Go, with the standard library only:

```go
// verifyTiltas checks a Tiltas webhook. secret is the whsec_… value; body is
// the raw request body, exactly as received.
func verifyTiltas(secret string, h http.Header, body []byte) error {
	key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
	if err != nil {
		return err
	}
	id, ts := h.Get("webhook-id"), h.Get("webhook-timestamp")
	unix, err := strconv.ParseInt(ts, 10, 64)
	if id == "" || err != nil {
		return errors.New("missing webhook headers")
	}
	if d := time.Since(time.Unix(unix, 0)); d > 5*time.Minute || d < -5*time.Minute {
		return errors.New("timestamp too far from now")
	}
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(id + "." + ts + "."))
	mac.Write(body)
	want := mac.Sum(nil)
	for _, sig := range strings.Fields(h.Get("webhook-signature")) {
		if v, b64, ok := strings.Cut(sig, ","); ok && v == "v1" {
			if got, err := base64.StdEncoding.DecodeString(b64); err == nil && hmac.Equal(got, want) {
				return nil
			}
		}
	}
	return errors.New("no valid signature")
}
```

## Answer fast, retry safely

- Answer with any `2xx` within 15 seconds; do the work afterwards, from a queue.
- Anything else is retried: a timeout, a network error, a redirect or any other status. The retries come after 5
  seconds, 5 minutes, 30 minutes, 2 hours, 5 hours, 10 hours and 10 hours: 8 attempts over about 27.5 hours, with the
  same `webhook-id`. After the last one the event is marked `failed`.
- Delivery is **at least once, in no particular order**. Deduplicate by `webhook-id`, and use `timestamp`, or read the
  resource again, for the latest state.
- Webhooks are hints. Keep a slow poll of your Networks' Devices and Services as a safety net.

## Delivery log

```sh
curl -sS "$TILTAS/partner/webhook/deliveries?status=failed&limit=50" -H "$AUTH"
```

```json
{
  "data": [
    {
      "id": "msg_2b7kq9xw4mz8rt3vjh5c",
      "type": "device.online",
      "account_id": "acc_x4tq9mzr2e",
      "status": "pending",
      "attempts": 2,
      "created_at": "2026-12-01T10:04:03Z",
      "last_attempt_at": "2026-12-01T10:04:08Z",
      "next_attempt_at": "2026-12-01T10:09:08Z",
      "delivered_at": null,
      "response_status": 503,
      "error": "answered 503",
      "payload": { "type": "device.online", "timestamp": "2026-12-01T10:04:03Z", "data": { "…": "…" } }
    }
  ],
  "next_cursor": null
}
```

Newest first. Filter with `status` (`pending`, `delivered`, `failed`), page with `limit` (1–200) and `cursor` (the
`next_cursor` of the previous page). Delivered and failed events stay 30 days; `payload` lets you process an event you
missed.

## Rotate the secret

```sh
curl -sS -X POST "$TILTAS/partner/webhook/rotate-secret" -H "$AUTH"
```

```json
{ "secret": "whsec_…", "previous_valid_until": "2026-12-02T10:00:00Z" }
```

The new secret is shown once. For 24 hours every delivery carries two signatures, one per secret, so you can deploy
the new secret without losing an event.
