> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fibre.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Webhooks

> Get a signed HTTP request when a sandbox is ready, goes to sleep, crashes or is deleted, and when a build finishes, instead of polling. Verify the signature, handle retries, test and inspect deliveries.

Your app often needs to **react** when something happens to a sandbox. You might want to show "ready" in your
interface, bill a user when their session ends, alert someone when a sandbox crashes, or deploy when an image
build finishes. You could ask Fibre about every sandbox over and over (this is called *polling*), but that is slow
and wasteful.

**Webhooks turn this around: Fibre tells you.** You give Fibre the address of an endpoint on your server, once.
From then on, whenever something happens, Fibre sends a `POST` request to that address describing the event. Each
request is signed so you can check it really came from Fibre, it is retried until your server accepts it, and
every delivery is recorded.

## Events

These are the events Fibre can send you:

| Event | When | `data` |
| - | - | - |
| `sandbox.ready` | A sandbox started, **or woke from sleep** | `name` (its ID), `restored` (`true` after a wake) |
| `sandbox.stopped` | It went to sleep | `name`, `reason` (`idle` when it slept on its own) |
| `sandbox.crashed` | Its main program died, or it ran out of disk | `name`, `reason` |
| `sandbox.deleted` | It was deleted, or its lifetime ended | `name`, `reason` |
| `build.succeeded` | An image build finished | `build_id`, `image` |
| `build.failed` | An image build failed | `build_id`, `error` |
| `ping` | You asked for a test | `webhook_id` |

Every request has a JSON body with the same shape:

```json title="body" theme={null}
{
  "id": "6f1c8e0a-…",
  "type": "sandbox.ready",
  "created_at": "2026-11-21T02:31:07.512Z",
  "data": {
    "kind": "sandbox",
    "name": "sbx-1a2b3c4d5e",
    "restored": true
  }
}
```

It also carries three headers:

| Header | Value |
| - | - |
| `Fibre-Event-Id` | The event's `id`: **the same on every retry**, so you can drop duplicates |
| `Fibre-Event-Type` | The event's `type` |
| `Fibre-Signature` | `t=<unix seconds>,v1=<HMAC-SHA256 hex>`: proof the request came from Fibre |

## Verify the signature

Your endpoint is reachable from the internet, so anyone could send it a request that looks like a Fibre event.
**Always check the signature before trusting a webhook.**

Here is how it works. When you create the webhook, Fibre gives you a **secret** that only you and Fibre know.
For each request, Fibre computes an HMAC-SHA256 of the timestamp, a dot, and the raw body (`"<t>.<body>"`),
using that secret as the key, and puts the result in the `Fibre-Signature` header. Your server computes the same
value with its copy of the secret. If the two match, the request is genuine. Checking the timestamp too protects
you against someone replaying an old request.

Here is a complete handler in TypeScript and in Python:

```typescript title="TypeScript (Express)" norun reason="runs in your own server" theme={null}
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";

const SECRET = process.env.FIBRE_WEBHOOK_SECRET!;   // shown once, when you create the webhook
const app = express();

app.post("/fibre/webhooks", express.raw({ type: "application/json" }), (req, res) => {
  const header = req.get("Fibre-Signature") ?? "";
  const t = header.match(/t=(\d+)/)?.[1];
  const sigs = [...header.matchAll(/v1=([0-9a-f]+)/g)].map((m) => m[1]);
  const expected = createHmac("sha256", SECRET).update(`${t}.${req.body}`).digest("hex");

  const valid = sigs.some((s) => s.length === expected.length && timingSafeEqual(Buffer.from(s), Buffer.from(expected)));
  const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300;          // refuse replays older than 5 minutes
  if (!valid || !fresh) return res.status(400).send("bad signature");

  const event = JSON.parse(req.body.toString());
  if (alreadyHandled(event.id)) return res.sendStatus(200);               // a retry of one you processed

  if (event.type === "sandbox.ready") markReady(event.data.name);
  if (event.type === "sandbox.stopped") endBillingSession(event.data.name);
  if (event.type === "sandbox.crashed") alertOnCall(event.data);

  res.sendStatus(200);                                                    // answer fast; do slow work after
});
```

```python title="Python (Flask)" norun reason="runs in your own server" theme={null}
import hashlib, hmac, json, os, re, time
from flask import Flask, request

SECRET = os.environ["FIBRE_WEBHOOK_SECRET"].encode()
app = Flask(__name__)

@app.post("/fibre/webhooks")
def fibre_webhook():
    header = request.headers.get("Fibre-Signature", "")
    t = re.search(r"t=(\d+)", header).group(1)
    sigs = re.findall(r"v1=([0-9a-f]+)", header)
    expected = hmac.new(SECRET, f"{t}.".encode() + request.get_data(), hashlib.sha256).hexdigest()
    if not any(hmac.compare_digest(s, expected) for s in sigs) or abs(time.time() - int(t)) > 300:
        return "bad signature", 400

    event = json.loads(request.get_data())
    # … handle event["type"] once per event["id"]
    return "", 200
```

