The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Merge branch 'main' into tim/multiple-tags-cleanup
Tim Wilsonc5f7e9f15206
diff --cc apps/web/app/api/links/[linkId]/route.tsindex 9b20154e81,8794e752d9..3f91ac12e7--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@@ -1,11 -1,9 +1,9 @@@import { DubApiError, ErrorCodes } from "@/lib/api/errors";import { deleteLink, editLink, processLink } from "@/lib/api/links";import { withAuth } from "@/lib/auth";- import { qstash } from "@/lib/cron";import prisma from "@/lib/prisma";-import { LinkWithTagIdsProps } from "@/lib/types";+import { NewLinkProps } from "@/lib/types";import { updateLinkBodySchema } from "@/lib/zod/schemas/links";- import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { NextResponse } from "next/server";// GET /api/links/[linkId] – get a linkdiff --cc apps/web/app/api/links/route.tsindex 79a2834e6d,62ad270650..9604d0a9f4--- a/apps/web/app/api/links/route.ts+++ b/apps/web/app/api/links/route.ts@@@ -1,7 -1,7 +1,6 @@@import { DubApiError, ErrorCodes } from "@/lib/api/errors";- import { addLink, getLinksForWorkspace, processLink } from "@/lib/api/links";+ import { createLink, getLinksForWorkspace, processLink } from "@/lib/api/links";import { withAuth } from "@/lib/auth";- import { qstash } from "@/lib/cron";-import { LinkWithTagIdsProps } from "@/lib/types";import { ratelimit } from "@/lib/upstash";import {createLinkBodySchema,diff --cc apps/web/lib/api/links/bulk-create-links.tsindex 0000000000,3c9e262b43..3df08f092emode 000000,100644..100644--- a/apps/web/lib/api/links/bulk-create-links.ts+++ b/apps/web/lib/api/links/bulk-create-links.ts@@@ -1,0 -1,124 +1,124 @@@+ import prisma from "@/lib/prisma";+ import { recordLink } from "@/lib/tinybird";-import { LinkProps, LinkWithTagIdsProps, RedisLinkProps } from "@/lib/types";++import { LinkProps, ProcessedLinkProps, RedisLinkProps } from "@/lib/types";+ import { formatRedisLink, redis } from "@/lib/upstash";+ import { getParamsFromURL, linkConstructor, truncate } from "@dub/utils";+ import { combineTagIds } from "./utils";++ export async function bulkCreateLinks({+ links,+ }: {- links: LinkWithTagIdsProps[];++ links: ProcessedLinkProps[];+ }) {+ if (links.length === 0) return [];++ // create links via $transaction (because Prisma doesn't support nested createMany)+ // ref: https://github.com/prisma/prisma/issues/8131#issuecomment-997667070+ const createdLinks = await prisma.$transaction(+ links.map(({ tagId, tagIds, ...link }) => {+ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =+ getParamsFromURL(link.url);++ const combinedTagIds = combineTagIds({ tagId, tagIds });++ return prisma.link.create({+ data: {+ ...link,+ title: truncate(link.title, 120),+ description: truncate(link.description, 240),+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,+ geo: link.geo || undefined,+ ...(combinedTagIds.length > 0 && {+ tags: {+ createMany: {+ data: combinedTagIds.map((tagId) => ({ tagId })),+ },+ },+ }),+ },+ include: {+ tags: {+ select: {+ tagId: true,+ tag: {+ select: {+ id: true,+ name: true,+ color: true,+ },+ },+ },+ },+ },+ });+ }),+ );++ await propagateBulkLinkChanges(createdLinks);++ return createdLinks.map((link) => {+ const shortLink = linkConstructor({+ domain: link.domain,+ key: link.key,+ });+ const tags = link.tags.map(({ tag }) => tag);+ return {+ ...link,+ shortLink,+ tagId: tags?.[0]?.id ?? null, // backwards compatibility+ tags,+ qrCode: `https://api.dub.co/qr?url=${shortLink}`,+ workspaceId: `ws_${link.projectId}`,+ };+ });+ }++ export async function propagateBulkLinkChanges(+ links: (LinkProps & { tags: { tagId: string }[] })[],+ ) {+ const pipeline = redis.pipeline();++ // split links into domains for better write effeciency in Redis+ const linksByDomain: Record<string, Record<string, RedisLinkProps>> = {};++ await Promise.all(+ links.map(async (link) => {+ const { domain, key } = link;++ if (!linksByDomain[domain]) {+ linksByDomain[domain] = {};+ }+ // this technically will be a synchronous function since isIframeable won't be run for bulk link creation+ const formattedLink = await formatRedisLink(link);+ linksByDomain[domain][key.toLowerCase()] = formattedLink;++ // record link in Tinybird+ await recordLink({ link });+ }),+ );++ Object.entries(linksByDomain).forEach(([domain, links]) => {+ pipeline.hset(domain, links);+ });++ await Promise.all([+ // update Redis+ pipeline.exec(),+ // update links usage for workspace+ prisma.project.update({+ where: {+ id: links[0].projectId!, // this will always be present+ },+ data: {+ linksUsage: {+ increment: links.length,+ },+ },+ }),+ ]);+ }diff --cc apps/web/lib/api/links/create-link.tsindex 0000000000,da90bab676..8c5737d347mode 000000,100644..100644--- a/apps/web/lib/api/links/create-link.ts+++ b/apps/web/lib/api/links/create-link.ts@@@ -1,0 -1,141 +1,141 @@@+ import { qstash } from "@/lib/cron";+ import prisma from "@/lib/prisma";+ import { isStored, storage } from "@/lib/storage";+ import { recordLink } from "@/lib/tinybird";-import { LinkWithTagIdsProps } from "@/lib/types";++import { ProcessedLinkProps } from "@/lib/types";+ import { formatRedisLink, redis } from "@/lib/upstash";+ import {+ APP_DOMAIN_WITH_NGROK,+ getParamsFromURL,+ linkConstructor,+ truncate,+ } from "@dub/utils";+ import { Prisma } from "@prisma/client";+ import { combineTagIds, dubLinkChecks } from "./utils";+-export async function createLink(link: LinkWithTagIdsProps) {++export async function createLink(link: ProcessedLinkProps) {+ let { key, url, expiresAt, title, description, image, proxy, geo } = link;++ const combinedTagIds = combineTagIds(link);++ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =+ getParamsFromURL(url);++ const { tagId, tagIds, ...rest } = link;++ const response = await prisma.link.create({+ data: {+ ...rest,+ key,+ title: truncate(title, 120),+ description: truncate(description, 240),+ // if it's an uploaded image, make this null first because we'll update it later+ image: proxy && image && !isStored(image) ? null : image,+ utm_source,+ utm_medium,+ utm_campaign,+ utm_term,+ utm_content,+ expiresAt: expiresAt ? new Date(expiresAt) : null,+ geo: geo || Prisma.JsonNull,+ ...(combinedTagIds.length > 0 && {+ tags: {+ createMany: {+ data: combinedTagIds.map((tagId) => ({ tagId })),+ },+ },+ }),+ },+ include: {+ tags: {+ select: {+ tag: {+ select: {+ id: true,+ name: true,+ color: true,+ },+ },+ },+ },+ },+ });++ const uploadedImageUrl = `${process.env.STORAGE_BASE_URL}/images/${response.id}`;++ await Promise.all([+ // record link in Redis+ redis.hset(link.domain, {+ [link.key.toLowerCase()]: await formatRedisLink(response),+ }),+ // record link in Tinybird+ recordLink({+ link: {+ ...response,+ tags: response.tags.map(({ tag }) => ({+ tagId: tag.id,+ })),+ },+ }),+ // if proxy image is set, upload image to R2 and update the link with the uploaded image URL+ ...(proxy && image && !isStored(image)+ ? [+ // upload image to R2+ storage.upload(`images/${response.id}`, image, {+ width: 1200,+ height: 630,+ }),+ // update the null image we set earlier to the uploaded image URL+ prisma.link.update({+ where: {+ id: response.id,+ },+ data: {+ image: uploadedImageUrl,+ },+ }),+ ]+ : []),+ // delete public links after 30 mins+ !response.userId &&+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/delete`,+ // delete after 30 mins+ delay: 30 * 60,+ body: {+ linkId: response.id,+ },+ }),+ // update links usage for workspace+ link.projectId &&+ prisma.project.update({+ where: {+ id: link.projectId,+ },+ data: {+ linksUsage: {+ increment: 1,+ },+ },+ }),+ // if the link is a dub.sh link, do some checks+ link.domain === "dub.sh" && dubLinkChecks(link),+ ]);++ const shortLink = linkConstructor({+ domain: response.domain,+ key: response.key,+ });+ const tags = response.tags.map(({ tag }) => tag);+ return {+ ...response,+ // optimistically set the image URL to the uploaded image URL+ image:+ proxy && image && !isStored(image) ? uploadedImageUrl : response.image,+ tagId: tags?.[0]?.id ?? null, // backwards compatibility+ tags,+ shortLink,+ qrCode: `https://api.dub.co/qr?url=${shortLink}`,+ workspaceId: `ws_${response.projectId}`,+ };+ }diff --cc apps/web/lib/api/links/edit-link.tsindex 0000000000,414658835b..b7889cf950mode 000000,100644..100644--- a/apps/web/lib/api/links/edit-link.ts+++ b/apps/web/lib/api/links/edit-link.ts@@@ -1,0 -1,143 +1,143 @@@+ import prisma from "@/lib/prisma";+ import { isStored, storage } from "@/lib/storage";+ import { recordLink } from "@/lib/tinybird";-import { LinkWithTagIdsProps } from "@/lib/types";++import { LinkProps, ProcessedLinkProps } from "@/lib/types";+ import { formatRedisLink, redis } from "@/lib/upstash";+ import {+ SHORT_DOMAIN,+ getParamsFromURL,+ linkConstructor,+ truncate,+ } from "@dub/utils";+ import { Prisma } from "@prisma/client";+ import { combineTagIds } from "./utils";++ export async function editLink({+ oldDomain = SHORT_DOMAIN,+ oldKey,+ updatedLink,+ }: {+ oldDomain?: string;+ oldKey: string;- updatedLink: LinkWithTagIdsProps;++ updatedLink: ProcessedLinkProps &++ Pick<LinkProps, "id" | "clicks" | "lastClicked" | "updatedAt">;+ }) {+ let {+ id,+ domain,+ key,+ url,+ expiresAt,+ title,+ description,+ image,+ proxy,+ geo,+ } = updatedLink;+ const changedKey = key.toLowerCase() !== oldKey.toLowerCase();+ const changedDomain = domain !== oldDomain;++ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =+ getParamsFromURL(url);++ // exclude fields that should not be updated+ const {+ id: _,+ clicks,+ lastClicked,+ updatedAt,+ tagId,+ tagIds,+ ...rest+ } = updatedLink;++ const combinedTagIds = combineTagIds({ tagId, tagIds });++ if (proxy && image && !isStored(image)) {+ // only upload image if proxy is true and image is not stored in R2+ await storage.upload(`images/${id}`, image, {+ width: 1200,+ height: 630,+ });+ }+- const [response, ..._effects] = await Promise.all([- prisma.link.update({- where: {- id,- },- data: {- ...rest,- key,- title: truncate(title, 120),- description: truncate(description, 240),- image:- proxy && image && !isStored(image)- ? `${process.env.STORAGE_BASE_URL}/images/${id}`- : image,- utm_source,- utm_medium,- utm_campaign,- utm_term,- utm_content,- expiresAt: expiresAt ? new Date(expiresAt) : null,- geo: geo || Prisma.JsonNull,- tags: {- deleteMany: {- tagId: {- notIn: combinedTagIds,- },++ const response = await prisma.link.update({++ where: {++ id,++ },++ data: {++ ...rest,++ key,++ title: truncate(title, 120),++ description: truncate(description, 240),++ image:++ proxy && image && !isStored(image)++ ? `${process.env.STORAGE_BASE_URL}/images/${id}`++ : image,++ utm_source,++ utm_medium,++ utm_campaign,++ utm_term,++ utm_content,++ expiresAt: expiresAt ? new Date(expiresAt) : null,++ geo: geo || Prisma.JsonNull,++ tags: {++ deleteMany: {++ tagId: {++ notIn: combinedTagIds,+ },- connectOrCreate: combinedTagIds.map((tagId) => ({- where: { linkId_tagId: { linkId: id, tagId } },- create: { tagId },- })),+ },++ connectOrCreate: combinedTagIds.map((tagId) => ({++ where: { linkId_tagId: { linkId: id, tagId } },++ create: { tagId },++ })),+ },- include: {- tags: {- select: {- tag: {- select: {- id: true,- name: true,- color: true,- },++ },++ include: {++ tags: {++ select: {++ tag: {++ select: {++ id: true,++ name: true,++ color: true,+ },+ },+ },+ },- }),++ },++ });++++ await Promise.all([+ // record link in Redis+ redis.hset(updatedLink.domain, {- [updatedLink.key.toLowerCase()]: await formatRedisLink(updatedLink),++ [updatedLink.key.toLowerCase()]: await formatRedisLink(response),+ }),+ // record link in Tinybird+ recordLink({+ link: {- ...updatedLink,- tags: updatedLink.tagIds.map((tagId) => ({- tagId,- })),++ ...response,++ tags: [],+ },+ }),+ // if key is changed: delete the old key in Redis+ (changedDomain || changedKey) &&+ redis.hdel(oldDomain, oldKey.toLowerCase()),+ ]);++ const shortLink = linkConstructor({+ domain: response.domain,+ key: response.key,+ });++ const tags = response.tags.map(({ tag }) => tag);++ return {+ ...response,+ tagId: tags?.[0]?.id ?? null, // backwards compatibility+ tags,+ shortLink,+ qrCode: `https://api.dub.co/qr?url=${shortLink}`,+ workspaceId: `ws_${response.projectId}`,+ };+ }diff --cc apps/web/lib/api/links/get-links-for-workspace.tsindex 0000000000,82f765cd13..1c66d9bfcbmode 000000,100644..100644--- a/apps/web/lib/api/links/get-links-for-workspace.ts+++ b/apps/web/lib/api/links/get-links-for-workspace.ts@@@ -1,0 -1,88 +1,103 @@@+ import prisma from "@/lib/prisma";+ import z from "@/lib/zod";+ import { getLinksQuerySchema } from "@/lib/zod/schemas/links";+ import { linkConstructor } from "@dub/utils";+ import { combineTagIds } from "./utils";++ export async function getLinksForWorkspace({+ workspaceId,+ domain,+ tagId,+ tagIds,++ tagNames,+ search,+ sort = "createdAt",+ page,+ userId,+ showArchived,+ withTags,+ }: z.infer<typeof getLinksQuerySchema> & {+ workspaceId: string;+ }) {+ const combinedTagIds = combineTagIds({ tagId, tagIds });++ const links = await prisma.link.findMany({+ where: {+ projectId: workspaceId,+ archived: showArchived ? undefined : false,+ ...(domain && { domain }),+ ...(search && {+ OR: [+ {+ key: { contains: search },+ },+ {+ url: { contains: search },+ },+ ],+ }),+ ...(withTags && {+ tags: {+ some: {},+ },+ }),- ...(combinedTagIds.length > 0 && {- tags: { some: { tagId: { in: combinedTagIds } } },- }),++ ...(combinedTagIds.length > 0++ ? {++ tags: { some: { tagId: { in: combinedTagIds } } },++ }++ : tagNames++ ? {++ tags: {++ some: {++ tag: {++ name: {++ in: tagNames,++ },++ },++ },++ },++ }++ : {}),+ ...(userId && { userId }),+ },+ include: {+ user: true,+ tags: {+ include: {+ tag: {+ select: {+ id: true,+ name: true,+ color: true,+ },+ },+ },+ },+ },+ orderBy: {+ [sort]: "desc",+ },+ take: 100,+ ...(page && {+ skip: (page - 1) * 100,+ }),+ });++ return links.map((link) => {+ const shortLink = linkConstructor({+ domain: link.domain,+ key: link.key,+ });++ const tags = link.tags.map(({ tag }) => tag);++ return {+ ...link,+ tagId: tags?.[0]?.id ?? null, // backwards compatibility+ tags,+ shortLink,+ qrCode: `https://api.dub.co/qr?url=${shortLink}`,+ workspaceId: `ws_${link.projectId}`,+ };+ });+ }diff --cc apps/web/lib/api/links/process-link.tsindex 0000000000,4ff1be55f9..af692a740fmode 000000,100644..100644--- a/apps/web/lib/api/links/process-link.ts+++ b/apps/web/lib/api/links/process-link.ts@@@ -1,0 -1,238 +1,267 @@@-import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/edge-config";++import { isBlacklistedDomain } from "@/lib/edge-config";+ import { getRandomKey } from "@/lib/planetscale";+ import prisma from "@/lib/prisma";-import { LinkWithTagIdsProps, WorkspaceProps } from "@/lib/types";++import { NewLinkProps, ProcessedLinkProps, WorkspaceProps } from "@/lib/types";+ import {+ DUB_DOMAINS,+ SHORT_DOMAIN,+ getDomainWithoutWWW,+ getUrlFromString,+ isDubDomain,+ isValidUrl,+ } from "@dub/utils";+ import { combineTagIds, keyChecks, processKey } from "./utils";+-export async function processLink({++export async function processLink<T extends Record<string, any>>({+ payload,+ workspace,+ userId,+ bulk = false,+ skipKeyChecks = false, // only skip when key doesn't change (e.g. when editing a link)+ }: {- payload: LinkWithTagIdsProps;++ payload: NewLinkProps & T;+ workspace?: WorkspaceProps;+ userId?: string;+ bulk?: boolean;+ skipKeyChecks?: boolean;-}) {++}): Promise<++ | {++ link: NewLinkProps & T;++ error: string;++ code?: string;++ status?: number;++ }++ | {++ link: ProcessedLinkProps & T;++ error: null;++ code?: never;++ status?: never;++ }++> {+ let {+ domain,+ key,+ url,+ image,+ proxy,+ password,+ rewrite,+ expiresAt,+ ios,+ android,+ geo,++ tagNames,+ } = payload;++ const tagIds = combineTagIds(payload);++ // url checks+ if (!url) {+ return {+ link: payload,+ error: "Missing destination url.",+ code: "bad_request",+ };+ }+ const processedUrl = getUrlFromString(url);+ if (!isValidUrl(processedUrl)) {+ return {+ link: payload,+ error: "Invalid destination url.",+ code: "unprocessable_entity",+ };+ }++ // free plan restrictions+ if (!workspace || workspace.plan === "free") {+ if (proxy || password || rewrite || expiresAt || ios || android || geo) {+ return {+ link: payload,+ error:+ "You can only use custom social media cards, password-protection, link cloaking, link expiration, device and geo targeting on a Pro plan and above. Upgrade to Pro to use these features.",+ code: "forbidden",+ };+ }+ }++ // if domain is not defined, set it to the workspace's primary domain+ if (!domain) {+ domain = workspace?.domains?.find((d) => d.primary)?.slug || SHORT_DOMAIN;+ }++ // checks for default short domain+ if (domain === SHORT_DOMAIN) {- const keyBlacklisted = await isBlacklistedKey(key);- if (keyBlacklisted) {- return {- link: payload,- error: "Invalid key.",- code: "unprocessable_entity",- };- }+ const domainBlacklisted = await isBlacklistedDomain(url);+ if (domainBlacklisted) {+ return {+ link: payload,+ error: "Invalid url.",+ code: "unprocessable_entity",+ };+ }++ // checks for other Dub-owned domains (chatg.pt, spti.fi, etc.)+ } else if (isDubDomain(domain)) {+ // coerce type with ! cause we already checked if it exists+ const { allowedHostnames } = DUB_DOMAINS.find((d) => d.slug === domain)!;+ const urlDomain = getDomainWithoutWWW(url) || "";+ if (allowedHostnames && !allowedHostnames.includes(urlDomain)) {+ return {+ link: payload,+ error: `Invalid url. You can only use ${domain} short links for URLs starting with ${allowedHostnames+ .map((d) => `\`${d}\``)+ .join(", ")}.`,+ code: "unprocessable_entity",+ };+ }++ // else, check if the domain belongs to the workspace+ } else if (!workspace?.domains?.find((d) => d.slug === domain)) {+ return {+ link: payload,+ error: "Domain does not belong to workspace.",+ code: "forbidden",+ };+ }++ if (!key) {+ key = await getRandomKey({+ domain,+ prefix: payload["prefix"],+ long: domain === "loooooooo.ng",+ });+ } else if (!skipKeyChecks) {+ const processedKey = processKey(key);+ if (processedKey === null) {+ return {+ link: payload,+ error: "Invalid key.",+ code: "unprocessable_entity",+ };+ }+ key = processedKey;++ const response = await keyChecks({ domain, key, workspace });+ if (response.error) {+ return {+ link: payload,+ ...response,+ };+ }+ }++ if (bulk) {+ if (image) {+ return {+ link: payload,+ error: "You cannot set custom social cards with bulk link creation.",+ code: "unprocessable_entity",+ };+ }+ if (rewrite) {+ return {+ link: payload,+ error: "You cannot use link cloaking with bulk link creation.",+ code: "unprocessable_entity",+ };+ }++ // only perform tag validity checks if:+ // - not bulk creation (we do that check separately in the route itself)+ // - tagIds are present+ } else if (tagIds.length > 0) {+ const tags = await prisma.tag.findMany({+ select: {+ id: true,+ },+ where: { projectId: workspace?.id, id: { in: tagIds } },+ });++ if (tags.length !== tagIds.length) {+ return {+ link: payload,+ error:+ "Invalid tagIds detected: " ++ tagIds+ .filter(+ (tagId) => tags.find(({ id }) => tagId === id) === undefined,+ )+ .join(", "),+ code: "unprocessable_entity",+ };+ }++ } else if (tagNames && tagNames.length > 0) {++ const tags = await prisma.tag.findMany({++ select: {++ name: true,++ },++ where: {++ projectId: workspace?.id,++ name: { in: tagNames },++ },++ });++++ if (tags.length !== tagNames.length) {++ return {++ link: payload,++ error:++ "Invalid tagNames detected: " +++ tagNames++ .filter(++ (tagName) =>++ tags.find(({ name }) => tagName === name) === undefined,++ )++ .join(", "),++ status: 422,++ };++ }+ }++ // custom social media image checks (see if R2 is configured)+ if (proxy && !process.env.STORAGE_SECRET_ACCESS_KEY) {+ return {+ link: payload,+ error: "Missing storage access key.",+ code: "bad_request",+ };+ }++ // expire date checks+ if (expiresAt) {+ const date = new Date(expiresAt);+ if (isNaN(date.getTime())) {+ return {+ link: payload,+ error: "Invalid expiry date. Expiry date must be in ISO-8601 format.",+ code: "unprocessable_entity",+ };+ }+ // check if expiresAt is in the future+ if (new Date(expiresAt) < new Date()) {+ return {+ link: payload,+ error: "Expiry date must be in the future.",+ code: "unprocessable_entity",+ };+ }+ }++ // remove polyfill attributes from payload+ delete payload["shortLink"];+ delete payload["qrCode"];+ delete payload["prefix"];++ return {+ link: {+ ...payload,+ domain,+ key,+ url: processedUrl,+ // make sure projectId is set to the current workspace+ projectId: workspace?.id || null,+ // if userId is passed, set it (we don't change the userId if it's already set, e.g. when editing a link)- ...(userId && {- userId,- }),++ userId: userId || payload.userId || null,+ },+ error: null,+ };+ }diff --cc apps/web/lib/api/links/utils.tsindex 0000000000,3b4715ab1e..662527f5cfmode 000000,100644..100644--- a/apps/web/lib/api/links/utils.ts+++ b/apps/web/lib/api/links/utils.ts@@@ -1,0 -1,119 +1,128 @@@-import { isReservedKey, isReservedUsername } from "@/lib/edge-config";++import {++ isBlacklistedKey,++ isReservedKey,++ isReservedUsername,++} from "@/lib/edge-config";+ import { checkIfKeyExists } from "@/lib/planetscale";+ import { SimpleLinkProps, WorkspaceProps } from "@/lib/types";+ import {+ DEFAULT_REDIRECTS,+ GOOGLE_FAVICON_URL,+ SHORT_DOMAIN,+ getApexDomain,+ isDubDomain,+ log,+ validKeyRegex,+ } from "@dub/utils";++ export function combineTagIds({+ tagId,+ tagIds,+ }: {+ tagId?: string | null;+ tagIds?: string[];+ }): string[] {+ // Use tagIds if present, fall back to tagId+ if (tagIds && Array.isArray(tagIds) && tagIds.length > 0) {+ return tagIds;+ }+ return tagId ? [tagId] : [];+ }++ export async function keyChecks({+ domain,+ key,+ workspace,+ }: {+ domain: string;+ key: string;+ workspace?: WorkspaceProps;+ }) {+ if (key.length === 0) {+ if (workspace?.plan === "free") {+ return {+ error:+ "You can only set a redirect for your root domain on a Pro plan and above. Upgrade to Pro to unlock this feature.",+ code: "forbidden",+ };+ } else {+ return {+ error:+ "To set a redirect for your root domain, navigate to your Domains tab and click 'Edit' on the domain you want to update.",+ code: "unprocessable_entity",+ };+ }+ }++ const link = await checkIfKeyExists(domain, key);+ if (link) {+ return {+ error: "Duplicate key: This short link already exists.",+ code: "conflict",+ };+ }++ if (isDubDomain(domain) && process.env.NEXT_PUBLIC_IS_DUB) {- if (- domain === SHORT_DOMAIN &&- (DEFAULT_REDIRECTS[key] || (await isReservedKey(key)))- ) {- return {- error: "Duplicate key: This short link already exists.",- code: "conflict",- };++ if (domain === SHORT_DOMAIN) {++ if (DEFAULT_REDIRECTS[key] || (await isReservedKey(key))) {++ return {++ error: "Duplicate key: This short link already exists.",++ code: "conflict",++ };++ }++ if (await isBlacklistedKey(key)) {++ return {++ error: "Invalid key.",++ code: "unprocessable_entity",++ };++ }+ }++ if (key.length <= 3 && (!workspace || workspace.plan === "free")) {+ return {+ error: `You can only use keys that are 3 characters or less on a Pro plan and above. Upgrade to Pro to register a ${key.length}-character key.`,+ code: "forbidden",+ };+ }+ if (+ (await isReservedUsername(key)) &&+ (!workspace || workspace.plan === "free")+ ) {+ return {+ error:+ "This is a premium key. You can only use this key on a Pro plan and above. Upgrade to Pro to register this key.",+ code: "forbidden",+ };+ }+ }+ return {+ error: null,+ };+ }++ export function processKey(key: string) {+ if (!validKeyRegex.test(key)) {+ return null;+ }+ // remove all leading and trailing slashes from key+ key = key.replace(/^\/+|\/+$/g, "");+ // replace all special characters+ key = key.normalize("NFD").replace(/[\u0300-\u036f]/g, "");++ return key;+ }++ export async function dubLinkChecks(link: SimpleLinkProps) {+ const invalidFavicon = await fetch(+ `${GOOGLE_FAVICON_URL}${getApexDomain(link.url)}`,+ ).then((res) => !res.ok);++ if (invalidFavicon) {+ return await log({+ message: `Suspicious link detected: ${link.domain}/${link.key} → ${link.url}`,+ type: "links",+ mention: true,+ });+ }+ return null;+ }diff --cc apps/web/lib/zod/schemas/links.tsindex fbda47d646,31c9fd98ee..2d7ddb93c6--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@@ -1,8 -1,22 +1,23 @@@import z from "@/lib/zod";+ import { getUrlFromString, isValidUrl, validDomainRegex } from "@dub/utils";import { booleanQuerySchema } from ".";import { TagSchema } from "./tags";+import { getRandomKey } from "@/lib/planetscale";+ export const getUrlQuerySchema = z.object({+ url: z+ .string()+ .transform((v) => getUrlFromString(v))+ .refine((v) => isValidUrl(v), { message: "Invalid URL" }),+ });++ export const getDomainQuerySchema = z.object({+ domain: z+ .string()+ .min(1, "Missing required `domain` query parameter.")+ .refine((v) => validDomainRegex.test(v), { message: "Invalid domain" }),+ });+const LinksQuerySchema = z.object({domain: z.string()