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.

final changes

Steven Tey36137486ffb9
diff --git a/apps/web/app/api/ai/completion/route.ts b/apps/web/app/api/ai/completion/route.ts
index 9e4a5936ba..45eef2d21a 100644
--- a/apps/web/app/api/ai/completion/route.ts
+++ b/apps/web/app/api/ai/completion/route.ts
@@ -1,13 +1,12 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";
+import { throwIfAIUsageExceeded } from "@/lib/api/links/usage-checks";
+import { withWorkspace } from "@/lib/auth";
import z from "@/lib/zod";
import { anthropic } from "@ai-sdk/anthropic";
import { prismaEdge } from "@dub/prisma/edge";
import { waitUntil } from "@vercel/functions";
import { streamText } from "ai";
-export const runtime = "edge";
-
const completionSchema = z.object({
prompt: z.string(),
model: z
@@ -17,43 +16,42 @@ const completionSchema = z.object({
});
// POST /api/ai/completion – Generate AI completion
-export const POST = withWorkspaceEdge(
- async ({ req, workspace }) => {
- try {
- const {
- // comment for better diff
- prompt,
- model,
- } = completionSchema.parse(await req.json());
+export const POST = withWorkspace(async ({ req, workspace }) => {
+ try {
+ const {
+ // comment for better diff
+ prompt,
+ model,
+ } = completionSchema.parse(await req.json());
- const result = streamText({
- model: anthropic(model),
- messages: [
- {
- role: "user",
- content: prompt,
- },
- ],
- maxTokens: 300,
- });
- // only count usage for the sonnet model
- if (model === "claude-3-5-sonnet-latest") {
- waitUntil(
- prismaEdge.project.update({
- where: { id: workspace.id.replace("ws_", "") },
- data: {
- aiUsage: {
- increment: 1,
- },
- },
- }),
- );
- }
+ throwIfAIUsageExceeded(workspace);
- return result.toDataStreamResponse();
- } catch (error) {
- return handleAndReturnErrorResponse(error);
+ const result = streamText({
+ model: anthropic(model),
+ messages: [
+ {
+ role: "user",
+ content: prompt,
+ },
+ ],
+ maxTokens: 300,
+ });
+ // only count usage for the sonnet model
+ if (model === "claude-3-5-sonnet-latest") {
+ waitUntil(
+ prismaEdge.project.update({
+ where: { id: workspace.id.replace("ws_", "") },
+ data: {
+ aiUsage: {
+ increment: 1,
+ },
+ },
+ }),
+ );
}
- },
- { needNotExceededAI: true },
-);
+
+ return result.toDataStreamResponse();
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+});
diff --git a/apps/web/app/api/callback/plain/route.ts b/apps/web/app/api/callback/plain/route.ts
index 0536cb09c0..14b1c1c4d1 100644
--- a/apps/web/app/api/callback/plain/route.ts
+++ b/apps/web/app/api/callback/plain/route.ts
@@ -171,11 +171,13 @@ export async function POST(req: NextRequest) {
badgeColor:
plan === "enterprise"
? "RED"
- : plan.startsWith("business")
- ? "GREEN"
- : plan === "pro"
- ? "BLUE"
- : "GREY",
+ : plan === "advanced"
+ ? "ORANGE"
+ : plan.startsWith("business")
+ ? "GREEN"
+ : plan === "pro"
+ ? "BLUE"
+ : "GREY",
},
},
],
diff --git a/apps/web/lib/api/links/usage-checks.ts b/apps/web/lib/api/links/usage-checks.ts
index 8a2be20264..0b3dad819d 100644
--- a/apps/web/lib/api/links/usage-checks.ts
+++ b/apps/web/lib/api/links/usage-checks.ts
@@ -31,3 +31,16 @@ export const throwIfLinksUsageExceeded = (workspace: WorkspaceWithUsers) => {
});
}
};
+
+export const throwIfAIUsageExceeded = (workspace: WorkspaceWithUsers) => {
+ if (workspace.aiUsage >= workspace.aiLimit) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: exceededLimitError({
+ plan: workspace.plan,
+ limit: workspace.aiLimit,
+ type: "AI",
+ }),
+ });
+ }
+};
diff --git a/apps/web/lib/auth/workspace-edge.ts b/apps/web/lib/auth/workspace-edge.ts
deleted file mode 100644
index 4256ab84b1..0000000000
--- a/apps/web/lib/auth/workspace-edge.ts
+++ /dev/null
@@ -1,415 +0,0 @@
-import {
- DubApiError,
- exceededLimitError,
- handleAndReturnErrorResponse,
-} from "@/lib/api/errors";
-import { BetaFeatures, PlanProps, WorkspaceProps } from "@/lib/types";
-import { ratelimit } from "@/lib/upstash";
-import { prismaEdge } from "@dub/prisma/edge";
-import { API_DOMAIN, getSearchParams } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
-import { getToken } from "next-auth/jwt";
-import { AxiomRequest, withAxiom } from "next-axiom";
-import { NextRequest } from "next/server";
-import {
- PermissionAction,
- getPermissionsByRole,
-} from "../api/rbac/permissions";
-import { throwIfNoAccess } from "../api/tokens/permissions";
-import { Scope, mapScopesToPermissions } from "../api/tokens/scopes";
-import { getFeatureFlags } from "../edge-config";
-import { hashToken } from "./hash-token";
-import type { Session } from "./utils";
-
-interface WithWorkspaceEdgeHandler {
- ({
- req,
- params,
- searchParams,
- headers,
- session,
- workspace,
- permissions,
- }: {
- req: Request;
- params: Record<string, string>;
- searchParams: Record<string, string>;
- headers?: Record<string, string>;
- session: Session;
- workspace: WorkspaceProps;
- permissions: PermissionAction[];
- }): Promise<Response>;
-}
-
-export const withWorkspaceEdge = (
- handler: WithWorkspaceEdgeHandler,
- {
- requiredPlan = [
- "free",
- "pro",
- "business",
- "business plus",
- "business max",
- "business extra",
- "enterprise",
- ], // if the action needs a specific plan
- needNotExceededAI, // if the action needs the user to not have exceeded their AI usage
- featureFlag, // if the action needs a specific feature flag
- requiredPermissions = [],
- }: {
- requiredPlan?: Array<PlanProps>;
- needNotExceededAI?: boolean;
- featureFlag?: BetaFeatures;
- requiredPermissions?: PermissionAction[];
- } = {},
-) => {
- return withAxiom(
- async (
- req: AxiomRequest,
- { params = {} }: { params: Record<string, string> | undefined },
- ) => {
- const searchParams = getSearchParams(req.url);
-
- let apiKey: string | undefined = undefined;
- let headers = {};
-
- 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_");
-
- 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")) {
- // @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 = idOrSlug.replace("ws_", "");
- } else {
- workspaceSlug = idOrSlug;
- }
- }
-
- if (apiKey) {
- const hashedKey = await hashToken(apiKey);
- 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 prismaEdge.restrictedToken.findUnique(prismaArgs);
- } else {
- token = await prismaEdge.token.findUnique(prismaArgs);
- }
-
- 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.",
- });
- }
-
- // Rate limit checks for API keys
- const rateLimit = token?.rateLimit || 600;
-
- 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(),
- };
-
- 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;
- }
-
- waitUntil(
- // update last used time for the token
- (async () => {
- const prismaArgs = {
- where: {
- hashedKey,
- },
- data: {
- lastUsed: new Date(),
- },
- };
-
- if (isRestrictedToken) {
- await prismaEdge.restrictedToken.update(prismaArgs);
- } else {
- await prismaEdge.token.update(prismaArgs);
- }
- })(),
- );
-
- session = {
- user: {
- id: token.user.id,
- name: token.user.name || "",
- email: token.user.email || "",
- isMachine: token.user.isMachine,
- },
- };
- } else {
- session = (await getToken({
- req: req as NextRequest,
- secret: process.env.NEXTAUTH_SECRET,
- })) as unknown as Session;
-
- if (!session?.user?.id) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Unauthorized: Login required.",
- });
- }
- }
-
- const workspace = (await prismaEdge.project.findUnique({
- where: {
- id: workspaceId || undefined,
- slug: workspaceSlug || undefined,
- },
- include: {
- users: {
- where: {
- userId: session.user.id,
- },
- select: {
- role: true,
- },
- },
- domains: {
- select: {
- id: true,
- slug: true,
- primary: true,
- verified: true,
- },
- },
- },
- })) as WorkspaceProps;
-
- // workspace doesn't exist
- if (!workspace || !workspace.users) {
- throw new DubApiError({
- code: "not_found",
- message: "Workspace not found.",
- });
- }
-
- // Machine users have owner role by default
- // Only workspace owners can create machine users
- if (session.user.isMachine) {
- workspace.users[0].role = "owner";
- }
-
- 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),
- );
-
- // Prevent integration tokens from accessing API endpoints without explicit permissions
- if (token.installationId && requiredPermissions.length === 0) {
- throw new DubApiError({
- code: "forbidden",
- message:
- "You don't have the necessary permissions to complete this request.",
- });
- }
- }
-
- // Check user has permission to make the action
- throwIfNoAccess({
- permissions,
- requiredPermissions,
- workspaceId: workspace.id,
- externalRequest: Boolean(apiKey),
- });
-
- // beta feature checks
- if (featureFlag) {
- const flags = await getFeatureFlags({
- workspaceId: workspace.id,
- });
-
- if (!flags[featureFlag]) {
- throw new DubApiError({
- code: "forbidden",
- message: "Unauthorized: Beta feature.",
- });
- }
- }
-
- // workspace exists but user is not part of it
- if (workspace.users.length === 0) {
- const pendingInvites = await prismaEdge.projectInvite.findUnique({
- where: {
- email_projectId: {
- email: session.user.email,
- projectId: workspace.id,
- },
- },
- select: {
- expires: true,
- },
- });
- 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.",
- });
- }
- }
-
- // AI usage overage checks
- if (needNotExceededAI && workspace.aiUsage > workspace.aiLimit) {
- throw new DubApiError({
- code: "forbidden",
- message: exceededLimitError({
- plan: workspace.plan,
- limit: workspace.aiLimit,
- type: "AI",
- }),
- });
- }
-
- const url = new URL(req.url || "", API_DOMAIN);
-
- // plan checks
- if (!requiredPlan.includes(workspace.plan)) {
- throw new DubApiError({
- code: "forbidden",
- message: "Unauthorized: Need higher plan.",
- });
- }
-
- // 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);
- return handleAndReturnErrorResponse(error, headers);
- }
- },
- );
-};
diff --git a/apps/web/ui/layout/sidebar/workspace-dropdown.tsx b/apps/web/ui/layout/sidebar/workspace-dropdown.tsx
index 043e8a5661..4abccecdd3 100644
--- a/apps/web/ui/layout/sidebar/workspace-dropdown.tsx
+++ b/apps/web/ui/layout/sidebar/workspace-dropdown.tsx
@@ -296,7 +296,7 @@ const getPlanColor = (plan: string) =>
plan === "enterprise"
? "text-purple-700"
: plan === "advanced"
- ? "text-orange-900"
+ ? "text-amber-800"
: plan.startsWith("business")
? "text-blue-900"
: plan === "pro"
diff --git a/apps/web/ui/workspaces/plan-badge.tsx b/apps/web/ui/workspaces/plan-badge.tsx
index 23d5234ccd..f28c964cb7 100644
--- a/apps/web/ui/workspaces/plan-badge.tsx
+++ b/apps/web/ui/workspaces/plan-badge.tsx
@@ -8,11 +8,13 @@ export default function PlanBadge({ plan }: { plan: PlanProps }) {
variant={
plan === "enterprise"
? "violet"
- : plan.startsWith("business")
- ? "sky"
- : plan === "pro"
- ? "blue"
- : "black"
+ : plan === "advanced"
+ ? "amber"
+ : plan.startsWith("business")
+ ? "sky"
+ : plan === "pro"
+ ? "blue"
+ : "black"
}
>
{capitalize(plan)}
diff --git a/packages/ui/src/badge.tsx b/packages/ui/src/badge.tsx
index b1e1ae843c..d8c6ac69c1 100644
--- a/packages/ui/src/badge.tsx
+++ b/packages/ui/src/badge.tsx
@@ -14,6 +14,7 @@ const badgeVariants = cva(
black: "border-black bg-black text-white",
gray: "border-neutral-200 bg-neutral-100 text-neutral-800",
neutral: "border-neutral-400 text-neutral-500",
+ amber: "border-amber-800 bg-amber-800 text-white",
blueGradient:
"bg-gradient-to-r from-blue-100 via-blue-100/50 to-blue-100 border border-blue-200 text-blue-900",
rainbow: