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.

Improvements to tracking page

Steven Tey1eba8c1b5cf2
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/add-hostname-modal.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/add-hostname-modal.tsx
index da4b4dfe10..6595eaec62 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/add-hostname-modal.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/add-hostname-modal.tsx
@@ -3,7 +3,7 @@
import { X } from "@/ui/shared/icons";
import { Button, Modal, useMediaQuery } from "@dub/ui";
import { cn, validDomainRegex } from "@dub/utils";
-import { useCallback, useMemo, useState } from "react";
+import { useState } from "react";
import { toast } from "sonner";
const isValidHostname = (hostname: string) => {
@@ -14,87 +14,54 @@ const isValidHostname = (hostname: string) => {
);
};
-const AddHostnameForm = ({
+const AddHostnameModal = ({
+ showModal,
+ setShowModal,
existingHostnames,
onAdd,
- onCancel,
}: {
+ showModal: boolean;
+ setShowModal: (showModal: boolean) => void;
existingHostnames: string[];
- onAdd: (hostname: string) => void;
- onCancel?: () => void;
+ onAdd: (hostname: string) => void | Promise<void>;
}) => {
const [hostname, setHostname] = useState("");
+ const [isLoading, setIsLoading] = useState(false);
const { isMobile } = useMediaQuery();
- return (
- <form
- className="bg-neutral-50"
- onSubmit={(e) => {
- e.preventDefault();
- e.stopPropagation();
+ const close = () => {
+ if (isLoading) {
+ return;
+ }
- if (existingHostnames.includes(hostname)) {
- toast.error("Hostname already exists.");
- return;
- }
+ setShowModal(false);
+ };
- if (!isValidHostname(hostname)) {
- toast.error("Enter a valid domain.");
- return;
- }
+ const handleAdd = async () => {
+ if (isLoading) {
+ return;
+ }
- onAdd(hostname);
- setHostname("");
- }}
- >
- <div className="relative flex-1 rounded-md px-6 py-5">
- <input
- type="text"
- required
- value={hostname}
- onChange={(e) => setHostname(e.target.value)}
- autoComplete="off"
- autoFocus={!isMobile}
- placeholder="example.com or *.example.com"
- className={cn(
- "block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
- )}
- />
- </div>
+ if (existingHostnames.includes(hostname)) {
+ toast.error("Hostname already exists.");
+ return;
+ }
- <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-6 py-5">
- <Button
- onClick={() => onCancel?.()}
- variant="secondary"
- text="Cancel"
- className="h-8 w-fit px-3"
- />
- <Button
- type="submit"
- variant="primary"
- text="Add hostname"
- className="h-8 w-fit px-3"
- disabled={!isValidHostname(hostname)}
- />
- </div>
- </form>
- );
-};
+ if (!isValidHostname(hostname)) {
+ toast.error("Enter a valid domain.");
+ return;
+ }
-interface AddHostnameModalProps {
- showModal: boolean;
- setShowModal: (showModal: boolean) => void;
- existingHostnames: string[];
- onAdd: (hostname: string) => void;
-}
+ setIsLoading(true);
+ try {
+ await onAdd(hostname);
+ setHostname("");
+ setShowModal(false);
+ } finally {
+ setIsLoading(false);
+ }
+ };
-const AddHostnameModal = ({
- showModal,
- setShowModal,
- existingHostnames,
- onAdd,
-}: AddHostnameModalProps) => {
- const close = () => setShowModal(false);
return (
<Modal showModal={showModal} setShowModal={setShowModal}>
<div className="flex items-center justify-between border-b border-neutral-200 p-4">
@@ -108,16 +75,48 @@ const AddHostnameModal = ({
</button>
</div>
- <div className="bg-neutral-50">
- <AddHostnameForm
- existingHostnames={existingHostnames}
- onCancel={close}
- onAdd={(hostname) => {
- onAdd(hostname);
- close();
- }}
- />
- </div>
+ <form
+ className="bg-neutral-50"
+ onSubmit={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ void handleAdd();
+ }}
+ >
+ <div className="relative flex-1 rounded-md px-6 py-5">
+ <input
+ type="text"
+ required
+ value={hostname}
+ onChange={(e) => setHostname(e.target.value)}
+ autoComplete="off"
+ autoFocus={!isMobile}
+ placeholder="example.com or *.example.com"
+ className={cn(
+ "block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",
+ )}
+ />
+ </div>
+
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-6 py-5">
+ <Button
+ type="button"
+ onClick={close}
+ variant="secondary"
+ text="Cancel"
+ className="h-8 w-fit px-3"
+ disabled={isLoading}
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ text="Add hostname"
+ className="h-8 w-fit px-3"
+ disabled={!isValidHostname(hostname)}
+ loading={isLoading}
+ />
+ </div>
+ </form>
</Modal>
);
};
@@ -127,26 +126,19 @@ export function useAddHostnameModal({
onAdd,
}: {
existingHostnames: string[];
- onAdd: (hostname: string) => void;
+ onAdd: (hostname: string) => void | Promise<void>;
}) {
const [showAddHostnameModal, setShowAddHostnameModal] = useState(false);
- const AddHostnameModalCallback = useCallback(() => {
- return (
+ return {
+ setShowAddHostnameModal,
+ addHostnameModal: (
<AddHostnameModal
showModal={showAddHostnameModal}
setShowModal={setShowAddHostnameModal}
existingHostnames={existingHostnames}
onAdd={onAdd}
/>
- );
- }, [showAddHostnameModal, existingHostnames, onAdd]);
-
- return useMemo(
- () => ({
- setShowAddHostnameModal,
- AddHostnameModal: AddHostnameModalCallback,
- }),
- [AddHostnameModalCallback],
- );
+ ),
+ };
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/configure-tracking-section.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/configure-tracking-section.tsx
index 468be47485..8028ea23bb 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/configure-tracking-section.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/configure-tracking-section.tsx
@@ -267,6 +267,11 @@ export function ConfigureTrackingSection() {
<HostnameField
hostnames={field.value}
onChange={field.onChange}
+ onSave={(allowedHostnames) =>
+ handleSubmit((data) =>
+ onSubmit({ ...data, allowedHostnames }),
+ )()
+ }
disabled={disabled}
disabledTooltip={disabledTooltip}
/>
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/hostname-field.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/hostname-field.tsx
index 9492bff288..f1792ccf22 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/hostname-field.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/hostname-field.tsx
@@ -13,18 +13,22 @@ import { HostnameMenu } from "./hostname-menu";
export function HostnameField({
hostnames,
onChange,
+ onSave,
disabled,
disabledTooltip,
}: {
hostnames: string[];
onChange: (hostnames: string[]) => void;
+ onSave?: (hostnames: string[]) => void | Promise<void>;
disabled?: boolean;
disabledTooltip?: string;
}) {
- const { AddHostnameModal, setShowAddHostnameModal } = useAddHostnameModal({
+ const { addHostnameModal, setShowAddHostnameModal } = useAddHostnameModal({
existingHostnames: hostnames,
- onAdd: (hostname) => {
- onChange([...hostnames, hostname]);
+ onAdd: async (hostname) => {
+ const nextHostnames = [...hostnames, hostname];
+ await onSave?.(nextHostnames);
+ onChange(nextHostnames);
},
});
@@ -55,9 +59,13 @@ export function HostnameField({
key={hostname}
hostname={hostname}
disabled={disabled}
- onDelete={() =>
- onChange(hostnames.filter((item) => item !== hostname))
- }
+ onDelete={async () => {
+ const nextHostnames = hostnames.filter(
+ (item) => item !== hostname,
+ );
+ await onSave?.(nextHostnames);
+ onChange(nextHostnames);
+ }}
/>
))}
</div>
@@ -73,7 +81,7 @@ export function HostnameField({
</>
)}
</div>
- <AddHostnameModal />
+ {addHostnameModal}
</>
);
}
@@ -85,12 +93,12 @@ function HostnameRow({
}: {
hostname: string;
disabled?: boolean;
- onDelete: () => void;
+ onDelete: () => void | Promise<void>;
}) {
const { setShowConfirmModal, confirmModal } = useConfirmModal({
- title: "Delete Hostname",
+ title: "Delete hostname",
description: `Are you sure you want to delete "${hostname}"? This action cannot be undone.`,
- confirmText: "Delete Hostname",
+ confirmText: "Delete hostname",
onConfirm: onDelete,
});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsx
index 4652931a9c..ba05739bce 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/tracking/verify-install.tsx
@@ -1,15 +1,12 @@
"use client";
import { verifyWorkspaceSetup } from "@/lib/actions/verify-workspace-setup";
-import {
- toVerifySiteUrl,
- type VerifyInstallationResult,
-} from "@/lib/analytics/verify-installation";
+import type { VerifyInstallationResult } from "@/lib/analytics/verify-installation";
import { clientAccessCheck } from "@/lib/client-access-check";
import useWorkspace from "@/lib/swr/use-workspace";
import { UserAvatar } from "@/ui/users/user-avatar";
import { Button, Combobox, Globe } from "@dub/ui";
-import { cn, OG_AVATAR_URL, timeAgo } from "@dub/utils";
+import { cn, getPrettyUrl, OG_AVATAR_URL, timeAgo } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
import { type ReactNode, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
@@ -17,18 +14,34 @@ import { toast } from "sonner";
const HOSTNAME_REQUIRED_MESSAGE =
"A hostname is required in order to verify installation.";
-const VERIFY_DOCS_HREF = "https://dub.co/docs/sdks/client-side";
+const isVerifiableHostname = (hostname: string) =>
+ !hostname.startsWith("*.") &&
+ hostname !== "localhost" &&
+ !hostname.startsWith("localhost:");
+
+const VERIFY_DOCS_HREF = "https://dub.co/docs/sdks/client-side/introduction";
const VERIFY_SUPPORT_HREF = "https://dub.co/support";
const ERROR_HEADLINE = {
not_installed: "Script is not installed.",
missing_attributes: "Script missing attributes.",
+ missing_refer_domain: "Script is missing the referral link domain.",
duplicate: "Duplicate script.",
malformed: "Malformed script.",
unreachable: "We couldn’t reach this hostname.",
unsupported: "Wildcard hostnames can’t be verified.",
};
+const getErrorHeadline = (
+ result: Extract<VerifyInstallationResult, { status: "error" }>,
+) => {
+ if (result.error === "missing_refer_domain" && result.referDomain) {
+ return `Script is missing the referral link domain (${result.referDomain}).`;
+ }
+
+ return ERROR_HEADLINE[result.error];
+};
+
type LastVerified = {
hostname: string;
verifiedAt: string;
@@ -67,9 +80,9 @@ export function VerifyInstall({ hostnames }: { hostnames: string[] }) {
const hostnameOptions = useMemo(
() =>
- hostnames.map((hostname) => ({
+ hostnames.filter(isVerifiableHostname).map((hostname) => ({
value: hostname,
- label: hostname.startsWith("*.") ? hostname : toVerifySiteUrl(hostname),
+ label: getPrettyUrl(hostname),
icon: <Globe className="size-4 text-neutral-600" />,
})),
[hostnames],
@@ -153,12 +166,12 @@ export function VerifyInstall({ hostnames }: { hostnames: string[] }) {
searchPlaceholder="Search hostnames..."
buttonProps={{
className: cn("h-10 w-full", helperTone && "bg-bg-default"),
- disabled: hostnames.length === 0 || isPending,
+ disabled: hostnameOptions.length === 0 || isPending,
disabledTooltip:
- hostnames.length === 0
+ hostnameOptions.length === 0
? HOSTNAME_REQUIRED_MESSAGE
: isPending
- ? "Verification in progress"
+ ? "Verification in progress..."
: undefined,
}}
matchTriggerWidth
@@ -172,7 +185,7 @@ export function VerifyInstall({ hostnames }: { hostnames: string[] }) {
{showError && resultForSelection?.status === "error" && (
<HelperText tone="error">
- {ERROR_HEADLINE[resultForSelection.error]} After correcting, try
+ {getErrorHeadline(resultForSelection)} After correcting, try
verifying again and if the issue still persists, check out our{" "}
<a
href={VERIFY_DOCS_HREF}
diff --git a/apps/web/lib/actions/verify-workspace-setup.ts b/apps/web/lib/actions/verify-workspace-setup.ts
index f78780aa45..34ea0704ef 100644
--- a/apps/web/lib/actions/verify-workspace-setup.ts
+++ b/apps/web/lib/actions/verify-workspace-setup.ts
@@ -56,13 +56,21 @@ export const verifyWorkspaceSetup = authActionClient
apiKey: process.env.FIRECRAWL_API_KEY,
});
- const scrapeResult = await firecrawl.scrapeUrl(toVerifySiteUrl(hostname), {
- formats: ["rawHtml"],
- onlyMainContent: false,
- parsePDF: false,
- maxAge: 0,
- waitFor: 5000,
- });
+ const [scrapeResult, program] = await Promise.all([
+ firecrawl.scrapeUrl(toVerifySiteUrl(hostname), {
+ formats: ["rawHtml"],
+ onlyMainContent: false,
+ parsePDF: false,
+ maxAge: 0,
+ waitFor: 5000,
+ }),
+ workspace.defaultProgramId
+ ? prisma.program.findUnique({
+ where: { id: workspace.defaultProgramId },
+ select: { domain: true },
+ })
+ : null,
+ ]);
if (!scrapeResult.success || !scrapeResult.rawHtml) {
return {
@@ -72,13 +80,18 @@ export const verifyWorkspaceSetup = authActionClient
};
}
- const analysis = analyzeDubAnalyticsScript(scrapeResult.rawHtml);
+ const analysis = analyzeDubAnalyticsScript(scrapeResult.rawHtml, {
+ referDomain: program?.domain,
+ });
if (analysis !== "ok") {
return {
status: "error",
hostname,
error: analysis,
+ ...(analysis === "missing_refer_domain" && program?.domain
+ ? { referDomain: program.domain }
+ : {}),
};
}
diff --git a/apps/web/lib/analytics/verify-installation.ts b/apps/web/lib/analytics/verify-installation.ts
index 80b9dd161f..354e84e056 100644
--- a/apps/web/lib/analytics/verify-installation.ts
+++ b/apps/web/lib/analytics/verify-installation.ts
@@ -1,6 +1,7 @@
type VerifyErrorCode =
| "not_installed"
| "missing_attributes"
+ | "missing_refer_domain"
| "duplicate"
| "malformed";
@@ -21,6 +22,7 @@ export type VerifyInstallationResult =
status: "error";
hostname: string;
error: VerifyError;
+ referDomain?: string;
};
const SCRIPT_TAG_RE = /<script\b[^>]*>/gi;
@@ -33,9 +35,46 @@ const CONVERSION_SRC_RE =
const SDK_NAME_RE =
/data-sdkn\s*=\s*(?:["']@dub\/analytics["']|@dub\/analytics(?=[\s>/]))/i;
const PUBLISHABLE_KEY_RE = /data-publishable-key=/i;
+const ATTR_RE = (name: string) =>
+ new RegExp(`${name}\\s*=\\s*(["'])([\\s\\S]*?)\\1`, "i");
+
+const decodeHtmlEntities = (value: string) =>
+ value
+ .replace(/&quot;/gi, '"')
+ .replace(/&#34;/g, '"')
+ .replace(/&#x22;/gi, '"')
+ .replace(/&apos;/gi, "'")
+ .replace(/&#39;/g, "'")
+ .replace(/&amp;/gi, "&");
+
+const normalizeReferDomain = (value: string) =>
+ value.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/\/$/, "");
+
+const getScriptAttr = (tag: string, name: string) => {
+ const match = tag.match(ATTR_RE(name));
+ return match ? decodeHtmlEntities(match[2]) : null;
+};
+
+const parseScriptReferDomain = (tag: string) => {
+ const rawDomains = getScriptAttr(tag, "data-domains");
+ if (rawDomains) {
+ try {
+ const parsed = JSON.parse(rawDomains) as { refer?: unknown };
+ if (typeof parsed.refer === "string" && parsed.refer.trim()) {
+ return parsed.refer.trim();
+ }
+ } catch {
+ // Fall through to the legacy data-short-domain attribute.
+ }
+ }
+
+ const shortDomain = getScriptAttr(tag, "data-short-domain");
+ return shortDomain?.trim() || null;
+};
export function analyzeDubAnalyticsScript(
html: string,
+ { referDomain }: { referDomain?: string | null } = {},
): "ok" | VerifyErrorCode {
const scriptTags = html.match(SCRIPT_TAG_RE) ?? [];
const dubScripts = scriptTags.filter((tag) => DUB_SCRIPT_RE.test(tag));
@@ -68,6 +107,18 @@ export function analyzeDubAnalyticsScript(
return "missing_attributes";
}
+ const expectedReferDomain = referDomain?.trim();
+ if (expectedReferDomain) {
+ const scriptReferDomain = parseScriptReferDomain(tag);
+ if (
+ !scriptReferDomain ||
+ normalizeReferDomain(scriptReferDomain) !==
+ normalizeReferDomain(expectedReferDomain)
+ ) {
+ return "missing_refer_domain";
+ }
+ }
+
return "ok";
}
diff --git a/apps/web/lib/api/fraud/constants.ts b/apps/web/lib/api/fraud/constants.ts
index 7fdc01cdd4..c1098d837d 100644
--- a/apps/web/lib/api/fraud/constants.ts
+++ b/apps/web/lib/api/fraud/constants.ts
@@ -33,7 +33,7 @@ export const FRAUD_RULES: FraudRuleInfo[] = [
type: "referralSourceBanned",
name: "Banned referral source",
description:
- "A conversion, event, or click was made on a banned referral domain.",
+ "A conversion, event, or click was made on a banned referral source.",
scope: "conversionEvent",
configurable: true,
},
diff --git a/apps/web/tests/analytics/verify-installation.test.ts b/apps/web/tests/analytics/verify-installation.test.ts
new file mode 100644
index 0000000000..628c902ee8
--- /dev/null
+++ b/apps/web/tests/analytics/verify-installation.test.ts
@@ -0,0 +1,79 @@
+import { analyzeDubAnalyticsScript } from "@/lib/analytics/verify-installation";
+import { describe, expect, it } from "vitest";
+
+const pageWithScript = (attrs: string) =>
+ `<html><body><script src="https://www.dubcdn.com/analytics/script.js" ${attrs}></script></body></html>`;
+
+describe("analyzeDubAnalyticsScript", () => {
+ it("passes a basic Dub script without a required refer domain", () => {
+ expect(analyzeDubAnalyticsScript(pageWithScript("defer"))).toBe("ok");
+ });
+
+ it("requires data-domains.refer when a program domain is provided", () => {
+ expect(
+ analyzeDubAnalyticsScript(pageWithScript("defer"), {
+ referDomain: "refer.acme.com",
+ }),
+ ).toBe("missing_refer_domain");
+ });
+
+ it("accepts a matching data-domains refer value", () => {
+ expect(
+ analyzeDubAnalyticsScript(
+ pageWithScript(`defer data-domains='{"refer":"refer.acme.com"}'`),
+ { referDomain: "refer.acme.com" },
+ ),
+ ).toBe("ok");
+ });
+
+ it("accepts HTML-encoded data-domains JSON", () => {
+ expect(
+ analyzeDubAnalyticsScript(
+ pageWithScript(
+ `defer data-domains="{&quot;refer&quot;:&quot;refer.acme.com&quot;}"`,
+ ),
+ { referDomain: "refer.acme.com" },
+ ),
+ ).toBe("ok");
+ });
+
+ it("accepts data-domains with additional keys", () => {
+ expect(
+ analyzeDubAnalyticsScript(
+ pageWithScript(
+ `defer data-domains='{"refer":"refer.acme.com","site":"site.acme.com"}'`,
+ ),
+ { referDomain: "refer.acme.com" },
+ ),
+ ).toBe("ok");
+ });
+
+ it("rejects a data-domains refer value that does not match the program domain", () => {
+ expect(
+ analyzeDubAnalyticsScript(
+ pageWithScript(`defer data-domains='{"refer":"other.link"}'`),
+ { referDomain: "refer.acme.com" },
+ ),
+ ).toBe("missing_refer_domain");
+ });
+
+ it("normalizes protocol and casing when comparing refer domains", () => {
+ expect(
+ analyzeDubAnalyticsScript(
+ pageWithScript(
+ `defer data-domains='{"refer":"https://Refer.Acme.com/"}'`,
+ ),
+ { referDomain: "refer.acme.com" },
+ ),
+ ).toBe("ok");
+ });
+
+ it("accepts the legacy data-short-domain attribute", () => {
+ expect(
+ analyzeDubAnalyticsScript(
+ pageWithScript(`defer data-short-domain="refer.acme.com"`),
+ { referDomain: "refer.acme.com" },
+ ),
+ ).toBe("ok");
+ });
+});