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.

add betaFeature check, stripeConnectId prop

Steven Tey01a094db659a
diff --git a/apps/web/app/api/track/customer/route.ts b/apps/web/app/api/track/customer/route.ts
index 1182d1468f..4ba1f18226 100644
--- a/apps/web/app/api/track/customer/route.ts
+++ b/apps/web/app/api/track/customer/route.ts
@@ -1,5 +1,5 @@
import { parseRequestBody } from "@/lib/api/utils";
-import { withSessionEdge } from "@/lib/auth/session-edge";
+import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";
import { recordCustomer } from "@/lib/tinybird";
import { trackCustomerRequestSchema } from "@/lib/zod/schemas";
import { waitUntil } from "@vercel/functions";
@@ -8,19 +8,22 @@ import { NextResponse } from "next/server";
export const runtime = "edge";
// POST /api/track/customer – Track a customer object
-export const POST = withSessionEdge(async ({ req, workspace }) => {
- const { customerId, customerName, customerEmail, customerAvatar } =
- trackCustomerRequestSchema.parse(await parseRequestBody(req));
+export const POST = withWorkspaceEdge(
+ async ({ req, workspace }) => {
+ const { customerId, customerName, customerEmail, customerAvatar } =
+ trackCustomerRequestSchema.parse(await parseRequestBody(req));
- waitUntil(
- recordCustomer({
- customer_id: customerId,
- name: customerName,
- email: customerEmail,
- avatar: customerAvatar,
- workspace_id: workspace.id,
- }),
- );
+ waitUntil(
+ recordCustomer({
+ customer_id: customerId,
+ name: customerName,
+ email: customerEmail,
+ avatar: customerAvatar,
+ workspace_id: workspace.id,
+ }),
+ );
- return NextResponse.json({ success: true });
-});
+ return NextResponse.json({ success: true });
+ },
+ { betaFeature: true },
+);
diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.ts
index c4d5a2104d..4cb522c66e 100644
--- a/apps/web/app/api/track/lead/route.ts
+++ b/apps/web/app/api/track/lead/route.ts
@@ -1,6 +1,6 @@
import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
-import { withSessionEdge } from "@/lib/auth/session-edge";
+import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";
import { createCustomer, getCustomer } from "@/lib/planetscale";
import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";
import { clickEventSchemaTB, trackLeadRequestSchema } from "@/lib/zod/schemas";
@@ -11,74 +11,77 @@ import { NextResponse } from "next/server";
export const runtime = "edge";
// POST /api/track/lead – Track a lead conversion event
-export const POST = withSessionEdge(async ({ req, workspace }) => {
- const {
- clickId,
- eventName,
- metadata,
- customerName,
- customerEmail,
- customerAvatar,
- customerId: externalId,
- } = trackLeadRequestSchema.parse(await parseRequestBody(req));
+export const POST = withWorkspaceEdge(
+ async ({ req, workspace }) => {
+ const {
+ clickId,
+ eventName,
+ metadata,
+ customerName,
+ customerEmail,
+ customerAvatar,
+ customerId: externalId,
+ } = trackLeadRequestSchema.parse(await parseRequestBody(req));
- if (externalId) {
- const customer = await getCustomer({
- externalId,
- workspaceId: workspace.id,
- });
-
- if (customer) {
- throw new DubApiError({
- code: "conflict",
- message: `A customer with the customerId ${externalId} already exists in this workspace.`,
+ if (externalId) {
+ const customer = await getCustomer({
+ externalId,
+ workspaceId: workspace.id,
});
- }
- }
- waitUntil(
- (async () => {
- const clickEvent = await getClickEvent({ clickId });
-
- if (!clickEvent || clickEvent.data.length === 0) {
- return;
+ if (customer) {
+ throw new DubApiError({
+ code: "conflict",
+ message: `A customer with the customerId ${externalId} already exists in this workspace.`,
+ });
}
+ }
- const customerId = nanoid(16);
- const clickData = clickEventSchemaTB
- .omit({ timestamp: true })
- .parse(clickEvent.data[0]);
+ waitUntil(
+ (async () => {
+ const clickEvent = await getClickEvent({ clickId });
- await Promise.all([
- recordLead({
- ...clickData,
- event_name: eventName,
- event_id: nanoid(16),
- customer_id: customerId,
- metadata,
- }),
+ if (!clickEvent || clickEvent.data.length === 0) {
+ return;
+ }
- workspace.stripeConnectId &&
- externalId &&
- (createCustomer({
- id: customerId,
- name: customerName || "",
- email: customerEmail || "",
- avatar: customerAvatar || "",
- externalId,
- projectId: workspace.id,
- projectConnectId: workspace.stripeConnectId,
- }),
- recordCustomer({
+ const customerId = nanoid(16);
+ const clickData = clickEventSchemaTB
+ .omit({ timestamp: true })
+ .parse(clickEvent.data[0]);
+
+ await Promise.all([
+ recordLead({
+ ...clickData,
+ event_name: eventName,
+ event_id: nanoid(16),
customer_id: customerId,
- name: customerName,
- email: customerEmail,
- avatar: customerAvatar,
- workspace_id: workspace.id,
- })),
- ]);
- })(),
- );
+ metadata,
+ }),
+
+ workspace.stripeConnectId &&
+ externalId &&
+ (createCustomer({
+ id: customerId,
+ name: customerName || "",
+ email: customerEmail || "",
+ avatar: customerAvatar || "",
+ externalId,
+ projectId: workspace.id,
+ projectConnectId: workspace.stripeConnectId,
+ }),
+ recordCustomer({
+ customer_id: customerId,
+ name: customerName,
+ email: customerEmail,
+ avatar: customerAvatar,
+ workspace_id: workspace.id,
+ })),
+ ]);
+ })(),
+ );
- return NextResponse.json({ success: true });
-});
+ return NextResponse.json({ success: true });
+ },
+ { betaFeature: true },
+);
diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.ts
index 472c37d9a3..fb93c72348 100644
--- a/apps/web/app/api/track/sale/route.ts
+++ b/apps/web/app/api/track/sale/route.ts
@@ -1,5 +1,5 @@
import { parseRequestBody } from "@/lib/api/utils";
-import { withSessionEdge } from "@/lib/auth/session-edge";
+import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";
import { getLeadEvent, recordSale } from "@/lib/tinybird";
import { clickEventSchemaTB, trackSaleRequestSchema } from "@/lib/zod/schemas";
import { nanoid } from "@dub/utils";
@@ -9,48 +9,51 @@ import { NextResponse } from "next/server";
export const runtime = "edge";
// POST /api/track/sale – Track a sale conversion event
-export const POST = withSessionEdge(async ({ req }) => {
- const {
- customerId,
- paymentProcessor,
- productId,
- amount,
- currency,
- recurring,
- recurringInterval,
- recurringIntervalCount,
- refunded,
- metadata,
- } = trackSaleRequestSchema.parse(await parseRequestBody(req));
+export const POST = withWorkspaceEdge(
+ async ({ req }) => {
+ const {
+ customerId,
+ paymentProcessor,
+ productId,
+ amount,
+ currency,
+ recurring,
+ recurringInterval,
+ recurringIntervalCount,
+ refunded,
+ metadata,
+ } = trackSaleRequestSchema.parse(await parseRequestBody(req));
- waitUntil(
- (async () => {
- const leadEvent = await getLeadEvent({ customer_id: customerId });
+ waitUntil(
+ (async () => {
+ const leadEvent = await getLeadEvent({ customer_id: customerId });
- if (!leadEvent || leadEvent.data.length === 0) {
- return;
- }
+ if (!leadEvent || leadEvent.data.length === 0) {
+ return;
+ }
- const clickData = clickEventSchemaTB
- .omit({ timestamp: true })
- .parse(leadEvent.data[0]);
+ const clickData = clickEventSchemaTB
+ .omit({ timestamp: true })
+ .parse(leadEvent.data[0]);
- await recordSale({
- ...clickData,
- customer_id: customerId,
- event_id: nanoid(16),
- payment_processor: paymentProcessor,
- product_id: productId,
- amount,
- currency,
- recurring: recurring ? 1 : 0,
- recurring_interval: recurringInterval,
- recurring_interval_count: recurringIntervalCount,
- refunded: refunded ? 1 : 0,
- metadata: metadata ? JSON.stringify(metadata) : "",
- });
- })(),
- );
+ await recordSale({
+ ...clickData,
+ customer_id: customerId,
+ event_id: nanoid(16),
+ payment_processor: paymentProcessor,
+ product_id: productId,
+ amount,
+ currency,
+ recurring: recurring ? 1 : 0,
+ recurring_interval: recurringInterval,
+ recurring_interval_count: recurringIntervalCount,
+ refunded: refunded ? 1 : 0,
+ metadata: metadata ? JSON.stringify(metadata) : "",
+ });
+ })(),
+ );
- return NextResponse.json({ success: true });
-});
+ return NextResponse.json({ success: true });
+ },
+ { betaFeature: true },
+);
diff --git a/apps/web/lib/auth/session-edge.ts b/apps/web/lib/auth/session-edge.ts
deleted file mode 100644
index bdf7f545b5..0000000000
--- a/apps/web/lib/auth/session-edge.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-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,
- getWorkspaceById,
- getWorkspaceBySlug,
- updateTokenLastUsed,
-} from "../planetscale";
-import { ratelimit } from "../upstash";
-import { hashToken } from "./hash-token";
-
-interface Handler {
- ({ req, workspace }: { req: Request; workspace: Project }): Promise<Response>;
-}
-
-export const withSessionEdge =
- (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 {
- if (!authorizationHeader) {
- throw new DubApiError({
- code: "bad_request",
- message:
- "Missing authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",
- });
- }
-
- 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",
- });
- }
- }
-
- const apiKey = authorizationHeader.replace("Bearer ", "");
- const hashedKey = await hashToken(apiKey);
- const user = await getToken(hashedKey);
-
- if (!user) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Unauthorized: Invalid API key.",
- });
- }
-
- // Check rate limit
- const { success, limit, reset, remaining } = await ratelimit(
- 600,
- "1 m",
- ).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.",
- });
- }
-
- // Fetch workspace
- const idOrSlug =
- params?.idOrSlug ||
- searchParams.workspaceId ||
- params?.slug ||
- searchParams.projectSlug;
-
- 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:
- // Check user/apiKey has access to workspace
-
- if (!workspace) {
- throw new DubApiError({
- code: "not_found",
- message: "Workspace not found.",
- });
- }
-
- // Update token last used
- waitUntil(() => updateTokenLastUsed(hashedKey));
-
- return await handler({ req, workspace });
- } catch (error) {
- return handleAndReturnErrorResponse(error, headers);
- }
- };
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 34aa3bf916..1e143a3104 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -83,6 +83,7 @@ export interface WorkspaceProps {
plan: PlanProps;
stripeId: string | null;
billingCycleStart: number;
+ stripeConnectId: string | null;
createdAt: Date;
domains: {
slug: string;