# Webhook Adapter API Reference

> The IntegrationWebhook interface for Type.com webhook adapters: its contexts, receive results, fixtures, management operations, and limits.

Canonical page: https://docs.type.com/automations/reference/webhook-adapters/

A webhook adapter is a small TypeScript module. It registers a webhook with a provider, verifies each incoming request, and changes requests into events. Type hosts the callback URL. For a guide, see [Webhooks](https://docs.type.com/automations/webhooks/index.md#with-code-a-webhook-adapter).

Slack and GitHub do not need an adapter. Type receives their events for you.

## Ownership

- A **connection** owns the webhook registration. An **automation** subscribes to it.
- Two automations that use the same connection and the same webhook key share one registration. They must use the same credential account.
- Only an integration manager can install the adapter, publish code changes, or run `setup`, `renew`, and `remove` on request. Without granular integration permissions, integration managers are workspace owners, admins, and the person who added the connection. With granular permissions, they are workspace owners, admins, and the connection's designated managers.
- Type pins the registration to the credential account that installed it. Type never moves it to a different account. For a personal account, only its owner can run lifecycle operations or publish code changes.
- Scheduled renewal and the removal during a disconnect run without a person. They keep working after the person who installed the adapter leaves the workspace.

## Module exports

An adapter file exports these values:

| Export | Required | Meaning |
| --- | --- | --- |
| `default` | Yes | An object that satisfies `IntegrationWebhook`. It must have `setup`, `receive`, and `remove`. |
| `events` | Yes | An array of event schemas. Make each one with `webhookEvent()`. |
| `fixtures` | Yes | 2 to 20 receive fixtures. At least one must accept an event, and at least one must reject a request. |
| `settings` | No | Non-secret JSON settings. The default is `{}`. |

Type.com typechecks the adapter against `IntegrationWebhook` and runs its fixtures when you deploy or test it. Type saves the adapter file and the relative modules that it imports. Other files in the project are not part of the adapter.

Add the adapter to the automation's `deployment`:

```ts title="src/main.ts"

export default automation({
  output: z.object({ meetingId: z.string() }),
  deployment: {
    webhooks: {
      meetings: { connectionId: "orgint_example", entrypoint: "src/webhook.ts" },
    },
    subscriptions: {
      meetingReady: {
        title: "Log a completed meeting",
        description: "Record each completed meeting",
        source: {
          kind: "integration",
          connectionId: "orgint_example",
          webhook: "meetings",
          events: ["meeting.completed"],
        },
        schema: meetingCompleted,
        entry: "record",
      },
    },
  },
  stages: {
    record: code({
      input: meetingCompleted,
      transitions: [],
      run: ({ input }) => complete({ meetingId: input.data.id }),
    }),
  },
});
```

The webhook key (`meetings`) names the registration on the connection. The subscription ID (`meetingReady`) names the subscription, and `entry` names the stage that gets its events. The webhook key and the subscription ID do not need to match.

- A webhook key starts with a lowercase letter. It can have lowercase letters, digits, `_`, and `-`. The maximum length is 64 characters.
- Each adapter in `webhooks` must be used by a subscription in the same automation.
- To use an adapter that is already installed, set `source.webhook` and omit `webhooks`.

## `webhookEvent()`

```ts
function webhookEvent<Type extends string, Data extends ZodType>(type: Type, data: Data): ZodObject<{
  id: ZodString;
  type: ZodLiteral<Type>;
  resourceId: ZodOptional<ZodNullable<ZodString>>;
  resourceType: ZodOptional<ZodNullable<ZodString>>;
  data: Data;
}>;
```

Defines one event shape. Use the same schema in the adapter `events` export and in the subscription `schema`. You can put it in its own module and import it from both files:

```ts title="src/events.ts"

export const meetingCompleted = webhookEvent(
  "meeting.completed",
  z.object({ id: z.string().min(1), title: z.string(), summary: z.string().nullable() }),
);
```

Then export the list from the adapter module:

```ts title="src/webhook.ts"

export const events = [meetingCompleted];
```

## `IntegrationWebhook`

```ts
interface IntegrationWebhook {
  setup(ctx: WebhookSetupContext): Result<WebhookRegistration, Error> | PromiseLike<...>;
  receive(ctx: WebhookReceiveContext, request: WebhookRequest): Result<WebhookReceiveResult, Error> | PromiseLike<...>;
  remove(ctx: WebhookSetupContext): Result<void, Error> | PromiseLike<...>;
  renew?(ctx: WebhookSetupContext): Result<WebhookRegistration, Error> | PromiseLike<...>;
}
```

| Method | When Type calls it | Return |
| --- | --- | --- |
| `setup` | At first activation, when you enable the automation again after a failure, and when a manager runs `setup`. | `{ id, state, renewAt? }` |
| `receive` | For each incoming `GET` or `POST`. | Events, a challenge response, or a rejection. |
| `remove` | When a manager removes the registration, or when a connection is disconnected. | `ok(undefined)`, also when the registration is already gone. |
| `renew` | Optional. When `renewAt` comes, or when a manager asks. | The updated registration with its next `renewAt`. |

Each method returns a `Result` from `neverthrow`, directly or in a promise. Return `err(error)` when a method cannot get a successful result.

> **Caution:** `setup` must be idempotent. If Type calls it again, it must find or recover the same provider registration. This includes the case where an earlier request succeeded but its response was lost. Do not create a second webhook after a timeout.

## `WebhookRegistration`

```ts
interface WebhookRegistration {
  id: string; // 1 to 500 characters
  state: JsonValue; // encrypted at rest
  renewAt?: string; // ISO date-time, at least 1 minute in the future
}
```

Put the data that later calls need in `state`, for example a provider signing key or a lease ID. Type encrypts `state`. Management responses never show it. A registration with `renewAt` needs a `renew` method.

## `WebhookReceiveContext`

| Field | Meaning |
| --- | --- |
| `now` | The host time, as an ISO string. Use it for timestamp checks. |
| `settings` | The non-secret settings of the adapter. |
| `secret` | A random signing key that Type makes and saves before `setup`. Do not log it. |
| `registration` | The last saved registration, or `null`. |
| `crypto` | Cryptographic helpers. See [below](#crypto). |

`receive` has no provider API, no network, no file system, and no agent access.

## `WebhookSetupContext`

Has all fields of `WebhookReceiveContext`, and these:

| Field or method | Meaning |
| --- | --- |
| `url` | The callback URL to register with the provider. |
| `events` | The event types that the adapter declares. |
| `operationId` | For `setup`: the same value for all attempts on this registration, also after code repairs. For other methods: a new value for each call. Use it as an idempotency key. |
| `request({ method, path, query?, headers?, body? })` | An authorized request to the connection's API. `method` is `GET`, `POST`, `PUT`, `PATCH`, or `DELETE`. `path` is relative to the base URL. Returns `{ status, data }`. |
| `save(registration)` | Saves the registration before the next external step. A challenge can then use the saved state. |

Check `status` after each `request`. A non-success status does not prove that an operation failed or succeeded. If a lifecycle call fails after a request other than `GET`, Type.com records the issue `outcome_unknown`, because the provider can have applied the change.

## `WebhookRequest`

```ts
interface WebhookRequest {
  method: "GET" | "POST";
  headers: Record<string, string>; // lowercase names
  query: Record<string, string>;
  rawBody: string; // the UTF-8 body, at most 1 MiB
}
```

Verify the signature against `rawBody` before you parse it. Type gives a `HEAD` request to `receive` as a `GET`.

## `WebhookReceiveResult`

Return exactly one of these:

```ts
// An authenticated delivery. 0 to 100 events.
ok({ kind: "events", events: [{ id, type, resourceType, resourceId, data }] });

// A verified challenge. No automation runs.
ok({ kind: "respond", status: 200, body: challenge, contentType: "text/plain" });

// A request that failed authentication. Type records no event.
ok({ kind: "reject", status: 401 });
```

| Kind | Rules |
| --- | --- |
| `events` | At most 100 events. An empty list accepts the request and starts no work. |
| `respond` | `status` is 200, 202, or 204. `body` is a string of at most 8,192 characters. `contentType` is `text/plain` or `application/json`. Encode JSON as a string. |
| `reject` | `status` is 400, 401, or 403. |

Type.com sends `respond` and `reject` results also before the registration is ready, so a provider challenge works during `setup`.

Each event has these fields:

| Field | Rules |
| --- | --- |
| `id` | 1 to 300 characters. Use the provider's event ID. It must stay the same when the provider retries. A random ID stops retry deduplication. |
| `type` | 1 to 200 characters. One of the adapter's declared events. If an event has another type, Type answers `503` and records nothing. |
| `resourceType`, `resourceId` | Required in the result. Use `null` when the event has no resource. Up to 200 and 2,000 characters. Both must be set to match a `resources` filter. |
| `data` | JSON. |

## `crypto`

```ts
interface WebhookCrypto {
  hmac(input: { algorithm: "sha256" | "sha1" | "sha512"; key: string; keyEncoding?: "utf8" | "base64" | "hex"; data: string; encoding: "hex" | "base64" }): string;
  digest(input: { algorithm: "sha256" | "sha512"; data: string; encoding: "hex" | "base64" }): string;
  equal(left: string, right: string): boolean; // constant-time comparison
  verify(input: { algorithm: "sha256" | "sha512" | "ed25519"; publicKey: string; data: string; signature: string; encoding: "hex" | "base64" }): boolean;
}
```

Use `equal` to compare signatures. Do not use `===`.

## Fixtures

Each adapter needs 2 to 20 fixtures. Type runs `receive` with each fixture when you deploy or test the adapter, and compares the result with `expected`. Fixtures cannot call live APIs.

```ts
interface WebhookFixture {
  name: string; // 1 to 200 characters
  request: WebhookRequest;
  secret: string; // a fake key, at most 4,096 characters
  registration: WebhookRegistration | null;
  now: string; // a fixed ISO date-time
  expected: WebhookReceiveResult; // the exact result
}
```

Add fixtures for a forged signature, changed body bytes, an old timestamp, missing required fields, and each provider challenge.

## Status values

| Status | Meaning |
| --- | --- |
| `pending` | Saved, not yet set up. |
| `creating` | `setup` is in progress. |
| `ready` | The registration accepts events. |
| `renewing` | `renew` is in progress. The registration still accepts events. |
| `removing` | `remove` is in progress. |
| `needs_attention` | A lifecycle call failed or its lease expired. A manager must act. |
| `removed` | The key is retired. Use a new key to register again. |

A summary can also have an `issue` with a `code` and the `stage` where it happened:

| Issue code | Meaning |
| --- | --- |
| `operation_failed` | The call failed before it sent a request other than `GET`. |
| `outcome_unknown` | The call failed after a request other than `GET`. Check the provider before you retry. |
| `interrupted` | The call did not finish before its lease expired, for example because a server stopped. |
| `connection_unavailable` | The credential account changed or is no longer usable. `list` and `get` report a ready registration in this state as `needs_attention`. After `remove`, it means that Type retired the callback but could not clean up the provider registration. |

## Management operations

Integration managers use the `manage_integration_webhooks` tool in Type, or `type.integrations.webhooks()` in the SDK. Every request has `connectionId`. Operations that change a registration also need `key` and `expectedRevision`.

| Operation | Extra fields | Result |
| --- | --- | --- |
| `list` | — | Summaries for the connection. |
| `get` | `key` | The summary, the adapter definition with its fixtures, and its code files. |
| `test` | `definition`, `codeFiles` | Typecheck and run fixtures. Changes nothing. |
| `replace` | `key`, `expectedRevision`, `definition`, `codeFiles` | Publish a tested code repair. Events and settings must not change. |
| `setup` | `key`, `expectedRevision` | Create or recover the same registration. Allowed when `pending`, `ready`, or `needs_attention`. |
| `renew` | `key`, `expectedRevision` | Renew a ready registration now. |
| `remove` | `key`, `expectedRevision` | Remove a registration that no automation subscribes to. |

If `expectedRevision` is not the current revision, the operation fails with a conflict. Read the registration again, then decide.

The revision covers the adapter code, its imported modules, its events, and its settings. A deploy that supplies different adapter code for an existing key fails with a conflict. Use `replace` to repair code. To change events or settings, use a new key.

## Behavior and guarantees

- **Before ready:** Type.com answers incoming events with `503` until the registration is ready and the first subscription is active. Type does not keep events that come before this point.
- **Delivery:** For each verified event, Type queues the event for every matching active subscriber in one commit, then answers `202`. If the commit fails, Type answers `503` and the provider must retry.
- **Retries:** Each subscriber gets an event ID only once. A provider retry with the same event ID does not run a subscriber again.
- **New subscribers:** Type does not replay earlier events to a subscriber that you add later.
- **Pause:** Events that come while a subscriber is paused are not saved for that subscriber. Resume does not replay them.
- **Credential change:** If someone reconnects or changes the credential, Type answers `404` until a manager runs `setup`. For a personal account, only its owner can do this.
- **Renewal:** Type checks for due renewals every minute, 20 registrations at a time. Set `renewAt` well before the provider expiry. If a renewal fails before it sends a request other than `GET`, the registration stays `ready` and Type tries again about 5 minutes later. Otherwise it becomes `needs_attention`.
- **Disconnect:** Type tries to remove the provider registration, then deletes the credential even if removal fails. You can have to remove the provider registration by hand.

## Responses

| Status | When |
| --- | --- |
| `202` | Type.com accepted the events, or the request had no events. |
| `200`, `202`, `204` | `receive` returned a `respond` result. |
| `400`, `401`, `403` | `receive` returned a `reject` result. |
| `404` | The URL is unknown, the registration is removed or being removed, the connection is not connected, or the credential changed. |
| `413` | The body is larger than 1 MiB. |
| `429` | The workspace reached the rate limit. Type sets `Retry-After: 60`. |
| `503` | The registration is not ready, `receive` failed, or Type could not save the events. The provider must retry. |

## Limits

| Item | Limit |
| --- | --- |
| Incoming request | `GET` or `POST`. UTF-8 body up to 1 MiB. |
| `receive` call | 5 seconds, including startup. 32 MiB VM memory. |
| `setup`, `renew`, `remove` call | 60 seconds. |
| Provider requests and `save` calls | 32 for each lifecycle call. |
| Provider response | 1 MiB. Type rejects a truncated response. |
| Registration state or call result | 64 KiB of JSON. |
| Events per request | 100. |
| Challenge body | 8,192 characters. |
| Incoming rate | 120 requests per minute for each workspace. More requests get `429`. |
| Adapters per automation request | 20. |
| Fixtures per adapter | 2 to 20. |
