> This page is for Paperwork API, version v2.
> For other versions, use one of these documentation indexes:
> - v1 (default): https://docs.cloudraker.com/paperwork/v1/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.cloudraker.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.cloudraker.com/_mcp/server.

# Webhooks

A webhook tells your server that a job reached a new state. Each delivery has a JWT signature. You verify it with the public keys of your organization. There is no shared secret.

## Subscribe

Use one of two methods. They work together.

**Per job.** Add `notify` to the body of a capability call:

```json
{
  "file": { "url": "https://files.example.com/invoice.pdf" },
  "notify": { "url": "https://example.com/hooks/cloudraker" }
}
```

`notify` also accepts `{ "endpoint": "whe_…" }`, the id of a saved endpoint. An unknown id gives `400 invalid_request`, and the API creates no job. Endpoint ids of `/v1` do not work on `/v2`.

**Per organization.** Add an endpoint on the [Webhooks](https://dash.cloudraker.com/webhooks) page of Dash. Select **Add endpoint**, enter the URL and select the events. With no event filter, the endpoint gets every event. An organization has at most 20 endpoints.

The `notify` target of a job gets every event of that job. An endpoint with a matching filter gets the event too. The API sends one delivery per URL.

The URL must use `https`, with 512 characters or fewer. The API refuses internal hosts and hosts on `cloudraker.run`. The API checks the URL again before each attempt.

## Events

| Event             | Sent when                                       |
| ----------------- | ----------------------------------------------- |
| `job.succeeded`   | The job succeeded.                              |
| `job.failed`      | The job failed.                                 |
| `job.needs_input` | The job waits for a person. It is not terminal. |
| `job.cancelled`   | The creating credential cancelled the job.      |
| `job.expired`     | The work passed its time limit.                 |

## The body

The body is JSON. `data.job` is the Job object:

```json
{
  "type": "job.succeeded",
  "created_at": "2026-11-07T14:02:13Z",
  "data": {
    "job": { "object": "job", "id": "job_01JC9M…", "capability": "parse", "status": "succeeded" }
  }
}
```

## Verify the signature

The `x-cr-signature` header holds a JWT. The public keys are at the JWKS of your organization:

```text
https://{slug}.cloudraker.run/.well-known/jwks.json
```

| Claim               | Value                                                                  |
| ------------------- | ---------------------------------------------------------------------- |
| `iss`               | `https://{slug}.cloudraker.run`                                        |
| `sub`               | `webhook`                                                              |
| `aud`               | The exact URL of the endpoint.                                         |
| `jti`               | The delivery id, `whd_…`. The same on each retry and on a replay.      |
| `type`              | The event type.                                                        |
| `job_id`            | The job.                                                               |
| `body_sha256`       | The SHA-256 of the raw body, as 64 lowercase hex characters.           |
| `iat`, `nbf`, `exp` | The issue time, the start time and the end time. `exp` is `iat` + 300. |

1. Read the raw body bytes. Do not parse and serialize the JSON first.
2. Verify the JWT signature with the key that has the `kid` of the JWT. Allow RS256 only.
3. Check `iss`, `aud` and `exp`.
4. Compute the SHA-256 of the raw body and compare it with `body_sha256`.
5. Drop a delivery with a `jti` that you already processed.

**`TypeScript (jose)`**

```ts title="TypeScript (jose)"
import { createHash } from 'node:crypto'
import { createRemoteJWKSet, jwtVerify } from 'jose'

const ISSUER = `https://${process.env.CRK_SLUG}.cloudraker.run`
const JWKS = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks.json`))

export async function verifyWebhook(rawBody: Buffer, token: string, endpointUrl: string) {
  // jwtVerify checks the signature, iss, aud, exp and nbf.
  const { payload } = await jwtVerify(token, JWKS, {
    issuer: ISSUER,
    audience: endpointUrl,
    algorithms: ['RS256'],
  })
  const digest = createHash('sha256').update(rawBody).digest('hex')
  if (digest !== payload.body_sha256) throw new Error('The body hash does not match.')
  return payload
}

// Hono example
app.post('/hooks/cloudraker', async (c) => {
  const rawBody = Buffer.from(await c.req.arrayBuffer())
  const token = c.req.header('x-cr-signature') ?? ''
  try {
    await verifyWebhook(rawBody, token, 'https://example.com/hooks/cloudraker')
  } catch {
    return c.text('bad signature', 401)
  }
  const event = JSON.parse(rawBody.toString('utf8'))
  // Drop a jti that you already processed, then handle event.type.
  return c.body(null, 204)
})
```

**`Python (PyJWT)`**

```python title="Python (PyJWT)"
import hashlib
import os

import jwt
from jwt import PyJWKClient

ISSUER = f"https://{os.environ['CRK_SLUG']}.cloudraker.run"
JWKS = PyJWKClient(f"{ISSUER}/.well-known/jwks.json")


def verify_webhook(raw_body: bytes, token: str, endpoint_url: str) -> dict:
    # jwt.decode checks the signature, iss, aud, exp and nbf.
    signing_key = JWKS.get_signing_key_from_jwt(token).key
    claims = jwt.decode(
        token,
        signing_key,
        algorithms=["RS256"],
        issuer=ISSUER,
        audience=endpoint_url,
        options={"require": ["iss", "aud", "exp", "jti", "body_sha256"]},
    )
    if hashlib.sha256(raw_body).hexdigest() != claims["body_sha256"]:
        raise ValueError("The body hash does not match.")
    return claims


# Flask example
@app.post("/hooks/cloudraker")
def hook():
    try:
        verify_webhook(
            request.get_data(),
            request.headers.get("x-cr-signature", ""),
            "https://example.com/hooks/cloudraker",
        )
    except (jwt.PyJWTError, ValueError):
        return "bad signature", 401
    event = request.get_json()
    # Drop a jti that you already processed, then handle event["type"].
    return "", 204
```

The `/v1` webhook verifier does not verify a v2 webhook. `/v1` uses another header, issuer and claim set.

## Retries

| Rule            | Value                                        |
| --------------- | -------------------------------------------- |
| Success         | A `2xx` answer.                              |
| Attempt timeout | 10 seconds.                                  |
| Attempts        | At most 5.                                   |
| Wait            | min(300, 5 x 2^n) seconds after attempt `n`. |
| Redirects       | Not followed. A `3xx` is a failed attempt.   |

Each attempt signs the body again with the same `jti`. After the fifth failed attempt, the delivery status is `failed`. The [Webhooks](https://dash.cloudraker.com/webhooks) page of Dash shows each delivery and can replay it. A replay uses the same `jti`.

> **Warning**
>
> Do not act on a webhook before you verify the signature.