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.

migrate /ai/completion to withWorkspaceEdge

Steven Tey450fbac0e15b
diff --git a/apps/web/app/api/ai/completion/route.ts b/apps/web/app/api/ai/completion/route.ts
index 9aa6c58d10..a080cde6a1 100644
--- a/apps/web/app/api/ai/completion/route.ts
+++ b/apps/web/app/api/ai/completion/route.ts
@@ -1,14 +1,10 @@
import { anthropic } from "@/lib/anthropic";
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import {
- getWorkspaceViaEdge,
- incrementWorkspaceAIUsage,
-} from "@/lib/planetscale";
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";
+import { prismaEdge } from "@/lib/prisma/edge";
import z from "@/lib/zod";
-import { getSearchParams } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { AnthropicStream, StreamingTextResponse } from "ai";
-import { NextRequest } from "next/server";
export const runtime = "edge";
@@ -21,55 +17,55 @@ const completionSchema = z.object({
});
// POST /api/ai/completion – Generate AI completion
-export async function POST(req: NextRequest) {
- const searchParams = getSearchParams(req.url);
- const { workspaceId } = searchParams;
- const workspace = await getWorkspaceViaEdge(workspaceId);
-
- if (!anthropic) {
- console.error("Anthropic is not configured. Skipping the request.");
- return new Response(null, { status: 200 });
- }
-
- if (!workspace) {
- return new Response("Workspace not found", { status: 404 });
- }
+export const POST = withWorkspaceEdge(
+ async ({ req, workspace }) => {
+ if (!anthropic) {
+ console.error("Anthropic is not configured. Skipping the request.");
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Anthropic API key is not configured.",
+ });
+ }
- if (workspace.aiUsage > workspace.aiLimit) {
- return new Response(
- "You've reached your AI usage limit. Upgrade to Pro to get unlimited AI credits.",
- { status: 429 },
- );
- }
+ try {
+ const {
+ // comment for better diff
+ prompt,
+ model,
+ } = completionSchema.parse(await req.json());
- try {
- const {
- // comment for better diff
- prompt,
- model,
- } = completionSchema.parse(await req.json());
+ const response = await anthropic.messages.create({
+ messages: [
+ {
+ role: "user",
+ content: prompt,
+ },
+ ],
+ model,
+ stream: true,
+ max_tokens: 300,
+ });
- const response = await anthropic.messages.create({
- messages: [
- {
- role: "user",
- content: prompt,
- },
- ],
- model,
- stream: true,
- max_tokens: 300,
- });
+ const stream = AnthropicStream(response);
- const stream = AnthropicStream(response);
+ // only count usage for the sonnet model
+ if (model === "claude-3-sonnet-20240229") {
+ waitUntil(
+ prismaEdge.project.update({
+ where: { id: workspace.id.replace("ws_", "") },
+ data: {
+ aiUsage: {
+ increment: 1,
+ },
+ },
+ }),
+ );
+ }
- // only count usage for the sonnet model
- if (model === "claude-3-sonnet-20240229") {
- waitUntil(incrementWorkspaceAIUsage(workspaceId));
+ return new StreamingTextResponse(stream);
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
}
-
- return new StreamingTextResponse(stream);
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
-}
+ },
+ { needNotExceededAI: true },
+);
diff --git a/apps/web/lib/api/errors.ts b/apps/web/lib/api/errors.ts
index 15c2eedc40..0a337ce0a6 100644
--- a/apps/web/lib/api/errors.ts
+++ b/apps/web/lib/api/errors.ts
@@ -213,10 +213,10 @@ export const exceededLimitError = ({
}: {
plan: PlanProps;
limit: number;
- type: "clicks" | "links" | "domains" | "tags" | "users";
+ type: "clicks" | "links" | "AI" | "domains" | "tags" | "users";
}) => {
return `You've reached your ${
- type === "links" ? "monthly" : ""
+ type === "links" || type === "AI" ? "monthly" : ""
} limit of ${limit} ${
limit === 1 ? type.slice(0, -1) : type
} on the ${capitalize(plan)} plan. Please upgrade to add more ${type}.`;
diff --git a/apps/web/lib/auth/workspace-edge.ts b/apps/web/lib/auth/workspace-edge.ts
new file mode 100644
index 0000000000..07c9bdc85e
--- /dev/null
+++ b/apps/web/lib/auth/workspace-edge.ts
@@ -0,0 +1,351 @@
+import {
+ DubApiError,
+ exceededLimitError,
+ handleAndReturnErrorResponse,
+} from "@/lib/api/errors";
+import { PlanProps, WorkspaceProps } from "@/lib/types";
+import { ratelimit } from "@/lib/upstash";
+import { API_DOMAIN, getSearchParams } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
+import { StreamingTextResponse } from "ai";
+import { getToken } from "next-auth/jwt";
+import { NextRequest } from "next/server";
+import { prismaEdge } from "../prisma/edge";
+import { hashToken } from "./hash-token";
+import { Session } from "./utils";
+
+interface WithWorkspaceEdgeHandler {
+ ({
+ req,
+ params,
+ searchParams,
+ headers,
+ session,
+ workspace,
+ }: {
+ req: Request;
+ params: Record<string, string>;
+ searchParams: Record<string, string>;
+ headers?: Record<string, string>;
+ session: Session;
+ workspace: WorkspaceProps;
+ }): Promise<Response | StreamingTextResponse>;
+}
+
+export const withWorkspaceEdge = (
+ handler: WithWorkspaceEdgeHandler,
+ {
+ requiredPlan = [
+ "free",
+ "pro",
+ "business",
+ "business plus",
+ "business max",
+ "business extra",
+ "enterprise",
+ ], // if the action needs a specific plan
+ requiredRole = ["owner", "member"],
+ needNotExceededClicks, // if the action needs the user to not have exceeded their clicks usage
+ needNotExceededLinks, // if the action needs the user to not have exceeded their links usage
+ needNotExceededAI, // if the action needs the user to not have exceeded their AI usage
+ allowAnonymous, // special case for /api/links (POST /api/links) – allow no session
+ allowSelf, // special case for removing yourself from a workspace
+ skipLinkChecks, // special case for /api/links/exists – skip link checks
+ domainChecks,
+ }: {
+ requiredPlan?: Array<PlanProps>;
+ requiredRole?: Array<"owner" | "member">;
+ needNotExceededClicks?: boolean;
+ needNotExceededLinks?: boolean;
+ needNotExceededAI?: boolean;
+ allowAnonymous?: boolean;
+ allowSelf?: boolean;
+ skipLinkChecks?: boolean;
+ domainChecks?: boolean;
+ } = {},
+) => {
+ return async (
+ req: Request,
+ { 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 ", "");
+ }
+
+ const domain = params?.domain || searchParams.domain;
+ const key = searchParams.key;
+ const linkId =
+ params?.linkId ||
+ searchParams.linkId ||
+ searchParams.externalId ||
+ undefined;
+
+ let session: Session | undefined;
+ let workspaceId: string | undefined;
+ let workspaceSlug: string | undefined;
+
+ const idOrSlug =
+ params?.idOrSlug ||
+ searchParams.workspaceId ||
+ params?.slug ||
+ searchParams.projectSlug;
+
+ // if there's no workspace ID or slug
+ if (!idOrSlug) {
+ // for /api/links (POST /api/links) – allow no session (but warn if user provides apiKey)
+ if (allowAnonymous && !apiKey) {
+ // @ts-expect-error
+ return await handler({
+ req,
+ params: params || {},
+ searchParams,
+ headers,
+ });
+ } else {
+ 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_")) {
+ workspaceId = idOrSlug.replace("ws_", "");
+ } else {
+ workspaceSlug = idOrSlug;
+ }
+
+ if (apiKey) {
+ const hashedKey = await hashToken(apiKey);
+
+ const token = await prismaEdge.token.findUnique({
+ where: {
+ hashedKey,
+ },
+ select: {
+ user: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ },
+ },
+ });
+ if (!token) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Unauthorized: Invalid API key.",
+ });
+ }
+
+ 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.",
+ });
+ }
+ waitUntil(
+ prismaEdge.token.update({
+ where: {
+ hashedKey,
+ },
+ data: {
+ lastUsed: new Date(),
+ },
+ }),
+ );
+ session = {
+ user: {
+ id: token.user.id,
+ name: token.user.name || "",
+ email: token.user.email || "",
+ },
+ };
+ } 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: {
+ slug: true,
+ primary: true,
+ },
+ },
+ },
+ })) as WorkspaceProps;
+
+ if (!workspace || !workspace.users) {
+ // workspace doesn't exist
+ throw new DubApiError({
+ code: "not_found",
+ message: "Workspace not found.",
+ });
+ }
+
+ // 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.",
+ });
+ }
+ }
+
+ // workspace role checks
+ if (
+ !requiredRole.includes(workspace.users[0].role) &&
+ !(allowSelf && searchParams.userId === session.user.id)
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Unauthorized: Insufficient permissions.",
+ });
+ }
+
+ // clicks usage overage checks
+ if (needNotExceededClicks && workspace.usage > workspace.usageLimit) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: exceededLimitError({
+ plan: workspace.plan,
+ limit: workspace.usageLimit,
+ type: "clicks",
+ }),
+ });
+ }
+
+ // links usage overage checks
+ if (
+ needNotExceededLinks &&
+ workspace.linksUsage > workspace.linksLimit &&
+ (workspace.plan === "free" || workspace.plan === "pro")
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: exceededLimitError({
+ plan: workspace.plan,
+ limit: workspace.linksLimit,
+ type: "links",
+ }),
+ });
+ }
+
+ // 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",
+ }),
+ });
+ }
+
+ // plan checks
+ if (!requiredPlan.includes(workspace.plan)) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Unauthorized: Need higher plan.",
+ });
+ }
+
+ // analytics API checks
+ const url = new URL(req.url || "", API_DOMAIN);
+ 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: params || {},
+ searchParams,
+ headers,
+ session,
+ workspace,
+ });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error, headers);
+ }
+ };
+};
diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.ts
index 0e2646c5e4..5c1104bf71 100644
--- a/apps/web/lib/planetscale.ts
+++ b/apps/web/lib/planetscale.ts
@@ -24,15 +24,6 @@ export const getWorkspaceViaEdge = async (workspaceId: string) => {
: null;
};
-export const incrementWorkspaceAIUsage = async (workspaceId: string) => {
- if (!DATABASE_URL) return null;
-
- return await conn.execute(
- "UPDATE Project p SET p.aiUsage = p.aiUsage + 1 WHERE id = ?",
- [workspaceId.replace("ws_", "")],
- );
-};
-
export const getDomainViaEdge = async (domain: string) => {
if (!DATABASE_URL) return null;