# Webhooks

> Verify webhook signatures and parse events with @morevoice/sdk: constructEvent, the edge-runtime variants, the legacy scheme and test headers.

`webhooks.constructEvent()` checks a delivery's [Standard Webhooks](https://www.standardwebhooks.com) signature and returns the parsed event; the `…Async` variants do the same on WebCrypto for edge runtimes. Pass the **raw** request body: the signature covers the exact bytes MoreVoice sent.

How signing works, and how to verify without the SDK, is on [verifying signatures](https://docs.morevoice.ai/webhooks/verify/). The events themselves are in the [event catalogue](https://docs.morevoice.ai/webhooks/events/).

```ts title="app/webhooks/route.ts"
// A webhook endpoint for any runtime with Fetch API handlers:
// Next.js route handlers, Hono, Bun, Deno, Cloudflare Workers.
import { webhooks, WebhookVerificationError } from "@morevoice/sdk";

const secret = process.env.MOREVOICE_WEBHOOK_SECRET!; // whsec_…

export async function POST(request: Request): Promise<Response> {
	const body = await request.text(); // the raw body, exactly as sent
	try {
		const event = await webhooks.constructEventAsync(body, request.headers, secret);
		if (event.type === "call.ended") {
			console.log(`Call ${event.data.object.id} ended`);
		}
		// Acknowledge fast; do slow work afterwards.
		return new Response(null, { status: 204 });
	} catch (err) {
		if (err instanceof WebhookVerificationError) {
			return new Response(err.code, { status: 400 });
		}
		throw err;
	}
}
```

## Examples

### On Node's http module

`constructEvent()` is the synchronous form, for Node servers. Collect the body as bytes and pass it as it arrived.

```ts title="server.ts"
// A webhook endpoint on Node's http module. Express, Fastify and Koa work the same way: give constructEvent the raw
// body (express.raw({ type: "application/json" })), before any JSON parser touches it.
import { createServer } from "node:http";
import { webhooks, WebhookVerificationError } from "@morevoice/sdk";

const secret = process.env.MOREVOICE_WEBHOOK_SECRET!; // whsec_…

createServer(async (req, res) => {
	if (req.method !== "POST" || req.url !== "/webhooks/morevoice") return void res.writeHead(404).end();
	const chunks: Buffer[] = [];
	for await (const chunk of req) chunks.push(chunk as Buffer);
	try {
		const event = webhooks.constructEvent(Buffer.concat(chunks), req.headers, secret);
		console.log(`${event.type} ${event.id}`);
		res.writeHead(204).end(); // acknowledge fast; do slow work afterwards
	} catch (err) {
		if (err instanceof WebhookVerificationError) return void res.writeHead(400).end(err.code);
		throw err;
	}
}).listen(3000);
```

### Verify now, handle later

`verifySignature()` (and `verifySignatureAsync()` on WebCrypto) checks a delivery without parsing it, and returns the webhook ID, its timestamp and the body: hand them to a queue and acknowledge at once.

```ts title="worker.ts"
// Verify a delivery at the edge and pass it on unparsed: verifySignatureAsync checks the signature on WebCrypto and
// returns the webhook ID (use it to drop repeats), its timestamp and the body as text.
import { webhooks, WebhookVerificationError } from "@morevoice/sdk";

interface Queue {
	send(message: { id: string; payload: string }): Promise<void>;
}

export async function receive(request: Request, queue: Queue, secret: string): Promise<Response> {
	try {
		const { id, payload } = await webhooks.verifySignatureAsync(await request.text(), request.headers, secret);
		await queue.send({ id, payload }); // a worker parses and handles it
		return new Response(null, { status: 202 });
	} catch (err) {
		if (err instanceof WebhookVerificationError) return new Response(err.code, { status: 400 });
		throw err;
	}
}
```

### Test your endpoint

`generateTestHeaders()` signs a payload the way MoreVoice does, so your tests can post genuine-looking deliveries to your endpoint, and check that a changed body is refused.

```ts title="webhooks.test.ts"
// Test your webhook endpoint with deliveries signed the way MoreVoice signs them (run with `node --test`, while the
// endpoint runs locally with the same MOREVOICE_WEBHOOK_SECRET). generateTestHeaders signs a payload; verifySignature
// is the check the endpoint runs.
import assert from "node:assert/strict";
import { test } from "node:test";
import { webhooks, WebhookVerificationError } from "@morevoice/sdk";

const secret = process.env.MOREVOICE_WEBHOOK_SECRET!; // a test secret (whsec_…), never your live one
const payload = JSON.stringify({ id: "evt_test_1", object: "event", type: "call.ended", data: { object: { id: "call_test_1" } } });

test("a signed delivery verifies, a changed one doesn't", () => {
	const headers = webhooks.generateTestHeaders({ payload, secret });
	assert.equal(webhooks.verifySignature(payload, headers, secret).id, headers["webhook-id"]);
	assert.throws(() => webhooks.verifySignature(payload.replace("ended", "created"), headers, secret), WebhookVerificationError);
});

test("the endpoint accepts a signed delivery", async () => {
	const headers = webhooks.generateTestHeaders({ payload, secret });
	const res = await fetch("http://127.0.0.1:3000/webhooks/morevoice", { method: "POST", headers: { ...headers, "content-type": "application/json" }, body: payload });
	assert.equal(res.status, 204);
});
```

### Legacy signatures on an edge runtime

Endpoints created before webhooks v2 are signed with the legacy scheme. `verifyLegacyAsync()` checks it on WebCrypto; `verifyLegacy()` is the synchronous form (see [verifying signatures](https://docs.morevoice.ai/webhooks/verify/#endpoints-created-before-v2)).

```ts title="app/webhooks/legacy/route.ts"
// The legacy signature (endpoints created before webhooks v2) on an edge runtime: verifyLegacyAsync is verifyLegacy
// on WebCrypto.
import { webhooks, WebhookVerificationError } from "@morevoice/sdk";

export async function POST(request: Request): Promise<Response> {
	try {
		const event = await webhooks.verifyLegacyAsync(await request.text(), request.headers, process.env.MOREVOICE_WEBHOOK_SECRET!);
		console.log(event.event); // e.g. "call.ended"
		return new Response(null, { status: 204 });
	} catch (err) {
		if (err instanceof WebhookVerificationError) return new Response(err.code, { status: 400 });
		throw err;
	}
}
```

## API

Exported from `@morevoice/sdk` (source: `packages/sdk-ts/src/lib/webhooks.ts`).

### `SECRET_PREFIX`

*constant*

Prefix of a Standard Webhooks secret (`whsec_<base64 key>`).

```ts
const SECRET_PREFIX = "whsec_";
```

### `PUBLIC_KEY_PREFIX`

*constant*

Prefix of a Standard Webhooks Ed25519 public key (`whpk_<base64 of 32 bytes>`): what an `ed25519` endpoint is verified with.

```ts
const PUBLIC_KEY_PREFIX = "whpk_";
```

### `DEFAULT_TOLERANCE_SEC`

*constant*

Default replay window: a signature older or newer than this many seconds is refused.

```ts
const DEFAULT_TOLERANCE_SEC = 300;
```

### `WebhookSecret`

*type*

A Standard Webhooks secret: `"whsec_<base64>"` as shown in the dashboard, the same base64 without the prefix, or the
raw key bytes. Pass several (an array) while you rotate your own copy: any one of them may verify.
For an Ed25519 endpoint, its public key `"whpk_<base64>"` (the endpoint's `public_key`) instead.

```ts
type WebhookSecret = string | Uint8Array;
```

### `RawBody`

*type*

The request body exactly as received: a string, a Node Buffer, or any Uint8Array / ArrayBuffer.

```ts
type RawBody = string | Uint8Array | ArrayBuffer;
```

### `WebhookVerificationErrorCode`

*type*

```ts
type WebhookVerificationErrorCode =
	/** A required header is absent. */
	| "missing_header"
	/** A header is present but malformed (e.g. a non-numeric timestamp). */
	| "invalid_header"
	/** The timestamp is outside the tolerance window (replay protection, or a badly skewed clock). */
	| "timestamp_out_of_range"
	/** No signature matches: wrong secret, or the body / id / timestamp was altered. */
	| "bad_signature"
	/** The secret you passed is not a usable key (empty, or not base64 after "whsec_"; a "whpk_" key that is not 32 bytes). */
	| "invalid_secret"
	/** The signature is valid but the body is not JSON. */
	| "invalid_payload"
	/** Ed25519 ("whpk_") verification needs node:crypto on the sync path: use the async variant (WebCrypto) here. */
	| "unsupported_runtime";
```

### `WebhookVerificationError`

*class*

```ts
class WebhookVerificationError extends Error {
	readonly name = "WebhookVerificationError";
	readonly code: WebhookVerificationErrorCode;
	constructor(code: WebhookVerificationErrorCode, message: string);
}
```

### `VerifyOptions`

*interface*

```ts
interface VerifyOptions {
	/** Accept timestamps within ± this many seconds of now (default 300). `Infinity` turns the check off. */
	toleranceSec?: number;
	/** The current time in milliseconds since the epoch, like `Date.now` (tests, or a trusted clock). */
	now?: () => number;
}
```

### `VerifiedWebhook`

*interface*

A request whose signature checked out.

```ts
interface VerifiedWebhook {
	/** The `webhook-id` (Standard) or `x-webhook-id` (legacy, may be empty). */
	id: string;
	/** Unix seconds from the timestamp header. */
	timestamp: number;
	/** The body as text (UTF-8), not yet parsed. */
	payload: string;
}
```

### `StandardWebhookHeaders`

*type*

The three Standard Webhooks headers, as `generateTestHeaders` returns them (a plain record: pass it to fetch).

```ts
type StandardWebhookHeaders = {
	"webhook-id": string;
	"webhook-timestamp": string;
	"webhook-signature": string;
};
```

### `verifySignature()`

*function*

Check a Standard Webhooks signature and return the verified (unparsed) payload. Throws `WebhookVerificationError`.
`secret` is the endpoint's `whsec_…` secret, or for an Ed25519 endpoint its `whpk_…` public key (v1a signatures).

```ts
function verifySignature(rawBody: RawBody, headers: HeadersLike, secret: WebhookSecret | readonly WebhookSecret[], opts: VerifyOptions = {}): VerifiedWebhook;
```

### `verifySignatureAsync()`

*function*

`verifySignature` on WebCrypto, for edge runtimes (Vercel/Next.js edge, Cloudflare Workers, Deno, browsers).

```ts
function verifySignatureAsync(rawBody: RawBody, headers: HeadersLike, secret: WebhookSecret | readonly WebhookSecret[], opts: VerifyOptions = {}): Promise<VerifiedWebhook>;
```

### `constructEvent()`

*function*

Verify a webhook delivery and return its event. The body is parsed only after the signature checks out.

```ts
const event = webhooks.constructEvent(req.body, req.headers, process.env.MOREVOICE_WEBHOOK_SECRET!);
```

Throws `WebhookVerificationError` (`code`: missing_header | invalid_header | timestamp_out_of_range | bad_signature |
invalid_secret | invalid_payload); answer 400 and MoreVoice retries.

```ts
function constructEvent<T = MoreVoiceEvent>(rawBody: RawBody, headers: HeadersLike, secret: WebhookSecret | readonly WebhookSecret[], opts: VerifyOptions = {}): T;
```

### `constructEventAsync()`

*function*

`constructEvent` on WebCrypto, for edge runtimes.

```ts
function constructEventAsync<T = MoreVoiceEvent>(rawBody: RawBody, headers: HeadersLike, secret: WebhookSecret | readonly WebhookSecret[], opts: VerifyOptions = {}): Promise<T>;
```

### `verifyLegacy()`

*function*

Verify a delivery signed with the legacy `X-Webhook-Signature: sha256=<hex>` scheme (endpoints created before
webhooks v2; kept for one deprecation cycle) and return its body `{ id, event, createdAt, data }`.

```ts
function verifyLegacy<T = LegacyWebhookEvent>(rawBody: RawBody, headers: HeadersLike, secret: WebhookSecret | readonly WebhookSecret[], opts: VerifyOptions = {}): T;
```

### `verifyLegacyAsync()`

*function*

`verifyLegacy` on WebCrypto, for edge runtimes.

```ts
function verifyLegacyAsync<T = LegacyWebhookEvent>(rawBody: RawBody, headers: HeadersLike, secret: WebhookSecret | readonly WebhookSecret[], opts: VerifyOptions = {}): Promise<T>;
```

### `generateTestHeaders()`

*function*

Sign a payload the way MoreVoice does, for testing your own webhook or tool endpoint:

```ts
const headers = webhooks.generateTestHeaders({ payload: body, secret: "whsec_…" });
await fetch("http://localhost:3000/tools", { method: "POST", headers, body });
```

Several secrets produce one "v1,…" entry each (what MoreVoice sends while a secret rotates).

```ts
function generateTestHeaders(p: { payload: string | Uint8Array; secret: WebhookSecret | readonly WebhookSecret[]; id?: string; timestamp?: number }): StandardWebhookHeaders;
```

### `webhooks`

*constant*

The webhook helpers as one namespace (`import { webhooks } from "@morevoice/sdk"`; the client exposes `mv.webhooks`).

```ts
const webhooks: {
	constructEvent: typeof constructEvent;
	constructEventAsync: typeof constructEventAsync;
	verifySignature: typeof verifySignature;
	verifySignatureAsync: typeof verifySignatureAsync;
	verifyLegacy: typeof verifyLegacy;
	verifyLegacyAsync: typeof verifyLegacyAsync;
	generateTestHeaders: typeof generateTestHeaders;
};
```

### `HeadersLike`

*type*

Anything headers can arrive as.

```ts
type HeadersLike = { get(name: string): string | null } | Readonly<Record<string, HeaderValue>> | Iterable<readonly [string, string]>;
```

### `HeaderValue`

*type*

```ts
type HeaderValue = string | readonly string[] | number | null | undefined;
```

Exported from `@morevoice/sdk` (source: `packages/sdk-ts/src/lib/event-envelope.ts`).

### `EventEnvelope`

*interface*

One event, as signed and delivered. `TObject` is the payload (`data.object`).

```ts
interface EventEnvelope<TType extends string = string, TObject = Record<string, unknown>> {
	/** `evt_…`; the same on every redelivery, so receivers dedupe on it (it is also the `webhook-id` header). */
	id: string;
	object: "event";
	type: TType;
	/** ISO-8601 UTC, second precision. */
	created: string;
	api_version: string;
	livemode: boolean;
	/** `org_…` */
	org_id: string;
	data: { object: TObject; previous_attributes?: Record<string, unknown> };
	request?: { id: string | null; idempotency_key: string | null };
}
```

### `MoreVoiceEvent`

*type*

Every event the API documents, discriminated by `type`: what `webhooks.constructEvent` returns.
`switch (event.type) { case "call.analyzed": event.data.object.summary … }` narrows the payload.

```ts
type MoreVoiceEvent = [KnownEvent] extends [never] ? EventEnvelope : KnownEvent;
```

### `EventOf`

*type*

The event of one type: `EventOf<"call.ended">`.

```ts
type EventOf<T extends keyof EventTypeMap> = EventTypeMap[T];
```

### `UnknownEvent`

*type*

An event whose type this SDK does not know yet (a newer server): the envelope with an untyped payload.

```ts
type UnknownEvent = EventEnvelope<string, Record<string, unknown>>;
```

### `AnyEvent`

*type*

Any event, known or not (for code that stores or forwards events generically).

```ts
type AnyEvent = MoreVoiceEvent | UnknownEvent;
```

### `isKnownEvent()`

*function*

True when this SDK knows the event's type (its payload is typed); false for types newer than the SDK.

```ts
function isKnownEvent(event: { type: string }): event is MoreVoiceEvent;
```

### `LegacyWebhookEvent`

*interface*

The pre-v2 body that endpoints still on `api_version: "legacy"` receive (signed with `X-Webhook-Signature`).

```ts
interface LegacyWebhookEvent {
	id: string;
	event: string;
	createdAt: string;
	data: Record<string, unknown>;
}
```
