콘텐츠로 이동

verifyWebhookRequest

verifyWebhookRequest(headers, body, secret, options?): Result<VerifiedWebhookRequest, WebhookVerificationError>

Defined in: packages/webhook/src/security/verify-webhook-request.ts:145

Checks that a webhook request came from a k-msg sender that holds secret and was signed recently.

It verifies the signature header, an HMAC of <X-Webhook-Timestamp>.<body>, in constant time, then checks that the signed time is within toleranceMs of now. A request that passes can still be a repeat: webhooks are delivered at least once, so skip event ids you have already processed.

WebhookRequestHeaders

The request headers.

WebhookRequestBody

The raw request body, preferably its bytes, before any decoding or JSON parsing.

string

The endpoint’s signing secret (or the sender’s shared secretKey).

VerifyWebhookRequestOptions = {}

Result<VerifiedWebhookRequest, WebhookVerificationError>

The signed time, or a WebhookVerificationError whose code says which check failed.

TypeError when secret is empty, and RangeError when toleranceMs is negative, NaN, or infinite.

const body = await request.arrayBuffer();
const verified = verifyWebhookRequest(
request.headers,
body,
env.WEBHOOK_SECRET,
);
if (verified.isFailure) {
return new Response(verified.error.code, { status: 401 });
}
const event = JSON.parse(new TextDecoder().decode(body));