# Webhook

> Webhooks and events: everything that happens, delivered to your server, signed.

```python
hook = noclick.Webhook.from_name("https://api.yourco.test/noclick/events", create_if_missing=True,
                                 events=["operation.*", "human.answered"])
secret = hook.reveal_secret()   # needs the webhooks:reveal scope

# in your receiver
event = noclick.Webhook.verify(request_body, request_headers, secret)
print(event.type, event.data)
```

Every event is also kept for 30 days: `noclick.Event.list(type="domain.*")`.

## Webhook

```typescript
class Webhook
```

An endpoint on your server that receives events, signed with its secret. One created for a
user (inside `asUser`, or with `user`) receives only that user's events; your account's
own receive every event, your users' included.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `url` | `string` |  |
| `events` | `string[]` | The event types it receives; `*` matches the rest of a name. |
| `enabled` | `boolean` |  |
| `status` | `WebhookStatus` | `healthy`, `failing` (its latest deliveries failed; retries continue) or `disabled`. |
| `description` | `string | null` |  |
| `successRate24h` | `number | null` | The share of attempts in the last 24 hours your server answered 2xx (null if none). |
| `lastFailure` | `JsonObject | null` | The latest failed attempt: `at`, `response_status` and `error` (null if none). |
| `userId` | `string | null` | The user whose events it receives (null: every event). |
| `createdAt` | `Date | null` |  |
| `secret` | `string | null` | The signing secret (`nk_whsec_...`), on the object that created the webhook (`create`, or `fromName` when it created one), `rotateSecret` or `revealSecret`; any other read leaves it out. |

Types:

```typescript
type WebhookStatus = "healthy" | "failing" | "disabled";

type JsonObject = { [key: string]: unknown };
```

### Webhook.create

```typescript
static create(
  url: string,
  options: WebhookCreateOptions & AllowExisting,
): Promise<Webhook>
```

