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 feat/improve-api
Kiran K2a6e07df8e3b
diff --cc apps/web/app/api/analytics/route.tsindex 18c66f82c7,84e82dc61f..5383298f8c--- a/apps/web/app/api/analytics/route.ts+++ b/apps/web/app/api/analytics/route.ts@@@ -1,52 -1,34 +1,52 @@@import { withAuth } from "@/lib/auth";-import { getDomainOrLink } from "@/lib/planetscale";+import { handleAndReturnErrorResponse } from "@/lib/errors";import prisma from "@/lib/prisma";+import z, { domainKeySchema } from "@/lib/zod";import { NextResponse } from "next/server";+const updatePublicStatsSchema = z.object({+ publicStats: z.boolean(),+});+- // GET /api/stats – get the publicStats setting for a link+ // GET /api/analytics – get the publicStats setting for a linkexport const GET = withAuth(async ({ searchParams }) => {- const { domain, key } = searchParams;- if (!domain || !key) {- return new Response("Missing domain or key", { status: 400 });+ try {+ const { domain, key } = domainKeySchema.parse(searchParams);+ const response = await prisma.link.findUnique({+ where: {+ domain_key: {+ domain,+ key,+ },+ },+ select: {+ publicStats: true,+ },+ });+ return NextResponse.json(response);+ } catch (error) {+ return handleAndReturnErrorResponse(error);}- const response = await getDomainOrLink({ domain, key });- return NextResponse.json(response);});- // PUT /api/stats – update the publicStats setting for a link+ // PUT /api/analytics – update the publicStats setting for a linkexport const PUT = withAuth(async ({ req, searchParams }) => {- const { domain, key } = searchParams;- if (!domain || !key) {- return new Response("Missing domain or key", { status: 400 });+ try {+ const { domain, key } = domainKeySchema.parse(searchParams);+ const { publicStats } = updatePublicStatsSchema.parse(await req.json());+ const response = await prisma.link.update({+ where: {+ domain_key: {+ domain,+ key,+ },+ },+ data: {+ publicStats,+ },+ });+ return NextResponse.json(response);+ } catch (error) {+ return handleAndReturnErrorResponse(error);}- const { publicStats } = await req.json();- const response =- key === "_root"- ? await prisma.domain.update({- where: { slug: domain },- data: { publicStats },- })- : await prisma.link.update({- where: { domain_key: { domain, key } },- data: { publicStats },- });- return NextResponse.json(response);});diff --cc apps/web/lib/auth/index.tsindex 6885262ed7,aea552bcfe..01905c07bc--- a/apps/web/lib/auth/index.ts+++ b/apps/web/lib/auth/index.ts@@@ -92,301 -91,297 +92,301 @@@ export const withAuthlet session: Session | undefined;let headers = {};- // if there's no projectSlug defined- if (!slug) {- if (allowAnonymous) {- // @ts-expect-error- return handler({- req,- params: params || {},- searchParams,- headers,- });- } else {- return new Response(- "Project slug not found. Did you forget to include a `projectSlug` query parameter?",- {- status: 400,- },- );+ try {+ // if there's no projectSlug defined+ if (!slug) {+ if (allowAnonymous) {+ // @ts-expect-error+ return 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 authorizationHeader = req.headers.get("Authorization");- if (authorizationHeader) {- if (!authorizationHeader.includes("Bearer ")) {- return new Response(- "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://dub.sh/auth ",- {- status: 400,- },- );- }- const apiKey = authorizationHeader.replace("Bearer ", "");+ const authorizationHeader = req.headers.get("Authorization");+ if (authorizationHeader) {+ if (!authorizationHeader.includes("Bearer ")) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "Misconfigured authorization header. Did you forget to add 'Bearer '?",+ docUrl: "https://dub.sh/auth",+ });+ }+ const apiKey = authorizationHeader.replace("Bearer ", "");- const url = new URL(req.url || "", API_DOMAIN);+ const url = new URL(req.url || "", API_DOMAIN);- if (url.pathname.includes("/stats")) {- if (url.pathname.includes("/analytics")) {- return new Response("API access is not available for Analytics yet.", {- status: 403,- });- }++ if (url.pathname.includes("/analytics")) {+ throw new DubApiError({+ code: "forbidden",- message: "API access is not available for stats yet.",++ message: "API access is not available for Analytics yet.",+ });+ }- const hashedKey = hashToken(apiKey, {- noSecret: true,- });+ 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,+ },});- }+ if (!user) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Unauthorized: Invalid API key.",+ });+ }- const { success, limit, reset, remaining } = await ratelimit(- 10,- "1 s",- ).limit(apiKey);+ 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(),- };+ headers = {+ "Retry-After": reset.toString(),+ "X-RateLimit-Limit": limit.toString(),+ "X-RateLimit-Remaining": remaining.toString(),+ "X-RateLimit-Reset": reset.toString(),+ };- 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,+ 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.",+ });+ }}- }- 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,+ },},- },- metadata: true,- },- }),- linkId- ? prisma.link.findUnique({- where: {- id: linkId,+ domains: {+ select: {+ slug: true,+ primary: true,+ },},- })- : domain &&- key &&- (key === "_root"- ? prisma.domain.findUnique({- where: {- slug: domain,- },- })- : prisma.link.findUnique({- where: {- domain_key: {- domain,- key,+ metadata: true,+ },+ }),+ linkId+ ? prisma.link.findUnique({+ where: {+ id: linkId,+ },+ })+ : domain &&+ key &&+ (key === "_root"+ ? prisma.domain.findUnique({+ where: {+ slug: domain,},- },- })),- ])) as [ProjectProps, LinkProps | undefined];+ })+ : prisma.link.findUnique({+ where: {+ domain_key: {+ domain,+ key,+ },+ },+ })),+ ])) as [ProjectProps, LinkProps | undefined];- if (!project || !project.users) {- // project doesn't exist- return new Response("Project not found.", {- status: 404,- headers,- });- }+ 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,});- } else {- return new Response("Project invite pending.", {- status: 409,- 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.",});}- }- // 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,- });- }+ // 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",+ }),+ });+ }- // 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,- },- );- }+ // 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",+ }),+ });+ }- // 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,- },- );- }+ // plan checks+ if (!requiredPlan.includes(project.plan)) {+ throw new DubApiError({+ code: "forbidden",+ message: "Unauthorized: Need higher plan.",+ });+ }- // 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.",+ });}}