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.

authenticate all track endpoints with `workspaceId`

Kiran K9d613a99ae74
diff --git a/apps/web/app/api/track/customer/route.ts b/apps/web/app/api/track/customer/route.ts
index 485f24d5fa..1182d1468f 100644
--- a/apps/web/app/api/track/customer/route.ts
+++ b/apps/web/app/api/track/customer/route.ts
@@ -1,12 +1,14 @@
import { parseRequestBody } from "@/lib/api/utils";
-import { withWorkspace } from "@/lib/auth";
+import { withSessionEdge } from "@/lib/auth/session-edge";
import { recordCustomer } from "@/lib/tinybird";
import { trackCustomerRequestSchema } from "@/lib/zod/schemas";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
+export const runtime = "edge";
+
// POST /api/track/customer – Track a customer object
-export const POST = withWorkspace(async ({ req, workspace }) => {
+export const POST = withSessionEdge(async ({ req, workspace }) => {
const { customerId, customerName, customerEmail, customerAvatar } =
trackCustomerRequestSchema.parse(await parseRequestBody(req));
diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.ts
index ac40c2b37a..2010f3a0ee 100644
--- a/apps/web/app/api/track/lead/route.ts
+++ b/apps/web/app/api/track/lead/route.ts
@@ -9,9 +9,7 @@ import { NextResponse } from "next/server";
export const runtime = "edge";
// POST /api/track/lead – Track a lead conversion event
-export const POST = withSessionEdge(async ({ req, searchParams }) => {
- const { workspaceId } = searchParams;
-
+export const POST = withSessionEdge(async ({ req, workspace }) => {
const {
clickId,
eventName,
@@ -54,7 +52,7 @@ export const POST = withSessionEdge(async ({ req, searchParams }) => {
name: customerName,
email: customerEmail,
avatar: customerAvatar,
- workspace_id: workspaceId,
+ workspace_id: workspace.id,
}),
]);
})(),
diff --git a/apps/web/lib/auth/session-edge.ts b/apps/web/lib/auth/session-edge.ts
index 30cb74c9c5..bdf7f545b5 100644
--- a/apps/web/lib/auth/session-edge.ts
+++ b/apps/web/lib/auth/session-edge.ts
@@ -1,15 +1,26 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { getSearchParams } from "@dub/utils";
+import { Project } from "@prisma/client";
import { internal_runWithWaitUntil as waitUntil } from "next/dist/server/web/internal-edge-wait-until";
-import { getToken, updateTokenLastUsed } from "../planetscale";
+import {
+ getToken,
+ getWorkspaceById,
+ getWorkspaceBySlug,
+ updateTokenLastUsed,
+} from "../planetscale";
import { ratelimit } from "../upstash";
import { hashToken } from "./hash-token";
-import { WithSessionHandler } from "./session";
+
+interface Handler {
+ ({ req, workspace }: { req: Request; workspace: Project }): Promise<Response>;
+}
export const withSessionEdge =
- (handler: WithSessionHandler) =>
+ (handler: Handler) =>
async (req: Request, { params }: { params: Record<string, string> }) => {
let headers = {};
+ let workspace: Project | null = null;
+ const searchParams = getSearchParams(req.url);
const authorizationHeader = req.headers.get("Authorization");
try {
@@ -62,24 +73,41 @@ export const withSessionEdge =
});
}
- // Update token last used
- waitUntil(() => updateTokenLastUsed(hashedKey));
+ // Fetch workspace
+ const idOrSlug =
+ params?.idOrSlug ||
+ searchParams.workspaceId ||
+ params?.slug ||
+ searchParams.projectSlug;
- const session = {
- user: {
- id: user.id,
- name: user.name || "",
- email: user.email || "",
- },
- };
+ if (!idOrSlug) {
+ throw new DubApiError({
+ code: "not_found",
+ message:
+ "Workspace id not found. Did you forget to include a `workspaceId` query parameter? Learn more: https://d.to/id",
+ });
+ }
+
+ if (idOrSlug.startsWith("ws_")) {
+ workspace = await getWorkspaceById(idOrSlug);
+ } else {
+ workspace = await getWorkspaceBySlug(idOrSlug);
+ }
// TODO:
- // Extract workspaceId and validate it
+ // Check user/apiKey has access to workspace
+
+ if (!workspace) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Workspace not found.",
+ });
+ }
- // Fetch search params
- const searchParams = getSearchParams(req.url);
+ // Update token last used
+ waitUntil(() => updateTokenLastUsed(hashedKey));
- return await handler({ req, params, searchParams, session });
+ return await handler({ req, workspace });
} catch (error) {
return handleAndReturnErrorResponse(error, headers);
}
diff --git a/apps/web/lib/auth/session.ts b/apps/web/lib/auth/session.ts
index 5803abc01a..e003ebc464 100644
--- a/apps/web/lib/auth/session.ts
+++ b/apps/web/lib/auth/session.ts
@@ -6,7 +6,7 @@ import { getSearchParams } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { Session, getSession } from "./utils";
-export interface WithSessionHandler {
+interface WithSessionHandler {
({
req,
params,
diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.ts
index d73c134f5a..31129352eb 100644
--- a/apps/web/lib/planetscale.ts
+++ b/apps/web/lib/planetscale.ts
@@ -1,7 +1,7 @@
import { nanoid, punyEncode } from "@dub/utils";
import { connect } from "@planetscale/database";
-import { User } from "@prisma/client";
-import { DomainProps, WorkspaceProps } from "./types";
+import { Project, User } from "@prisma/client";
+import { DomainProps } from "./types";
export const DATABASE_URL =
process.env.PLANETSCALE_DATABASE_URL || process.env.DATABASE_URL;
@@ -16,13 +16,11 @@ export const getWorkspaceViaEdge = async (workspaceId: string) => {
if (!DATABASE_URL) return null;
const { rows } =
- (await conn.execute("SELECT * FROM Project WHERE id = ?", [
+ (await conn.execute<Project>("SELECT * FROM Project WHERE id = ? LIMIT 1", [
workspaceId.replace("ws_", ""),
])) || {};
- return rows && Array.isArray(rows) && rows.length > 0
- ? (rows[0] as WorkspaceProps)
- : null;
+ return rows && Array.isArray(rows) && rows.length > 0 ? rows[0] : null;
};
export const incrementWorkspaceAIUsage = async (workspaceId: string) => {
@@ -156,3 +154,21 @@ export const updateTokenLastUsed = async (hashedKey: string) => {
[hashedKey],
);
};
+
+export const getWorkspaceById = async (workspaceId: string) => {
+ const { rows } = await conn.execute<Project>(
+ "SELECT * FROM Project WHERE id = ? LIMIT 1",
+ [workspaceId.replace("ws_", "")],
+ );
+
+ return rows && Array.isArray(rows) && rows.length > 0 ? rows[0] : null;
+};
+
+export const getWorkspaceBySlug = async (workspaceSlug: string) => {
+ const { rows } = await conn.execute<Project>(
+ "SELECT * FROM Project WHERE slug = ? LIMIT 1",
+ [workspaceSlug],
+ );
+
+ return rows && Array.isArray(rows) && rows.length > 0 ? rows[0] : null;
+};