The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
fix: use constant-time comparison for Shopify and HubSpot webhook signatures (#4449)
Kiran K6884316f5310
diff --git a/apps/web/app/(ee)/api/hubspot/webhook/route.ts b/apps/web/app/(ee)/api/hubspot/webhook/route.tsindex 7e2b4f49b7..1f1f814d93 100644--- a/apps/web/app/(ee)/api/hubspot/webhook/route.ts+++ b/apps/web/app/(ee)/api/hubspot/webhook/route.ts@@ -1,6 +1,7 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { withAxiom } from "@/lib/axiom/server";import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";+import { timingSafeCompare } from "@/lib/webhook/timing-safe-compare";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import crypto from "crypto";import { logAndRespond } from "../../cron/utils";@@ -35,8 +36,8 @@ export const POST = withAxiom(async (req) => {.update(sourceString).digest("hex");- // Compare with provided signature- if (signature !== expectedHash) {+ // Compare with provided signature using constant-time comparison+ if (!timingSafeCompare(signature, expectedHash)) {throw new DubApiError({code: "unauthorized",message: "Invalid webhook signature.",diff --git a/apps/web/app/(ee)/api/intercom/webhook/verify-webhook-signature.ts b/apps/web/app/(ee)/api/intercom/webhook/verify-webhook-signature.tsindex eea0353851..9152b0136c 100644--- a/apps/web/app/(ee)/api/intercom/webhook/verify-webhook-signature.ts+++ b/apps/web/app/(ee)/api/intercom/webhook/verify-webhook-signature.ts@@ -1,4 +1,5 @@import { DubApiError } from "@/lib/api/errors";+import { timingSafeCompare } from "@/lib/webhook/timing-safe-compare";import crypto from "crypto";const INTERCOM_CLIENT_SECRET = process.env.INTERCOM_CLIENT_SECRET || "";@@ -51,22 +52,7 @@ export async function verifyIntercomWebhookSignature(});}- const providedBuffer = Buffer.from(providedSignature, "utf8");- const expectedBuffer = Buffer.from(expectedSignature, "utf8");-- if (providedBuffer.length !== expectedBuffer.length) {- throw new DubApiError({- code: "unauthorized",- message: "Invalid webhook signature.",- });- }-- const isSignatureValid = crypto.timingSafeEqual(- Uint8Array.from(providedBuffer),- Uint8Array.from(expectedBuffer),- );-- if (!isSignatureValid) {+ if (!timingSafeCompare(providedSignature, expectedSignature)) {throw new DubApiError({code: "unauthorized",message: "Invalid webhook signature.",diff --git a/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts b/apps/web/app/(ee)/api/shopify/integration/webhook/route.tsindex 41813984ed..7a41d1def6 100644--- a/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts+++ b/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts@@ -2,6 +2,7 @@ import { captureWebhookLog } from "@/lib/api-logs/capture-webhook-log";import { isLocalDev } from "@/lib/api/environment";import { withAxiom } from "@/lib/axiom/server";import { prisma } from "@/lib/prisma";+import { timingSafeCompare } from "@/lib/webhook/timing-safe-compare";import { waitUntil } from "@vercel/functions";import { logAndRespond } from "app/(ee)/api/cron/utils";import crypto from "crypto";@@ -42,7 +43,7 @@ export const POST = withAxiom(async (req: Request) => {.update(data, "utf8").digest("base64");- if (generatedSignature !== signature) {+ if (!timingSafeCompare(signature, generatedSignature)) {return logAndRespond("Shopify webhook signature verification failed. Skipping...",{diff --git a/apps/web/app/api/dub/webhook/route.ts b/apps/web/app/api/dub/webhook/route.tsindex 9b2cfc974c..7dc78bf3be 100644--- a/apps/web/app/api/dub/webhook/route.ts+++ b/apps/web/app/api/dub/webhook/route.ts@@ -1,5 +1,6 @@import { withAxiom } from "@/lib/axiom/server";import { webhookPayloadSchema } from "@/lib/webhook/schemas";+import { timingSafeCompare } from "@/lib/webhook/timing-safe-compare";import crypto from "crypto";import { leadCreated } from "./lead-created";import { saleCreated } from "./sale-created";@@ -20,7 +21,7 @@ export const POST = withAxiom(async (req: Request) => {.update(JSON.stringify(body)).digest("hex");- if (webhookSignature !== computedSignature) {+ if (!timingSafeCompare(webhookSignature, computedSignature)) {return new Response("Invalid signature", { status: 400 });}diff --git a/apps/web/app/api/oauth/token/exchange-code-for-token.ts b/apps/web/app/api/oauth/token/exchange-code-for-token.tsindex 97d38373f8..ea3d92aca7 100644--- a/apps/web/app/api/oauth/token/exchange-code-for-token.ts+++ b/apps/web/app/api/oauth/token/exchange-code-for-token.ts@@ -5,6 +5,7 @@ import { hashToken } from "@/lib/auth";import { installIntegration } from "@/lib/integrations/install";import { generateRandomName } from "@/lib/names";import { prisma } from "@/lib/prisma";+import { timingSafeCompare } from "@/lib/webhook/timing-safe-compare";import { authCodeExchangeSchema } from "@/lib/zod/schemas/oauth";import { waitUntil } from "@vercel/functions";import { NextRequest } from "next/server";@@ -100,7 +101,8 @@ export const exchangeAuthCodeForToken = async (});}- if (app.hashedClientSecret !== (await hashToken(clientSecret))) {+ const hashedClientSecret = await hashToken(clientSecret);+ if (!timingSafeCompare(hashedClientSecret, app.hashedClientSecret)) {throw new DubApiError({code: "unauthorized",message: "Invalid client_secret",diff --git a/apps/web/app/api/oauth/token/refresh-access-token.ts b/apps/web/app/api/oauth/token/refresh-access-token.tsindex 9a98ce21ca..c19b029a9b 100644--- a/apps/web/app/api/oauth/token/refresh-access-token.ts+++ b/apps/web/app/api/oauth/token/refresh-access-token.ts@@ -4,6 +4,7 @@ import { createToken } from "@/lib/api/oauth/utils";import { hashToken } from "@/lib/auth";import { generateRandomName } from "@/lib/names";import { prisma } from "@/lib/prisma";+import { timingSafeCompare } from "@/lib/webhook/timing-safe-compare";import { refreshTokenSchema } from "@/lib/zod/schemas/oauth";import { NextRequest } from "next/server";import * as z from "zod/v4";@@ -68,7 +69,8 @@ export const refreshAccessToken = async (});}- if (oAuthApp.hashedClientSecret !== (await hashToken(clientSecret))) {+ const hashedClientSecret = await hashToken(clientSecret);+ if (!timingSafeCompare(hashedClientSecret, oAuthApp.hashedClientSecret)) {throw new DubApiError({code: "unauthorized",message: "Invalid client_secret",diff --git a/apps/web/app/api/veriff/webhook/route.ts b/apps/web/app/api/veriff/webhook/route.tsindex b560aeb05d..54f71df5e3 100644--- a/apps/web/app/api/veriff/webhook/route.ts+++ b/apps/web/app/api/veriff/webhook/route.ts@@ -1,4 +1,5 @@import { withAxiom } from "@/lib/axiom/server";+import { timingSafeCompare } from "@/lib/webhook/timing-safe-compare";import { logAndRespond } from "app/(ee)/api/cron/utils";import crypto from "crypto";import { handleDecisionEvent } from "./handle-decision-event";@@ -18,17 +19,7 @@ export const POST = withAxiom(async (req: Request) => {const expectedApiKey = process.env.VERIFF_API_KEY;- if (!expectedApiKey || !authClient) {- return logAndRespond("Invalid auth client.", { status: 401 });- }-- const authClientBuffer = Uint8Array.from(Buffer.from(authClient));- const expectedApiKeyBuffer = Uint8Array.from(Buffer.from(expectedApiKey));-- if (- authClientBuffer.length !== expectedApiKeyBuffer.length ||- !crypto.timingSafeEqual(authClientBuffer, expectedApiKeyBuffer)- ) {+ if (!expectedApiKey || !timingSafeCompare(authClient, expectedApiKey)) {return logAndRespond("Invalid auth client.", { status: 401 });}@@ -43,16 +34,7 @@ export const POST = withAxiom(async (req: Request) => {.update(rawBody).digest("hex");- const computedSignatureBuffer = Uint8Array.from(- Buffer.from(computedSignature),- );- const signatureBuffer = Uint8Array.from(Buffer.from(signature));-- const isSignatureValid =- computedSignatureBuffer.length === signatureBuffer.length &&- crypto.timingSafeEqual(computedSignatureBuffer, signatureBuffer);-- if (!isSignatureValid) {+ if (!timingSafeCompare(signature, computedSignature)) {return logAndRespond("Invalid signature.", { status: 400 });}diff --git a/apps/web/lib/email/unsubscribe-token.ts b/apps/web/lib/email/unsubscribe-token.tsindex ce597e7b9e..c2ca8dd9d9 100644--- a/apps/web/lib/email/unsubscribe-token.ts+++ b/apps/web/lib/email/unsubscribe-token.ts@@ -1,4 +1,5 @@-import { createHmac, timingSafeEqual } from "crypto";+import { timingSafeCompare } from "@/lib/webhook/timing-safe-compare";+import { createHmac } from "crypto";const TOKEN_SECRET =process.env.UNSUBSCRIBE_TOKEN_SECRET || process.env.NEXTAUTH_SECRET;@@ -41,12 +42,7 @@ export function verifyUnsubscribeToken(token: string): string | null {.digest("hex").slice(0, 24);- if (- !timingSafeEqual(- Uint8Array.from(Buffer.from(signature)),- Uint8Array.from(Buffer.from(expectedSignature)),- )- ) {+ if (!timingSafeCompare(signature, expectedSignature)) {return null;}diff --git a/apps/web/lib/integrations/slack/verify-request.ts b/apps/web/lib/integrations/slack/verify-request.tsindex bbe2c342f8..bf51a60cf7 100644--- a/apps/web/lib/integrations/slack/verify-request.ts+++ b/apps/web/lib/integrations/slack/verify-request.ts@@ -1,3 +1,4 @@+import { timingSafeCompare } from "@/lib/webhook/timing-safe-compare";import { createHmac } from "crypto";interface SlackRequestVerificationOptions {@@ -63,7 +64,7 @@ export const verifySlackSignature = async (req: Request, body: string) => {hmac.update(`${signatureVersion}:${requestTimestampSec}:${options.body}`);const expectedSignature = hmac.digest("hex");- if (!signatureHash || signatureHash !== expectedSignature) {+ if (!timingSafeCompare(signatureHash, expectedSignature)) {throw new Error(`${verifyErrorPrefix}: signature mismatch`);}};diff --git a/apps/web/lib/webhook/timing-safe-compare.ts b/apps/web/lib/webhook/timing-safe-compare.tsnew file mode 100644index 0000000000..fc30d65d45--- /dev/null+++ b/apps/web/lib/webhook/timing-safe-compare.ts@@ -0,0 +1,40 @@+import crypto from "crypto";++/**+ * Performs constant-time comparison of two strings to prevent timing attacks.+ *+ * This function compares two strings in a way that takes the same amount of time+ * regardless of where the strings differ, mitigating timing side-channel attacks+ * (CWE-208).+ *+ * Use this for comparing security-sensitive values like:+ * - Webhook signatures+ * - HMAC digests+ * - API keys+ * - Authentication tokens+ *+ * @param provided - The value provided by the client/request+ * @param expected - The expected/computed value+ * @returns true if the strings match, false otherwise+ */+export function timingSafeCompare(+ provided: string | null | undefined,+ expected: string,+): boolean {+ if (!provided) {+ return false;+ }++ const providedBuffer = Buffer.from(provided, "utf8");+ const expectedBuffer = Buffer.from(expected, "utf8");++ // Length check before constant-time comparison+ if (providedBuffer.length !== expectedBuffer.length) {+ return false;+ }++ return crypto.timingSafeEqual(+ Uint8Array.from(providedBuffer),+ Uint8Array.from(expectedBuffer),+ );+}