> [!WARNING]
>
> **Compute the signature over the raw body, exactly as it arrived.** If you parse the JSON first and convert it back
> to text, the bytes change and the signature will not match. In Express, use `express.raw()` on this route, as
> shown above.

## Try it end to end

You can see real deliveries without deploying anything, because a sandbox has a public address and can act as
your receiver. This small receiver checks each request's signature and writes down what arrived.

**1. Start a receiver**

```typescript title="TypeScript" run theme={null}
import { Fibre, Sandbox } from "@fibre-dev/sdk";

const fibre = new Fibre();
const receiver = await Sandbox.create({ exposedPort: 3000, lifetime: 900, labels: { docs: "webhooks" } });

await receiver.files.write("/app/receiver.js", `
const http = require("http"), fs = require("fs"), crypto = require("crypto");
http.createServer((req, res) => {
  let body = "";
  req.on("data", (c) => (body += c));
  req.on("end", () => {
    const secret = fs.existsSync("/app/secret") ? fs.readFileSync("/app/secret", "utf8").trim() : "";
    const header = req.headers["fibre-signature"] || "";
    const t = (header.match(/t=(\\d+)/) || [])[1];
    const expected = crypto.createHmac("sha256", secret).update(t + "." + body).digest("hex");
    const valid = header.includes("v1=" + expected);
    fs.appendFileSync("/app/received.log", JSON.stringify({ type: req.headers["fibre-event-type"], valid }) + "\\n");
    res.writeHead(valid ? 200 : 400); res.end();
  });
}).listen(3000);
`);
await receiver.spawn(["node", "/app/receiver.js"], { keep: true });
await receiver.run("until curl -s -o /dev/null localhost:3000; do sleep 1; done", { timeout: 60 });
```

```python title="Python" run theme={null}
from fibre import Fibre, Sandbox

fibre = Fibre()
receiver = Sandbox.create(exposed_port=3000, lifetime=900, labels={"docs": "webhooks"})

receiver.files.write("/app/receiver.js", r"""
const http = require("http"), fs = require("fs"), crypto = require("crypto");
http.createServer((req, res) => {
  let body = "";
  req.on("data", (c) => (body += c));
  req.on("end", () => {
    const secret = fs.existsSync("/app/secret") ? fs.readFileSync("/app/secret", "utf8").trim() : "";
    const header = req.headers["fibre-signature"] || "";
    const t = (header.match(/t=(\d+)/) || [])[1];
    const expected = crypto.createHmac("sha256", secret).update(t + "." + body).digest("hex");
    const valid = header.includes("v1=" + expected);
    fs.appendFileSync("/app/received.log", JSON.stringify({ type: req.headers["fibre-event-type"], valid }) + "\n");
    res.writeHead(valid ? 200 : 400); res.end();
  });
}).listen(3000);
""")
receiver.spawn(["node", "/app/receiver.js"], keep=True)
receiver.run("until curl -s -o /dev/null localhost:3000; do sleep 1; done", timeout=60)
```

```bash title="curl" run capture=RECV=.id theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"exposed_port": 3000, "lifetime_sec": 900, "labels": {"docs": "webhooks"}}'
```

```bash title="curl: the receiver program" run theme={null}
cat <<'EOF' | curl -sS -o /dev/null -X PUT "$FIBRE_API_URL/v1/sandboxes/$RECV/files/content?path=/app/receiver.js" \
  -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @-
const http = require("http"), fs = require("fs"), crypto = require("crypto");
http.createServer((req, res) => {
  let body = "";
  req.on("data", (c) => (body += c));
  req.on("end", () => {
    const secret = fs.existsSync("/app/secret") ? fs.readFileSync("/app/secret", "utf8").trim() : "";
    const header = req.headers["fibre-signature"] || "";
    const t = (header.match(/t=(\d+)/) || [])[1];
    const expected = crypto.createHmac("sha256", secret).update(t + "." + body).digest("hex");
    const valid = header.includes("v1=" + expected);
    fs.appendFileSync("/app/received.log", JSON.stringify({ type: req.headers["fibre-event-type"], valid }) + "\n");
    res.writeHead(valid ? 200 : 400); res.end();
  });
}).listen(3000);
EOF
curl -sS -o /dev/null -X POST "$FIBRE_API_URL/v1/sandboxes/$RECV/commands" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["node", "/app/receiver.js"], "keep": true}'
curl -sS -o /dev/null -X POST "$FIBRE_API_URL/v1/sandboxes/$RECV/exec" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["sh", "-c", "until curl -s -o /dev/null localhost:3000; do sleep 1; done"]}'
```

