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.

Merge branch 'main' into feat/improve-api

Steven Tey77652d7d6d70
diff --cc apps/web/app/api/analytics/edge/[endpoint]/route.ts
index 1e85ddd988,b6781d171a..625eaf4a0d
--- a/apps/web/app/api/analytics/edge/[endpoint]/route.ts
+++ b/apps/web/app/api/analytics/edge/[endpoint]/route.ts
@@@ -1,24 -1,11 +1,19 @@@
import { getAnalytics } from "@/lib/analytics";
-import { exceededLimitError } from "@/lib/api/errors";
+import {
+ DubApiError,
+ exceededLimitError,
+ handleAndReturnErrorResponse,
+} from "@/lib/api/errors";
+ import { getIdentityHash } from "@/lib/edge";
import { isBlacklistedReferrer } from "@/lib/edge-config";
import { getDomainOrLink, getProjectViaEdge } from "@/lib/planetscale";
import { ratelimit } from "@/lib/upstash";
- import {
- DEMO_LINK_ID,
- DUB_PROJECT_ID,
- LOCALHOST_IP,
- getSearchParams,
- } from "@dub/utils";
- import { ipAddress } from "@vercel/edge";
+ import { DEMO_LINK_ID, DUB_PROJECT_ID, getSearchParams } from "@dub/utils";
import { NextResponse, type NextRequest } from "next/server";
+import {
+ getAnalyticsEdgeQuerySchema,
+ analyticsEndpointSchema,
+} from "@/lib/zod/schemas/analytics";
export const runtime = "edge";
@@@ -26,71 -13,27 +21,70 @@@ export const GET = async
req: NextRequest,
{ params }: { params: Record<string, string> },
) => {
- const { endpoint } = params;
- const searchParams = getSearchParams(req.url);
- const { domain, key, interval } = searchParams;
+ try {
+ const searchParams = getSearchParams(req.url);
+ const { endpoint } = analyticsEndpointSchema.parse(params);
+ const parsedParams = getAnalyticsEdgeQuerySchema.parse(searchParams);
+ const { domain, key, interval } = parsedParams;
- let link;
+ let link;
- // demo link (dub.sh/try)
- if (domain === "dub.sh" && key === "try") {
- // Rate limit in production
- if (process.env.NODE_ENV !== "development") {
- if (await isBlacklistedReferrer(req.headers.get("referer"))) {
- return new Response("Don't DDoS me pls 🥺", { status: 429 });
- }
- const identity_hash = await getIdentityHash(req);
- const { success } = await ratelimit(
- 15,
- endpoint === "clicks" ? "10 s" : "1 h",
- ).limit(`demo-analytics:${identity_hash}:${endpoint}`);
+ // demo link (dub.sh/try)
+ if (domain === "dub.sh" && key === "try") {
+ // Rate limit in production
+ if (process.env.NODE_ENV !== "development") {
+ if (await isBlacklistedReferrer(req.headers.get("referer"))) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Don't DDoS me pls 🥺",
+ });
+ }
- const ip = ipAddress(req) || LOCALHOST_IP;
++ const identity_hash = await getIdentityHash(req);
+ const { success } = await ratelimit(
+ 15,
+ endpoint === "clicks" ? "10 s" : "1 h",
- ).limit(`${ip}:${domain}:${key}:${endpoint}`);
++ ).limit(`demo-analytics:${identity_hash}:${endpoint}`);
- if (!success) {
- return new Response("Don't DDoS me pls 🥺", { status: 429 });
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Don't DDoS me pls 🥺",
+ });
+ }
+ }
-
+ link = {
+ id: DEMO_LINK_ID,
+ projectId: DUB_PROJECT_ID,
+ };
+ } else {
+ link = await getDomainOrLink({ domain, key });
+ // if the link is explicitly private (publicStats === false)
+ if (!link?.publicStats) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Analytics for this link are not public",
+ });
+ }
+ const project =
+ link?.projectId && (await getProjectViaEdge(link.projectId));
+ if (
+ (!project || project.plan === "free") &&
+ (interval === "all" || interval === "90d")
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Need higher plan",
+ });
+ }
+ if (project && project.usage > project.usageLimit) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: exceededLimitError({
+ plan: project.plan,
+ limit: project.usageLimit,
+ type: "clicks",
+ }),
+ });
}
}
diff --cc apps/web/app/api/metatags/route.ts
index 806131af63,33bd1a586a..74c8b18ac3
--- a/apps/web/app/api/metatags/route.ts
+++ b/apps/web/app/api/metatags/route.ts
@@@ -1,51 -1,39 +1,51 @@@
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { ratelimit } from "@/lib/upstash";
+import z from "@/lib/zod";
- import { LOCALHOST_IP, isValidUrl } from "@dub/utils";
- import { ipAddress } from "@vercel/edge";
+ import { isValidUrl } from "@dub/utils";
import { getToken } from "next-auth/jwt";
import { NextRequest } from "next/server";
import { getMetaTags } from "./utils";
+ import { getIdentityHash } from "@/lib/edge";
+const getMetaTagQuerySchema = z.object({
+ url: z.string().refine((v) => isValidUrl(v), { message: "Invalid URL" }),
+});
+
export const runtime = "edge";
export async function GET(req: NextRequest) {
- const url = req.nextUrl.searchParams.get("url");
- if (!url || !isValidUrl(url)) {
- return new Response("Invalid URL", { status: 400 });
- }
+ try {
+ const { url } = getMetaTagQuerySchema.parse({
+ url: req.nextUrl.searchParams.get("url"),
+ });
- // Rate limit if user is not logged in
- const session = await getToken({
- req,
- secret: process.env.NEXTAUTH_SECRET,
- });
- if (!session?.email) {
- const identity_hash = await getIdentityHash(req);
- const { success } = await ratelimit().limit(`metatags:${identity_hash}`);
- if (!success) {
- return new Response("Don't DDoS me pls 🥺", { status: 429 });
+ // Rate limit if user is not logged in
+ const session = await getToken({
+ req,
+ secret: process.env.NEXTAUTH_SECRET,
+ });
+ if (!session?.email) {
- const ip = ipAddress(req) || LOCALHOST_IP;
- const { success } = await ratelimit().limit(ip);
++ const identity_hash = await getIdentityHash(req);
++ const { success } = await ratelimit().limit(`metatags:${identity_hash}`);
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Don't DDoS me pls 🥺",
+ });
+ }
}
- }
- const metatags = await getMetaTags(url);
- return new Response(JSON.stringify(metatags), {
- status: 200,
- headers: {
- "Content-Type": "application/json",
- "Access-Control-Allow-Origin": "*",
- },
- });
+ const metatags = await getMetaTags(url);
+ return new Response(JSON.stringify(metatags), {
+ status: 200,
+ headers: {
+ "Content-Type": "application/json",
+ "Access-Control-Allow-Origin": "*",
+ },
+ });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
}
export function OPTIONS() {
diff --cc apps/web/app/api/qr/route.tsx
index 463b97d3c7,6e89877ebc..4b5e4bb9a5
--- a/apps/web/app/api/qr/route.tsx
+++ b/apps/web/app/api/qr/route.tsx
@@@ -1,9 -1,13 +1,9 @@@
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+ import { getIdentityHash } from "@/lib/edge";
-import {
- DEFAULT_BGCOLOR,
- DEFAULT_FGCOLOR,
- DEFAULT_INCLUDEMARGIN,
- DEFAULT_LEVEL,
- QR_LEVELS,
-} from "@/lib/qr/constants";
import { QRCodeSVG } from "@/lib/qr/utils";
import { ratelimit } from "@/lib/upstash";
+import { getQRCodeQuerySchema } from "@/lib/zod/schemas/qr";
- import { LOCALHOST_IP, getSearchParams } from "@dub/utils";
- import { ipAddress } from "@vercel/edge";
++import { getSearchParams } from "@dub/utils";
import { getToken } from "next-auth/jwt";
import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";
@@@ -11,50 -15,51 +11,50 @@@
export const runtime = "edge";
export async function GET(req: NextRequest) {
- // Rate limit if user is not logged in
- const session = await getToken({
- req,
- secret: process.env.NEXTAUTH_SECRET,
- });
- if (!session?.email) {
- const identity_hash = await getIdentityHash(req);
- const { success } = await ratelimit().limit(`qr:${identity_hash}`);
- if (!success) {
- return new Response("Don't DDoS me pls 🥺", { status: 429 });
+ try {
+ // Rate limit if user is not logged in
+ const session = await getToken({
+ req,
+ secret: process.env.NEXTAUTH_SECRET,
+ });
+ if (!session?.email) {
- const ip = ipAddress(req) || LOCALHOST_IP;
- const { success } = await ratelimit().limit(ip);
++ const identity_hash = await getIdentityHash(req);
++ const { success } = await ratelimit().limit(`qr:${identity_hash}`);
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Don't DDoS me pls 🥺",
+ });
+ }
}
- }
-
- const url = req.nextUrl.searchParams.get("url") || "https://dub.co";
- const size = parseInt(req.nextUrl.searchParams.get("size") || "600", 10);
- const level = req.nextUrl.searchParams.get("level") || DEFAULT_LEVEL;
- if (!QR_LEVELS.includes(level)) {
- return new Response("Invalid QR code level.", { status: 400 });
- }
- const fgColor = req.nextUrl.searchParams.get("fgColor") || DEFAULT_FGCOLOR;
- const bgColor = req.nextUrl.searchParams.get("bgColor") || DEFAULT_BGCOLOR;
- const includeMargin =
- req.nextUrl.searchParams.get("includeMargin") || DEFAULT_INCLUDEMARGIN;
+ const params = getSearchParams(req.url);
+ const { url, size, level, fgColor, bgColor, includeMargin } =
+ getQRCodeQuerySchema.parse(params);
- // const logo = req.nextUrl.searchParams.get("logo") || "https://assets.dub.co/logo.png";
+ // const logo = req.nextUrl.searchParams.get("logo") || "https://assets.dub.co/logo.png";
- return new ImageResponse(
- QRCodeSVG({
- value: url,
- size,
- level,
- includeMargin: includeMargin === "true",
- fgColor,
- bgColor,
- // imageSettings: {
- // src: logo,
- // height: size / 4,
- // width: size / 4,
- // excavate: true,
- // },
- }),
- {
- width: size,
- height: size,
- },
- );
+ return new ImageResponse(
+ QRCodeSVG({
+ value: url,
+ size,
+ level,
+ includeMargin,
+ fgColor,
+ bgColor,
+ // imageSettings: {
+ // src: logo,
+ // height: size / 4,
+ // width: size / 4,
+ // excavate: true,
+ // },
+ }),
+ {
+ width: size,
+ height: size,
+ },
+ );
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
}
diff --cc apps/web/lib/auth/index.ts
index 47ce9ea136,9387d4904c..41d53a5cb1
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@@ -100,302 -113,289 +114,293 @@@ export const withAuth =
let session: Session | undefined;
let headers = {};
+ const slug = params?.slug || searchParams.projectSlug;
+
- // 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 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 ")) {
- 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 ", "");
-
- if (apiKey) {
- const url = new URL(req.url || "", API_DOMAIN);
++ if (apiKey) {
+ const url = new URL(req.url || "", API_DOMAIN);
- 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 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);
-
- 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,
+ 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.",
+ });
+ }
}
- }
- 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,
+ },
},
- })
- : 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,
+ },
+ })
+ : domain &&
+ key &&
+ (key === "_root"
+ ? prisma.domain.findUnique({
+ where: {
+ slug: domain,
},
- },
- })),
- ])) as [ProjectProps, LinkProps | 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,
+ },
+ },
+ })),
+ ])) as [ProjectProps, LinkProps | 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,
});
- } 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 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.",
+ });
}
}
@@@ -433,95 -437,87 +438,95 @@@ interface WithSessionHandler
export const withSession =
(handler: WithSessionHandler) =>
async (req: Request, { params }: { params: Record<string, string> }) => {
- let session: Session | undefined;
- let headers = {};
-
- 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://d.to/auth ",
- {
- status: 400,
- },
- );
- }
- const apiKey = authorizationHeader.replace("Bearer ", "");
+ try {
+ let session: Session | undefined;
+ let headers = {};
+
+ 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 '? Learn more: https://dub.sh/auth ",
++ "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth ",
+ });
+ }
+ const apiKey = authorizationHeader.replace("Bearer ", "");
- 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);
-
- 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,
+ 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) {
+ 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) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Unauthorized: Login required.",
+ });
+ }
}
- 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 });
- }
- }
- const searchParams = getSearchParams(req.url);
- return handler({ req, params, searchParams, session });
+ const searchParams = getSearchParams(req.url);
+ return await handler({ req, params, searchParams, session });
+ } catch (error) {
+ console.error("withSession Error -->", error.message);
+ return handleAndReturnErrorResponse(error);
+ }
};
// Internal use only (for admin portal)