The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
create webhook signature
Kiran K112059b71297
diff --git a/apps/web/app/api/webhooks/callback/route.ts b/apps/web/app/api/webhooks/callback/route.tsindex d9412173f5..111519dad1 100644--- a/apps/web/app/api/webhooks/callback/route.ts+++ b/apps/web/app/api/webhooks/callback/route.ts@@ -1,3 +1,4 @@+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import z from "@/lib/zod";const schema = z.object({@@ -12,9 +13,15 @@ const schema = z.object({// POST /api/webhooks/callback – listen to webhooks status from QStashexport const POST = async (req: Request) => {const body = await req.json();++ await verifyQstashSignature(req, body);+const parsedPayload = schema.parse(body);console.log("Webhook callback", parsedPayload);+ // TODO:+ // Store the logs in TB+return new Response("OK");};diff --git a/apps/web/lib/webhook/publish.ts b/apps/web/lib/webhook/publish.tsindex 80d3414ead..16cf545544 100644--- a/apps/web/lib/webhook/publish.ts+++ b/apps/web/lib/webhook/publish.ts@@ -4,6 +4,7 @@ import { Webhook } from "@prisma/client";import { WebhookTrigger } from "../types";import { clickEventSchemaTB } from "../zod/schemas/clicks";import { LinkSchema } from "../zod/schemas/links";+import { createWebhookSignature } from "./signature";interface SendToWebhookArgs {webhookUrl?: string;@@ -18,14 +19,15 @@ export const sendToWebhook = async ({data,}: SendToWebhookArgs) => {const url = webhookUrl || webhook?.url;+ const secret = webhook?.secret || ""; // TODO: A signature is mustif (!url) {console.error("No webhook URL provided. Skipping webhook event.");return;}- // Receive webhook status from QStash at this URLconst callbackUrl = `${APP_DOMAIN_WITH_NGROK}/api/webhooks/callback`;+ const signature = createWebhookSignature(secret, data);const response = await qstash.publishJSON({url,@@ -33,13 +35,17 @@ export const sendToWebhook = async ({data,},headers: {- "X-Dub-Header1": "Header Value 1",+ "Dub-Signature": signature,},callback: callbackUrl,failureCallback: callbackUrl,});- console.log("Webhook response", response);+ if (response.messageId) {+ console.log(+ `Webhook event sent to ${url} with messageId: ${response.messageId}`,+ );+ }};// Transform payload to match the webhook event schemadiff --git a/apps/web/lib/webhook/signature.ts b/apps/web/lib/webhook/signature.tsnew file mode 100644index 0000000000..7aadb69445--- /dev/null+++ b/apps/web/lib/webhook/signature.ts@@ -0,0 +1,9 @@+import crypto from "crypto";++export const createWebhookSignature = (secret: string, rawBody: any) => {+ if (!secret) {+ throw new Error("A secret must be provided to create a webhook signature.");+ }++ return crypto.createHmac("sha256", secret).update(rawBody).digest("hex");+};