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.

Update QR code schema and constants

Kiran Kd6ad18e5a8ef
diff --git a/apps/web/app/api/projects/route.ts b/apps/web/app/api/projects/route.ts
index 7161de76a0..c84e454360 100644
--- a/apps/web/app/api/projects/route.ts
+++ b/apps/web/app/api/projects/route.ts
@@ -2,158 +2,155 @@ import {
addDomainToVercel,
domainExists,
setRootDomain,
- validateDomain,
} from "@/lib/api/domains";
import { withSession } from "@/lib/auth";
import { isReservedKey } from "@/lib/edge-config";
-import { handleAndReturnErrorResponse } from "@/lib/errors";
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/errors";
import prisma from "@/lib/prisma";
+import z from "@/lib/zod";
import {
DEFAULT_REDIRECTS,
FREE_PROJECTS_LIMIT,
+ validDomainRegex,
validSlugRegex,
} from "@dub/utils";
import { NextResponse } from "next/server";
-// GET /api/projects - get all projects for the current user
-export const GET = withSession(async ({ session }) => {
- try {
- const projects = await prisma.project.findMany({
- where: {
- users: {
- some: {
- userId: session.user.id,
- },
- },
- },
- include: {
- domains: true,
- users: {
- where: {
- userId: session.user.id,
- },
- select: {
- role: true,
- },
- },
- },
- });
- return NextResponse.json(projects);
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
+const createProjectSchema = z.object({
+ name: z.string().min(1),
+ slug: z
+ .string()
+ .min(1)
+ .max(48, "Slug must be less than 48 characters")
+ .transform((v) => v.toLowerCase())
+ .refine((v) => validSlugRegex.test(v), { message: "Invalid slug format" })
+ .refine(async (v) => !((await isReservedKey(v)) || DEFAULT_REDIRECTS[v]), {
+ message: "Cannot use reserved slugs",
+ }),
+ domain: z
+ .string()
+ .refine((v) => validDomainRegex.test(v), {
+ message: "Invalid domain format",
+ })
+ .optional(),
});
-export const POST = withSession(async ({ req, session }) => {
- const { name, slug, domain } = await req.json();
-
- if (!name || !slug) {
- return new Response("Missing name or slug", { status: 422 });
- }
- let slugError: string | null = null;
-
- // check if slug is too long
- if (slug.length > 48) {
- slugError = "Slug must be less than 48 characters";
-
- // check if slug is valid
- } else if (!validSlugRegex.test(slug)) {
- slugError = "Invalid slug";
-
- // check if slug is reserved
- } else if ((await isReservedKey(slug)) || DEFAULT_REDIRECTS[slug]) {
- slugError = "Cannot use reserved slugs";
- }
-
- if (domain) {
- const validDomain = await validateDomain(domain);
- if (slugError || validDomain !== true) {
- return NextResponse.json(
- {
- slugError,
- domainError: validDomain === true ? null : validDomain,
- },
- { status: 422 },
- );
- }
- }
-
- const freeProjects = await prisma.project.count({
+// GET /api/projects - get all projects for the current user
+export const GET = withSession(async ({ session }) => {
+ const projects = await prisma.project.findMany({
where: {
- plan: "free",
users: {
some: {
userId: session.user.id,
- role: "owner",
+ },
+ },
+ },
+ include: {
+ domains: true,
+ users: {
+ where: {
+ userId: session.user.id,
+ },
+ select: {
+ role: true,
},
},
},
});
+ return NextResponse.json(projects);
+});
- if (freeProjects >= FREE_PROJECTS_LIMIT) {
- return new Response(
- `You can only create up to ${FREE_PROJECTS_LIMIT} free projects. Additional projects require a paid plan.`,
- { status: 403 },
+export const POST = withSession(async ({ req, session }) => {
+ try {
+ const { name, slug, domain } = await createProjectSchema.parseAsync(
+ await req.json(),
);
- }
- const [slugExist, domainExist] = await Promise.all([
- prisma.project.findUnique({
+ const freeProjects = await prisma.project.count({
where: {
- slug,
- },
- select: {
- slug: true,
- },
- }),
- domain ? domainExists(domain) : false,
- ]);
- if (slugExist || domainExist) {
- return NextResponse.json(
- {
- slugError: slugExist ? "Slug is already in use." : null,
- domainError: domainExist ? "Domain is already in use." : null,
- },
- { status: 422 },
- );
- }
- const [projectResponse, domainRepsonse] = await Promise.all([
- prisma.project.create({
- data: {
- name,
- slug,
+ plan: "free",
users: {
- create: {
+ some: {
userId: session.user.id,
role: "owner",
},
},
- ...(domain && {
- domains: {
+ },
+ });
+
+ if (freeProjects >= FREE_PROJECTS_LIMIT) {
+ throw new DubApiError({
+ code: "exceeded_limit",
+ message: `You can only create up to ${FREE_PROJECTS_LIMIT} free projects. Additional projects require a paid plan.`,
+ });
+ }
+
+ const [slugExist, domainExist] = await Promise.all([
+ prisma.project.findUnique({
+ where: {
+ slug,
+ },
+ select: {
+ slug: true,
+ },
+ }),
+ domain ? domainExists(domain) : false,
+ ]);
+
+ if (slugExist) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "Slug is already in use.",
+ });
+ }
+
+ if (domainExist) {
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: "Domain is already in use.",
+ });
+ }
+
+ const [projectResponse, domainRepsonse] = await Promise.all([
+ prisma.project.create({
+ data: {
+ name,
+ slug,
+ users: {
create: {
- slug: domain,
- primary: true,
+ userId: session.user.id,
+ role: "owner",
},
},
- }),
- billingCycleStart: new Date().getDate(),
- },
- include: {
- domains: true,
- },
- }),
- domain && addDomainToVercel(domain),
- ]);
+ ...(domain && {
+ domains: {
+ create: {
+ slug: domain,
+ primary: true,
+ },
+ },
+ }),
+ billingCycleStart: new Date().getDate(),
+ },
+ include: {
+ domains: true,
+ },
+ }),
+ domain && addDomainToVercel(domain),
+ ]);
- // if domain is specified and it was successfully added to Vercel
- // update it in Redis cache
- if (domain && !domainRepsonse.error) {
- await setRootDomain({
- id: projectResponse.domains[0].id,
- domain,
- projectId: projectResponse.id,
- });
- }
+ // if domain is specified and it was successfully added to Vercel
+ // update it in Redis cache
+ if (domain && domainRepsonse && !domainRepsonse.error) {
+ await setRootDomain({
+ id: projectResponse.domains[0].id,
+ domain,
+ projectId: projectResponse.id,
+ });
+ }
- return NextResponse.json(projectResponse);
+ return NextResponse.json(projectResponse);
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
});
diff --git a/apps/web/app/api/qr/route.tsx b/apps/web/app/api/qr/route.tsx
index 67d179bf47..0bd54ff51d 100644
--- a/apps/web/app/api/qr/route.tsx
+++ b/apps/web/app/api/qr/route.tsx
@@ -1,13 +1,8 @@
-import {
- DEFAULT_BGCOLOR,
- DEFAULT_FGCOLOR,
- DEFAULT_INCLUDEMARGIN,
- DEFAULT_LEVEL,
- QR_LEVELS,
-} from "@/lib/qr/constants";
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/errors";
import { QRCodeSVG } from "@/lib/qr/utils";
import { ratelimit } from "@/lib/upstash";
-import { LOCALHOST_IP } from "@dub/utils";
+import { getQRCodeQuerySchema } from "@/lib/zod/schemas/qr";
+import { LOCALHOST_IP, getSearchParams } from "@dub/utils";
import { ipAddress } from "@vercel/edge";
import { getToken } from "next-auth/jwt";
import { ImageResponse } from "next/og";
@@ -16,51 +11,50 @@ import { NextRequest } from "next/server";
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 ip = ipAddress(req) || LOCALHOST_IP;
- const { success } = await ratelimit().limit(ip);
- 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);
+ 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 parsed = getQRCodeQuerySchema.parse(params);
+ const { url, size, level, fgColor, bgColor, includeMargin } = parsed;
- // const logo = req.nextUrl.searchParams.get("logo") || "https://d2vwwcvoksz7ty.cloudfront.net/logo.png";
+ // const logo = req.nextUrl.searchParams.get("logo") || "https://d2vwwcvoksz7ty.cloudfront.net/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 --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index 01905c07bc..707c7fe00e 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -422,87 +422,94 @@ interface WithSessionHandler {
export const withSession =
(handler: WithSessionHandler) =>
async (req: Request, { params }: { params: Record<string, string> }) => {
- let session: Session | undefined;
- let headers = {};
+ try {
+ 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://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 '? Learn more: https://dub.sh/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 handler({ req, params, searchParams, session });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
};
// Internal use only (for admin portal)
diff --git a/apps/web/lib/errors.ts b/apps/web/lib/errors/index.ts
similarity index 86%
rename from apps/web/lib/errors.ts
rename to apps/web/lib/errors/index.ts
index 2f8019a779..3cf6c0a73e 100644
--- a/apps/web/lib/errors.ts
+++ b/apps/web/lib/errors/index.ts
@@ -1,9 +1,9 @@
-import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
+// import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
import { NextResponse } from "next/server";
import { ZodError } from "zod";
import { generateErrorMessage } from "zod-error";
-import z from "./zod";
+import z from "../zod";
export const ErrorCode = z.enum([
"bad_request",
@@ -33,13 +33,13 @@ const errorCodeToHttpStatus: Record<z.infer<typeof ErrorCode>, number> = {
internal_server_error: 500,
};
-const prismaErrorMapping: Record<
- PrismaClientKnownRequestError["code"],
- ErrorResponse["error"]["code"]
-> = {
- P2025: "not_found",
- P2002: "conflict",
-};
+// const prismaErrorMapping: Record<
+// PrismaClientKnownRequestError["code"],
+// ErrorResponse["error"]["code"]
+// > = {
+// P2025: "not_found",
+// P2002: "conflict",
+// };
const ErrorSchema = z.object({
error: z.object({
@@ -119,18 +119,18 @@ export function handleApiError(error: any): ErrorResponse & { status: number } {
}
// Prisma errors
- if (error instanceof PrismaClientKnownRequestError) {
- const code = prismaErrorMapping[error.code] ?? error.message;
-
- return {
- error: {
- code,
- message: error.message,
- doc_url: `${docErrorUrl}#${code}`,
- },
- status: errorCodeToHttpStatus[code],
- };
- }
+ // if (error instanceof PrismaClientKnownRequestError) {
+ // const code = prismaErrorMapping[error.code] ?? error.message;
+
+ // return {
+ // error: {
+ // code,
+ // message: error.message,
+ // doc_url: `${docErrorUrl}#${code}`,
+ // },
+ // status: errorCodeToHttpStatus[code],
+ // };
+ // }
// DubApiError errors
if (error instanceof DubApiError) {
diff --git a/apps/web/lib/openapi/links/get-qr.ts b/apps/web/lib/openapi/links/get-qr.ts
index c45a509972..5ab1eb1c36 100644
--- a/apps/web/lib/openapi/links/get-qr.ts
+++ b/apps/web/lib/openapi/links/get-qr.ts
@@ -1,8 +1,7 @@
-import { ZodOpenApiOperationObject } from "zod-openapi";
-
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import { getQRCodeQuerySchema } from "@/lib/zod/schemas/qr";
+import { ZodOpenApiOperationObject } from "zod-openapi";
export const getQRCode: ZodOpenApiOperationObject = {
operationId: "getQRCode",
diff --git a/apps/web/lib/qr/constants.ts b/apps/web/lib/qr/constants.ts
index 2b78b96510..73fd0b49b9 100644
--- a/apps/web/lib/qr/constants.ts
+++ b/apps/web/lib/qr/constants.ts
@@ -15,7 +15,7 @@ export const DEFAULT_INCLUDEMARGIN = false;
export const MARGIN_SIZE = 4;
-export const QR_LEVELS = ["L", "M", "Q", "H"];
+export const QR_LEVELS = ["L", "M", "Q", "H"] as const;
// This is *very* rough estimate of max amount of QRCode allowed to be covered.
// It is "wrong" in a lot of ways (area is a terrible way to estimate, it
diff --git a/apps/web/lib/zod/index.ts b/apps/web/lib/zod/index.ts
index 32898654ae..b9ca34a5a8 100644
--- a/apps/web/lib/zod/index.ts
+++ b/apps/web/lib/zod/index.ts
@@ -8,4 +8,4 @@ export default z;
export const domainKeySchema = z.object({
domain: z.string().min(1),
key: z.string().min(1),
-});
+});
\ No newline at end of file
diff --git a/apps/web/lib/zod/schemas/index.ts b/apps/web/lib/zod/schemas/index.ts
index 3f9e8250a3..7db9b9d48a 100644
--- a/apps/web/lib/zod/schemas/index.ts
+++ b/apps/web/lib/zod/schemas/index.ts
@@ -7,6 +7,15 @@ export const roleSchema = z
.enum(roles)
.describe("The role of the authenticated user in the project.");
+// TODO: Move to tags.ts
export const tagColorSchema = z
.enum(tagColors)
.describe("The color of the tag.");
+
+// A boolean query schema that coerces the value to a boolean
+export const booleanQuerySchema = z
+ .enum(["true", "false"])
+ .transform((value) => value == "true")
+ .openapi({
+ type: "boolean",
+ });
diff --git a/apps/web/lib/zod/schemas/qr.ts b/apps/web/lib/zod/schemas/qr.ts
index 506e7395e8..fc1353d1bc 100644
--- a/apps/web/lib/zod/schemas/qr.ts
+++ b/apps/web/lib/zod/schemas/qr.ts
@@ -1,4 +1,11 @@
+import {
+ DEFAULT_BGCOLOR,
+ DEFAULT_FGCOLOR,
+ DEFAULT_INCLUDEMARGIN,
+ QR_LEVELS,
+} from "@/lib/qr/constants";
import z from "@/lib/zod";
+import { booleanQuerySchema } from ".";
export const getQRCodeQuerySchema = z.object({
url: z
@@ -9,7 +16,7 @@ export const getQRCodeQuerySchema = z.object({
.describe(
"The URL to generate a QR code for. Defaults to `https://dub.co` if not provided.",
),
- size: z
+ size: z.coerce
.number()
.optional()
.default(600)
@@ -17,7 +24,7 @@ export const getQRCodeQuerySchema = z.object({
"The size of the QR code in pixels. Defaults to `600` if not provided.",
),
level: z
- .enum(["L", "M", "Q", "H"])
+ .enum(QR_LEVELS)
.optional()
.default("L")
.describe(
@@ -26,21 +33,20 @@ export const getQRCodeQuerySchema = z.object({
fgColor: z
.string()
.optional()
- .default("#000000")
+ .default(DEFAULT_FGCOLOR)
.describe(
"The foreground color of the QR code in hex format. Defaults to `#000000` if not provided.",
),
bgColor: z
.string()
.optional()
- .default("#ffffff")
+ .default(DEFAULT_BGCOLOR)
.describe(
"The background color of the QR code in hex format. Defaults to `#ffffff` if not provided.",
),
- includeMargin: z.coerce
- .boolean()
+ includeMargin: booleanQuerySchema
.optional()
- .default(false)
+ .default(`${DEFAULT_INCLUDEMARGIN}`)
.describe(
"Whether to include a margin around the QR code. Defaults to `false` if not provided.",
),
diff --git a/apps/web/ui/modals/add-project-modal.tsx b/apps/web/ui/modals/add-project-modal.tsx
index f249b124d6..3c14c2e94e 100644
--- a/apps/web/ui/modals/add-project-modal.tsx
+++ b/apps/web/ui/modals/add-project-modal.tsx
@@ -138,22 +138,20 @@ function AddProjectModalHelper({
toast.success("Successfully created project!");
setShowAddProjectModal(false);
}
- } else if (res.status === 422) {
- const {
- slugError: slugErrorResponse,
- domainError: domainErrorResponse,
- } = await res.json();
+ } else {
+ const { error } = await res.json();
+ const message = error.message;
- if (slugErrorResponse) {
- setSlugError(slugErrorResponse);
- toast.error(slugErrorResponse);
+ if(message.toLowerCase().includes("slug")) {
+ alert(message);
+ setSlugError(message);
}
- if (domainErrorResponse) {
- setDomainError(domainErrorResponse);
- toast.error(domainErrorResponse);
+
+ if(message.toLowerCase().includes("domain")) {
+ setDomainError(message);
}
- } else {
- toast.error(await res.text());
+
+ toast.error(error.message);
}
setSaving(false);
});