# Webhooks

Kajiya can call an HTTPS endpoint of yours when a job is dispatched, starts, finishes or has to wait, when your balance runs low, and when a spend cap holds jobs. Every delivery is signed so you can check that it came from Kajiya.

## Set up

1. In the dashboard, open **Limits & alerts**, enter your endpoint URL and save.
2. The first time a URL is saved, Kajiya creates a signing secret (`whsec_...`) and shows it once. Store it with your receiver.
3. Choose **Send test event** and check that a `test` event arrives.

With the API (needs an `admin` key):

```bash
curl -X PATCH "https://kajiya.app/api/v1/settings" \
  -H "Authorization: Bearer $KAJIYA_ADMIN_KEY" -H "Content-Type: application/json" \
  -d '{"webhook_url": "https://ci.example.com/kajiya"}'
# -> { ..., "webhook_secret": "whsec_...", "note": "Store the webhook secret now; it is shown only once." }

curl -X POST "https://kajiya.app/api/v1/webhook/test" -H "Authorization: Bearer $KAJIYA_ADMIN_KEY"
```

The URL must use `https`, point to a public host (not `localhost`, a private or internal address, or a name that resolves to one), have no user name or password in it, and be at most 500 characters. Send `"webhook_url": null` to stop deliveries.

## Events

| Type | Sent when | `data` |
|---|---|---|
| `job.dispatched` | Kajiya registered a runner for a job and picked a machine | The job |
| `job.started` | The job's VM started (billing starts) | The job |
| `job.finished` | The VM powered off (`state: "done"`, with cost) or failed to start (`state: "failed"`, not billed) | The job |
| `job.waiting` | A job first had to wait, or its wait reason changed | Repository, job name, label, `reason`, `message` |
| `balance.low` | Your balance dropped below the low-balance threshold after a job finished | `balance_usd`, `threshold_usd` |
| `spend_cap.reached` | A spend cap held a job for the first time in that day or month | `cap` (`daily` or `monthly`), `message` |
| `test` | You asked for a test event | `message` |

Every event has the same envelope: `id` (the same value as the `Kajiya-Delivery` header), `type`, `created_at` and `data`. In job events, `runtime_seconds`, `billed_seconds` and `cost_usd` are `null` until the job has finished.

### job.dispatched

```json
{
  "id": "evt_3vQm8KcR0yJb1TfWzAa9sLx2pN",
  "type": "job.dispatched",
  "created_at": "2026-12-04T09:12:04.000Z",
  "data": {
    "id": 1287,
    "repo": "acme/api",
    "name": "test (3)",
    "label": "kajiya-4",
    "vcpu": 4,
    "state": "dispatched",
    "github_run_id": 12045567890,
    "github_job_id": 33861234567,
    "github_url": "https://github.com/acme/api/actions/runs/12045567890/job/33861234567",
    "runtime_seconds": null,
    "billed_seconds": null,
    "cost_usd": null
  }
}
```

### job.started

```json
{
  "id": "evt_Hq2LwZ7nVd4cEo8RkT1mYb6uSa",
  "type": "job.started",
  "created_at": "2026-12-04T09:12:09.000Z",
  "data": {
    "id": 1287,
    "repo": "acme/api",
    "name": "test (3)",
    "label": "kajiya-4",
    "vcpu": 4,
    "state": "running",
    "github_run_id": 12045567890,
    "github_job_id": 33861234567,
    "github_url": "https://github.com/acme/api/actions/runs/12045567890/job/33861234567",
    "runtime_seconds": null,
    "billed_seconds": null,
    "cost_usd": null
  }
}
```

### job.finished

```json
{
  "id": "evt_9bXr5MtA2qWc7UeLs0DkHy3vNj",
  "type": "job.finished",
  "created_at": "2026-12-04T09:19:01.000Z",
  "data": {
    "id": 1287,
    "repo": "acme/api",
    "name": "test (3)",
    "label": "kajiya-4",
    "vcpu": 4,
    "state": "done",
    "github_run_id": 12045567890,
    "github_job_id": 33861234567,
    "github_url": "https://github.com/acme/api/actions/runs/12045567890/job/33861234567",
    "runtime_seconds": 412,
    "billed_seconds": 420,
    "cost_usd": 0.0021
  }
}
```

### job.waiting

