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.

5.1 KB
Raw Blame
import { createId } from "@/lib/api/create-id";
import { DubApiError } from "@/lib/api/errors";
import { scopesToName, validateScopesForRole } from "@/lib/api/tokens/scopes";
import { parseRequestBody } from "@/lib/api/utils";
import { hashToken, withWorkspace } from "@/lib/auth";
import { generateRandomName } from "@/lib/names";
import { prisma } from "@/lib/prisma";
import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { createTokenSchema, tokenSchema } from "@/lib/zod/schemas/token";
import { sendEmail } from "@dub/email";
import APIKeyCreated from "@dub/email/templates/api-key-created";
import { nanoid } from "@dub/utils";
import { Prisma, User } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
import * as z from "zod/v4";

const MAX_WORKSPACE_TOKENS = 100;

const getTokensQuerySchema = z.object({
  userId: z.string().optional(),
});

// GET /api/tokens - get all tokens for a workspace
export const GET = withWorkspace(
  async ({ workspace, searchParams }) => {
    const { userId } = getTokensQuerySchema.parse(searchParams);

    const tokens = await prisma.restrictedToken.findMany({
      where: {
        projectId: workspace.id,
        installationId: null,
        ...(userId && {
          userId,
        }),
      },
      select: {
        id: true,
        name: true,
        partialKey: true,
        scopes: true,
        expires: true,
        lastUsed: true,
        createdAt: true,
        updatedAt: true,
        user: true,
      },
      orderBy: [{ lastUsed: "desc" }, { createdAt: "desc" }],
      take: 100,
    });

    return NextResponse.json(tokenSchema.array().parse(tokens));
  },
  {
    requiredPermissions: ["tokens.read"],
  },
);

// POST /api/tokens – create a new token for a workspace
export const POST = withWorkspace(
  async ({ req, session, workspace }) => {
    await assertRateLimit({
      policy: RATELIMIT_POLICIES.createToken,
      identifier: workspace.id,
    });

    const { name, isMachine, scopes } = createTokenSchema.parse(
      await parseRequestBody(req),
    );

    const role = workspace.users[0].role;

    // Only workspace owners can create machine users
    if (isMachine && role !== "owner") {
      throw new DubApiError({
        code: "forbidden",
        message: "Only workspace owners can create machine users.",
      });
    }

    if (!validateScopesForRole(scopes, role)) {
      throw new DubApiError({
        code: "unprocessable_entity",
        message: "Some of the given scopes are not available for your role.",
      });
    }

    const token = `dub_${nanoid(24)}`;
    const hashedKey = await hashToken(token);
    const partialKey = `dub_...${token.slice(-4)}`;

    // Create token
    await prisma.$transaction(
      async (tx) => {
        const totalTokens = await tx.restrictedToken.count({
          where: {
            projectId: workspace.id,
            installationId: null, // Skip OAuth installations tokens
          },
        });

        if (totalTokens >= MAX_WORKSPACE_TOKENS) {
          throw new DubApiError({
            code: "forbidden",
            message: `You've reached your limit of ${MAX_WORKSPACE_TOKENS} API keys for this workspace. Please contact support to increase this limit.`,
          });
        }

        let machineUser: Pick<User, "id"> | null = null;

        // Create machine user if needed
        if (isMachine) {
          machineUser = await tx.user.create({
            data: {
              id: createId({ prefix: "user_" }),
              name: `${generateRandomName()} (Machine User)`,
              isMachine: true,
            },
            select: {
              id: true,
            },
          });

          // Add machine user to workspace
          await tx.projectUsers.create({
            data: {
              role: "member",
              userId: machineUser.id,
              projectId: workspace.id,
            },
          });
        }

        return await tx.restrictedToken.create({
          data: {
            name,
            hashedKey,
            partialKey,
            userId: isMachine ? machineUser?.id! : session.user.id,
            projectId: workspace.id,
            scopes: [...new Set(scopes)].join(" "),
          },
        });
      },
      {
        isolationLevel: Prisma.TransactionIsolationLevel.ReadUncommitted,
        maxWait: 5000,
        timeout: 5000,
      },
    );

    waitUntil(
      sendEmail({
        to: session.user.email,
        subject: `A new API key has been created for your workspace ${workspace.name} on Dub`,
        react: APIKeyCreated({
          email: session.user.email,
          token: {
            name,
            type: scopesToName(scopes).name,
            permissions: scopesToName(scopes).description,
          },
          workspace: {
            name: workspace.name,
            slug: workspace.slug,
          },
        }),
      }),
    );

    return NextResponse.json({ token });
  },
  {
    requiredPermissions: ["tokens.write"],
  },
);