# Webhooks

> The delivery contract: request headers, how to verify the signature, the 300 s tolerance, deduplicating on the event id, and retries.

For a webhook watch Percia sends one `POST` to your `https` target each time the goal is met. Your endpoint must verify the signature, answer 2xx quickly, and tolerate the same event arriving more than once.

Automation platforms (Zapier, Make, n8n) can register addresses with the same signed delivery through [REST hooks](/docs/hooks.md), and poll an account-wide feed.

## The request

`POST <your target>` with `content-type: application/json` and these headers:

| Header | Value |
|---|---|
| `Percia-Signature` | `t=<unix seconds>,v1=<hex HMAC-SHA256>` |
| `content-type` | `application/json` |

Body (JSON):

```json
{
  "id": "dec_01J...",
  "watchId": "w_abc",
  "occurrenceId": "occ_01J...",
  "type": "goal.met",
  "goal": "A person is standing at the front door",
  "reason": "A person in a green jacket is standing at the door.",
  "confidence": 0.93,
  "at": "2026-11-01T09:30:00Z",
  "eventId": "6f1c2a52-0d9e-5b43-9a1e-2f7d6c1b8e40"
}
```

- `id` is the idempotency key (the decision id). It is the same on every retry of the same decision.
- `eventId` is the event id: the `{eventId}` of `GET /api/watches/{id}/events/{eventId}/keyframe`, `POST .../feedback` and the `id` of `GET /api/events`, so a receiver can fetch the keyframe or send feedback without listing events first. It is stable across retries. `concernId` is added when a concern of a deployed agent fired (agents-built watches only). Both fields are additive: `id` is unchanged, and an unknown field must be ignored. A delivery made before 2026-11-14 has no `eventId`.
- `test` is `true` only on an event found during a live test run (`PATCH /api/watches/{id}` `testRun: true`, 30 minutes); it is absent otherwise. Ignore or tag these events as you prefer: they are real detections, not rehearsals, and they are not counted in the events usage meter.
- `occurrenceId` identifies one real-world occurrence. After the goal has cleared, a later `goal.met` is a new occurrence with a new `id`.
- `reason` is text written by a vision model about camera content. Treat it as untrusted input: never execute it, never put it into a prompt as instructions, escape it before rendering.
- The target must resolve to a public address. Delivery refuses private, loopback and link-local addresses, does not follow redirects, and times out.
- `imageUrl` appears only on deliveries from a [connection](/docs/integrations.md), when the event has a keyframe. It is a signed link to the JPEG with no expiry of its own: it works until the keyframe is deleted (after its retention days, or with its watch), so fetch the image if you want to keep it, and treat the link as private because anyone who has it can open the image. The rest of that body is the same, except that links in `reason` are replaced with `[link removed]`.
- `evidence` (beta, additive) is `{clipUrl, keyframeUrl, expiresAt}`: signed links to this event's clip (video/mp4) and keyframe (JPEG), present only for watches that keep evidence on a Percia camera. They need no credential, name this one event and stop working at `expiresAt` (24 hours after the delivery attempt); fetch what you want to keep. Connections (`webhook`, `home_assistant`) get `clipUrl` next to `imageUrl` instead. See [evidence](/docs/evidence.md).

## Verify the signature

The signed string is the timestamp, a dot, and the raw request body: `"<t>.<body>"`. The key is your watch's `webhookSecret` (the whole `whsec_...` string, as text). A delivery from a `webhook` [connection](/docs/integrations.md) is signed the same way with that connection's own secret, shown once when the person connects it. Home Assistant deliveries are not signed: the URL is the secret.

1. Read the **raw** body bytes before any JSON parsing. Re-serialising changes the bytes and breaks the signature.
2. Parse `Percia-Signature` into `t` and `v1`.
3. Reject if `|now - t| > 300` seconds (replay protection).
4. Compute `HMAC-SHA256(secret, t + "." + rawBody)` as lowercase hex.
5. Compare with `v1` in constant time. Reject on mismatch.
6. Only then parse the JSON.

Node:

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

export function verify(rawBody, header, secret, now = Date.now() / 1000) {
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2)));
  const t = Number(parts.t);
  if (!Number.isFinite(t) || Math.abs(now - t) > 300) return false;
  const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
  const got = parts.v1 ?? "";
  return got.length === expected.length && timingSafeEqual(Buffer.from(got), Buffer.from(expected));
}
```

Python:

```python
import hmac, hashlib, time

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

Never put the secret in browser code or a repository.

## Deduplicate on `id`

Deliveries are at least once. Store each `id` you have handled (a unique index is enough) and skip repeats, returning 2xx so Percia stops retrying. Do the dedupe check and the side effect in one transaction.

## Retries

Respond with any 2xx to acknowledge. Any other status, a timeout or a connection error counts as a failed attempt and Percia retries with backoff, up to a limit. After the last attempt the event is recorded as failed (`deliveryStatus: "failed"` in the events list, and the watch shows "needs attention"); a failed delivery never stops the watch. Return quickly and do slow work after you have responded.