Start delivering `events` to `url`, an `https` address your server answers. `secret` is shown on the
result this once. A scope has one webhook per address: another throws `Conflict` with `existingId`, or
with `allowExisting: true` returns the one already there, as it is (its events don't change, and its
`secret` isn't shown: `revealSecret()` reads it).

Parameters:

- `url` (`string`, required)
- `options.events` (`readonly string[]`, required): The event types it receives; `operation.*` or `*` for more at once.
- `options.description` (`string`)
- `options.allowExisting` (`boolean`): A taken name returns the object already there, as it is: nothing about it changes.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.idempotencyKey` (`string`): Makes a retried create safe: the same key returns the first result. Generated when omitted.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The new webhook. Its `secret` is shown this once: store it where your receiver reads it.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Webhook.fromName

```typescript
static fromName(
  url: string,
  options?: CallOptions & {
    createIfMissing?: boolean;
    events?: readonly string[];
    description?: string;
  },
): Webhook
```

A lazy reference to the webhook delivering to `url` for the current (or given) user; `url` names
it, since a scope has one webhook per address. Given `events` or `description`, it gets the webhook
and sets them, on every run. `createIfMissing` creates it with `events` (and `description`) when
there's none; without it, a missing webhook throws `NotFound`. Each run with fields is a write: do it
at startup or in a setup script, not per request.
`secret` holds the signing secret when this call created it; otherwise read it with `revealSecret()`.

Parameters:

- `url` (`string`, required)
- `options.createIfMissing` (`boolean`)
- `options.events` (`readonly string[]`)
- `options.description` (`string`)
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A webhook that loads (or is created, or has your fields set) the first time it's used.
When this call created it, `secret` holds its signing secret; otherwise read it with
`reveal_secret()`.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Webhook.fromId

```typescript
static fromId(webhookId: string, options?: CallOptions): Webhook
```

A lazy reference to a webhook by id.

Parameters:

- `webhookId` (`string`, required)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.

Returns: A webhook that loads the first time you read a field. Nothing is sent yet.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Webhook.get

```typescript
static get(webhookId: string, options?: CallOptions): Promise<Webhook>
```

Load a webhook by id now; an unknown id raises `noclick.NotFound`.

Parameters:

- `webhookId` (`string`, required)
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The webhook, loaded (without its secret).

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Webhook.list

```typescript
static list(options?: ReadOptions & { limit?: number }): Promise<Webhook[]>
```

Your account's webhooks (or the current user's, or those `userFilter` covers).

Parameters:

- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Every matching webhook, newest first, fetched page by page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Webhook.listPage

```typescript
static listPage(options?: ReadOptions & PageOptions): Promise<Page<Webhook>>
```

One page of webhooks; pass `nextCursor` back as `cursor`.

Parameters:

- `options.cursor` (`string | null`): The `next_cursor` of the page before; omit it for the first page.
- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A page whose `data` holds the webhooks and whose `next_cursor` is `None` on the last page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Webhook.update

```typescript
update(changes: WebhookChanges): Promise<this>
```

Change where it delivers, what it receives, or pause it (`enabled: false`).

Parameters:

- `changes` (`WebhookChanges`, required)

Returns: This webhook, updated.

Types:

```typescript
/** A field you leave out is unchanged; `description: null` clears it. */
interface WebhookChanges {
  url?: string;
  events?: readonly string[];
  /** `false` pauses it: events that happen meanwhile are not delivered later. */
  enabled?: boolean;
  description?: string | null;
}
```

### Webhook.delete

```typescript
delete(): Promise<void>
```

Delete the webhook; deliveries still retrying stop.

### Webhook.rotateSecret

```typescript
rotateSecret(options?: { graceS?: number }): Promise<string>
```

Replace the signing secret. For `graceS` (default a day, at most 7 days) each delivery is
signed with both, so deliveries keep verifying while you deploy the new one; `graceS: 0` if the
old one leaked. Resolves to the new secret, shown this once (also on `hook.secret`).

Parameters:

- `options.graceS` (`number`)

Returns: The new secret, shown this once (also on `hook.secret`).

### Webhook.revealSecret

```typescript
revealSecret(): Promise<string>
```

Read the current signing secret, so a receiver that starts from code (or a webhook `fromName`
found rather than created) can verify deliveries. Needs a key with the `webhooks:reveal` scope,
which full access leaves out; every reveal is recorded with the key that made it.

Returns: The secret (`nk_whsec_...`), also on `hook.secret`.

### Webhook.test

```typescript
test(eventType?): Promise<WebhookDelivery>
```

Send a sample event of `eventType` now, signed like a real one, and wait up to 10 seconds for
your server's answer. It isn't retried and isn't recorded in `Event.list`.

Parameters:

- `eventType` (`string`, default `"operation.succeeded"`)

Returns: The delivery: its `status` (`succeeded` or `failed`), `response_status` and `response_body`.

### Webhook.deliveries

```typescript
deliveries(
  options?: {
    status?: WebhookDeliveryStatus | readonly WebhookDeliveryStatus[];
    event?: Event | string;
    limit?: number;
  },
): Promise<WebhookDelivery[]>
```

Deliveries newest first (the last 30 days), optionally only those with `status` or of one `event`.

Parameters:

- `options.status` (`WebhookDeliveryStatus | readonly WebhookDeliveryStatus[]`)
- `options.event` (`Event | string`)
- `options.limit` (`number`): Return at most this many.

Returns: Every matching delivery, fetched page by page (or the first `limit`).

Types:

```typescript
type WebhookDeliveryStatus = "pending" | "retrying" | "succeeded" | "failed";
```

### Webhook.redeliver

```typescript
redeliver(delivery: WebhookDelivery | string): Promise<WebhookDelivery>
```

Send a delivery's event again now (the same event id), whatever its status.

Parameters:

- `delivery` (`WebhookDelivery | string`, required)

Returns: The delivery, with this attempt counted in `attempts` and its outcome in `status`.

### Webhook.verify

```typescript
static verify(
  payload: string | Uint8Array | ArrayBuffer,
  headers: WebhookHeaders,
  secret: string | readonly string[],
  options?: { toleranceS?: number },
): Promise<Event>
```

Check a delivery in your receiver: `payload` is the raw body exactly as it arrived (not parsed
and re-serialized), `headers` its headers and `secret` the webhook's, or several while you
rotate. The `NoClick-Signature` header is `t=<unix seconds>,v1=<hex>`, where the hex is
HMAC-SHA256 of `"<t>.<body>"` keyed with the secret; a timestamp more than `toleranceS`
(300) from now is refused, so a captured delivery can't be replayed. Sends nothing.
Throws `WebhookSignatureError` for a missing or malformed header, a stale timestamp, or no match.

Parameters:

- `payload` (`string | Uint8Array | ArrayBuffer`, required)
- `headers` (`WebhookHeaders`, required)
- `secret` (`string | readonly string[]`, required)
- `options.toleranceS` (`number`, default `300`)

Returns: The event the body carries, ready to act on.

Types:

```typescript
/** Request headers as `fetch` (`Headers`) or Node (`req.headers`) hands them over. */
type WebhookHeaders = Headers | Readonly<Record<string, string | readonly string[] | undefined>>;
```

## WebhookDelivery

```typescript
interface WebhookDelivery
```

One event sent (or on its way) to one webhook. `status` is `pending` (not tried yet),
`retrying` (an attempt failed; `nextRetryAt` says when the next one is), `succeeded` (your
server answered 2xx) or `failed` (three days of retries ran out). `responseStatus` and
`responseBody` (its first 4 KB) are from the latest attempt; `requestBody` is the JSON sent.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `webhookId` | `string | null` |  |
| `eventId` | `string | null` |  |
| `eventType` | `string | null` |  |
| `status` | `WebhookDeliveryStatus` |  |
| `attempts` | `number` |  |
| `responseStatus` | `number | null` |  |
| `responseBody` | `string | null` |  |
| `requestBody` | `string | null` |  |
| `durationMs` | `number | null` |  |
| `error` | `string | null` | Why the latest attempt failed (`Answered 502`, `No answer within 10 seconds.`); null once it succeeded. |
| `nextRetryAt` | `Date | null` |  |
| `createdAt` | `Date | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |
| `ok` | `boolean` | Whether your server accepted it (a 2xx). |

Types:

```typescript
type WebhookDeliveryStatus = "pending" | "retrying" | "succeeded" | "failed";

type JsonObject = { [key: string]: unknown };
```

## Event

```typescript
class Event
```

Something that happened: an operation finished, a person answered, a domain went live.
`type` names it (see `Event.types()`) and `data` is the object it's about, as its own read
returns it (`data.object` names the kind, `data.id` its id). Delivered to your webhooks, and
kept for 30 days.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `type` | `string` | What happened, like `operation.succeeded`. |
| `data` | `JsonObject` | The object the event is about, as its own read returns it. |
| `userId` | `string | null` | The user it happened for (null for your account's own). |
| `createdAt` | `Date | null` |  |
| `deliveries` | `WebhookDelivery[]` | Where this event went: one delivery per webhook that subscribes to it. The full view carries them (`Event.get(id)`, or `await event.refresh()` for one from a listing). |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

### Event.fromId

```typescript
static fromId(eventId: string, options?: CallOptions): Event
```

A lazy reference to an event by id.

Parameters:

- `eventId` (`string`, required)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.

Returns: An event that loads the first time you read a field. Nothing is sent yet.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Event.get

```typescript
static get(eventId: string, options?: CallOptions): Promise<Event>
```

Load an event by id now, with its deliveries; an unknown id (or one older than 30 days) throws `NotFound`.

Parameters:

- `eventId` (`string`, required)
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The event, loaded.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Event.list

```typescript
static list(options?: EventListOptions & { limit?: number }): Promise<Event[]>
```

Events newest first, from the last 30 days. Outside `asUser` you read your account's own
events; `userFilter` reads your users'.

Parameters:

- `options.type` (`string | readonly string[]`): One type or several; `*` matches the rest of a name (`domain.*`).
- `options.since` (`Date | string`)
- `options.until` (`Date | string`)
- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Every matching event, fetched page by page (or the first `limit`).

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Event.listPage

```typescript
static listPage(options?: EventListOptions & PageOptions): Promise<Page<Event>>
```

One page of events; pass `nextCursor` back as `cursor`.

Parameters:

- `options.cursor` (`string | null`): The `next_cursor` of the page before; omit it for the first page.
- `options.limit` (`number`): Return at most this many.
- `options.type` (`string | readonly string[]`): One type or several; `*` matches the rest of a name (`domain.*`).
- `options.since` (`Date | string`)
- `options.until` (`Date | string`)
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A page whose `data` holds the events and whose `next_cursor` is `None` on the last page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Event.types

```typescript
static types(options?: { client?: NoClick }): Promise<EventType[]>
```

The catalog of event types a webhook can subscribe to, in catalog order (grouped by area).

Parameters:

- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Every event type with what it means, in catalog order (grouped by `area`).

## EventType

```typescript
interface EventType
```

One kind of event: its `name` (`operation.succeeded`), what it means, and its `area` (the part
before the first dot). `emitted` is whether NoClick sends it today: the rest are listed so your
code can subscribe before the primitive behind them ships.

| Attribute | Type | Description |
| --- | --- | --- |
| `name` | `string` |  |
| `description` | `string` |  |
| `emitted` | `boolean` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |
| `area` | `string` | What the event is about: `operation`, `human`, `domain`, ... |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```
