The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
wip
Kiran K2bc956abf9a0
diff --git a/apps/web/app/(ee)/api/track/click/route.ts b/apps/web/app/(ee)/api/track/click/route.tsindex 7ede09d7dd..05cbd644f5 100644--- a/apps/web/app/(ee)/api/track/click/route.ts+++ b/apps/web/app/(ee)/api/track/click/route.ts@@ -1,3 +1,4 @@+import { allowedHostnamesCache } from "@/lib/analytics/allowed-hostnames-cache";import { verifyAnalyticsAllowedHostnames } from "@/lib/analytics/verify-analytics-allowed-hostnames";import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { linkCache } from "@/lib/api/links/cache";@@ -57,11 +58,12 @@ export const POST = withAxiom(async (req: AxiomRequest) => {const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;- let [cachedClickId, cachedLink] = await redis.mget<- [string, RedisLinkProps]+ let [cachedClickId, cachedLink, cachedAllowedHostnames] = await redis.mget<+ [string, RedisLinkProps, string[]]>([recordClickCache._createKey({ domain, key, ip }),linkCache._createKey({ domain, key }),+ allowedHostnamesCache._createKey({ domain }),]);// assign a new clickId if there's no cached clickId@@ -101,32 +103,46 @@ export const POST = withAxiom(async (req: AxiomRequest) => {// if there's no cached clickId, track the click eventif (!cachedClickId) {- waitUntil(- (async () => {- const workspace = await getWorkspaceViaEdge(cachedLink.projectId!);- const allowedHostnames = workspace?.allowedHostnames as string[];-- if (- verifyAnalyticsAllowedHostnames({- allowedHostnames,- req,- })- ) {- await recordClick({- req,- clickId,- linkId: cachedLink.id,- domain,- key,- url: finalUrl,- workspaceId: cachedLink.projectId,- skipRatelimit: true,- ...(referrer && { referrer }),- shouldPassClickId: true,- });- }- })(),- );+ console.log("cachedAllowedHostnames", cachedAllowedHostnames);++ if (!cachedAllowedHostnames) {+ const workspace = await getWorkspaceViaEdge(cachedLink.projectId!);+ cachedAllowedHostnames = workspace?.allowedHostnames as string[];++ console.log("workspace", workspace);++ waitUntil(+ allowedHostnamesCache.mset({+ allowedHostnames: JSON.stringify(cachedAllowedHostnames),+ domains: workspace?.domains.map(({ slug }) => slug) ?? [],+ }),+ );+ }++ if (+ !verifyAnalyticsAllowedHostnames({+ allowedHostnames: cachedAllowedHostnames,+ req,+ })+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: "Click tracking is not allowed from this referrer.",+ });+ }++ await recordClick({+ req,+ clickId,+ linkId: cachedLink.id,+ domain,+ key,+ url: finalUrl,+ workspaceId: cachedLink.projectId,+ skipRatelimit: true,+ ...(referrer && { referrer }),+ shouldPassClickId: true,+ });}const isPartnerLink = Boolean(cachedLink.programId && cachedLink.partnerId);diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.tsindex 388719e60f..1381b48745 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts@@ -1,3 +1,4 @@+import { allowedHostnamesCache } from "@/lib/analytics/allowed-hostnames-cache";import { DubApiError } from "@/lib/api/errors";import { parseRequestBody } from "@/lib/api/utils";import { validateAllowedHostnames } from "@/lib/api/validate-allowed-hostnames";@@ -6,7 +7,6 @@ import { deleteWorkspace } from "@/lib/api/workspaces";import { withWorkspace } from "@/lib/auth";import { getFeatureFlags } from "@/lib/edge-config";import { storage } from "@/lib/storage";-import { redis } from "@/lib/upstash";import {updateWorkspaceSchema,WorkspaceSchema,@@ -113,21 +113,24 @@ export const PATCH = withWorkspace(await storage.delete(workspace.logo.replace(`${R2_URL}/`, ""));}- // Sync the allowedHostnames cache- const cacheKey = `allowedHostnamesCache:${workspace.id}`;+ // Sync the allowedHostnames cache for workspace domainsconst current = JSON.stringify(workspace.allowedHostnames);const next = JSON.stringify(response.allowedHostnames);+ const domains = response.domains.map(({ slug }) => slug);if (current !== next) {if (Array.isArray(response.allowedHostnames) &&response.allowedHostnames.length > 0) {- await redis.set(cacheKey, next, {- ex: 60 * 60 * 24 * 7, // 7 days+ allowedHostnamesCache.mset({+ allowedHostnames: next,+ domains,});} else {- await redis.del(cacheKey);+ allowedHostnamesCache.deleteMany({+ domains,+ });}}})(),diff --git a/apps/web/lib/analytics/allowed-hostnames-cache.ts b/apps/web/lib/analytics/allowed-hostnames-cache.tsnew file mode 100644index 0000000000..d0320b8e8b--- /dev/null+++ b/apps/web/lib/analytics/allowed-hostnames-cache.ts@@ -0,0 +1,52 @@+import { redis } from "@/lib/upstash";++const CACHE_EXPIRATION = 60 * 60 * 24 * 7; // 7 days+const CACHE_KEY_PREFIX = "allowedHostnamesCache";++class AllowedHostnamesCache {+ async mset({+ allowedHostnames,+ domains,+ }: {+ allowedHostnames: string;+ domains: string[];+ }) {+ if (domains.length === 0) {+ return;+ }++ const pipeline = redis.pipeline();++ domains.forEach((domain) => {+ pipeline.set(this._createKey({ domain }), allowedHostnames, {+ ex: CACHE_EXPIRATION,+ });+ });++ return await pipeline.exec();+ }++ async deleteMany({ domains }: { domains: string[] }) {+ if (domains.length === 0) {+ return;+ }++ const pipeline = redis.pipeline();++ domains.forEach((domain) => {+ pipeline.del(this._createKey({ domain }));+ });++ return await pipeline.exec();+ }++ async delete({ domain }: { domain: string }) {+ return await redis.del(this._createKey({ domain }));+ }++ _createKey({ domain }: { domain: string }) {+ return `${CACHE_KEY_PREFIX}:${domain}`;+ }+}++export const allowedHostnamesCache = new AllowedHostnamesCache();diff --git a/apps/web/lib/planetscale/get-link-with-allowed-hostnames.ts b/apps/web/lib/planetscale/get-link-with-allowed-hostnames.tsdeleted file mode 100644index 257af2d257..0000000000--- a/apps/web/lib/planetscale/get-link-with-allowed-hostnames.ts+++ /dev/null@@ -1,22 +0,0 @@-import { punyEncode } from "@dub/utils";-import { conn } from "./connection";--export const getLinkWithAllowedHostnames = async (- domain: string,- key: string,-) => {- const { rows } = await conn.execute<{- id: string;- url: string;- projectId: string;- folderId: string | null;- userId: string;- allowedHostnames: string[];- trackConversion: boolean;- }>(- "SELECT Link.id, Link.url, projectId, folderId, userId, allowedHostnames, trackConversion FROM Link LEFT JOIN Project ON Link.projectId = Project.id WHERE domain = ? AND `key` = ?",- [domain, punyEncode(decodeURIComponent(key))],- );-- return rows && Array.isArray(rows) && rows.length > 0 ? rows[0] : null;-};