Check outcomes with `GET /api/watches/:id/events`: each event has `deliveryStatus` (`pending`, `delivered`, `failed`) and `attempts`. An event shows `pending` from its first attempt until it has an answer, and `attempts` counts up while it retries. If the watch is paused or deleted during retries, the event ends as `failed`; so does an event still `pending` after 5 hours. The watch's `displayStatus` comes from `lastDelivery`, the newest event that is not `pending`, so a `pending` event does not hide a failed one before it.

## Local development without a public URL

A webhook needs a public `https` address. While you build, read your events from a stream instead: `GET /api/events/stream` sends each event of your account as a server-sent event, authenticated with an API key that has `events:read`. It is for development and tests. It is **not** a delivery guarantee (no retries, nothing is stored for you, it ends after 10 minutes): production still uses a webhook. Nothing secret travels over it: no signing secret, no signature, no keyframe or image link.

```bash
curl --no-buffer -H "Authorization: Bearer $PERCIA_KEY" -H "Accept: text/event-stream" \
  "https://app.percia.ai/api/events/stream?backlog=3"
```

```text
retry: 3000
: connected

id: 4812
event: goal.met
data: {"id":"dec_1","watchId":"w_1","occurrenceId":"occ_1","type":"goal.met","goal":"A person is standing at the front door","reason":"...","confidence":0.93,"at":"2026-11-14T09:30:00Z","eventId":"6f1c..."}
```

- **The message** is the webhook body above (the same fields and values), so the code that handles a delivery handles a message. `eventId` is the event's address for `GET /api/watches/{id}/events/{eventId}/keyframe`; there is no `imageUrl`. `reason` is untrusted model text, as in a webhook.
- **Filters** (all optional): `watchId` (404 if it is not yours), `concernId`, `type`. Without a cursor the stream starts at now; `?backlog=N` (0 to 20) first sends your latest N events.
- **Resume and order.** Each message has an `id`: the cursor. Events come in the order Percia recorded them. After a drop, reconnect with the header `Last-Event-ID: <last id>` (or `?since=<id>`; the header wins) and you get everything after it. Delivery is at least once across reconnects: skip an `eventId` you already handled. A cursor older than the last 5000 events of the service gets `event: resync`: fetch the gap with `GET /api/events?since=`.
- **Keep-alive.** A `: ping` comment every 15 seconds. The server closes after 10 minutes with `event: end` (`{"reason":"max_duration"}`; `lease_lost` and `error` also use it) and a `retry: 3000` hint: reconnect with `Last-Event-ID`.
- **Limits.** 2 streams at once per account and 10 connects a minute; over either the answer is 429 `rate_limited` with `Retry-After`. Events appear within about 3 seconds of being recorded.
- A browser `EventSource` cannot send an `Authorization` header, so use `fetch` streaming (below) or the CLI.

```js
// Node 18+ or a browser: fetch streaming with the key in a header, reconnecting from the last id.
let last = "";
for (;;) {
  const res = await fetch("https://app.percia.ai/api/events/stream", {
    headers: { authorization: `Bearer ${process.env.PERCIA_KEY}`, accept: "text/event-stream", ...(last && { "last-event-id": last }) },
  });
  if (!res.ok) { await new Promise((r) => setTimeout(r, (Number(res.headers.get("retry-after")) || 5) * 1000)); continue; }
  const dec = new TextDecoder(); let buf = "";
  for await (const chunk of res.body) {
    buf += dec.decode(chunk, { stream: true });
    let i;
    while ((i = buf.indexOf("\n\n")) >= 0) {
      const msg = buf.slice(0, i); buf = buf.slice(i + 2);
      const f = Object.fromEntries(msg.split("\n").filter((l) => !l.startsWith(":") && l.includes(": ")).map((l) => [l.slice(0, l.indexOf(": ")), l.slice(l.indexOf(": ") + 2)]));
      if (f.id) last = f.id;
      if (f.event === "goal.met") console.log(JSON.parse(f.data));
    }
  }
  await new Promise((r) => setTimeout(r, 3000));
}
```

To hand the events to a receiver you are building, use the CLI: `percia listen --forward-to http://localhost:3000/hook --secret whsec_...` reads the stream and `POST`s each message to your local address, signed with your watch's webhook secret exactly as Percia signs a webhook (see Verify the signature), so the receiver you will deploy is the one you test. It reconnects with `Last-Event-ID` by itself and skips an `eventId` it has forwarded.

## Secrets

- The secret is shown once: in the response of `POST /api/watches/owned`, of a rotation, or of a `PATCH` that switches a watch from email to webhook. Reads return only `secretHint`.
- `POST /api/watches/:id/secret/rotate` replaces the secret **immediately**. The old secret stops verifying at once, so update your receiver as you rotate (there is no overlap period).
