From fa89ae2ef129df370a9ba7aedc8b1e3493facc9e Mon Sep 17 00:00:00 2001 From: Andrew Lee <5784515+andyrewlee@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:02:55 -0800 Subject: [PATCH] Verify five additional native webhook sources --- catalog/services/clerk.yaml | 8 +++ catalog/services/paddle.yaml | 8 +++ catalog/services/polar.yaml | 8 +++ catalog/services/resend.yaml | 8 +++ catalog/services/stripe.yaml | 8 +++ dist/generated/webhooks.d.ts | 30 ++++++++++ dist/generated/webhooks.js | 50 +++++++++++++++++ dist/signatures.d.ts | 6 ++ dist/signatures.js | 16 ++++++ dist/triggers.js | 28 +++------- dist/webhooks.d.ts | 7 ++- dist/webhooks.js | 88 ++++++++++++++++++++++++++++- src/generated/webhooks.ts | 50 +++++++++++++++++ src/signatures.ts | 28 ++++++++++ src/triggers.ts | 30 +++------- src/webhooks.ts | 104 ++++++++++++++++++++++++++++++++++- test/catalog.test.mjs | 2 +- test/webhooks.test.mjs | 68 ++++++++++++++++++++++- 18 files changed, 500 insertions(+), 47 deletions(-) diff --git a/catalog/services/clerk.yaml b/catalog/services/clerk.yaml index 83de99d..5660505 100644 --- a/catalog/services/clerk.yaml +++ b/catalog/services/clerk.yaml @@ -1,6 +1,14 @@ format: 1 id: clerk name: Clerk +surfaces: + webhook: + protocol: svix-hmac + setup: import + events: + - user.created + - user.updated + - user.deleted reference: revision: 0621be370cd4d86c32c310390df03f5a64b1a105 path: catalog/checked/clerk.yaml diff --git a/catalog/services/paddle.yaml b/catalog/services/paddle.yaml index 5564092..eb29519 100644 --- a/catalog/services/paddle.yaml +++ b/catalog/services/paddle.yaml @@ -1,6 +1,14 @@ format: 1 id: paddle name: Paddle +surfaces: + webhook: + protocol: paddle-hmac + setup: import + events: + - transaction.completed + - transaction.payment_failed + - subscription.canceled reference: revision: 0621be370cd4d86c32c310390df03f5a64b1a105 path: catalog/checked/paddle.yaml diff --git a/catalog/services/polar.yaml b/catalog/services/polar.yaml index 1c2aad7..1a8aa95 100644 --- a/catalog/services/polar.yaml +++ b/catalog/services/polar.yaml @@ -1,6 +1,14 @@ format: 1 id: polar name: Polar +surfaces: + webhook: + protocol: polar-hmac + setup: import + events: + - order.paid + - order.refunded + - subscription.canceled reference: revision: 0621be370cd4d86c32c310390df03f5a64b1a105 path: catalog/checked/polar.yaml diff --git a/catalog/services/resend.yaml b/catalog/services/resend.yaml index e610e4b..b5c0681 100644 --- a/catalog/services/resend.yaml +++ b/catalog/services/resend.yaml @@ -1,6 +1,14 @@ format: 1 id: resend name: Resend +surfaces: + webhook: + protocol: svix-hmac + setup: import + events: + - email.received + - email.delivered + - email.bounced reference: revision: 0621be370cd4d86c32c310390df03f5a64b1a105 path: catalog/checked/resend.yaml diff --git a/catalog/services/stripe.yaml b/catalog/services/stripe.yaml index 20445db..69448ed 100644 --- a/catalog/services/stripe.yaml +++ b/catalog/services/stripe.yaml @@ -1,6 +1,14 @@ format: 1 id: stripe name: Stripe +surfaces: + webhook: + protocol: stripe-hmac + setup: import + events: + - checkout.session.completed + - payment_intent.payment_failed + - charge.refunded reference: revision: 0621be370cd4d86c32c310390df03f5a64b1a105 path: catalog/checked/stripe.yaml diff --git a/dist/generated/webhooks.d.ts b/dist/generated/webhooks.d.ts index 2bc19b3..710baaa 100644 --- a/dist/generated/webhooks.d.ts +++ b/dist/generated/webhooks.d.ts @@ -1,4 +1,10 @@ export declare const webhooks: { + readonly clerk: { + readonly name: "Clerk"; + readonly protocol: "svix-hmac"; + readonly setup: "import"; + readonly events: readonly ["user.created", "user.updated", "user.deleted"]; + }; readonly github: { readonly name: "GitHub"; readonly protocol: "github-hmac"; @@ -17,4 +23,28 @@ export declare const webhooks: { readonly setup: "challenge"; readonly events: readonly ["page.created", "page.content_updated"]; }; + readonly paddle: { + readonly name: "Paddle"; + readonly protocol: "paddle-hmac"; + readonly setup: "import"; + readonly events: readonly ["transaction.completed", "transaction.payment_failed", "subscription.canceled"]; + }; + readonly polar: { + readonly name: "Polar"; + readonly protocol: "polar-hmac"; + readonly setup: "import"; + readonly events: readonly ["order.paid", "order.refunded", "subscription.canceled"]; + }; + readonly resend: { + readonly name: "Resend"; + readonly protocol: "svix-hmac"; + readonly setup: "import"; + readonly events: readonly ["email.received", "email.delivered", "email.bounced"]; + }; + readonly stripe: { + readonly name: "Stripe"; + readonly protocol: "stripe-hmac"; + readonly setup: "import"; + readonly events: readonly ["checkout.session.completed", "payment_intent.payment_failed", "charge.refunded"]; + }; }; diff --git a/dist/generated/webhooks.js b/dist/generated/webhooks.js index 359007d..7fd0818 100644 --- a/dist/generated/webhooks.js +++ b/dist/generated/webhooks.js @@ -1,4 +1,14 @@ export const webhooks = { + "clerk": { + "name": "Clerk", + "protocol": "svix-hmac", + "setup": "import", + "events": [ + "user.created", + "user.updated", + "user.deleted" + ] + }, "github": { "name": "GitHub", "protocol": "github-hmac", @@ -27,5 +37,45 @@ export const webhooks = { "page.created", "page.content_updated" ] + }, + "paddle": { + "name": "Paddle", + "protocol": "paddle-hmac", + "setup": "import", + "events": [ + "transaction.completed", + "transaction.payment_failed", + "subscription.canceled" + ] + }, + "polar": { + "name": "Polar", + "protocol": "polar-hmac", + "setup": "import", + "events": [ + "order.paid", + "order.refunded", + "subscription.canceled" + ] + }, + "resend": { + "name": "Resend", + "protocol": "svix-hmac", + "setup": "import", + "events": [ + "email.received", + "email.delivered", + "email.bounced" + ] + }, + "stripe": { + "name": "Stripe", + "protocol": "stripe-hmac", + "setup": "import", + "events": [ + "checkout.session.completed", + "payment_intent.payment_failed", + "charge.refunded" + ] } }; diff --git a/dist/signatures.d.ts b/dist/signatures.d.ts index 21f2339..71f5309 100644 --- a/dist/signatures.d.ts +++ b/dist/signatures.d.ts @@ -3,3 +3,9 @@ export declare function encodeHex(bytes: Uint8Array): string; export declare function signedBytes(prefix: string, body: Uint8Array): Uint8Array; export declare function isFreshTimestamp(value: string, toleranceSeconds: number, nowMs: number): boolean; export declare function decodeBase64(value: string): Uint8Array | null; +/** Verify a Standard Webhooks signature using the transport's decoded key and header values. */ +export declare function verifyStandardDelivery(body: Uint8Array, { id, timestamp, signatures }: { + readonly id: string | null; + readonly timestamp: string | null; + readonly signatures: string | null; +}, secret: Uint8Array, nowMs: number, toleranceSeconds: number): Promise; diff --git a/dist/signatures.js b/dist/signatures.js index 3242cd8..3062b3b 100644 --- a/dist/signatures.js +++ b/dist/signatures.js @@ -32,3 +32,19 @@ export function decodeBase64(value) { return null; } } +/** Verify a Standard Webhooks signature using the transport's decoded key and header values. */ +export async function verifyStandardDelivery(body, { id, timestamp, signatures }, secret, nowMs, toleranceSeconds) { + if (id === null || id === "" || id.includes(".") || + timestamp === null || !isFreshTimestamp(timestamp, toleranceSeconds, nowMs) || + signatures === null || signatures.length > 1024) { + return null; + } + const key = await crypto.subtle.importKey("raw", secret, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]); + const message = signedBytes(`${id}.${timestamp}.`, body); + for (const signature of signatures.split(/\s+/u)) { + const value = signature.startsWith("v1,") ? decodeBase64(signature.slice(3)) : null; + if (value?.length === 32 && await crypto.subtle.verify("HMAC", key, value, message)) + return id; + } + return null; +} diff --git a/dist/triggers.js b/dist/triggers.js index 92e9acb..b624191 100644 --- a/dist/triggers.js +++ b/dist/triggers.js @@ -1,26 +1,16 @@ import { triggers } from "./generated/triggers.js"; -import { decodeBase64, isFreshTimestamp, signedBytes } from "./signatures.js"; +import { decodeBase64, verifyStandardDelivery } from "./signatures.js"; export { triggers }; /** Returns the authenticated delivery ID. Use it with the binding ID as an idempotency key. */ export async function verifyWebhookDelivery(body, headers, secret, nowMs = Date.now()) { - const id = headers.get("webhook-id"); - const timestamp = headers.get("webhook-timestamp"); - const signatures = headers.get("webhook-signature"); - if (id === null || id === "" || id.includes(".") || - timestamp === null || !isFreshTimestamp(timestamp, triggers.webhook.toleranceSeconds, nowMs) || - signatures === null || signatures.length > 1024 || - !secret.startsWith("whsec_")) { + if (!secret.startsWith("whsec_")) return null; - } - const bytes = decodeBase64(secret.slice("whsec_".length)); - if (bytes === null || bytes.length < 24 || bytes.length > 64) + const key = decodeBase64(secret.slice("whsec_".length)); + if (key === null || key.length < 24 || key.length > 64) return null; - const key = await crypto.subtle.importKey("raw", bytes, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]); - const message = signedBytes(`${id}.${timestamp}.`, body); - for (const signature of signatures.split(/\s+/u)) { - const value = signature.startsWith("v1,") ? decodeBase64(signature.slice(3)) : null; - if (value?.length === 32 && await crypto.subtle.verify("HMAC", key, value, message)) - return id; - } - return null; + return verifyStandardDelivery(body, { + id: headers.get("webhook-id"), + timestamp: headers.get("webhook-timestamp"), + signatures: headers.get("webhook-signature"), + }, key, nowMs, triggers.webhook.toleranceSeconds); } diff --git a/dist/webhooks.d.ts b/dist/webhooks.d.ts index 66fe87d..730cc82 100644 --- a/dist/webhooks.d.ts +++ b/dist/webhooks.d.ts @@ -1,9 +1,13 @@ import { webhooks } from "./generated/webhooks.js"; export { webhooks }; export type NativeWebhookId = keyof typeof webhooks; +type EndpointProtocol = "svix-hmac" | "polar-hmac" | "stripe-hmac" | "paddle-hmac"; +type AccountProtocol = "github-hmac" | "linear-hmac" | "notion-hmac"; +/** The verifier used a destination-specific secret for providers without a signed account field. */ +export declare const WEBHOOK_ENDPOINT_ACCOUNT = "endpoint"; export interface WebhookDefinition { readonly name: string; - readonly protocol: "github-hmac" | "linear-hmac" | "notion-hmac"; + readonly protocol: AccountProtocol | EndpointProtocol; readonly setup: "generate" | "import" | "challenge"; readonly events: ReadonlyArray; } @@ -16,5 +20,6 @@ export type WebhookReceipt = { readonly event: string; }; export declare function readNotionChallenge(body: Uint8Array): string | null; +export declare function isWebhookEndpointSecret(source: NativeWebhookId, secret: string): boolean; /** Verify exact bytes and return only the authenticated data needed to select and deduplicate a trigger. */ export declare function verifyNativeWebhook(source: NativeWebhookId, body: Uint8Array, headers: Headers, secret: string, nowMs?: number): Promise; diff --git a/dist/webhooks.js b/dist/webhooks.js index e4559aa..3d670fa 100644 --- a/dist/webhooks.js +++ b/dist/webhooks.js @@ -1,6 +1,8 @@ import { webhooks } from "./generated/webhooks.js"; -import { decodeHex, encodeHex } from "./signatures.js"; +import { decodeBase64, decodeHex, encodeHex, isFreshTimestamp, signedBytes, verifyStandardDelivery } from "./signatures.js"; export { webhooks }; +/** The verifier used a destination-specific secret for providers without a signed account field. */ +export const WEBHOOK_ENDPOINT_ACCOUNT = "endpoint"; const invalid = { type: "invalid" }; const ignored = { type: "ignored" }; const encoder = new TextEncoder(); @@ -68,8 +70,92 @@ function readNotionEvent(data) { event: data.type, }; } +const endpointSignature = { + "stripe-hmac": { header: "stripe-signature", separator: ",", time: "t", signature: "v1", join: ".", tolerance: 300 }, + "paddle-hmac": { header: "paddle-signature", separator: ";", time: "ts", signature: "h1", join: ":", tolerance: 5 }, +}; +async function verifyTimedBody(protocol, body, headers, key, nowMs) { + const definition = endpointSignature[protocol]; + const header = headers.get(definition.header); + if (header === null || header.length > 1024) + return false; + const fields = header.split(definition.separator).flatMap(part => { + const field = part.trim(); + const equals = field.indexOf("="); + return equals < 0 ? [] : [[field.slice(0, equals), field.slice(equals + 1)]]; + }); + const times = fields.filter(([name]) => name === definition.time).map(([, value]) => value); + const [time] = times; + if (times.length !== 1 || time === undefined || !isFreshTimestamp(time, definition.tolerance, nowMs)) + return false; + const message = signedBytes(time + definition.join, body); + const mac = await crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]); + for (const [name, signature] of fields) { + const value = name === definition.signature && signature !== undefined ? decodeHex(signature, 32) : null; + if (value !== null && await crypto.subtle.verify("HMAC", mac, value, message)) + return true; + } + return false; +} +function standardSecret(secret) { + const raw = secret.startsWith("whsec_") ? decodeBase64(secret.slice("whsec_".length)) : null; + return raw !== null && raw.length >= 24 && raw.length <= 64 ? raw : null; +} +export function isWebhookEndpointSecret(source, secret) { + const { protocol } = webhooks[source]; + if (!/^[!-~]{16,512}$/u.test(secret)) + return false; + if (protocol === "svix-hmac") { + return standardSecret(secret) !== null; + } + if (protocol === "polar-hmac" || protocol === "stripe-hmac") + return secret.startsWith("whsec_"); + return protocol === "paddle-hmac" && secret.startsWith("pdl_ntfset_"); +} +async function verifyEndpointWebhook(source, protocol, body, headers, secret, nowMs) { + if (!isWebhookEndpointSecret(source, secret)) + return invalid; + let authenticatedId = null; + if (protocol === "svix-hmac" || protocol === "polar-hmac") { + const prefix = protocol === "svix-hmac" ? "svix-" : "webhook-"; + const id = headers.get(prefix + "id"); + if (id === null || !/^[a-z\d_-]{1,256}$/iu.test(id)) + return invalid; + const fields = { + id, + timestamp: headers.get(prefix + "timestamp"), + signatures: headers.get(prefix + "signature"), + }; + const standard = standardSecret(secret); + if (standard !== null) { + authenticatedId = await verifyStandardDelivery(body, fields, standard, nowMs, 300); + } + // Polar also supports secrets issued before it switched to base64 key material. + if (authenticatedId === null && protocol === "polar-hmac") { + authenticatedId = await verifyStandardDelivery(body, fields, encoder.encode(secret), nowMs, 300); + } + if (authenticatedId === null) + return invalid; + } + else if (!await verifyTimedBody(protocol, body, headers, encoder.encode(secret), nowMs)) { + return invalid; + } + const payload = parseObject(body); + if (payload === null) + return invalid; + const event = protocol === "paddle-hmac" ? payload.event_type : payload.type; + const id = authenticatedId ?? (protocol === "paddle-hmac" ? payload.event_id : payload.id); + const events = webhooks[source].events; + if (typeof event !== "string" || !events.includes(event) || + typeof id !== "string" || !/^[a-z\d_-]{1,256}$/iu.test(id)) + return ignored; + return { type: "event", id, account: WEBHOOK_ENDPOINT_ACCOUNT, event }; +} /** Verify exact bytes and return only the authenticated data needed to select and deduplicate a trigger. */ export async function verifyNativeWebhook(source, body, headers, secret, nowMs = Date.now()) { + if (source !== "github" && source !== "linear" && source !== "notion") { + return verifyEndpointWebhook(source, webhooks[source].protocol, body, headers, secret, nowMs); + } const signature = headers.get(signatureHeaders[source]); if (signature === null || (source !== "linear" && !signature.startsWith("sha256="))) return invalid; diff --git a/src/generated/webhooks.ts b/src/generated/webhooks.ts index 53e2b8c..aa3e4cf 100644 --- a/src/generated/webhooks.ts +++ b/src/generated/webhooks.ts @@ -2,6 +2,16 @@ import type { WebhookDefinition } from "../webhooks.js" export const webhooks = { + "clerk": { + "name": "Clerk", + "protocol": "svix-hmac", + "setup": "import", + "events": [ + "user.created", + "user.updated", + "user.deleted" + ] + }, "github": { "name": "GitHub", "protocol": "github-hmac", @@ -30,5 +40,45 @@ export const webhooks = { "page.created", "page.content_updated" ] + }, + "paddle": { + "name": "Paddle", + "protocol": "paddle-hmac", + "setup": "import", + "events": [ + "transaction.completed", + "transaction.payment_failed", + "subscription.canceled" + ] + }, + "polar": { + "name": "Polar", + "protocol": "polar-hmac", + "setup": "import", + "events": [ + "order.paid", + "order.refunded", + "subscription.canceled" + ] + }, + "resend": { + "name": "Resend", + "protocol": "svix-hmac", + "setup": "import", + "events": [ + "email.received", + "email.delivered", + "email.bounced" + ] + }, + "stripe": { + "name": "Stripe", + "protocol": "stripe-hmac", + "setup": "import", + "events": [ + "checkout.session.completed", + "payment_intent.payment_failed", + "charge.refunded" + ] } } as const satisfies Readonly> diff --git a/src/signatures.ts b/src/signatures.ts index a190672..72ddea0 100644 --- a/src/signatures.ts +++ b/src/signatures.ts @@ -33,3 +33,31 @@ export function decodeBase64(value: string): Uint8Array | null { return null } } + +/** Verify a Standard Webhooks signature using the transport's decoded key and header values. */ +export async function verifyStandardDelivery( + body: Uint8Array, + { id, timestamp, signatures }: { + readonly id: string | null + readonly timestamp: string | null + readonly signatures: string | null + }, + secret: Uint8Array, + nowMs: number, + toleranceSeconds: number, +): Promise { + if ( + id === null || id === "" || id.includes(".") || + timestamp === null || !isFreshTimestamp(timestamp, toleranceSeconds, nowMs) || + signatures === null || signatures.length > 1024 + ) { + return null + } + const key = await crypto.subtle.importKey("raw", secret, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]) + const message = signedBytes(`${id}.${timestamp}.`, body) + for (const signature of signatures.split(/\s+/u)) { + const value = signature.startsWith("v1,") ? decodeBase64(signature.slice(3)) : null + if (value?.length === 32 && await crypto.subtle.verify("HMAC", key, value, message)) return id + } + return null +} diff --git a/src/triggers.ts b/src/triggers.ts index 7b82a63..82349dc 100644 --- a/src/triggers.ts +++ b/src/triggers.ts @@ -1,5 +1,5 @@ import { triggers } from "./generated/triggers.js" -import { decodeBase64, isFreshTimestamp, signedBytes } from "./signatures.js" +import { decodeBase64, verifyStandardDelivery } from "./signatures.js" export { triggers } @@ -16,24 +16,12 @@ export async function verifyWebhookDelivery( secret: string, nowMs = Date.now(), ): Promise { - const id = headers.get("webhook-id") - const timestamp = headers.get("webhook-timestamp") - const signatures = headers.get("webhook-signature") - if ( - id === null || id === "" || id.includes(".") || - timestamp === null || !isFreshTimestamp(timestamp, triggers.webhook.toleranceSeconds, nowMs) || - signatures === null || signatures.length > 1024 || - !secret.startsWith("whsec_") - ) { - return null - } - const bytes = decodeBase64(secret.slice("whsec_".length)) - if (bytes === null || bytes.length < 24 || bytes.length > 64) return null - const key = await crypto.subtle.importKey("raw", bytes, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]) - const message = signedBytes(`${id}.${timestamp}.`, body) - for (const signature of signatures.split(/\s+/u)) { - const value = signature.startsWith("v1,") ? decodeBase64(signature.slice(3)) : null - if (value?.length === 32 && await crypto.subtle.verify("HMAC", key, value, message)) return id - } - return null + if (!secret.startsWith("whsec_")) return null + const key = decodeBase64(secret.slice("whsec_".length)) + if (key === null || key.length < 24 || key.length > 64) return null + return verifyStandardDelivery(body, { + id: headers.get("webhook-id"), + timestamp: headers.get("webhook-timestamp"), + signatures: headers.get("webhook-signature"), + }, key, nowMs, triggers.webhook.toleranceSeconds) } diff --git a/src/webhooks.ts b/src/webhooks.ts index 4b48012..96b5268 100644 --- a/src/webhooks.ts +++ b/src/webhooks.ts @@ -1,13 +1,19 @@ import { webhooks } from "./generated/webhooks.js" -import { decodeHex, encodeHex } from "./signatures.js" +import { decodeBase64, decodeHex, encodeHex, isFreshTimestamp, signedBytes, verifyStandardDelivery } from "./signatures.js" export { webhooks } export type NativeWebhookId = keyof typeof webhooks +type EndpointProtocol = "svix-hmac" | "polar-hmac" | "stripe-hmac" | "paddle-hmac" +type AccountProtocol = "github-hmac" | "linear-hmac" | "notion-hmac" + +/** The verifier used a destination-specific secret for providers without a signed account field. */ +export const WEBHOOK_ENDPOINT_ACCOUNT = "endpoint" + export interface WebhookDefinition { readonly name: string - readonly protocol: "github-hmac" | "linear-hmac" | "notion-hmac" + readonly protocol: AccountProtocol | EndpointProtocol readonly setup: "generate" | "import" | "challenge" readonly events: ReadonlyArray } @@ -46,7 +52,7 @@ const signatureHeaders = { github: "x-hub-signature-256", linear: "linear-signature", notion: "x-notion-signature", -} as const satisfies Record +} as const function readGitHubEvent(data: Readonly>, id: string): WebhookReceipt { if (!isRecord(data.repository) || typeof data.repository.id !== "number" || @@ -84,6 +90,95 @@ function readNotionEvent(data: Readonly>): WebhookReceip } } +const endpointSignature = { + "stripe-hmac": { header: "stripe-signature", separator: ",", time: "t", signature: "v1", join: ".", tolerance: 300 }, + "paddle-hmac": { header: "paddle-signature", separator: ";", time: "ts", signature: "h1", join: ":", tolerance: 5 }, +} as const + +async function verifyTimedBody( + protocol: keyof typeof endpointSignature, + body: Uint8Array, + headers: Headers, + key: Uint8Array, + nowMs: number, +): Promise { + const definition = endpointSignature[protocol] + const header = headers.get(definition.header) + if (header === null || header.length > 1024) return false + const fields = header.split(definition.separator).flatMap(part => { + const field = part.trim() + const equals = field.indexOf("=") + return equals < 0 ? [] : [[field.slice(0, equals), field.slice(equals + 1)] as const] + }) + const times = fields.filter(([name]) => name === definition.time).map(([, value]) => value) + const [time] = times + if (times.length !== 1 || time === undefined || !isFreshTimestamp(time, definition.tolerance, nowMs)) return false + const message = signedBytes(time + definition.join, body) + const mac = await crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]) + for (const [name, signature] of fields) { + const value = name === definition.signature && signature !== undefined ? decodeHex(signature, 32) : null + if (value !== null && await crypto.subtle.verify("HMAC", mac, value, message)) return true + } + return false +} + +function standardSecret(secret: string) { + const raw = secret.startsWith("whsec_") ? decodeBase64(secret.slice("whsec_".length)) : null + return raw !== null && raw.length >= 24 && raw.length <= 64 ? raw : null +} + +export function isWebhookEndpointSecret(source: NativeWebhookId, secret: string): boolean { + const { protocol } = webhooks[source] + if (!/^[!-~]{16,512}$/u.test(secret)) return false + if (protocol === "svix-hmac") { + return standardSecret(secret) !== null + } + if (protocol === "polar-hmac" || protocol === "stripe-hmac") return secret.startsWith("whsec_") + return protocol === "paddle-hmac" && secret.startsWith("pdl_ntfset_") +} + +async function verifyEndpointWebhook( + source: NativeWebhookId, + protocol: EndpointProtocol, + body: Uint8Array, + headers: Headers, + secret: string, + nowMs: number, +): Promise { + if (!isWebhookEndpointSecret(source, secret)) return invalid + let authenticatedId: string | null = null + if (protocol === "svix-hmac" || protocol === "polar-hmac") { + const prefix = protocol === "svix-hmac" ? "svix-" : "webhook-" + const id = headers.get(prefix + "id") + if (id === null || !/^[a-z\d_-]{1,256}$/iu.test(id)) return invalid + const fields = { + id, + timestamp: headers.get(prefix + "timestamp"), + signatures: headers.get(prefix + "signature"), + } + const standard = standardSecret(secret) + if (standard !== null) { + authenticatedId = await verifyStandardDelivery(body, fields, standard, nowMs, 300) + } + // Polar also supports secrets issued before it switched to base64 key material. + if (authenticatedId === null && protocol === "polar-hmac") { + authenticatedId = await verifyStandardDelivery(body, fields, encoder.encode(secret), nowMs, 300) + } + if (authenticatedId === null) return invalid + } else if (!await verifyTimedBody(protocol, body, headers, encoder.encode(secret), nowMs)) { + return invalid + } + + const payload = parseObject(body) + if (payload === null) return invalid + const event = protocol === "paddle-hmac" ? payload.event_type : payload.type + const id = authenticatedId ?? (protocol === "paddle-hmac" ? payload.event_id : payload.id) + const events: ReadonlyArray = webhooks[source].events + if (typeof event !== "string" || !events.includes(event) || + typeof id !== "string" || !/^[a-z\d_-]{1,256}$/iu.test(id)) return ignored + return { type: "event", id, account: WEBHOOK_ENDPOINT_ACCOUNT, event } +} + /** Verify exact bytes and return only the authenticated data needed to select and deduplicate a trigger. */ export async function verifyNativeWebhook( source: NativeWebhookId, @@ -92,6 +187,9 @@ export async function verifyNativeWebhook( secret: string, nowMs = Date.now(), ): Promise { + if (source !== "github" && source !== "linear" && source !== "notion") { + return verifyEndpointWebhook(source, webhooks[source].protocol, body, headers, secret, nowMs) + } const signature = headers.get(signatureHeaders[source]) if (signature === null || (source !== "linear" && !signature.startsWith("sha256="))) return invalid const hex = source === "linear" ? signature : signature.slice("sha256=".length) diff --git a/test/catalog.test.mjs b/test/catalog.test.mjs index d3c2cf7..9de7f2f 100644 --- a/test/catalog.test.mjs +++ b/test/catalog.test.mjs @@ -51,7 +51,7 @@ test("a service belongs to each matching index with one entry per capability", ( test("discoverable entries do not implicitly become runtime adapters", () => { assert.deepEqual(Object.keys(providers), ["anthropic", "openai", "openrouter"]) assert.deepEqual(Object.keys(connectors), ["github", "linear", "notion"]) - assert.deepEqual(Object.keys(webhooks), ["github", "linear", "notion"]) + assert.deepEqual(Object.keys(webhooks), ["clerk", "github", "linear", "notion", "paddle", "polar", "resend", "stripe"]) assert.deepEqual(Object.keys(triggers), ["webhook"]) assert.deepEqual(Object.keys(channels), ["discord"]) assert.ok(catalogByKind.provider.some(entry => entry.id === "google-gemini")) diff --git a/test/webhooks.test.mjs b/test/webhooks.test.mjs index 3ab9f91..2d457c5 100644 --- a/test/webhooks.test.mjs +++ b/test/webhooks.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict" import { createHmac, randomBytes } from "node:crypto" import { test } from "node:test" -import { readNotionChallenge, verifyNativeWebhook } from "@checkfu/integrations/webhooks" +import { readNotionChallenge, verifyNativeWebhook, webhooks, WEBHOOK_ENDPOINT_ACCOUNT } from "@checkfu/integrations/webhooks" const account = "ae69a7ad-9d20-459f-9d46-152f5376b8a3" const eventId = "9fa2f7b0-26f9-4941-be94-229b12b4d5c0" @@ -44,3 +44,69 @@ test("Notion setup recognizes only the challenge and events require its verifica }) assert.deepEqual(await verifyNativeWebhook("notion", body, headers, "incorrect"), { type: "invalid" }) }) + +const paymentSecret = "whsec_example_stripe_endpoint_secret" +const paddleSecret = "pdl_ntfset_example_paddle_endpoint_secret" +const standardKey = randomBytes(32) +const standardSecret = "whsec_" + standardKey.toString("base64") + +function signEndpoint(spec, event, id, at) { + const time = String(Math.floor(at / 1000)) + const body = Buffer.from(JSON.stringify(event) + "\n") + const prefix = spec.prefix + if (prefix !== undefined) { + const mac = createHmac("sha256", spec.key).update(`${id}.${time}.`).update(body).digest("base64") + return { body, headers: new Headers({ + [prefix + "id"]: id, + [prefix + "timestamp"]: time, + [prefix + "signature"]: "v1,invalid v1," + mac, + }) } + } + const mac = createHmac("sha256", spec.secret).update(time + spec.join).update(body).digest("hex") + return { body, headers: new Headers({ + [spec.header]: [spec.time + "=" + time, spec.scheme + "=invalid", spec.scheme + "=" + mac] + .join(spec.separator), + }) } +} + +const newSources = [ + { source: "clerk", prefix: "svix-", secret: standardSecret, key: standardKey }, + { source: "resend", prefix: "svix-", secret: standardSecret, key: standardKey }, + { source: "polar", prefix: "webhook-", secret: standardSecret, key: standardKey }, + { source: "polar", prefix: "webhook-", secret: standardSecret, key: standardSecret, legacy: true }, + { source: "stripe", secret: paymentSecret, header: "stripe-signature", time: "t", scheme: "v1", join: ".", separator: "," }, + { source: "paddle", secret: paddleSecret, header: "paddle-signature", time: "ts", scheme: "h1", join: ":", separator: ";" }, +] + +for (const spec of newSources) { + test(`${spec.source}${spec.legacy ? " legacy" : ""} verifies the advertised events and preserves signed delivery identity`, async () => { + const id = "evt_01hv8x2axb33yr5y238zfwcn5p" + const payload = event => spec.source === "paddle" + ? { event_type: event, event_id: id, data: { name: "Café" } } + : { type: event, id: spec.prefix === undefined ? id : "different_body_id", data: { name: "Café" } } + const events = webhooks[spec.source].events + for (const event of events) { + const { body, headers } = signEndpoint(spec, payload(event), id, now) + const read = (props = {}) => verifyNativeWebhook( + spec.source, props.body ?? body, props.headers ?? headers, props.secret ?? spec.secret, props.now ?? now, + ) + const receipt = { type: "event", id, account: WEBHOOK_ENDPOINT_ACCOUNT, event } + assert.deepEqual(await read(), receipt) + const retry = signEndpoint(spec, payload(event), id, now + 1_000) + assert.deepEqual(await read({ headers: retry.headers, now: now + 1_000 }), receipt) + assert.deepEqual(await read({ body: body.subarray(0, -1) }), { type: "invalid" }) + assert.deepEqual(await read({ secret: "whsec_incorrect_endpoint_secret" }), { type: "invalid" }) + const maxAge = spec.source === "paddle" ? 5_000 : 300_000 + assert.deepEqual(await read({ now: now - maxAge - 1 }), { type: "invalid" }) + assert.deepEqual(await read({ now: now + maxAge + 1_000 }), { type: "invalid" }) + if (spec.prefix !== undefined) { + headers.set(spec.prefix + "id", "unverified") + assert.deepEqual(await read(), { type: "invalid" }) + } + } + const other = signEndpoint(spec, payload("other.event"), id, now) + assert.deepEqual(await verifyNativeWebhook(spec.source, other.body, other.headers, spec.secret, now), { + type: "ignored", + }) + }) +}