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 headers & cookies to async

Steven Tey5422b66bd5da
diff --git a/apps/web/app/robots.ts b/apps/web/app/robots.ts
index effd1c82ee..f94d38c03f 100644
--- a/apps/web/app/robots.ts
+++ b/apps/web/app/robots.ts
@@ -1,8 +1,8 @@
import { MetadataRoute } from "next";
-import { headers, type UnsafeUnwrappedHeaders } from "next/headers";
+import { headers } from "next/headers";
-export default function robots(): MetadataRoute.Robots {
- const headersList = (headers() as unknown as UnsafeUnwrappedHeaders);
+export default async function robots(): Promise<MetadataRoute.Robots> {
+ const headersList = await headers();
let domain = headersList.get("host") as string;
return {
diff --git a/apps/web/lib/actions/check-account-exists.ts b/apps/web/lib/actions/check-account-exists.ts
index 953f097c4b..ae82f75c89 100644
--- a/apps/web/lib/actions/check-account-exists.ts
+++ b/apps/web/lib/actions/check-account-exists.ts
@@ -1,8 +1,8 @@
"use server";
+import { getIP } from "@/lib/api/utils/get-ip";
import { ratelimit } from "@/lib/upstash";
import { prisma } from "@dub/prisma";
-import { getIP } from "../api/utils";
import z from "../zod";
import { emailSchema } from "../zod/schemas/auth";
import { throwIfAuthenticated } from "./auth/throw-if-authenticated";
@@ -20,7 +20,7 @@ export const checkAccountExistsAction = actionClient
const { email } = parsedInput;
const { success } = await ratelimit(8, "1 m").limit(
- `account-exists:${getIP()}`,
+ `account-exists:${await getIP()}`,
);
if (!success) {
diff --git a/apps/web/lib/actions/partners/create-program-application.ts b/apps/web/lib/actions/partners/create-program-application.ts
index 5a7fc04b8d..43067ea011 100644
--- a/apps/web/lib/actions/partners/create-program-application.ts
+++ b/apps/web/lib/actions/partners/create-program-application.ts
@@ -2,7 +2,7 @@
import { createId } from "@/lib/api/create-id";
import { notifyPartnerApplication } from "@/lib/api/partners/notify-partner-application";
-import { getIP } from "@/lib/api/utils";
+import { getIP } from "@/lib/api/utils/get-ip";
import { getSession } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import { ratelimit } from "@/lib/upstash";
@@ -34,7 +34,7 @@ export const createProgramApplicationAction = actionClient
// Limit to 3 requests per minute per program per IP
const { success } = await ratelimit(3, "1 m").limit(
- `create-program-application:${programId}:${getIP()}`,
+ `create-program-application:${programId}:${await getIP()}`,
);
if (!success) {
diff --git a/apps/web/lib/actions/send-otp.ts b/apps/web/lib/actions/send-otp.ts
index 2d66740fc0..17fb9a9af9 100644
--- a/apps/web/lib/actions/send-otp.ts
+++ b/apps/web/lib/actions/send-otp.ts
@@ -1,12 +1,12 @@
"use server";
+import { getIP } from "@/lib/api/utils/get-ip";
import { ratelimit, redis } from "@/lib/upstash";
import { sendEmail } from "@dub/email";
import VerifyEmail from "@dub/email/templates/verify-email";
import { prisma } from "@dub/prisma";
import { get } from "@vercel/edge-config";
import { flattenValidationErrors } from "next-safe-action";
-import { getIP } from "../api/utils";
import { generateOTP } from "../auth";
import { EMAIL_OTP_EXPIRY_IN } from "../auth/constants";
import { isGenericEmail } from "../is-generic-email";
@@ -30,7 +30,9 @@ export const sendOtpAction = actionClient
.action(async ({ parsedInput }) => {
const { email } = parsedInput;
- const { success } = await ratelimit(2, "1 m").limit(`send-otp:${getIP()}`);
+ const { success } = await ratelimit(2, "1 m").limit(
+ `send-otp:${await getIP()}`,
+ );
if (!success) {
throw new Error("Too many requests. Please try again later.");
diff --git a/apps/web/lib/api/audit-logs/record-audit-log.ts b/apps/web/lib/api/audit-logs/record-audit-log.ts
index bf5a8eb03f..9844f1d2d9 100644
--- a/apps/web/lib/api/audit-logs/record-audit-log.ts
+++ b/apps/web/lib/api/audit-logs/record-audit-log.ts
@@ -1,18 +1,22 @@
+import { getIP } from "@/lib/api/utils/get-ip";
import { tb } from "@/lib/tinybird";
import { log } from "@dub/utils";
import { ipAddress as getIPAddress } from "@vercel/functions";
-import { headers, type UnsafeUnwrappedHeaders } from "next/headers";
+import { headers } from "next/headers";
import { z } from "zod";
import { createId } from "../create-id";
-import { getIP } from "../utils";
import { prefixWorkspaceId } from "../workspaces/workspace-id";
import { auditLogSchemaTB, recordAuditLogInputSchema } from "./schemas";
type AuditLogInput = z.infer<typeof recordAuditLogInputSchema>;
-const transformAuditLogTB = (data: AuditLogInput) => {
- const headersList = headers() as unknown as UnsafeUnwrappedHeaders;
- const ipAddress = data.req ? getIPAddress(data.req) : getIP();
+const transformAuditLogTB = (
+ data: AuditLogInput,
+ {
+ headersList,
+ ipAddress,
+ }: { headersList: Headers; ipAddress: string | undefined },
+) => {
const userAgent = headersList.get("user-agent");
const auditLogInput = recordAuditLogInputSchema.parse({
@@ -41,9 +45,15 @@ const transformAuditLogTB = (data: AuditLogInput) => {
};
export const recordAuditLog = async (data: AuditLogInput | AuditLogInput[]) => {
+ const headersList = await headers();
+ const dataReq = Array.isArray(data)
+ ? data.map((d) => d.req).find((d) => d)
+ : data.req;
+ const ipAddress = dataReq ? getIPAddress(dataReq) : await getIP();
+
const auditLogs = Array.isArray(data)
- ? data.map(transformAuditLogTB)
- : [transformAuditLogTB(data)];
+ ? data.map((d) => transformAuditLogTB(d, { headersList, ipAddress }))
+ : [transformAuditLogTB(data, { headersList, ipAddress })];
try {
await recordAuditLogTB(auditLogs);
diff --git a/apps/web/lib/api/utils.ts b/apps/web/lib/api/utils.ts
index 942e4e4ce8..b6d4d07fb9 100644
--- a/apps/web/lib/api/utils.ts
+++ b/apps/web/lib/api/utils.ts
@@ -1,6 +1,5 @@
import { ipAddress } from "@vercel/functions";
import { getToken } from "next-auth/jwt";
-import { headers, type UnsafeUnwrappedHeaders } from "next/headers";
import { NextRequest } from "next/server";
import { ratelimit } from "../upstash";
import { DubApiError } from "./errors";
@@ -42,19 +41,3 @@ export const ratelimitOrThrow = async (
}
}
};
-
-export const getIP = () => {
- const FALLBACK_IP_ADDRESS = "0.0.0.0";
- const forwardedFor = (headers() as unknown as UnsafeUnwrappedHeaders).get(
- "x-forwarded-for",
- );
-
- if (forwardedFor) {
- return forwardedFor.split(",")[0] ?? FALLBACK_IP_ADDRESS;
- }
-
- return (
- (headers() as unknown as UnsafeUnwrappedHeaders).get("x-real-ip") ??
- FALLBACK_IP_ADDRESS
- );
-};
diff --git a/apps/web/lib/api/utils/get-ip.ts b/apps/web/lib/api/utils/get-ip.ts
new file mode 100644
index 0000000000..af10996d2e
--- /dev/null
+++ b/apps/web/lib/api/utils/get-ip.ts
@@ -0,0 +1,12 @@
+import { headers } from "next/headers";
+
+export const getIP = async () => {
+ const FALLBACK_IP_ADDRESS = "0.0.0.0";
+ const forwardedFor = (await headers()).get("x-forwarded-for");
+
+ if (forwardedFor) {
+ return forwardedFor.split(",")[0] ?? FALLBACK_IP_ADDRESS;
+ }
+
+ return (await headers()).get("x-real-ip") ?? FALLBACK_IP_ADDRESS;
+};
diff --git a/apps/web/lib/auth/track-dub-lead.ts b/apps/web/lib/auth/track-dub-lead.ts
index 5ade590a35..839843c970 100644
--- a/apps/web/lib/auth/track-dub-lead.ts
+++ b/apps/web/lib/auth/track-dub-lead.ts
@@ -3,7 +3,8 @@ import { User } from "next-auth";
import { cookies } from "next/headers";
export const trackDubLead = async (user: User) => {
- const clickId = (await cookies()).get("dub_id")?.value;
+ const cookieStore = await cookies();
+ const clickId = cookieStore.get("dub_id")?.value;
if (!clickId) {
console.log("No dub_id cookie found, skipping lead tracking...");
@@ -21,6 +22,6 @@ export const trackDubLead = async (user: User) => {
});
// delete the cookies
- (await cookies()).delete("dub_id");
- (await cookies()).delete("dub_partner_data");
+ cookieStore.delete("dub_id");
+ cookieStore.delete("dub_partner_data");
};
diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.ts
index 9df8b2f606..208bbc4426 100644
--- a/apps/web/lib/auth/workspace.ts
+++ b/apps/web/lib/auth/workspace.ts
@@ -61,375 +61,371 @@ export const withWorkspace = (
skipPermissionChecks?: boolean;
} = {},
) => {
- return withAxiom(
- async (
- req: AxiomRequest,
- { params = {} }: { params: Record<string, string> | undefined },
- ) => {
- const searchParams = getSearchParams(req.url);
-
- let apiKey: string | undefined = undefined;
- let headers = {};
- let workspace: WorkspaceWithUsers | undefined;
-
- try {
- 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://d.to/auth",
- });
- }
- apiKey = authorizationHeader.replace("Bearer ", "");
+ return withAxiom(async (req: AxiomRequest, { params: initialParams }) => {
+ const params = await initialParams;
+ const searchParams = getSearchParams(req.url);
+
+ let apiKey: string | undefined = undefined;
+ let headers = {};
+ let workspace: WorkspaceWithUsers | undefined;
+
+ try {
+ 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://d.to/auth",
+ });
}
+ apiKey = authorizationHeader.replace("Bearer ", "");
+ }
- let session: Session | undefined;
- let workspaceId: string | undefined;
- let workspaceSlug: string | undefined;
- let permissions: PermissionAction[] = [];
- let token: any | null = null;
- const isRestrictedToken = apiKey?.startsWith("dub_");
+ let session: Session | undefined;
+ let workspaceId: string | undefined;
+ let workspaceSlug: string | undefined;
+ let permissions: PermissionAction[] = [];
+ let token: any | null = null;
+ const isRestrictedToken = apiKey?.startsWith("dub_");
- const idOrSlug =
- params?.idOrSlug ||
- searchParams.workspaceId ||
- params?.slug ||
- searchParams.projectSlug;
+ const idOrSlug =
+ params?.idOrSlug ||
+ searchParams.workspaceId ||
+ params?.slug ||
+ searchParams.projectSlug;
- /*
+ /*
if there's no workspace ID or slug and it's not a restricted token:
- special case for anonymous link creation
- missing authorization header
- user is still using personal API keys
*/
- if (!idOrSlug && !isRestrictedToken) {
- // special case for anonymous link creation
- if (
- req.headers.has("dub-anonymous-link-creation") &&
- ["/links", "/api/links"].includes(req.nextUrl.pathname)
- ) {
- // @ts-expect-error
- return await handler({
- req,
- params,
- searchParams,
- headers,
- });
- // missing authorization header
- } else if (!authorizationHeader) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Missing Authorization header.",
- });
- // in case user is still using personal API keys
- } else {
- throw new DubApiError({
- code: "not_found",
- message:
- "Workspace ID not found. Did you forget to include a `workspaceId` query parameter? It looks like you might be using personal API keys, we also recommend refactoring to workspace API keys: https://d.to/keys",
- });
- }
+ if (!idOrSlug && !isRestrictedToken) {
+ // special case for anonymous link creation
+ if (
+ req.headers.has("dub-anonymous-link-creation") &&
+ ["/links", "/api/links"].includes(req.nextUrl.pathname)
+ ) {
+ // @ts-expect-error
+ return await handler({
+ req,
+ params,
+ searchParams,
+ headers,
+ });
+ // missing authorization header
+ } else if (!authorizationHeader) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Missing Authorization header.",
+ });
+ // in case user is still using personal API keys
+ } else {
+ throw new DubApiError({
+ code: "not_found",
+ message:
+ "Workspace ID not found. Did you forget to include a `workspaceId` query parameter? It looks like you might be using personal API keys, we also recommend refactoring to workspace API keys: https://d.to/keys",
+ });
}
+ }
- if (idOrSlug) {
- if (idOrSlug.startsWith("ws_")) {
- workspaceId = normalizeWorkspaceId(idOrSlug);
- } else {
- workspaceSlug = idOrSlug;
- }
+ if (idOrSlug) {
+ if (idOrSlug.startsWith("ws_")) {
+ workspaceId = normalizeWorkspaceId(idOrSlug);
+ } else {
+ workspaceSlug = idOrSlug;
}
+ }
- if (apiKey) {
- const hashedKey = await hashToken(apiKey);
+ if (apiKey) {
+ const hashedKey = await hashToken(apiKey);
- const cachedToken = await tokenCache.get({
- hashedKey,
- });
+ const cachedToken = await tokenCache.get({
+ hashedKey,
+ });
- if (!cachedToken) {
- const prismaArgs = {
- where: {
- hashedKey,
- },
- select: {
- ...(isRestrictedToken && {
- scopes: true,
- rateLimit: true,
- projectId: true,
- expires: true,
- installationId: true,
- }),
- user: {
- select: {
- id: true,
- name: true,
- email: true,
- isMachine: true,
- },
+ if (!cachedToken) {
+ const prismaArgs = {
+ where: {
+ hashedKey,
+ },
+ select: {
+ ...(isRestrictedToken && {
+ scopes: true,
+ rateLimit: true,
+ projectId: true,
+ expires: true,
+ installationId: true,
+ }),
+ user: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ isMachine: true,
},
},
- };
+ },
+ };
- if (isRestrictedToken) {
- token = await prisma.restrictedToken.findUnique(prismaArgs);
- } else {
- token = await prisma.token.findUnique(prismaArgs);
- }
+ if (isRestrictedToken) {
+ token = await prisma.restrictedToken.findUnique(prismaArgs);
+ } else {
+ token = await prisma.token.findUnique(prismaArgs);
}
+ }
- token = cachedToken || token;
+ token = cachedToken || token;
- if (!token || !token.user) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Unauthorized: Invalid API key.",
- });
- }
+ if (!token || !token.user) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Unauthorized: Invalid API key.",
+ });
+ }
- if (token.expires && token.expires < new Date()) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Unauthorized: Access token expired.",
- });
- }
+ if (token.expires && token.expires < new Date()) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Unauthorized: Access token expired.",
+ });
+ }
- if (!cachedToken) {
- waitUntil(
- tokenCache.set({
- hashedKey,
- token,
- }),
- );
- }
+ if (!cachedToken) {
+ waitUntil(
+ tokenCache.set({
+ hashedKey,
+ token,
+ }),
+ );
+ }
- // Rate limit checks for API keys
- const rateLimit = token.rateLimit || 600;
+ // Rate limit checks for API keys
+ const rateLimit = token.rateLimit || 600;
- const { success, limit, reset, remaining } = await ratelimit(
- rateLimit,
- "1 m",
- ).limit(apiKey);
+ const { success, limit, reset, remaining } = await ratelimit(
+ rateLimit,
+ "1 m",
+ ).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) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Too many requests.",
- });
- }
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Too many requests.",
+ });
+ }
- // Find workspaceId if it's a restricted token
- if (isRestrictedToken) {
- workspaceId = token.projectId;
- }
+ // Find workspaceId if it's a restricted token
+ if (isRestrictedToken) {
+ workspaceId = token.projectId;
+ }
- waitUntil(
- // update last used time for the token (only once every minute)
- (async () => {
- try {
- const { success } = await ratelimit(1, "1 m").limit(
- `last-used-${hashedKey}`,
- );
-
- if (success) {
- const prismaArgs = {
- where: {
- hashedKey,
- },
- data: {
- lastUsed: new Date(),
- },
- };
-
- if (isRestrictedToken) {
- await prisma.restrictedToken.update(prismaArgs);
- } else {
- await prisma.token.update(prismaArgs);
- }
+ waitUntil(
+ // update last used time for the token (only once every minute)
+ (async () => {
+ try {
+ const { success } = await ratelimit(1, "1 m").limit(
+ `last-used-${hashedKey}`,
+ );
+
+ if (success) {
+ const prismaArgs = {
+ where: {
+ hashedKey,
+ },
+ data: {
+ lastUsed: new Date(),
+ },
+ };
+
+ if (isRestrictedToken) {
+ await prisma.restrictedToken.update(prismaArgs);
+ } else {
+ await prisma.token.update(prismaArgs);
}
- } catch (error) {
- console.error(error);
}
- })(),
- );
-
- session = {
- user: {
- id: token.user.id,
- name: token.user.name || "",
- email: token.user.email || "",
- isMachine: token.user.isMachine,
- },
- };
- } else {
- session = await getSession();
-
- if (!session?.user?.id) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Unauthorized: Login required.",
- });
- }
- }
+ } catch (error) {
+ console.error(error);
+ }
+ })(),
+ );
- workspace = (await prisma.project.findUnique({
- where: {
- id: workspaceId || undefined,
- slug: workspaceSlug || undefined,
- },
- include: {
- users: {
- where: {
- userId: session.user.id,
- },
- select: {
- role: true,
- defaultFolderId: true,
- workspacePreferences: !apiKey, // Hide from API
- },
- },
+ session = {
+ user: {
+ id: token.user.id,
+ name: token.user.name || "",
+ email: token.user.email || "",
+ isMachine: token.user.isMachine,
},
- })) as WorkspaceWithUsers;
+ };
+ } else {
+ session = await getSession();
- // workspace doesn't exist
- if (!workspace || !workspace.users) {
+ if (!session?.user?.id) {
throw new DubApiError({
- code: "not_found",
- message: "Workspace not found.",
+ code: "unauthorized",
+ message: "Unauthorized: Login required.",
});
}
+ }
- // workspace exists but user is not part of it
- if (workspace.users.length === 0) {
- const pendingInvites = await prisma.projectInvite.findUnique({
+ workspace = (await prisma.project.findUnique({
+ where: {
+ id: workspaceId || undefined,
+ slug: workspaceSlug || undefined,
+ },
+ include: {
+ users: {
where: {
- email_projectId: {
- email: session.user.email,
- projectId: workspace.id,
- },
+ userId: session.user.id,
},
select: {
- expires: true,
+ role: true,
+ defaultFolderId: true,
+ workspacePreferences: !apiKey, // Hide from API
},
- });
+ },
+ },
+ })) as WorkspaceWithUsers;
+
+ // workspace doesn't exist
+ if (!workspace || !workspace.users) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Workspace not found.",
+ });
+ }
- if (!pendingInvites) {
- throw new DubApiError({
- code: "not_found",
- message: "Workspace not found.",
- });
- } else if (pendingInvites.expires < new Date()) {
- throw new DubApiError({
- code: "invite_expired",
- message: "Workspace invite expired.",
- });
- } else {
- throw new DubApiError({
- code: "invite_pending",
- message: "Workspace invite pending.",
- });
- }
- }
+ // workspace exists but user is not part of it
+ if (workspace.users.length === 0) {
+ const pendingInvites = await prisma.projectInvite.findUnique({
+ where: {
+ email_projectId: {
+ email: session.user.email,
+ projectId: workspace.id,
+ },
+ },
+ select: {
+ expires: true,
+ },
+ });
- // Machine users have owner role by default
- // Only workspace owners can create machine users
- if (session.user.isMachine) {
- workspace.users[0].role = "owner";
+ if (!pendingInvites) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Workspace not found.",
+ });
+ } else if (pendingInvites.expires < new Date()) {
+ throw new DubApiError({
+ code: "invite_expired",
+ message: "Workspace invite expired.",
+ });
+ } else {
+ throw new DubApiError({
+ code: "invite_pending",
+ message: "Workspace invite pending.",
+ });
}
+ }
- permissions = getPermissionsByRole(workspace.users[0].role);
-
- // Find the subset of permissions that the user has access to based on the token scopes
- if (isRestrictedToken) {
- const tokenScopes: Scope[] = token.scopes.split(" ") || [];
- permissions = mapScopesToPermissions(tokenScopes).filter((p) =>
- permissions.includes(p),
- );
- }
+ // Machine users have owner role by default
+ // Only workspace owners can create machine users
+ if (session.user.isMachine) {
+ workspace.users[0].role = "owner";
+ }
- // Check user has permission to make the action
- if (!skipPermissionChecks) {
- throwIfNoAccess({
- permissions,
- requiredPermissions,
- workspaceId: workspace.id,
- externalRequest: Boolean(apiKey),
- });
- }
+ permissions = getPermissionsByRole(workspace.users[0].role);
- // beta feature checks
- if (featureFlag) {
- let flags = await getFeatureFlags({
- workspaceId: workspace.id,
- });
+ // Find the subset of permissions that the user has access to based on the token scopes
+ if (isRestrictedToken) {
+ const tokenScopes: Scope[] = token.scopes.split(" ") || [];
+ permissions = mapScopesToPermissions(tokenScopes).filter((p) =>
+ permissions.includes(p),
+ );
+ }
- if (!flags[featureFlag]) {
- throw new DubApiError({
- code: "forbidden",
- message: "Unauthorized: Beta feature.",
- });
- }
- }
+ // Check user has permission to make the action
+ if (!skipPermissionChecks) {
+ throwIfNoAccess({
+ permissions,
+ requiredPermissions,
+ workspaceId: workspace.id,
+ externalRequest: Boolean(apiKey),
+ });
+ }
- const url = new URL(req.url || "", API_DOMAIN);
+ // beta feature checks
+ if (featureFlag) {
+ let flags = await getFeatureFlags({
+ workspaceId: workspace.id,
+ });
- // plan checks
- if (!requiredPlan.includes(workspace.plan)) {
+ if (!flags[featureFlag]) {
throw new DubApiError({
code: "forbidden",
- message: "Unauthorized: Need higher plan.",
+ message: "Unauthorized: Beta feature.",
});
}
+ }
- // analytics API checks
- if (
- workspace.plan === "free" &&
- apiKey &&
- url.pathname.includes("/analytics")
- ) {
- throw new DubApiError({
- code: "forbidden",
- message: "Analytics API is only available on paid plans.",
- });
- }
+ const url = new URL(req.url || "", API_DOMAIN);
- return await handler({
- req,
- params,
- searchParams,
- headers,
- session,
- workspace,
- permissions,
+ // plan checks
+ if (!requiredPlan.includes(workspace.plan)) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Unauthorized: Need higher plan.",
});
- } catch (error) {
- req.log.error(error);
-
- // Log the conversion events for debugging purposes
- waitUntil(
- (async () => {
- const paths = ["/track/lead", "/track/sale"];
-
- if (workspace && paths.includes(req.nextUrl.pathname)) {
- logConversionEvent({
- workspace_id: workspace.id,
- path: req.nextUrl.pathname,
- error: error.message,
- });
- }
- })(),
- );
+ }
- return handleAndReturnErrorResponse(error, headers);
+ // analytics API checks
+ if (
+ workspace.plan === "free" &&
+ apiKey &&
+ url.pathname.includes("/analytics")
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Analytics API is only available on paid plans.",
+ });
}
- },
- );
+
+ return await handler({
+ req,
+ params,
+ searchParams,
+ headers,
+ session,
+ workspace,
+ permissions,
+ });
+ } catch (error) {
+ req.log.error(error);
+
+ // Log the conversion events for debugging purposes
+ waitUntil(
+ (async () => {
+ const paths = ["/track/lead", "/track/sale"];
+
+ if (workspace && paths.includes(req.nextUrl.pathname)) {
+ logConversionEvent({
+ workspace_id: workspace.id,
+ path: req.nextUrl.pathname,
+ error: error.message,
+ });
+ }
+ })(),
+ );
+
+ return handleAndReturnErrorResponse(error, headers);
+ }
+ });
};
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index bfc167a913..4cb52b6c2c 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -18,7 +18,7 @@ import {
nanoid,
punyEncode,
} from "@dub/utils";
-import { ipAddress, geolocation } from "@vercel/functions";
+import { geolocation, ipAddress } from "@vercel/functions";
import { cookies } from "next/headers";
import {
NextFetchEvent,
@@ -153,12 +153,12 @@ export default async function LinkMiddleware(
webhookIds,
testVariants,
testCompletedAt,
- projectId: workspaceId
+ projectId: workspaceId,
} = cachedLink;
const geo = geolocation(req);
- const testUrl = resolveABTestURL({
+ const testUrl = await resolveABTestURL({
testVariants,
testCompletedAt,
});
@@ -301,7 +301,9 @@ export default async function LinkMiddleware(
const ua = userAgent(req);
const { country } =
- process.env.VERCEL === "1" && geolocation(req) ? geolocation(req) : LOCALHOST_GEO_DATA;
+ process.env.VERCEL === "1" && geolocation(req)
+ ? geolocation(req)
+ : LOCALHOST_GEO_DATA;
// rewrite to proxy page (/proxy/[domain]/[key]) if it's a bot and proxy is enabled
if (isBot && proxy) {
diff --git a/apps/web/lib/middleware/utils/resolve-ab-test-url.ts b/apps/web/lib/middleware/utils/resolve-ab-test-url.ts
index bb4b986ec7..0a6245cc64 100644
--- a/apps/web/lib/middleware/utils/resolve-ab-test-url.ts
+++ b/apps/web/lib/middleware/utils/resolve-ab-test-url.ts
@@ -1,11 +1,11 @@
import { ABTestVariantsSchema, MAX_TEST_COUNT } from "@/lib/zod/schemas/links";
-import { cookies, type UnsafeUnwrappedCookies } from "next/headers";
+import { cookies } from "next/headers";
import { z } from "zod";
/**
* Determines the destination URL for a link with A/B testVariants using weighted random selection
*/
-export const resolveABTestURL = ({
+export const resolveABTestURL = async ({
testVariants,
testCompletedAt,
}: {
@@ -26,7 +26,7 @@ export const resolveABTestURL = ({
return null;
}
- const cookieStore = (cookies() as unknown as UnsafeUnwrappedCookies);
+ const cookieStore = await cookies();
const urlFromCookie = cookieStore.get("dub_test_url")?.value;
if (
urlFromCookie &&