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 Wilsonf86b0f7780b1
diff --cc apps/web/app/api/route.tsindex 7927d7a015,a045ebb5f0..168f2b8a00--- a/apps/web/app/api/route.ts+++ b/apps/web/app/api/route.ts@@@ -1,6 -1,6 +1,6 @@@- import { COLORS_LIST } from "@/ui/links/tag-badge";++import { openApiObject } from "@/lib/openapi";import { NextResponse } from "next/server";- import { OpenAPIV3 } from "openapi-types";+ import { createDocument } from "zod-openapi";-import { openApiObject } from "@/lib/openapi";export const runtime = "edge";diff --cc apps/web/lib/api/links.tsindex 6853f2a7c5,62b27a998a..83d4f5b629--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@@ -27,23 -31,9 +31,24 @@@ importLinkWithTagIdsProps,ProjectProps,RedisLinkProps,+ TagProps,} from "../types";+ import z from "../zod";+const includeTags = {+ tags: {+ include: {+ tag: {+ select: {+ id: true,+ name: true,+ color: true,+ },+ },+ },+ },+};+export async function getLinksForProject({projectId,domain,@@@ -659,9 -645,20 +646,20 @@@ export async function bulkCreateLinks(// create link tags for valid tagIdslinkTags.length > 0 &&prisma.linkTag.createMany({- data: linkTags.filter(({ tagId }) => validTagIds.includes(tagId)),+ data: validLinkTags,skipDuplicates: true,}),+ // update links usage+ prisma.project.update({+ where: {+ id: createdLinks[0].projectId!, // this will always be present+ },+ data: {+ linksUsage: {+ increment: createdLinks.length,+ },+ },+ }),]);return createdLinks.map((link) => {@@@ -758,22 -767,20 +776,7 @@@ export async function editLink(})),},},- include: {- tags: {- select: {- tag: {- select: {- id: true,- name: true,- color: true,- },- },- },- },- },}),- ...(process.env.CLOUDINARY_URL- ? [- // only upload image to cloudinary if proxy is true and there's an image- proxy && image- ? cloudinary.v2.uploader.upload(image, {- public_id: key,- folder: domain,- overwrite: true,- invalidate: true,- })- : cloudinary.v2.uploader.destroy(`${domain}/${key}`, {- invalidate: true,- }),- ]- : []),// if key is changed: rename resource in Cloudinary, delete the old key in Redis and change the clicks key name...(changedDomain || changedKey? [diff --cc apps/web/lib/auth/index.tsindex bc554a3475,7c257df47d..99cc748eae--- a/apps/web/lib/auth/index.ts+++ b/apps/web/lib/auth/index.ts@@@ -53,31 -54,39 +54,39 @@@ interface WithAuthHandlersession: Session;project: ProjectProps;domain: string;- link?: LinkProps;+ link?: LinkProps & { tags: TagProps[] };}): Promise<Response>;}- export const withAuth =- (- handler: WithAuthHandler,- {- requiredPlan = ["free", "pro", "business", "enterprise"], // if the action needs a specific plan- requiredRole = ["owner", "member"],- needNotExceededClicks, // if the action needs the user to not have exceeded their clicks usage- needNotExceededLinks, // if the action needs the user to not have exceeded their links usage- allowAnonymous, // special case for /api/links (POST /api/links) – allow no session- allowSelf, // special case for removing yourself from a project- skipLinkChecks, // special case for /api/links/exists – skip link checks- }: {- requiredPlan?: Array<PlanProps>;- requiredRole?: Array<"owner" | "member">;- needNotExceededClicks?: boolean;- needNotExceededLinks?: boolean;- allowAnonymous?: boolean;- allowSelf?: boolean;- skipLinkChecks?: boolean;- } = {},- ) =>- async (++ export const withAuth = (+ handler: WithAuthHandler,+ {+ requiredPlan = [+ "free",+ "pro",+ "business",+ "business plus",+ "business max",+ "business extra",+ "enterprise",+ ], // if the action needs a specific plan+ requiredRole = ["owner", "member"],+ needNotExceededClicks, // if the action needs the user to not have exceeded their clicks usage+ needNotExceededLinks, // if the action needs the user to not have exceeded their links usage+ allowAnonymous, // special case for /api/links (POST /api/links) – allow no session+ allowSelf, // special case for removing yourself from a project+ skipLinkChecks, // special case for /api/links/exists – skip link checks+ }: {+ requiredPlan?: Array<PlanProps>;+ requiredRole?: Array<"owner" | "member">;+ needNotExceededClicks?: boolean;+ needNotExceededLinks?: boolean;+ allowAnonymous?: boolean;+ allowSelf?: boolean;+ skipLinkChecks?: boolean;+ } = {},+ ) => {+ return async (req: Request,{ params }: { params: Record<string, string> | undefined },) => {@@@ -121,310 -105,326 +105,348 @@@},);}- const apiKey = authorizationHeader.replace("Bearer ", "");+ apiKey = authorizationHeader.replace("Bearer ", "");+ }- const url = new URL(req.url || "", API_DOMAIN);+ const domain = params?.domain || searchParams.domain;+ const key = searchParams.key;- if (url.pathname.includes("/analytics")) {- return new Response("API access is not available for Analytics yet.", {- status: 403,- });+ let session: Session | undefined;+ let headers = {};++ const slug = params?.slug || searchParams.projectSlug;++ try {+ // if there's no projectSlug defined+ if (!slug) {+ // for /api/links (POST /api/links) – allow no session (but warn if user provides apiKey)+ if (allowAnonymous && !apiKey) {+ // @ts-expect-error+ return await handler({+ req,+ params: params || {},+ searchParams,+ headers,+ });+ } else {+ throw new DubApiError({+ code: "not_found",+ message:+ "Project slug not found. Did you forget to include a `projectSlug` query parameter?",+ });+ }}- const hashedKey = hashToken(apiKey, {- noSecret: true,- });+ if (apiKey) {+ const hashedKey = hashToken(apiKey, {+ noSecret: true,+ });- const user = await prisma.user.findFirst({- where: {- tokens: {- some: {- hashedKey,+ const user = await prisma.user.findFirst({+ where: {+ tokens: {+ some: {+ hashedKey,+ },},},- },- select: {- id: true,- name: true,- email: true,- },- });- if (!user) {- return new Response("Unauthorized: Invalid API key.", {- status: 401,+ select: {+ id: true,+ name: true,+ email: true,+ },});- }-- const { success, limit, reset, remaining } = await ratelimit(- 10,- "1 s",- ).limit(apiKey);-- headers = {- "Retry-After": reset.toString(),- "X-RateLimit-Limit": limit.toString(),- "X-RateLimit-Remaining": remaining.toString(),- "X-RateLimit-Reset": reset.toString(),- };+ if (!user) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Unauthorized: Invalid API key.",+ });+ }- if (!success) {- return new Response("Too many requests.", {- status: 429,- headers,- });- }- await prisma.token.update({- where: {- hashedKey,- },- data: {- lastUsed: new Date(),- },- });- session = {- user: {- id: user.id,- name: user.name || "",- email: user.email || "",- },- };- } else {- session = await getSession();- if (!session?.user?.id) {- return new Response("Unauthorized: Login required.", {- status: 401,- headers,+ const { success, limit, reset, remaining } = await ratelimit(+ 10,+ "1 s",+ ).limit(apiKey);++ headers = {+ "Retry-After": reset.toString(),+ "X-RateLimit-Limit": limit.toString(),+ "X-RateLimit-Remaining": remaining.toString(),+ "X-RateLimit-Reset": reset.toString(),+ };++ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Too many requests.",+ });+ }+ await prisma.token.update({+ where: {+ hashedKey,+ },+ data: {+ lastUsed: new Date(),+ },});+ session = {+ user: {+ id: user.id,+ name: user.name || "",+ email: user.email || "",+ },+ };+ } else {+ session = await getSession();+ if (!session?.user?.id) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Unauthorized: Login required.",+ });+ }}- }- const includeTags = {- tags: {- include: {- tag: {- select: {- id: true,- name: true,- color: true,++ const includeTags = {++ tags: {++ include: {++ tag: {++ select: {++ id: true,++ name: true,++ color: true,++ },+ },+ },+ },- },- };++ };+- let [project, link] = (await Promise.all([- prisma.project.findUnique({- where: {- slug,- },- select: {- id: true,- name: true,- slug: true,- logo: true,- usage: true,- usageLimit: true,- linksUsage: true,- linksLimit: true,- domainsLimit: true,- tagsLimit: true,- usersLimit: true,- plan: true,- stripeId: true,- billingCycleStart: true,- createdAt: true,- users: {- where: {- userId: session.user.id,- },- select: {- role: true,- },+ let [project, link] = (await Promise.all([+ prisma.project.findUnique({+ where: {+ slug,},- domains: {- select: {- slug: true,- primary: true,+ select: {+ id: true,+ name: true,+ slug: true,+ logo: true,+ usage: true,+ usageLimit: true,+ linksUsage: true,+ linksLimit: true,+ domainsLimit: true,+ tagsLimit: true,+ usersLimit: true,+ plan: true,+ stripeId: true,+ billingCycleStart: true,+ createdAt: true,+ users: {+ where: {+ userId: session.user.id,+ },+ select: {+ role: true,+ },},- },- inviteCode: true,- metadata: true,- },- }),- linkId- ? prisma.link.findUnique({- where: {- id: linkId,+ domains: {+ select: {+ slug: true,+ primary: true,+ },},- include: includeTags,- })- : domain &&- key &&- (key === "_root"- ? prisma.domain.findUnique({- where: {- slug: domain,- },- })- : prisma.link.findUnique({- where: {- domain_key: {- domain,- key,+ inviteCode: true,+ metadata: true,+ },+ }),+ linkId+ ? prisma.link.findUnique({+ where: {+ id: linkId,+ },++ include: includeTags,+ })+ : domain &&+ key &&+ (key === "_root"+ ? prisma.domain.findUnique({+ where: {+ slug: domain,},- },- include: includeTags,- })),- ])) as [- ProjectProps,- (LinkProps & { tags?: { tag: TagProps }[] }) | undefined,- ];-- if (!project || !project.users) {- // project doesn't exist- return new Response("Project not found.", {- status: 404,- headers,- });- }+ })+ : prisma.link.findUnique({+ where: {+ domain_key: {+ domain,+ key,+ },+ },++ include: includeTags,+ })),- ])) as [ProjectProps, LinkProps | undefined];++ ])) as [++ ProjectProps,++ (LinkProps & { tags?: { tag: TagProps }[] }) | undefined,++ ];++ if (!project || !project.users) {+ // project doesn't exist+ throw new DubApiError({+ code: "not_found",+ message: "Project not found.",+ });+ }- // prevent unauthorized access to domains that don't belong to the project- if (- domain &&- !isDubDomain(domain) &&- !project.domains.find((d) => d.slug === domain)- ) {- return new Response("Domain does not belong to project.", {- status: 403,- headers,- });- }+ // prevent unauthorized access to domains that don't belong to the project+ if (+ domain &&+ !isDubDomain(domain) &&+ !project.domains.find((d) => d.slug === domain)+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: "Domain does not belong to project.",+ });+ }- // project exists but user is not part of it- if (project.users.length === 0) {- const pendingInvites = await prisma.projectInvite.findUnique({- where: {- email_projectId: {- email: session.user.email,- projectId: project.id,+ // project exists but user is not part of it+ if (project.users.length === 0) {+ const pendingInvites = await prisma.projectInvite.findUnique({+ where: {+ email_projectId: {+ email: session.user.email,+ projectId: project.id,+ },+ },+ select: {+ expires: true,},- },- select: {- expires: true,- },- });- if (!pendingInvites) {- return new Response("Project not found.", {- status: 404,- headers,});- } else if (pendingInvites.expires < new Date()) {- return new Response("Project invite expired.", {- status: 410,- headers,+ if (!pendingInvites) {+ throw new DubApiError({+ code: "not_found",+ message: "Project not found.",+ });+ } else if (pendingInvites.expires < new Date()) {+ throw new DubApiError({+ code: "invite_expired",+ message: "Project invite expired.",+ });+ } else {+ throw new DubApiError({+ code: "invite_pending",+ message: "Project invite pending.",+ });+ }+ }++ // project role checks+ if (+ !requiredRole.includes(project.users[0].role) &&+ !(allowSelf && searchParams.userId === session.user.id)+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: "Unauthorized: Insufficient permissions.",});- } else {- return new Response("Project invite pending.", {- status: 409,- headers,+ }++ // clicks usage overage checks+ if (needNotExceededClicks && project.usage > project.usageLimit) {+ throw new DubApiError({+ code: "forbidden",+ message: exceededLimitError({+ plan: project.plan,+ limit: project.usageLimit,+ type: "clicks",+ }),});}- }- // project role checks- if (- !requiredRole.includes(project.users[0].role) &&- !(allowSelf && searchParams.userId === session.user.id)- ) {- return new Response("Unauthorized: Insufficient permissions.", {- status: 403,- headers,- });- }+ // links usage overage checks+ if (+ needNotExceededLinks &&+ project.linksUsage > project.linksLimit &&+ (project.plan === "free" || project.plan === "pro")+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: exceededLimitError({+ plan: project.plan,+ limit: project.linksLimit,+ type: "links",+ }),+ });+ }- // clicks usage overage checks- if (needNotExceededClicks && project.usage > project.usageLimit) {- return new Response(- exceededLimitError({- plan: project.plan,- limit: project.usageLimit,- type: "clicks",- }),- {- status: 403,- headers,- },- );- }+ // plan checks+ if (!requiredPlan.includes(project.plan)) {+ throw new DubApiError({+ code: "forbidden",+ message: "Unauthorized: Need higher plan.",+ });+ }- // links usage overage checks- if (- needNotExceededLinks &&- project.linksUsage > project.linksLimit &&- (project.plan === "free" || project.plan === "pro")- ) {- return new Response(- exceededLimitError({- plan: project.plan,- limit: project.linksLimit,- type: "links",- }),- {- status: 403,- headers,- },- );- }+ // analytics API checks+ const url = new URL(req.url || "", API_DOMAIN);+ if (+ project.plan === "free" &&+ apiKey &&+ url.pathname.includes("/analytics")+ ) {+ throw new DubApiError({+ code: "forbidden",+ message: "Analytics API is only available on paid plans.",+ });+ }- // plan checks- if (!requiredPlan.includes(project.plan)) {- // return res.status(403).end("Unauthorized: Need higher plan.");- return new Response("Unauthorized: Need higher plan.", {- status: 403,- headers,- });- }+ // link checks (if linkId or domain and key are provided)+ if ((linkId || (domain && key && key !== "_root")) && !skipLinkChecks) {+ // special case for getting domain by ID+ // TODO: refactor domains to use the same logic as links+ if (!link && searchParams.checkDomain === "true") {+ const domain = await prisma.domain.findUnique({+ where: {+ id: linkId,+ },+ });+ if (domain) {+ link = {+ ...domain,+ domain: domain.slug,+ key: "_root",+ url: domain.target || "",+ } as unknown as LinkProps;+ }+ }- // link checks (if linkId or domain and key are provided)- if ((linkId || (domain && key && key !== "_root")) && !skipLinkChecks) {- // special case for getting domain by ID- // TODO: refactor domains to use the same logic as links- if (!link && searchParams.checkDomain === "true") {- const domain = await prisma.domain.findUnique({- where: {- id: linkId,- },- });- if (domain) {- link = {- ...domain,- domain: domain.slug,- key: "_root",- url: domain.target || "",- } as unknown as LinkProps;+ // make sure the link is owned by the project+ if (!link || link.projectId !== project?.id) {+ throw new DubApiError({+ code: "not_found",+ message: "Link not found.",+ });}}- // make sure the link is owned by the project- if (!link || link.projectId !== project?.id) {- return new Response("Link not found.", {- status: 404,- headers,- });- }+ return await handler({+ req,+ params: params || {},+ searchParams,+ headers,+ session,+ project,+ domain,- link,++ link: link && {++ ...link,++ tags: link?.tags?.map(({ tag }) => tag) ?? [],++ },+ });+ } catch (error) {+ console.error("withAuth Error -->", error.message);+ return handleAndReturnErrorResponse(error);}-- return handler({- req,- params: params || {},- searchParams,- headers,- session,- project,- domain,- link: link && { ...link, tags: link?.tags?.map(({ tag }) => tag) ?? [] },- });};+ };interface WithSessionHandler {({