Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions catalog/services/clerk.yaml
Original file line number Diff line number Diff line change
@@ -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
Expand Down
8 changes: 8 additions & 0 deletions catalog/services/paddle.yaml
Original file line number Diff line number Diff line change
@@ -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
Expand Down
8 changes: 8 additions & 0 deletions catalog/services/polar.yaml
Original file line number Diff line number Diff line change
@@ -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
Expand Down
8 changes: 8 additions & 0 deletions catalog/services/resend.yaml
Original file line number Diff line number Diff line change
@@ -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
Expand Down
8 changes: 8 additions & 0 deletions catalog/services/stripe.yaml
Original file line number Diff line number Diff line change
@@ -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
Expand Down
30 changes: 30 additions & 0 deletions dist/generated/webhooks.d.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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"];
};
};
50 changes: 50 additions & 0 deletions dist/generated/webhooks.js
Original file line number Diff line number Diff line change
@@ -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",
Expand Down Expand Up @@ -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"
]
}
};
6 changes: 6 additions & 0 deletions dist/signatures.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,9 @@ export declare function encodeHex(bytes: Uint8Array): string;
export declare function signedBytes(prefix: string, body: Uint8Array): Uint8Array<ArrayBuffer>;
export declare function isFreshTimestamp(value: string, toleranceSeconds: number, nowMs: number): boolean;
export declare function decodeBase64(value: string): Uint8Array<ArrayBuffer> | 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<ArrayBuffer>, nowMs: number, toleranceSeconds: number): Promise<string | null>;
16 changes: 16 additions & 0 deletions dist/signatures.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
28 changes: 9 additions & 19 deletions dist/triggers.js
Original file line number Diff line number Diff line change
@@ -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);
}
7 changes: 6 additions & 1 deletion dist/webhooks.d.ts
Original file line number Diff line number Diff line change
@@ -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<string>;
}
Expand All @@ -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<WebhookReceipt>;
88 changes: 87 additions & 1 deletion dist/webhooks.js
Original file line number Diff line number Diff line change
@@ -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();
Expand Down Expand Up @@ -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;
Expand Down
Loading