**2. Register the webhook**

Now tell Fibre where to send events. `events` chooses which events you want; leave it out to receive all of them.
**The answer includes the `secret`, and this is the only time you will see it**, so store it where your server can
read it. Here, it is written to a file in the receiver.

```typescript title="TypeScript" run theme={null}
const hook = await fibre.json<{ id: string; secret: string }>("POST", "/v1/webhooks", {
  body: { url: `${receiver.url}/fibre/webhooks`, events: ["sandbox.ready", "sandbox.stopped", "sandbox.crashed", "sandbox.deleted"] },
});
await receiver.files.write("/app/secret", hook.secret);
```

```python title="Python" run theme={null}
hook = fibre.json("POST", "/v1/webhooks", json={
    "url": f"{receiver.url}/fibre/webhooks",
    "events": ["sandbox.ready", "sandbox.stopped", "sandbox.crashed", "sandbox.deleted"],
})
receiver.files.write("/app/secret", hook["secret"])
```

```bash title="curl" run capture=HOOK=.id theme={null}
URL=$(curl -sS "$FIBRE_API_URL/v1/sandboxes/$RECV" -H "Authorization: Bearer $FIBRE_API_KEY" | jq -r .url)
CREATED=$(curl -sS -X POST "$FIBRE_API_URL/v1/webhooks" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d "{\"url\": \"$URL/fibre/webhooks\", \"events\": [\"sandbox.ready\", \"sandbox.stopped\", \"sandbox.crashed\", \"sandbox.deleted\"]}")

# store the secret where the receiver reads it
echo "$CREATED" | jq -r .secret | curl -sS -o /dev/null -X PUT \
  "$FIBRE_API_URL/v1/sandboxes/$RECV/files/content?path=/app/secret" -H "Authorization: Bearer $FIBRE_API_KEY" --data-binary @-

echo "$CREATED" | jq 'del(.secret)'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "id": "…",
>   "url": "…",
>   "events": ["sandbox.ready", "sandbox.stopped", "sandbox.crashed", "sandbox.deleted"],
>   "enabled": true,
>   "created_at": "…"
> }
> ```
>
> The real answer also includes `secret`, which is left out above.

**3. Send a test, and cause a real event**

A test sends a `ping` event to your endpoint straight away. To see real events as well, start a sandbox and then
delete it: that sends `sandbox.ready` and then `sandbox.deleted`.

```typescript title="TypeScript" run theme={null}
await fibre.json("POST", `/v1/webhooks/${hook.id}/test`);

const worker = await Sandbox.create({ lifetime: 300, labels: { docs: "webhooks" } });
await worker.delete();

await new Promise((r) => setTimeout(r, 5000));
console.log(await receiver.files.read("/app/received.log"));
// {"type":"ping","valid":true}
// {"type":"sandbox.ready","valid":true}
// {"type":"sandbox.deleted","valid":true}
```

```python title="Python" run theme={null}
import time

fibre.json("POST", f"/v1/webhooks/{hook['id']}/test")

worker = Sandbox.create(lifetime=300, labels={"docs": "webhooks"})
worker.delete()

time.sleep(5)
print(receiver.files.read("/app/received.log"))
# {"type":"ping","valid":true}
# {"type":"sandbox.ready","valid":true}
# {"type":"sandbox.deleted","valid":true}
```

```bash title="curl" run theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/webhooks/$HOOK/test" -H "Authorization: Bearer $FIBRE_API_KEY"
echo
W=$(curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes" -H "Authorization: Bearer $FIBRE_API_KEY" \
  -H "Content-Type: application/json" -d '{"lifetime_sec": 300, "labels": {"docs": "webhooks"}}' | jq -r .id)
curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$W" -H "Authorization: Bearer $FIBRE_API_KEY"
sleep 5
curl -sS "$FIBRE_API_URL/v1/sandboxes/$RECV/files/content?path=/app/received.log" -H "Authorization: Bearer $FIBRE_API_KEY"
```

> [accordion] Output
>
> ```text title="output" expected theme={null}
> {"type":"sandbox.deleted","valid":true}
> ```

**Every delivery arrived, and every signature was valid.**

## Retries

Your endpoint must answer with a **`2xx` status within 10 seconds**. Anything else counts as a failure: an error
status, no answer in time, or a refused connection. After a failure, Fibre tries again, waiting longer each time:

