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.

3.7 KB
Raw Blame
import { DubApiError } from "@/lib/api/errors";
import {
  canInstallOAuthApp,
  UNVERIFIED_APP_INSTALL_MESSAGE,
} from "@/lib/api/oauth/can-install-oauth-app";
import { OAUTH_CONFIG } from "@/lib/api/oauth/constants";
import { createToken } from "@/lib/api/oauth/utils";
import { getGrantedScopesForRole } from "@/lib/api/tokens/scopes";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { authorizeRequestSchema } from "@/lib/zod/schemas/oauth";
import { SHOPIFY_INTEGRATION_ID, STRIPE_INTEGRATION_ID } from "@dub/utils";
import { NextResponse } from "next/server";

// POST /api/oauth/authorize - approve OAuth authorization request
export const POST = withWorkspace(
  async ({ session, req, workspace }) => {
    const {
      state,
      scope,
      client_id: clientId,
      redirect_uri: redirectUri,
      code_challenge: codeChallenge,
      code_challenge_method: codeChallengeMethod,
    } = authorizeRequestSchema.parse(await parseRequestBody(req));

    // Grant the subset of requested scopes the user can actually authorize
    const grantedScopes = getGrantedScopesForRole({
      scopes: scope,
      role: workspace.users[0].role,
    });

    const app = await prisma.oAuthApp.findUniqueOrThrow({
      where: {
        clientId,
      },
      select: {
        redirectUris: true,
        pkce: true,
        integration: {
          select: {
            id: true,
            verified: true,
            projectId: true,
            userId: true,
          },
        },
      },
    });

    if (!app.integration) {
      throw new DubApiError({
        code: "not_found",
        message: "Could not find OAuth application.",
      });
    }

    if (
      [STRIPE_INTEGRATION_ID, SHOPIFY_INTEGRATION_ID].includes(
        app.integration.id,
      ) &&
      (workspace.plan === "free" || workspace.plan === "pro")
    ) {
      throw new DubApiError({
        code: "bad_request",
        message:
          "This integration is only available for workspaces with a Business plan or higher. Please upgrade your plan to continue.",
      });
    }

    const redirectUris = (app.redirectUris || []) as string[];

    if (!redirectUris.includes(redirectUri)) {
      throw new DubApiError({
        code: "bad_request",
        message: "Invalid redirect_uri parameter for the application.",
      });
    }

    // If PKCE is required, ensure that the code_challenge and code_challenge_method are present
    if (app.pkce && (!codeChallenge || !codeChallengeMethod)) {
      throw new DubApiError({
        code: "bad_request",
        message: "Missing code_challenge or code_challenge_method parameters.",
      });
    }

    if (
      !canInstallOAuthApp({
        integration: app.integration,
        workspace,
        userId: session.user.id,
      })
    ) {
      throw new DubApiError({
        code: "forbidden",
        message: UNVERIFIED_APP_INSTALL_MESSAGE,
      });
    }

    const { code } = await prisma.oAuthCode.create({
      data: {
        clientId,
        redirectUri,
        projectId: workspace.id,
        userId: session.user.id,
        scopes: grantedScopes.join(" "),
        code: createToken({ length: OAUTH_CONFIG.CODE_LENGTH }),
        expiresAt: new Date(Date.now() + OAUTH_CONFIG.CODE_LIFETIME * 1000),
        ...(app.pkce && { codeChallenge, codeChallengeMethod }),
      },
    });

    // Generate the callback URL
    const callbackUrl = new URL(redirectUri);

    callbackUrl.searchParams.set("code", code);

    if (state) {
      callbackUrl.searchParams.set("state", state);
    }

    const response = {
      callbackUrl: callbackUrl.toString(),
    };

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