# Webhooks

Webhooks tell your agent or service when something happens on your team, so it can wait for an event instead of polling. Faceless sends a signed `POST` with a JSON event to each URL you register.

## Events

| Event                | Sent when                                                                                                                      | `data`                                                                                                   |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| `video.completed`    | A video finished generating and can be rendered (`POST /videos/{id}/render`) or edited                                         | `videoId`, `name`, `platform`, `model`, `seriesId`, `creditsUsed`, `renderedVideoUrl`, `statusUrl`       |
| `video.failed`       | A video's generation stopped for good                                                                                          | `videoId`, `name`, `platform`, `seriesId`, `error`, `refunded`, `creditsRefunded`                        |
| `post.published`     | A post went out on a platform                                                                                                  | `postId`, `videoId`, `platform`, `accountId`, `postUrl`, `platformPostId`, `postedAt`, `publishComplete` |
| `post.failed`        | A scheduled post failed, or is waiting for an account to be reconnected                                                        | `taskId`, `videoId`, `seriesId`, `platform`, `status`, `reason`, `error`, `needsReconnect`, `failedAt`   |
| `credits.low`        | A spend took the balance below your threshold. Sent once per dip, and sent again only after the balance has gone back above it | `balance`, `threshold`, `autoTopUp`                                                                      |
| `checkout.completed` | A Stripe Checkout was paid and its credits or plan were granted                                                                | `sessionId`, `kind` (`credits` or `plan`), `creditsAdded`, `plan`, `amountTotal`, `currency`             |
| `webhook.test`       | You called `POST /webhooks/{id}/test`                                                                                          | `message`, `endpointId`                                                                                  |

The `credits.low` threshold is your auto top-up threshold when auto top-up is on, otherwise 100 credits.

`post.published` and `post.failed` usually arrive within a minute or two of the post. A TikTok post can be accepted before TikTok finishes processing it; then `publishComplete` is `false`.

## The event body

```json
{
	"id": "evt_9c1f0e7a2b3d4c5e6f708192",
	"object": "event",
	"type": "video.completed",
	"created": 1764583500,
	"teamId": "665f1b2a9c31a2b3c4d5e000",
	"livemode": true,
	"data": {
		"videoId": "665f1b2a9c31a2b3c4d5e801",
		"name": "Ocean facts",
		"platform": "tts",
		"model": "storyboard",
		"seriesId": null,
		"creditsUsed": 20,
		"renderedVideoUrl": null,
		"statusUrl": "/api/v1/videos/665f1b2a9c31a2b3c4d5e801/status"
	}
}
```

Each request also carries these headers:

- `Faceless-Signature`: `t=<unix seconds>,v1=<hex signature>`
- `Faceless-Event-Id`: the event id
- `Faceless-Event-Type`: the event type
- `Faceless-Delivery-Id`: the delivery id, as shown in the delivery log

The same event can arrive more than once, for example after a retry or a redelivery. Store the event `id` and ignore repeats. Events can also arrive out of order, so read `created`, or fetch the current state with `GET /videos/{id}`.

## Create an endpoint

```bash
curl -X POST https://faceless.so/api/v1/webhooks \
  -H "Authorization: Bearer $FACELESS_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: my-agent-webhook-1" \
  -d '{"url":"https://example.com/hooks/faceless","events":["video.completed","video.failed","post.published","post.failed"]}'
```

- The answer includes `secret` (`whsec_...`) **once**. Store it with your other secrets.
- `events` defaults to `["*"]`, which means every event, including events added later.
- The URL must be public `https` on port 443 or 8443. Private, loopback, link-local and internal addresses are refused, both when you save the URL and again on every delivery.
- A team can have up to 10 endpoints.
- These endpoints need the `webhooks:write` scope, and the read endpoints need `webhooks:read`. Neither scope is in an OAuth grant unless the client asks for it.

Manage endpoints with:

- `GET /webhooks`: list them.
- `GET /webhooks/{id}`: read one.
- `PATCH /webhooks/{id}`: change `url`, `events`, `description` or `enabled`, or rotate the secret with `{"rotateSecret": true}`. The new secret is in that answer, and the old one stops working at once.
- `DELETE /webhooks/{id}`: delete one.

The CLI has the same commands: `faceless webhooks list|create|delete|test|deliveries`. MCP clients get `faceless_list_webhooks`, `faceless_create_webhook`, `faceless_delete_webhook`, `faceless_test_webhook` and `faceless_list_webhook_deliveries`.

## Verify the signature

The signature is the hex HMAC-SHA256 of `<t>.<raw body>`, keyed with your endpoint's secret. Check it against the **raw** request body, the exact bytes you received, before parsing the JSON. Reject a timestamp more than 5 minutes old, which stops replays.

```js
import crypto from "node:crypto";
import express from "express";

const app = express();

app.post("/hooks/faceless", express.raw({ type: "application/json" }), (req, res) => {
	const header = req.get("Faceless-Signature") || "";
	const parts = Object.fromEntries(header.split(",").map((kv) => kv.split("=")));
	const t = Number(parts.t);
	const expected = crypto.createHmac("sha256", process.env.FACELESS_WEBHOOK_SECRET).update(`${t}.${req.body}`).digest("hex");
	const given = Buffer.from(parts.v1 || "", "hex");
	const fresh = Math.abs(Date.now() / 1000 - t) <= 300;
	if (!fresh || given.length !== 32 || !crypto.timingSafeEqual(given, Buffer.from(expected, "hex"))) {
		return res.status(400).send("bad signature");
	}
	const event = JSON.parse(req.body);
	// Dedupe on event.id, then handle event.type.
	res.sendStatus(200);
});
```

In Python:

```python
import hmac, hashlib, time

def verify(raw_body: bytes, header: str, secret: str) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(","))
    t = int(parts.get("t", "0"))
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return abs(time.time() - t) <= 300 and hmac.compare_digest(expected, parts.get("v1", ""))
```

## Retries

- Answer with any `2xx` within 10 seconds. A redirect, any other status, a timeout or a connection error counts as a failure.
- A failed delivery is retried 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours and 24 hours after each failure: 8 attempts over about 45 hours. After that the delivery is `failed`.
- An endpoint that has failed 50 attempts in a row, with no success for three days, is switched off (`enabled: false`, `disabledReason: "failing"`). Switch it back on with `PATCH /webhooks/{id} {"enabled": true}`.
- Do slow work after you answer: acknowledge first, then process.

## Delivery logs

`GET /webhooks/{id}/deliveries` lists the endpoint's deliveries, newest first, for 30 days. Filter with `?status=pending|succeeded|failed`. Each delivery has:

- the event `type` and `eventId`;
- its `status` and `attempts`;
- `lastStatusCode`, `lastError` and `lastResponseMs` from the receiver;
- `nextAttemptAt` while retries remain;
- the exact `payload`.

`POST /webhooks/{id}/redeliver {"deliveryId": "..."}` sends one delivery again now. Use it after you fix your receiver. The event keeps its `id`.

## Test ping

```bash
curl -X POST https://faceless.so/api/v1/webhooks/$ENDPOINT_ID/test \
  -H "Authorization: Bearer $FACELESS_API_KEY"
```

This sends a signed `webhook.test` event at once and answers with `ok`, the receiver's `statusCode`, any `error` and `responseMs`. A test is attempted once and never retried.

## Polling still works

Webhooks are an addition. `GET /videos/{id}/status`, `GET /renders/{id}` and `GET /calendar` still answer as before, so an agent that cannot receive HTTP can keep polling.