| Attempt | After the previous one |
| - | - |
| 2 | 30 seconds |
| 3 | 2 minutes |
| 4 | 10 minutes |
| 5 | 1 hour |
| 6 | 6 hours |
| 7, the last | 24 hours |

Every attempt for the same event carries **the same `Fibre-Event-Id`**. Fibre guarantees that each event arrives
at least once, but occasionally it may arrive twice, for example if your `200` answer was lost on its way back. So
**remember the IDs you have handled, and skip an event you have already processed.**

> [!TIP]
>
> **Answer first, and do the work afterwards.** Save the event and return `200` immediately, then do the slow part
> (sending emails, billing, deploying) in a background job. If your handler takes longer than 10 seconds, Fibre treats
> it as a failure and sends the event again, even though your handler did its job.

## See what was delivered

When something goes wrong, it helps to see what Fibre sent and how your server replied. You can list an
endpoint's last 50 deliveries, newest first:

```typescript title="TypeScript" run theme={null}
const { deliveries } = await fibre.json<{ deliveries: any[] }>("GET", `/v1/webhooks/${hook.id}/deliveries`);
for (const d of deliveries) console.log(d.type, d.status, d.attempts, d.last_status); // sandbox.deleted succeeded 1 200
```

```python title="Python" run theme={null}
for d in fibre.json("GET", f"/v1/webhooks/{hook['id']}/deliveries")["deliveries"]:
    print(d["type"], d["status"], d["attempts"], d["last_status"])  # sandbox.deleted succeeded 1 200
```

```bash title="curl" run theme={null}
curl -sS "$FIBRE_API_URL/v1/webhooks/$HOOK/deliveries" -H "Authorization: Bearer $FIBRE_API_KEY" | jq '.deliveries[0]'
```

> [accordion] Response
>
> ```json title="response" expected theme={null}
> {
>   "id": "…",
>   "event_id": "…",
>   "type": "…",
>   "status": "succeeded",
>   "attempts": 1,
>   "last_status": 200,
>   "last_error": null,
>   "next_attempt_at": "…",
>   "delivered_at": "…",
>   "created_at": "…"
> }
> ```

A delivery's `status` is `pending` (waiting for its next attempt), `succeeded`, or `failed` (every attempt has been
used). `last_error` says what went wrong, such as `HTTP 500` or a timeout.

## Rotate the secret

If you think a secret may have leaked, replace it with a new one. **The old secret keeps working for 24 hours
alongside the new one**, so you have time to update your server without missing a single event. During those 24
hours, `Fibre-Signature` carries two `v1=` values, one for each secret, and a match with either one is enough.

```typescript title="TypeScript" run theme={null}
const { secret } = await fibre.json<{ secret: string }>("POST", `/v1/webhooks/${hook.id}/rotate`);
```

```python title="Python" run theme={null}
secret = fibre.json("POST", f"/v1/webhooks/{hook['id']}/rotate")["secret"]
```

```bash title="curl" run theme={null}
curl -sS -X POST "$FIBRE_API_URL/v1/webhooks/$HOOK/rotate" -H "Authorization: Bearer $FIBRE_API_KEY" | jq 'keys'
```

## Delete

To stop receiving events at an endpoint, delete it:

```typescript title="TypeScript" run theme={null}
await fibre.json("DELETE", `/v1/webhooks/${hook.id}`);
await receiver.delete();
```

```python title="Python" run theme={null}
fibre.json("DELETE", f"/v1/webhooks/{hook['id']}")
receiver.delete()
```

```bash title="curl" run theme={null}
curl -sS -X DELETE "$FIBRE_API_URL/v1/webhooks/$HOOK" -H "Authorization: Bearer $FIBRE_API_KEY"
curl -sS -o /dev/null -X DELETE "$FIBRE_API_URL/v1/sandboxes/$RECV" -H "Authorization: Bearer $FIBRE_API_KEY"
```

## Good to know

A few limits and rules:

| | |
| - | - |
| Endpoints | Up to 10 per account; each gets every event you picked |
| URLs | Public `https://` or `http://` addresses; private and internal addresses are refused |
| Timeout | 10 seconds per attempt |
| Attempts | 7 over about 31 hours, then the delivery is `failed` |
| Order | Not guaranteed: use `created_at` if order matters |

## Related

> [card] [Sleep and wake](https://docs.fibre.dev/sandboxes/sleep-and-wake.md)
>
> Understand what `sandbox.ready` with `restored`, and `sandbox.stopped`, tell you.

> [card] [Images and builds](https://docs.fibre.dev/setup/images.md)
>
> `build.succeeded` tells you an image is ready to run.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.