The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Return 4xx for invalid webhook and sync requests, and skip restricted Stripe payouts (#4771)
Rafi74eae0054483
diff --git a/apps/web/app/(ee)/api/cron/payouts/balance-available/route.ts b/apps/web/app/(ee)/api/cron/payouts/balance-available/route.tsindex 8e3856e692..05981fdeb7 100644--- a/apps/web/app/(ee)/api/cron/payouts/balance-available/route.ts+++ b/apps/web/app/(ee)/api/cron/payouts/balance-available/route.ts@@ -165,6 +165,21 @@ export const POST = withCron(async ({ rawBody }) => {);}+ // Stripe restricted the connected account, so a retry fails the same way (stripe-should-retry: false).+ // The funds stay on the account, and a later "balance.available" event runs this again.+ const isPayoutsNotAllowed =+ error instanceof Stripe.errors.StripeError &&+ error.code === "payouts_not_allowed";++ if (isPayoutsNotAllowed) {+ return logAndRespond(+ `Stripe does not allow payouts for partner ${partner.email} (${stripeAccount}), the account is restricted: ${error.message}. Skipping...`,+ {+ logLevel: "warn",+ },+ );+ }+throw error;}diff --git a/apps/web/app/api/dub/webhook/route.ts b/apps/web/app/api/dub/webhook/route.tsindex 7dc78bf3be..ce932000c1 100644--- a/apps/web/app/api/dub/webhook/route.ts+++ b/apps/web/app/api/dub/webhook/route.ts@@ -7,24 +7,39 @@ import { saleCreated } from "./sale-created";// POST /api/dub/webhook - receive webhooks for Dubexport const POST = withAxiom(async (req: Request) => {- const body = await req.json();- const { event, data } = webhookPayloadSchema.parse(body);-const webhookSignature = req.headers.get("Dub-Signature");if (!webhookSignature) {return new Response("No signature provided", { status: 401 });}+ // The sender signs JSON.stringify(payload), so the body is parsed before the signature check+ let body: unknown;++ try {+ body = await req.json();+ } catch {+ return new Response("Invalid JSON body", { status: 400 });+ }+const computedSignature = crypto.createHmac("sha256", `${process.env.DUB_WEBHOOK_SECRET}`).update(JSON.stringify(body)).digest("hex");if (!timingSafeCompare(webhookSignature, computedSignature)) {- return new Response("Invalid signature", { status: 400 });+ return new Response("Invalid signature", { status: 401 });}+ // Validate the payload only after the signature check, so unsigned requests cannot reach the schema+ const parsed = webhookPayloadSchema.safeParse(body);++ if (!parsed.success) {+ return new Response("Invalid webhook payload", { status: 400 });+ }++ const { event, data } = parsed.data;+let response = "OK";switch (event) {diff --git a/apps/web/app/api/links/sync/route.ts b/apps/web/app/api/links/sync/route.tsindex a61c027377..da46ea9631 100644--- a/apps/web/app/api/links/sync/route.ts+++ b/apps/web/app/api/links/sync/route.ts@@ -5,16 +5,22 @@ import { prisma } from "@/lib/prisma";import { SimpleLinkProps } from "@/lib/types";import { publishWorkspaceLinksUsageEvent } from "@/lib/upstash/redis-streams/workspace-links-usage";import { NextResponse } from "next/server";+import * as z from "zod/v4";++const syncLinksSchema = z.array(+ z.object({+ domain: z.string().min(1),+ key: z.string().min(1),+ }),+);// POST /api/links/sync – sync user's publicly created links to their accountsexport const POST = withWorkspace(async ({ req, session, workspace }) => {- let links: SimpleLinkProps[] = [];+ // The body comes from the hashes__dub cookie, so its shape is not guaranteed+ let links: Pick<SimpleLinkProps, "domain" | "key">[] = [];try {- links = await req.json();- if (!Array.isArray(links)) {- throw new Error("Invalid request body.");- }+ links = syncLinksSchema.parse(await req.json());} catch (e) {return new Response("Invalid request body.", { status: 400 });}diff --git a/apps/web/app/api/resend/webhook/route.ts b/apps/web/app/api/resend/webhook/route.tsindex db8ffb5b86..1ab65ecc31 100644--- a/apps/web/app/api/resend/webhook/route.ts+++ b/apps/web/app/api/resend/webhook/route.ts@@ -1,6 +1,6 @@import { withAxiom } from "@/lib/axiom/server";import { NextResponse } from "next/server";-import { Webhook } from "svix";+import { Webhook, WebhookVerificationError } from "svix";import { emailBounced } from "./email-bounced";import { emailDelivered } from "./email-delivered";import { emailOpened } from "./email-opened";@@ -10,16 +10,41 @@ const webhookSecret = process.env.RESEND_WEBHOOK_SECRET!;// POST /api/resend/webhook – listen to Resend webhooksexport const POST = withAxiom(async (req: Request) => {const rawBody = await req.text();++ const svixId = req.headers.get("svix-id");+ const svixTimestamp = req.headers.get("svix-timestamp");+ const svixSignature = req.headers.get("svix-signature");++ if (!svixId || !svixTimestamp || !svixSignature) {+ return NextResponse.json(+ { error: "Missing svix headers." },+ { status: 400 },+ );+ }+const webhook = new Webhook(webhookSecret);- // Throws on error, returns the verified content on success- webhook.verify(rawBody, {- "svix-id": req.headers.get("svix-id")!,- "svix-timestamp": req.headers.get("svix-timestamp")!,- "svix-signature": req.headers.get("svix-signature")!,- });+ let payload: { type?: string; data?: any };++ try {+ // Throws on an invalid signature, returns the parsed payload on success+ payload = webhook.verify(rawBody, {+ "svix-id": svixId,+ "svix-timestamp": svixTimestamp,+ "svix-signature": svixSignature,+ }) as typeof payload;+ } catch (error) {+ if (error instanceof WebhookVerificationError) {+ return NextResponse.json(+ { error: "Invalid signature." },+ { status: 401 },+ );+ }++ throw error;+ }- const { type, data } = JSON.parse(rawBody) || {};+ const { type, data } = payload || {};switch (type) {case "email.opened":