Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

add webhook verification

Kiran K35132a29924e
diff --git a/apps/web/.env.example b/apps/web/.env.example
index 677c1eeeac..cddced0f4d 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -142,4 +142,5 @@ TIKTOK_CLIENT_SECRET=
# Paypal
PAYPAL_CLIENT_ID=
-PAYPAL_CLIENT_SECRET=
\ No newline at end of file
+PAYPAL_CLIENT_SECRET=
+PAYPAL_WEBHOOK_ID=
\ No newline at end of file
diff --git a/apps/web/app/api/cron/payouts/charge-succeeded/create-paypal-token.ts b/apps/web/app/api/cron/payouts/charge-succeeded/create-paypal-token.ts
index d3d03df38d..ab4c1b0dd5 100644
--- a/apps/web/app/api/cron/payouts/charge-succeeded/create-paypal-token.ts
+++ b/apps/web/app/api/cron/payouts/charge-succeeded/create-paypal-token.ts
@@ -7,7 +7,7 @@ interface PaypalTokenResponse {
expires_in: number; // in seconds
}
-const CACHE_KEY = "paypal:token";
+const TOKEN_CACHE_KEY = "paypal:token";
/**
* Creates and caches a PayPal access token for batch payouts authentication.
@@ -16,7 +16,7 @@ const CACHE_KEY = "paypal:token";
* The token is cached in Redis with a 5-minute buffer before expiration.
*/
export async function createPaypalToken() {
- const cachedToken = await redis.get(CACHE_KEY);
+ const cachedToken = await redis.get(TOKEN_CACHE_KEY);
if (cachedToken) {
return cachedToken;
@@ -26,8 +26,6 @@ export async function createPaypalToken() {
`${paypalEnv.PAYPAL_CLIENT_ID}:${paypalEnv.PAYPAL_CLIENT_SECRET}`,
).toString("base64");
- console.log("Basic auth", basicAuth);
-
const response = await fetch(paypalEnv.PAYPAL_API_HOST + "/v1/oauth2/token", {
method: "POST",
headers: {
@@ -48,10 +46,8 @@ export async function createPaypalToken() {
const token = data as PaypalTokenResponse;
- console.log("Token created", token);
-
waitUntil(
- redis.set(CACHE_KEY, token.access_token, {
+ redis.set(TOKEN_CACHE_KEY, token.access_token, {
ex: token.expires_in - 60 * 5, // 5 min buffer
}),
);
diff --git a/apps/web/app/api/paypal/webhook/payment-payouts-batch-success.ts b/apps/web/app/api/paypal/webhook/payment-payouts-batch-success.ts
index 9b893ad689..fbf80f493a 100644
--- a/apps/web/app/api/paypal/webhook/payment-payouts-batch-success.ts
+++ b/apps/web/app/api/paypal/webhook/payment-payouts-batch-success.ts
@@ -15,8 +15,6 @@ const schema = z.object({
export const paymentPayoutsBatchSuccess = async (event: any) => {
const body = schema.parse(event);
- console.log(body);
-
const invoiceId =
body.resource.batch_header.sender_batch_header.sender_batch_id;
diff --git a/apps/web/app/api/paypal/webhook/payout-status-changed.ts b/apps/web/app/api/paypal/webhook/payout-status-changed.ts
index 7f4cd1a094..0abe17012f 100644
--- a/apps/web/app/api/paypal/webhook/payout-status-changed.ts
+++ b/apps/web/app/api/paypal/webhook/payout-status-changed.ts
@@ -24,8 +24,6 @@ const schema = z.object({
export async function payoutStatusChanged(event: any) {
const body = schema.parse(event);
- console.log(body);
-
const invoiceId = body.resource.sender_batch_id;
const paypalEmail = body.resource.payout_item.receiver;
const payoutItemId = body.resource.payout_item_id;
diff --git a/apps/web/app/api/paypal/webhook/route.ts b/apps/web/app/api/paypal/webhook/route.ts
index e69c77946d..6c5baebea0 100644
--- a/apps/web/app/api/paypal/webhook/route.ts
+++ b/apps/web/app/api/paypal/webhook/route.ts
@@ -1,6 +1,7 @@
import { log } from "@dub/utils";
import { paymentPayoutsBatchSuccess } from "./payment-payouts-batch-success";
import { payoutStatusChanged } from "./payout-status-changed";
+import { verifySignature } from "./verify-signature";
const relevantEvents = new Set([
// Individual payout item events
@@ -23,8 +24,15 @@ export const POST = async (req: Request) => {
const rawBody = await req.text();
const headers = req.headers;
- // TODO:
- // Verify the webhook signature
+ const isSignatureValid = await verifySignature({
+ event: rawBody,
+ headers,
+ });
+
+ if (!isSignatureValid) {
+ return new Response("Invalid signature", { status: 400 });
+ }
+
const body = JSON.parse(rawBody);
if (!relevantEvents.has(body.event_type)) {
diff --git a/apps/web/app/api/paypal/webhook/verify-signature.ts b/apps/web/app/api/paypal/webhook/verify-signature.ts
index a09d990496..6766095d37 100644
--- a/apps/web/app/api/paypal/webhook/verify-signature.ts
+++ b/apps/web/app/api/paypal/webhook/verify-signature.ts
@@ -1,3 +1,62 @@
-async function verifySignature(event, headers) {
- //
+import { paypalEnv } from "@/lib/paypal/env";
+import { redis } from "@/lib/upstash/redis";
+import { waitUntil } from "@vercel/functions";
+import crc32 from "crc-32";
+import crypto from "crypto";
+
+const CERT_CACHE_KEY = "paypal:cert";
+
+async function downloadAndCache(url: string) {
+ const cachedCertPem = await redis.get<string>(CERT_CACHE_KEY);
+
+ if (cachedCertPem) {
+ return cachedCertPem;
+ }
+
+ const response = await fetch(url);
+ const certPem = await response.text();
+
+ waitUntil(redis.set(CERT_CACHE_KEY, certPem));
+
+ return certPem;
+}
+
+export async function verifySignature({
+ event,
+ headers,
+}: {
+ event: string; // raw event data as string
+ headers: Headers;
+}) {
+ const transmissionId = headers.get("paypal-transmission-id");
+ const transmissionSig = headers.get("paypal-transmission-sig");
+ const timeStamp = headers.get("paypal-transmission-time");
+ const certUrl = headers.get("paypal-cert-url");
+
+ if (!transmissionId || !transmissionSig || !timeStamp || !certUrl) {
+ console.error("Missing required headers for signature verification");
+ return false;
+ }
+
+ const crc = (crc32.str(event) >>> 0).toString(); // Convert to unsigned 32-bit integer
+
+ const message = `${transmissionId}|${timeStamp}|${paypalEnv.PAYPAL_WEBHOOK_ID}|${crc}`;
+
+ const certPem = await downloadAndCache(certUrl);
+
+ if (!certPem) {
+ console.error("Failed to download or cache PayPal certificate");
+ return false;
+ }
+
+ try {
+ const signatureBuffer = Buffer.from(transmissionSig, "base64");
+ const verifier = crypto.createVerify("SHA256");
+ verifier.update(message);
+
+ return verifier.verify(certPem, new Uint8Array(signatureBuffer));
+ } catch (error) {
+ console.error("Signature verification failed", error);
+ return false;
+ }
}
diff --git a/apps/web/lib/paypal/env.ts b/apps/web/lib/paypal/env.ts
index 87674d39d2..7486d28714 100644
--- a/apps/web/lib/paypal/env.ts
+++ b/apps/web/lib/paypal/env.ts
@@ -9,4 +9,5 @@ export const paypalEnv = {
PAYPAL_API_HOST: isLive
? "https://api.paypal.com"
: "https://api-m.sandbox.paypal.com",
+ PAYPAL_WEBHOOK_ID: process.env.PAYPAL_WEBHOOK_ID || "",
};
diff --git a/apps/web/package.json b/apps/web/package.json
index 0fee146f97..71c83d79a5 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -67,6 +67,7 @@
"cmdk": "^0.2.0",
"cobe": "^0.6.3",
"concurrently": "^8.0.1",
+ "crc-32": "^1.2.2",
"csv-parse": "^5.5.6",
"date-fns": "^3.6.0",
"dub": "^0.59.1",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1841e17e4d..a9a189485c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -189,6 +189,9 @@ importers:
concurrently:
specifier: ^8.0.1
version: 8.0.1
+ crc-32:
+ specifier: ^1.2.2
+ version: 1.2.2
csv-parse:
specifier: ^5.5.6
version: 5.5.6
@@ -6327,6 +6330,11 @@ packages:
resolution: {integrity: sha512-H65gsXo1SKjf8zmrJ67eJk8aIRKV5ff2D4uKZIBZShbhGSpEmsQOPW/SKMKYhSTrqR7ufy6RP69rPogdaPh/kA==}
engines: {node: '>=4'}
+ resolution: {integrity: sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==}
+ engines: {node: '>=0.8'}
+ hasBin: true
+
resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==}
@@ -18687,6 +18695,8 @@ snapshots:
js-yaml: 3.14.1
parse-json: 4.0.0
+