Skip to content
Changelog

Report a bug

Webhook Adapter API

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.

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

  • 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.

An adapter file exports these values:

ExportRequiredMeaning
defaultYesAn object that satisfies IntegrationWebhook. It must have setup, receive, and remove.
eventsYesAn array of event schemas. Make each one with webhookEvent().
fixturesYes2 to 20 receive fixtures. At least one must accept an event, and at least one must reject a request.
settingsNoNon-secret JSON settings. The default is {}.

Type 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:

src/main.ts
import { automation, code, complete } from "@type-dot-com/sdk/automations";
import { z } from "zod";
import { meetingCompleted } from "./events";
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.
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:

src/events.ts
import { webhookEvent } from "@type-dot-com/sdk/webhooks";
import { z } from "zod";
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:

src/webhook.ts
import { meetingCompleted } from "./events";
export const events = [meetingCompleted];
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<...>;
}
MethodWhen Type calls itReturn
setupAt first activation, when you enable the automation again after a failure, and when a manager runs setup.{ id, state, renewAt? }
receiveFor each incoming GET or POST.Events, a challenge response, or a rejection.
removeWhen a manager removes the registration, or when a connection is disconnected.ok(undefined), also when the registration is already gone.
renewOptional. 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.

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.

FieldMeaning
nowThe host time, as an ISO string. Use it for timestamp checks.
settingsThe non-secret settings of the adapter.
secretA random signing key that Type makes and saves before setup. Do not log it.
registrationThe last saved registration, or null.
cryptoCryptographic helpers. See below.

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

Has all fields of WebhookReceiveContext, and these:

Field or methodMeaning
urlThe callback URL to register with the provider.
eventsThe event types that the adapter declares.
operationIdFor 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 records the issue outcome_unknown, because the provider can have applied the change.

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.

Return exactly one of these:

// 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 });
KindRules
eventsAt most 100 events. An empty list accepts the request and starts no work.
respondstatus 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.
rejectstatus is 400, 401, or 403.

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

Each event has these fields:

FieldRules
id1 to 300 characters. Use the provider’s event ID. It must stay the same when the provider retries. A random ID stops retry deduplication.
type1 to 200 characters. One of the adapter’s declared events. If an event has another type, Type answers 503 and records nothing.
resourceType, resourceIdRequired 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.
dataJSON.
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 ===.

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.

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.

StatusMeaning
pendingSaved, not yet set up.
creatingsetup is in progress.
readyThe registration accepts events.
renewingrenew is in progress. The registration still accepts events.
removingremove is in progress.
needs_attentionA lifecycle call failed or its lease expired. A manager must act.
removedThe 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 codeMeaning
operation_failedThe call failed before it sent a request other than GET.
outcome_unknownThe call failed after a request other than GET. Check the provider before you retry.
interruptedThe call did not finish before its lease expired, for example because a server stopped.
connection_unavailableThe 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.

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.

OperationExtra fieldsResult
list—Summaries for the connection.
getkeyThe summary, the adapter definition with its fixtures, and its code files.
testdefinition, codeFilesTypecheck and run fixtures. Changes nothing.
replacekey, expectedRevision, definition, codeFilesPublish a tested code repair. Events and settings must not change.
setupkey, expectedRevisionCreate or recover the same registration. Allowed when pending, ready, or needs_attention.
renewkey, expectedRevisionRenew a ready registration now.
removekey, expectedRevisionRemove 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.

  • Before ready: Type 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.
StatusWhen
202Type accepted the events, or the request had no events.
200, 202, 204receive returned a respond result.
400, 401, 403receive returned a reject result.
404The URL is unknown, the registration is removed or being removed, the connection is not connected, or the credential changed.
413The body is larger than 1 MiB.
429The workspace reached the rate limit. Type sets Retry-After: 60.
503The registration is not ready, receive failed, or Type could not save the events. The provider must retry.
ItemLimit
Incoming requestGET or POST. UTF-8 body up to 1 MiB.
receive call5 seconds, including startup. 32 MiB VM memory.
setup, renew, remove call60 seconds.
Provider requests and save calls32 for each lifecycle call.
Provider response1 MiB. Type rejects a truncated response.
Registration state or call result64 KiB of JSON.
Events per request100.
Challenge body8,192 characters.
Incoming rate120 requests per minute for each workspace. More requests get 429.
Adapters per automation request20.
Fixtures per adapter2 to 20.