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.

Support exact URL validation for partner group links

Kiran K3f56c381731d
diff --git a/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts b/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
index d5d9be53b4..21cf837fe9 100644
--- a/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
+++ b/apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
@@ -1,4 +1,5 @@
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { dedupeAdditionalLinks } from "@/lib/api/bounties/dedupe-additional-links";
import { isDiscountEquivalent } from "@/lib/api/discounts/is-discount-equivalent";
import { queueDiscountCodeDeletion } from "@/lib/api/discounts/queue-discount-code-deletion";
import { DubApiError } from "@/lib/api/errors";
@@ -104,13 +105,7 @@ export const PATCH = withWorkspace(
})
: null;
- // Deduplicate additionalLinks by domain, keeping the first occurrence
- const deduplicatedAdditionalLinks = additionalLinks
- ? additionalLinks.filter(
- (link, index, array) =>
- array.findIndex((l) => l.domain === link.domain) === index,
- )
- : additionalLinks;
+ const deduplicatedAdditionalLinks = dedupeAdditionalLinks(additionalLinks);
const additionalLinksInput = deduplicatedAdditionalLinks
? deduplicatedAdditionalLinks.length > 0
diff --git a/apps/web/app/(ee)/api/groups/route.ts b/apps/web/app/(ee)/api/groups/route.ts
index b038c00bc0..20774d1d75 100644
--- a/apps/web/app/(ee)/api/groups/route.ts
+++ b/apps/web/app/(ee)/api/groups/route.ts
@@ -1,12 +1,13 @@
import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";
+import { dedupeAdditionalLinks } from "@/lib/api/bounties/dedupe-additional-links";
import { createId } from "@/lib/api/create-id";
import { DubApiError, exceededLimitError } from "@/lib/api/errors";
import { getGroups } from "@/lib/api/groups/get-groups";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
+import { PartnerGroupAdditionalLink } from "@/lib/types";
import {
- additionalPartnerLinkSchema,
createGroupSchema,
DEFAULT_PARTNER_GROUP,
getGroupsQuerySchema,
@@ -115,16 +116,11 @@ export const POST = withWorkspace(
landerData,
} = program.groups[0];
- // Deduplicate additionalLinks by domain, keeping the first occurrence
- const deduplicatedAdditionalLinks =
- additionalLinks && Array.isArray(additionalLinks)
- ? (
- additionalLinks as z.infer<typeof additionalPartnerLinkSchema>[]
- ).filter(
- (link, index, array) =>
- array.findIndex((l) => l.domain === link.domain) === index,
- )
- : additionalLinks;
+ const deduplicatedAdditionalLinks = additionalLinks
+ ? Array.isArray(additionalLinks)
+ : dedupeAdditionalLinks(
+ additionalLinks as unknown as PartnerGroupAdditionalLink[],
+ );
return await tx.partnerGroup.create({
data: {
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/add-edit-group-additional-link-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/add-edit-group-additional-link-modal.tsx
index 77e6b371dc..6617fc07f7 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/add-edit-group-additional-link-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/add-edit-group-additional-link-modal.tsx
@@ -5,8 +5,8 @@ import { PartnerGroupAdditionalLink } from "@/lib/types";
import { MAX_ADDITIONAL_PARTNER_LINKS } from "@/lib/zod/schemas/groups";
import { Badge, Button, Input, Modal } from "@dub/ui";
import { CircleCheckFill } from "@dub/ui/icons";
-import { cn } from "@dub/utils";
-import { Dispatch, SetStateAction, useState } from "react";
+import { cn, isValidUrl } from "@dub/utils";
+import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -20,7 +20,7 @@ const URL_VALIDATION_MODES = [
{
value: "exact",
label: "Single page",
- description: "Restricts links to the homepage only",
+ description: "Restricts links to a specific page",
},
];
@@ -48,53 +48,115 @@ function AddDestinationUrlModalContent({
} = useForm<PartnerGroupAdditionalLink>({
defaultValues: {
domain: link?.domain || "",
+ url: link?.url || "",
validationMode: link?.validationMode || "domain",
},
});
- const [domain, validationMode] = watch(["domain", "validationMode"]);
+ const [domain, url, validationMode] = watch([
+ "domain",
+ "url",
+ "validationMode",
+ ]);
- const onSubmit = async (data: PartnerGroupAdditionalLink) => {
- const domainNormalized = data.domain.trim().toLowerCase();
+ useEffect(() => {
+ if (validationMode === "domain" && url) {
+ setValue("url", "");
+ } else if (validationMode === "exact" && domain) {
+ setValue("domain", "");
+ }
+ }, [validationMode, setValue, url, domain]);
- if (!isValidDomainFormat(domainNormalized)) {
- setError("domain", {
- type: "manual",
- message: "Please enter a valid domain (eg: acme.com).",
- });
- return;
+ const validateForm = (data: PartnerGroupAdditionalLink): boolean => {
+ // Domain mode validation
+ if (data.validationMode === "domain") {
+ if (!data.domain) {
+ return false;
+ }
+
+ const domainNormalized = data.domain.trim().toLowerCase();
+
+ if (!isValidDomainFormat(domainNormalized)) {
+ setError("domain", {
+ type: "manual",
+ message: "Please enter a valid domain (eg: acme.com).",
+ });
+ return false;
+ }
+
+ setValue("domain", domainNormalized, { shouldDirty: true });
+
+ const existingDomains = additionalLinks
+ .filter((l) => l.validationMode === "domain" && l.domain)
+ .map((l) => l.domain!);
+
+ if (
+ existingDomains.includes(domainNormalized) &&
+ domainNormalized !== link?.domain
+ ) {
+ setError("domain", {
+ type: "value",
+ message: `Domain ${domainNormalized} has already been added as a link domain`,
+ });
+ return false;
+ }
}
- setValue("domain", domainNormalized, { shouldDirty: true });
+ // Exact mode validation
+ else if (data.validationMode === "exact") {
+ const url = data.url?.trim();
- const existingDomains = additionalLinks.map((l) => l.domain);
+ if (!url) {
+ return false;
+ }
- if (
- existingDomains.includes(domainNormalized) &&
- domainNormalized !== link?.domain
- ) {
- setError("domain", {
- type: "value",
- message: `Domain ${domainNormalized} has already been added as a link domain`,
- });
+ if (!isValidUrl(url)) {
+ setError("url", {
+ type: "manual",
+ message: "Please enter a valid URL (eg: https://acme.com/page).",
+ });
+ return false;
+ }
+
+ const existingUrls = additionalLinks
+ .filter((l) => l.validationMode === "exact" && l.url)
+ .map((l) => l.url!);
+
+ if (existingUrls.includes(url) && url !== link?.url) {
+ setError("url", {
+ type: "value",
+ message: "This URL has already been added as an exact link",
+ });
+ return false;
+ }
+ }
+
+ return true;
+ };
+
+ const onSubmit = async (data: PartnerGroupAdditionalLink) => {
+ data = {
+ validationMode: data.validationMode,
+ domain: data.validationMode === "domain" ? data.domain : undefined,
+ url: data.validationMode === "exact" ? data.url : undefined,
+ };
+
+ if (!validateForm(data)) {
return;
}
let updatedAdditionalLinks: PartnerGroupAdditionalLink[];
if (link) {
- // Editing existing link - find and replace the specific link by domain
updatedAdditionalLinks = additionalLinks.map((existingLink) => {
- if (existingLink.domain === link.domain) {
- return {
- ...data,
- };
- }
+ const isMatch =
+ link.validationMode === "exact"
+ ? existingLink.url === link.url
+ : existingLink.domain === link.domain;
- return existingLink;
+ return isMatch ? data : existingLink;
});
} else {
- // Check if we're at the maximum number of additional links
if (additionalLinks.length >= MAX_ADDITIONAL_PARTNER_LINKS) {
toast.error(
`You can only create up to ${MAX_ADDITIONAL_PARTNER_LINKS} additional link domains.`,
@@ -102,9 +164,9 @@ function AddDestinationUrlModalContent({
return;
}
- // Creating new link
updatedAdditionalLinks = [...additionalLinks, data];
}
+
// Update the parent form state instead of calling API directly
onUpdateAdditionalLinks(updatedAdditionalLinks);
setIsOpen(false);
@@ -129,28 +191,11 @@ function AddDestinationUrlModalContent({
<div className="flex-1 overflow-y-auto">
<div className="space-y-6 p-6">
- <div className="space-y-2">
- <label className="block text-sm font-medium text-neutral-800">
- Link domain
- </label>
- <Input
- value={watch("domain") || ""}
- onChange={(e) => {
- setValue("domain", e.target.value);
- clearErrors("domain");
- }}
- type="text"
- placeholder="acme.com"
- className="max-w-full"
- error={errors.domain?.message}
- />
- </div>
-
<div>
<label className="text-sm font-medium text-neutral-800">
Allowed link types
</label>
- <div className="mt-3 grid grid-cols-1 gap-3">
+ <div className="mt-2 grid grid-cols-1 gap-3">
{URL_VALIDATION_MODES.map((type) => {
const isSelected = type.value === validationMode;
@@ -195,6 +240,38 @@ function AddDestinationUrlModalContent({
</div>
</div>
+ <div className="space-y-2">
+ <label className="block text-sm font-medium text-neutral-800">
+ {validationMode === "exact" ? "Link URL" : "Link domain"}
+ </label>
+
+ {validationMode === "exact" ? (
+ <Input
+ value={watch("url") || ""}
+ onChange={(e) => {
+ setValue("url", e.target.value);
+ clearErrors("url");
+ }}
+ type="text"
+ placeholder="https://acme.com/specific-page"
+ className="max-w-full"
+ error={errors.url?.message}
+ />
+ ) : (
+ <Input
+ value={watch("domain") || ""}
+ onChange={(e) => {
+ setValue("domain", e.target.value);
+ clearErrors("domain");
+ }}
+ type="text"
+ placeholder="acme.com"
+ className="max-w-full"
+ error={errors.domain?.message}
+ />
+ )}
+ </div>
+
{!link && (
<div className="flex items-start gap-2.5">
<input
@@ -230,15 +307,19 @@ function AddDestinationUrlModalContent({
variant="secondary"
onClick={() => setIsOpen(false)}
text="Cancel"
- className="h-10 w-fit"
+ className="h-9 w-fit"
/>
<Button
type="submit"
variant="primary"
text={isEditing ? "Update link domain" : "Add link domain"}
- className="h-10 w-fit"
- disabled={!domain || !validationMode}
+ className="h-9 w-fit"
+ disabled={
+ !validationMode ||
+ (validationMode === "domain" && !domain) ||
+ (validationMode === "exact" && !url)
+ }
/>
</div>
</div>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/group-additional-links.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/group-additional-links.tsx
index 741f3bd164..751496c231 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/group-additional-links.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/group-additional-links.tsx
@@ -272,8 +272,10 @@ function LinkDomain({
// Delete link domain
const deleteLinkDomain = async () => {
- const updatedAdditionalLinks = additionalLinks.filter(
- (existingLink) => existingLink.domain !== link.domain,
+ const updatedAdditionalLinks = additionalLinks.filter((existingLink) =>
+ link.validationMode === "exact"
+ ? existingLink.url !== link.url
+ : existingLink.domain !== link.domain,
);
// Update the parent form state instead of calling API directly
@@ -301,9 +303,13 @@ function LinkDomain({
<div className="h-full w-full rounded-full border border-white bg-gradient-to-t from-neutral-100" />
</div>
<div className="relative z-10 p-2">
- {link.domain ? (
+ {link.domain || link.url ? (
<LinkLogo
- apexDomain={getApexDomain(link.domain)}
+ apexDomain={getApexDomain(
+ (link.validationMode === "domain"
+ ? link.domain
+ : link.url)!,
+ )}
className="size-4 sm:size-6"
imageProps={{
loading: "lazy",
@@ -315,7 +321,9 @@ function LinkDomain({
</div>
</div>
<span className="text-content-default truncate text-sm font-semibold">
- {getPrettyUrl(link.domain)}
+ {getPrettyUrl(
+ link.validationMode === "domain" ? link.domain : link.url,
+ )}
</span>
</div>
diff --git a/apps/web/lib/api/bounties/dedupe-additional-links.ts b/apps/web/lib/api/bounties/dedupe-additional-links.ts
new file mode 100644
index 0000000000..66c9433dda
--- /dev/null
+++ b/apps/web/lib/api/bounties/dedupe-additional-links.ts
@@ -0,0 +1,26 @@
+import { PartnerGroupAdditionalLink } from "@/lib/types";
+
+export function dedupeAdditionalLinks(
+ additionalLinks?: PartnerGroupAdditionalLink[] | null,
+): PartnerGroupAdditionalLink[] | undefined {
+ if (!additionalLinks) {
+ return undefined;
+ }
+
+ const seen = new Set<string>();
+
+ return additionalLinks.filter((link) => {
+ const key =
+ link.validationMode === "domain"
+ ? link.domain?.toLowerCase()
+ : link.url?.toLowerCase();
+
+ if (!key || seen.has(key)) {
+ return false;
+ }
+
+ seen.add(key);
+
+ return true;
+ });
+}
diff --git a/apps/web/lib/api/links/validate-partner-link-url.ts b/apps/web/lib/api/links/validate-partner-link-url.ts
index ff48bb77a7..c84473abf5 100644
--- a/apps/web/lib/api/links/validate-partner-link-url.ts
+++ b/apps/web/lib/api/links/validate-partner-link-url.ts
@@ -23,8 +23,7 @@ export const validatePartnerLinkUrl = ({
});
}
- const { hostname: urlHostname, pathname: urlPathname } =
- getUrlObjFromString(url) ?? {};
+ const { hostname: urlHostname } = getUrlObjFromString(url) ?? {};
// Find matching additional link based on its domain
const additionalLink = additionalLinks.find((additionalLink) => {
@@ -39,15 +38,23 @@ export const validatePartnerLinkUrl = ({
}
// Check the validation mode
- if (
- additionalLink.validationMode === "exact" &&
- urlPathname &&
- urlPathname.slice(1).length > 0
- ) {
- throw new DubApiError({
- code: "bad_request",
- message: `The provided URL is not an exact match for the program's link domain (${additionalLink.domain}).`,
- });
+ if (additionalLink.validationMode === "exact") {
+ // For exact mode, compare the full URL
+ if (additionalLink.url && url !== additionalLink.url) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `The provided URL does not match the exact URL configured for this program: ${additionalLink.url}`,
+ });
+ } else if (!additionalLink.url) {
+ // Legacy support: if no URL is set but mode is exact, only allow domain root
+ const { pathname: urlPathname } = getUrlObjFromString(url) ?? {};
+ if (urlPathname && urlPathname.slice(1).length > 0) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: `The provided URL is not an exact match for the program's link domain (${additionalLink.domain}).`,
+ });
+ }
+ }
}
return true;
diff --git a/apps/web/lib/zod/schemas/groups.ts b/apps/web/lib/zod/schemas/groups.ts
index 46348fb853..3a2d0cdac9 100644
--- a/apps/web/lib/zod/schemas/groups.ts
+++ b/apps/web/lib/zod/schemas/groups.ts
@@ -1,7 +1,7 @@
import { isValidDomainFormat } from "@/lib/api/domains/is-valid-domain";
import { RESOURCE_COLORS } from "@/ui/colors";
import { PartnerLinkStructure } from "@dub/prisma/client";
-import { validSlugRegex } from "@dub/utils";
+import { isValidUrl, validSlugRegex } from "@dub/utils";
import slugify from "@sindresorhus/slugify";
import { z } from "zod";
import { DiscountSchema } from "./discount";
@@ -19,23 +19,58 @@ export const DEFAULT_PARTNER_GROUP = {
} as const;
export const MAX_DEFAULT_PARTNER_LINKS = 5;
+
export const MAX_ADDITIONAL_PARTNER_LINKS = 20;
export const GROUPS_MAX_PAGE_SIZE = 100;
-export const additionalPartnerLinkSchema = z.object({
- domain: z
- .string()
- .min(1, "domain is required")
- .refine((v) => isValidDomainFormat(v), {
- message: "Please enter a valid domain (eg: acme.com).",
- })
- .transform((v) => v.toLowerCase()),
- validationMode: z.enum([
- "domain", // domain match (e.g. if URL is example.com/path, example.com and example.com/another-path are allowed)
- "exact", // exact match (e.g. if URL is example.com/path, only example.com/path is allowed)
- ]),
-});
+export const additionalPartnerLinkSchema = z
+ .object({
+ domain: z
+ .string()
+ .refine((v) => isValidDomainFormat(v), {
+ message: "Please enter a valid domain (eg: acme.com).",
+ })
+ .transform((v) => v.toLowerCase())
+ .optional(),
+ url: z
+ .string()
+ .refine((v) => isValidUrl(v), {
+ message: "Please enter a valid URL (eg: https://acme.com/page)",
+ })
+ .transform((v) => v.toLowerCase())
+ .optional(),
+ validationMode: z.enum([
+ "domain", // domain match (e.g. if URL is example.com/path, example.com and example.com/another-path are allowed)
+ "exact", // exact match (e.g. if URL is example.com/path, only example.com/path is allowed)
+ ]),
+ })
+ .refine(
+ (data) => {
+ if (data.validationMode === "domain") {
+ return data.domain && data.domain.trim().length > 0;
+ }
+
+ return true;
+ },
+ {
+ message: "Domain is required when validation mode is domain.",
+ path: ["domain"],
+ },
+ )
+ .refine(
+ (data) => {
+ if (data.validationMode === "exact") {
+ return data.url && data.url.trim().length > 0;
+ }
+
+ return true;
+ },
+ {
+ message: "URL is required when validation mode is exact.",
+ path: ["url"],
+ },
+ );
// This is the standard response we send for all /api/groups/** endpoints
export const GroupSchema = z.object({