# Webhooks

> Get a signed HTTPS request when a sandbox becomes ready, errors, stops, finishes hydrating, degrades or recovers.

A webhook endpoint receives lifecycle events for every sandbox in your account, so your system can react without polling.

## Events

| Type | Sent when |
| - | - |
| `sandbox.ready` | A create, resume, fork or recover finished and the sandbox accepts work |
| `sandbox.error` | A sandbox failed to start or crashed |
| `sandbox.archived` | A stop completed (manual, auto-stop or forced) |
| `sandbox.hydrated` | A resumed or forked sandbox finished copying its files in |
| `sandbox.degraded` | The machine is up but we can't fully reach it (for example a firewall rule inside blocks our agent) |
| `sandbox.recovered` | A degraded sandbox is reachable again |
| `sandbox.cpu_braked` | A trial sandbox was slowed to 1 vCPU after 30 minutes at full CPU ([details](/docs/limits#trials-that-had-already-started)); `data` has `sandbox {id, name}`, `state`, `reason` (`trial_sustained_cpu`) and `vcpu` |
| `sandbox.cpu_unbraked` | That limit lifted because you paid; `data` has `sandbox`, `state` and `reason` (`paid`) |

## Register an endpoint

```bash title="CLI"
sbx webhook create https://example.com/hooks/sandboxer --name production --event ready --event error --event archived
```

```bash title="curl"
curl -sS -X POST https://sandboxer.com/api/v1/webhooks \
  -H "Authorization: Bearer $SANDBOXER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name":"production","url":"https://example.com/hooks/sandboxer","events":["sandbox.ready","sandbox.error","sandbox.archived"]}'
```

```typescript title="TypeScript"
const { webhook, secret } = await sbx.createWebhook({
  name: "production",
  url: "https://example.com/hooks/sandboxer",
  events: ["sandbox.ready", "sandbox.error", "sandbox.archived"],
});
// store `secret` now — it is shown once
```

The response includes a signing secret `whsec_…`, **shown only once**. Endpoints must be public HTTPS on port 443; redirects aren't followed.

## The request

```http
POST /hooks/sandboxer HTTP/1.1
Content-Type: application/json
Sandboxer-Event-Id: evt_6c1f0a9e2b7d4c3fa8e15b2d9c0e7f41
Sandboxer-Signature: t=1760184000,v1=5f2b8c…e91a

{"id":"evt_6c1f0a9e2b7d4c3fa8e15b2d9c0e7f41","type":"sandbox.ready","createdAt":"2026-10-11T12:00:00Z","data":{"sandbox":{"id":"sb_k3v9x2mq","name":"agent-pr-1842","state":"ready"},"previousState":"provisioning","state":"ready"}}
```

| Field | Notes |
| - | - |
| `id` | Unique per event; the same on every retry. Use it to deduplicate |
| `type` | One of the event types above |
| `createdAt` | When the event happened |
| `data.sandbox` | At least `id` and `name` |
| `data.previousState`, `data.state` | On ready / error / archived |
| `data.reason` | On degraded (null on recovered) |

Respond with any `2xx` within 5 seconds. Do slow work asynchronously.

## Verify the signature

`Sandboxer-Signature` is `t=<unix seconds>,v1=<hex>`, where the hex is HMAC-SHA256 with your secret over the string `"<t>.<raw body>"`. Always verify against the **raw** request body (before JSON parsing), compare in constant time, and reject old timestamps to stop replays.

```typescript title="Node.js"
import crypto from "node:crypto";
import express from "express";

const SECRET = process.env.SANDBOXER_WEBHOOK_SECRET!; // whsec_…
const TOLERANCE_S = 300;

export function verify(rawBody: Buffer, header: string | undefined): boolean {
  if (!header) return false;
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2) as [string, string]));
  const t = Number(parts.t);
  if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > TOLERANCE_S) return false;
  const expected = crypto.createHmac("sha256", SECRET).update(`${t}.`).update(rawBody).digest();
  const given = Buffer.from(parts.v1 ?? "", "hex");
  return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}

const app = express();
app.post("/hooks/sandboxer", express.raw({ type: "application/json" }), (req, res) => {
  if (!verify(req.body, req.header("Sandboxer-Signature"))) return res.status(400).end();
  const event = JSON.parse(req.body.toString("utf8"));
  // dedupe on event.id, then enqueue
  res.status(204).end();
});
```

```python title="Python"
import hashlib, hmac, json, os, time
from flask import Flask, request, abort

SECRET = os.environ["SANDBOXER_WEBHOOK_SECRET"].encode()  # whsec_…
TOLERANCE_S = 300

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

app = Flask(__name__)

@app.post("/hooks/sandboxer")
def hook():
    if not verify(request.get_data(), request.headers.get("Sandboxer-Signature")):
        abort(400)
    event = json.loads(request.get_data())
    # dedupe on event["id"], then enqueue
    return "", 204
```

The secret is used exactly as shown, including the `whsec_` prefix.

## Delivery and retries

- Delivery is **at least once**, and events can arrive out of order. Deduplicate on `id`; use `createdAt` and a fresh `GET /sandboxes/{id}` if order matters.
- A non-`2xx` response, a timeout or a connection error is retried with exponential backoff for up to **24 hours**.
- An endpoint that keeps failing for **3 days** is disabled automatically and shown as disabled on the dashboard. Fix it and re-enable it there.
- The dashboard's **Webhooks** page shows each endpoint's recent deliveries with status code, latency and the next retry.

## Manage endpoints

```bash
sbx webhook list
sbx webhook rotate wh_0123456789abcdef01234567   # new secret, shown once
sbx webhook remove wh_0123456789abcdef01234567
```

`PATCH /webhooks/{id}` changes the name, URL or events in place.

### Rotating without downtime

1. Rotate and store the new secret alongside the old one.
2. Verify incoming requests against **either** secret for a few minutes.
3. Drop the old secret.

## Testing locally

Expose your local receiver with `sbx forward --reverse` into a sandbox and host it, or use any tunnelling tool, then register that HTTPS URL as a temporary endpoint.