`reason` is one of `limit`, `repo_limit`, `paused`, `no_credit`, `daily_cap`, `monthly_cap` or `no_host`; see [wait reasons](/docs/queue-and-limits#wait-reasons).

```json
{
  "id": "evt_Pz6Fs1oKa8GmV3xQe5TcLw0rYd",
  "type": "job.waiting",
  "created_at": "2026-12-04T09:20:15.000Z",
  "data": {
    "repo": "acme/web",
    "name": "e2e (1)",
    "label": "kajiya-8",
    "github_run_id": 12045571234,
    "github_job_id": 33861299871,
    "reason": "repo_limit",
    "message": "This repository's concurrency cap is reached; starts when its running jobs finish."
  }
}
```

### balance.low

```json
{
  "id": "evt_Lm4Tq9Wz2Xc6Va1Rb8Nd3Ke7Ys",
  "type": "balance.low",
  "created_at": "2026-12-04T11:02:47.000Z",
  "data": {
    "balance_usd": 4.93,
    "threshold_usd": 5
  }
}
```

### spend_cap.reached

```json
{
  "id": "evt_Ry1Ud7Bk4Wq9Zs2Xm6Lc8Pv3Ta",
  "type": "spend_cap.reached",
  "created_at": "2026-12-04T17:45:30.000Z",
  "data": {
    "cap": "daily",
    "message": "Your daily spend cap is reached. Raise it in Settings or wait for the next UTC day."
  }
}
```

### test

```json
{
  "id": "evt_Ck5Nw0Ef3Gh8Jq2Lr6Ts9Vx1Yz",
  "type": "test",
  "created_at": "2026-12-04T10:00:00.000Z",
  "data": {
    "message": "Test event from Kajiya."
  }
}
```

## Headers

| Header | Value |
|---|---|
| `Content-Type` | `application/json` |
| `User-Agent` | `Kajiya-Webhooks/1` |
| `Kajiya-Event` | The event type, for example `job.finished` |
| `Kajiya-Delivery` | The event id. Retries of the same event reuse it. |
| `Kajiya-Signature` | `t=<unix seconds>,v1=<hex signature>` |

## Verifying signatures

`v1` is the lowercase hex HMAC-SHA256 of the string `<t>.<raw request body>`, keyed with your signing secret (the whole `whsec_...` string). To verify a delivery:

1. Read the **raw** request body. Parsing and re-serializing the JSON changes the bytes and breaks the signature.
2. Split the header on `,` and `=` to get `t` and `v1`.
3. Reject the delivery if `t` is more than 300 seconds away from your clock.
4. Compute the HMAC of `t + "." + body` and compare it with `v1` in constant time.

Each attempt, including a retry, is signed when it is sent, with the current time and the current secret.

### Node.js

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

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

createServer((req, res) => {
  const chunks = [];
  req.on("data", (c) => chunks.push(c));
  req.on("end", () => {
    const raw = Buffer.concat(chunks).toString("utf8");
    if (!verifyKajiya(raw, req.headers["kajiya-signature"], process.env.KAJIYA_WEBHOOK_SECRET)) {
      res.writeHead(401).end("bad signature");
      return;
    }
    const event = JSON.parse(raw);
    console.log(event.type, event.data);
    res.writeHead(200).end("ok");
  });
}).listen(8080);
```

### Python

```python
import hashlib
import hmac
import time


def verify_kajiya(raw_body: bytes, header: str, secret: str, tolerance_s: int = 300) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    try:
        t = int(parts["t"])
    except (KeyError, ValueError):
        return False
    if abs(time.time() - t) > tolerance_s:
        return False
    want = hmac.new(secret.encode(), parts["t"].encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(want, parts.get("v1", ""))


# Flask: verify_kajiya(request.get_data(), request.headers.get("Kajiya-Signature", ""), secret)
```

### Go

```go
package kajiya

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"time"
)

// Verify checks a Kajiya-Signature header against the raw request body.
func Verify(rawBody []byte, header, secret string, tolerance time.Duration) bool {
	var ts, sig string
	for _, part := range strings.Split(header, ",") {
		k, v, ok := strings.Cut(part, "=")
		if !ok {
			continue
		}
		switch k {
		case "t":
			ts = v
		case "v1":
			sig = v
		}
	}
	t, err := strconv.ParseInt(ts, 10, 64)
	if err != nil {
		return false
	}
	if d := time.Since(time.Unix(t, 0)); d > tolerance || d < -tolerance {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(ts + "."))
	mac.Write(rawBody)
	want := hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(want), []byte(sig))
}
```

Call it with `kajiya.Verify(body, r.Header.Get("Kajiya-Signature"), secret, 5*time.Minute)` after reading the body with `io.ReadAll(r.Body)`.

## Responding and retries

- Answer with any `2xx` status within 10 seconds. Do slow work after you answer.
- Anything else counts as a failure: another status code, a timeout, a connection error, or a redirect (Kajiya does not follow redirects).
- A failed delivery is retried after 30 s, 2 min, 10 min, 1 h, 6 h: 6 attempts over about 7 hours, after which it is marked `failed`.
- Up to 8 deliveries are sent at a time, so events can arrive out of order. Use `created_at` and the job's `state` rather than arrival order.

## Idempotency

The same event can arrive more than once, for example when your endpoint processed it but the answer timed out. Store the `Kajiya-Delivery` id of every event you have handled for at least a day and skip ids you have already seen.

## Delivery log

The dashboard shows recent deliveries under **Limits & alerts**, and `GET /api/v1/webhook/deliveries` returns the last 50 with their status, attempt count, last HTTP status and error. Deliveries are kept for 7 days.

## Rotating the secret

`POST /api/v1/webhook/rotate-secret` (or **Rotate secret** in the dashboard) returns a new secret once. The old one stops working at once: every delivery from then on, including retries of earlier events, is signed with the new secret. Update your receiver right after rotating; deliveries that fail in between are retried with the new signature.

## Testing locally

Kajiya only delivers to public `https` URLs. To receive events on your laptop, expose your local server through a tunnel service that gives you a public `https` address, set that address as the webhook URL, and send a test event.
