The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor Slack integration by introducing a new OAuthProvider class and updating installation and uninstall logic
Kiran K5609da48b720
diff --git a/apps/web/.env.example b/apps/web/.env.exampleindex e5843cb88e..0dbef05666 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -120,7 +120,6 @@ NEXT_PUBLIC_IS_DUB=CRON_SECRET=# Slack integration-SLACK_APP_INSTALL_URL=SLACK_CLIENT_ID=SLACK_CLIENT_SECRET=SLACK_SIGNING_SECRET=diff --git a/apps/web/app/(ee)/api/hubspot/callback/route.ts b/apps/web/app/(ee)/api/hubspot/callback/route.tsindex 006ad10372..2804b49472 100644--- a/apps/web/app/(ee)/api/hubspot/callback/route.ts+++ b/apps/web/app/(ee)/api/hubspot/callback/route.ts@@ -78,6 +78,9 @@ export const GET = async (req: Request) => {where: {slug: "hubspot",},+ select: {+ id: true,+ }});const credentials = {diff --git a/apps/web/app/api/integrations/uninstall/route.ts b/apps/web/app/api/integrations/uninstall/route.tsindex 3bf44c3d93..e5291a6820 100644--- a/apps/web/app/api/integrations/uninstall/route.ts+++ b/apps/web/app/api/integrations/uninstall/route.ts@@ -1,6 +1,6 @@import { DubApiError } from "@/lib/api/errors";import { withWorkspace } from "@/lib/auth";-import { uninstallSlackIntegration } from "@/lib/integrations/slack/uninstall";+import { slackOAuthProvider } from "@/lib/integrations/slack/oauth";import { webhookCache } from "@/lib/webhook/cache";import { isLinkLevelWebhook } from "@/lib/webhook/utils";import { prisma } from "@dub/prisma";@@ -54,7 +54,7 @@ export const DELETE = withWorkspace(waitUntil(Promise.all([...(integrationId === SLACK_INTEGRATION_ID- ? [uninstallSlackIntegration({ installation })]+ ? [slackOAuthProvider.uninstall(installation)]: []),...webhooks.map((webhook) =>diff --git a/apps/web/app/api/slack/callback/route.ts b/apps/web/app/api/slack/callback/route.tsindex 22e91485fa..813f7b25b0 100644--- a/apps/web/app/api/slack/callback/route.ts+++ b/apps/web/app/api/slack/callback/route.ts@@ -1,30 +1,16 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { getSession } from "@/lib/auth";import { installIntegration } from "@/lib/integrations/install";-import { getSlackEnv } from "@/lib/integrations/slack/env";-import { SlackCredential } from "@/lib/integrations/slack/type";-import { redis } from "@/lib/upstash";+import { slackOAuthProvider } from "@/lib/integrations/slack/oauth";+import { SlackAuthToken } from "@/lib/integrations/types";import { createWebhook } from "@/lib/webhook/create-webhook";-import z from "@/lib/zod";import { prisma } from "@dub/prisma";import { Project, WebhookReceiver } from "@dub/prisma/client";-import {- APP_DOMAIN_WITH_NGROK,- getSearchParams,- SLACK_INTEGRATION_ID,-} from "@dub/utils";import { redirect } from "next/navigation";export const dynamic = "force-dynamic";-const oAuthCallbackSchema = z.object({- code: z.string(),- state: z.string(),-});-export const GET = async (req: Request) => {- const env = getSlackEnv();-let workspace: Pick<Project, "id" | "slug" | "plan"> | null = null;try {@@ -37,17 +23,8 @@ export const GET = async (req: Request) => {});}- const { code, state } = oAuthCallbackSchema.parse(getSearchParams(req.url));-- // Find workspace that initiated the Stripe app install- const workspaceId = await redis.get<string>(`slack:install:state:${state}`);-- if (!workspaceId) {- throw new DubApiError({- code: "bad_request",- message: "Unknown state",- });- }+ const { token, contextId: workspaceId } =+ await slackOAuthProvider.exchangeCodeForToken(req);workspace = await prisma.project.findUniqueOrThrow({where: {@@ -60,38 +37,31 @@ export const GET = async (req: Request) => {},});- const formData = new FormData();- formData.append("code", code);- formData.append("client_id", env.SLACK_CLIENT_ID);- formData.append("client_secret", env.SLACK_CLIENT_SECRET);- formData.append(- "redirect_uri",- `${APP_DOMAIN_WITH_NGROK}/api/slack/callback`,- );-- const response = await fetch("https://slack.com/api/oauth.v2.access", {- method: "POST",- body: formData,+ const integration = await prisma.integration.findUniqueOrThrow({+ where: {+ slug: "slack",+ },+ select: {+ id: true,+ },});- const data = await response.json();-- const credentials: SlackCredential = {- appId: data.app_id,- botUserId: data.bot_user_id,- scope: data.scope,- accessToken: data.access_token,- tokenType: data.token_type,- authUser: data.authed_user,- team: data.team,+ const credentials: SlackAuthToken = {+ appId: token.app_id,+ botUserId: token.bot_user_id,+ scope: token.scope,+ accessToken: token.access_token,+ tokenType: token.token_type,+ authUser: token.authed_user,+ team: token.team,incomingWebhook: {- channel: data.incoming_webhook.channel,- channelId: data.incoming_webhook.channel_id,+ channel: token.incoming_webhook.channel,+ channelId: token.incoming_webhook.channel_id,},};const installation = await installIntegration({- integrationId: SLACK_INTEGRATION_ID,+ integrationId: integration.id,userId: session.user.id,workspaceId,credentials,@@ -99,7 +69,7 @@ export const GET = async (req: Request) => {await createWebhook({name: "Slack",- url: data.incoming_webhook.url,+ url: token.incoming_webhook.url,receiver: WebhookReceiver.slack,triggers: [],workspace,diff --git a/apps/web/lib/actions/get-integration-install-url.ts b/apps/web/lib/actions/get-integration-install-url.tsindex 539c8003f6..1dd780a775 100644--- a/apps/web/lib/actions/get-integration-install-url.ts+++ b/apps/web/lib/actions/get-integration-install-url.ts@@ -1,7 +1,7 @@"use server";import { hubSpotOAuthProvider } from "../integrations/hubspot/oauth";-import { getSlackInstallationUrl } from "../integrations/slack/install";+import { slackOAuthProvider } from "../integrations/slack/oauth";import z from "../zod";import { authActionClient } from "./safe-action";@@ -20,7 +20,7 @@ export const getIntegrationInstallUrl = authActionClientlet url: string | null = null;if (integrationSlug === "slack") {- url = await getSlackInstallationUrl(workspace.id);+ url = await slackOAuthProvider.generateAuthUrl(workspace.id);} else if (integrationSlug === "hubspot") {url = await hubSpotOAuthProvider.generateAuthUrl(workspace.id);} else {diff --git a/apps/web/lib/integrations/hubspot/oauth.ts b/apps/web/lib/integrations/hubspot/oauth.tsindex 559bb7147e..2346d7cd4c 100644--- a/apps/web/lib/integrations/hubspot/oauth.ts+++ b/apps/web/lib/integrations/hubspot/oauth.ts@@ -2,14 +2,14 @@ import { prisma } from "@dub/prisma";import { InstalledIntegration } from "@dub/prisma/client";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { OAuthProvider, OAuthProviderConfig } from "../oauth-provider";+import { HubSpotAuthToken } from "../types";import { hubSpotAuthTokenSchema } from "./schema";-import { HubSpotAuthToken } from "./types";class HubSpotOAuthProvider extends OAuthProvider<typeof hubSpotAuthTokenSchema> {- constructor(config: OAuthProviderConfig) {- super(config);+ constructor(provider: OAuthProviderConfig) {+ super(provider);}async refreshTokenForInstallation(@@ -54,8 +54,8 @@ class HubSpotOAuthProvider extends OAuthProvider<export const hubSpotOAuthProvider = new HubSpotOAuthProvider({name: "HubSpot",- clientId: process.env.HUBSPOT_CLIENT_ID || "",- clientSecret: process.env.HUBSPOT_CLIENT_SECRET || "",+ clientId: process.env.HUBSPOT_CLIENT_ID!,+ clientSecret: process.env.HUBSPOT_CLIENT_SECRET!,authUrl: "https://app.hubspot.com/oauth/authorize",tokenUrl: "https://api.hubapi.com/oauth/v1/token",redirectUri: `${APP_DOMAIN_WITH_NGROK}/api/hubspot/callback`,@@ -68,4 +68,5 @@ export const hubSpotOAuthProvider = new HubSpotOAuthProvider({"crm.schemas.contacts.write",].join(" "),tokenSchema: hubSpotAuthTokenSchema,+ tokenRequestStyle: "form",});diff --git a/apps/web/lib/integrations/hubspot/types.ts b/apps/web/lib/integrations/hubspot/types.tsdeleted file mode 100644index 7a362044e7..0000000000--- a/apps/web/lib/integrations/hubspot/types.ts+++ /dev/null@@ -1,6 +0,0 @@-import { z } from "zod";-import { hubSpotAuthTokenSchema, hubSpotContactSchema } from "./schema";--export type HubSpotAuthToken = z.infer<typeof hubSpotAuthTokenSchema>;--export type HubSpotContact = z.infer<typeof hubSpotContactSchema>;diff --git a/apps/web/lib/integrations/oauth-provider.ts b/apps/web/lib/integrations/oauth-provider.tsindex e9b1fa404e..d7f05134d5 100644--- a/apps/web/lib/integrations/oauth-provider.ts+++ b/apps/web/lib/integrations/oauth-provider.ts@@ -13,6 +13,7 @@ export interface OAuthProviderConfig {scopes: string;redisStatePrefix: string;tokenSchema: z.ZodSchema;+ tokenRequestStyle: "form" | "formdata" | "json";}const codeExchangeSchema = z.object({@@ -57,22 +58,51 @@ export class OAuthProvider<T extends z.ZodSchema> {throw new Error(`[${this.provider.name}] Invalid or expired state.`);}+ let body: BodyInit;+ let headers: Record<string, string> = {};++ switch (this.provider.tokenRequestStyle) {+ case "form":+ headers["Content-Type"] = "application/x-www-form-urlencoded";+ body = new URLSearchParams({+ code,+ client_id: this.provider.clientId,+ client_secret: this.provider.clientSecret,+ redirect_uri: this.provider.redirectUri,+ grant_type: "authorization_code",+ });+ break;++ case "formdata":+ const formData = new FormData();+ formData.append("code", code);+ formData.append("client_id", this.provider.clientId);+ formData.append("client_secret", this.provider.clientSecret);+ formData.append("redirect_uri", this.provider.redirectUri);+ body = formData;+ break;++ case "json":+ headers["Content-Type"] = "application/json";+ body = JSON.stringify({+ code,+ client_id: this.provider.clientId,+ client_secret: this.provider.clientSecret,+ redirect_uri: this.provider.redirectUri,+ });+ break;+ }+const response = await fetch(this.provider.tokenUrl, {method: "POST",- headers: {- "Content-Type": "application/x-www-form-urlencoded",- },- body: new URLSearchParams({- code,- client_id: this.provider.clientId,- client_secret: this.provider.clientSecret,- redirect_uri: this.provider.redirectUri,- grant_type: "authorization_code",- }),+ headers,+ body,});const result = await response.json();+ console.log("result", result)+if (!response.ok) {console.error(`[${this.provider.name}] exchangeCodeForToken`, result);diff --git a/apps/web/lib/integrations/slack/commands.ts b/apps/web/lib/integrations/slack/commands.tsindex 8843bfa361..e1f9881117 100644--- a/apps/web/lib/integrations/slack/commands.ts+++ b/apps/web/lib/integrations/slack/commands.ts@@ -5,17 +5,10 @@ import { createLinkBodySchema } from "@/lib/zod/schemas/links";import { prisma } from "@dub/prisma";import { User } from "@dub/prisma/client";import { APP_DOMAIN, SLACK_INTEGRATION_ID } from "@dub/utils";-import { SlackCredential } from "./type";+import { SlackAuthToken } from "../types";+import { slackSlashCommandSchema } from "./schema";import { verifySlackSignature } from "./verify-request";-const schema = z.object({- api_app_id: z.string(),- team_id: z.string(),- user_id: z.string(),- text: z.string().transform((text) => text.trim().split(" ")),- command: z.enum(["/shorten"]),-});-// Handle slash command from Slackexport const handleSlashCommand = async (req: Request) => {const body = await req.text();@@ -24,7 +17,7 @@ export const handleSlashCommand = async (req: Request) => {const rawFormData = new URLSearchParams(body);const formData = Object.fromEntries(rawFormData.entries());- const parsedInput = schema.safeParse(formData);+ const parsedInput = slackSlashCommandSchema.safeParse(formData);if (!parsedInput.success) {return {@@ -81,7 +74,7 @@ export const handleSlashCommand = async (req: Request) => {}// Find Dub user matching the Slack user profile- const credentials = installation.credentials as SlackCredential;+ const credentials = installation.credentials as SlackAuthToken;const slackUser = await findSlackUser({userId: data.user_id,credentials,@@ -150,7 +143,7 @@ const findSlackUser = async ({credentials,}: {userId: string;- credentials: SlackCredential;+ credentials: SlackAuthToken;}) => {const response = await fetch(`https://slack.com/api/users.profile.get?user=${userId}`,@@ -178,7 +171,7 @@ const createShortLink = async ({workspace,user,}: {- data: z.infer<typeof schema>;+ data: z.infer<typeof slackSlashCommandSchema>;workspace: WorkspaceProps;user: Pick<User, "id" | "name">;}) => {diff --git a/apps/web/lib/integrations/slack/constants.ts b/apps/web/lib/integrations/slack/constants.tsnew file mode 100644index 0000000000..e69de29bb2diff --git a/apps/web/lib/integrations/slack/env.ts b/apps/web/lib/integrations/slack/env.tsdeleted file mode 100644index c5511a2117..0000000000--- a/apps/web/lib/integrations/slack/env.ts+++ /dev/null@@ -1,30 +0,0 @@-import z from "@/lib/zod";--export const envSchema = z.object({- SLACK_APP_INSTALL_URL: z.string(),- SLACK_CLIENT_ID: z.string(),- SLACK_CLIENT_SECRET: z.string(),- SLACK_SIGNING_SECRET: z.string(),-});--type SlackEnv = z.infer<typeof envSchema>;--let env: SlackEnv | undefined;--export const getSlackEnv = () => {- if (env) {- return env;- }-- const parsed = envSchema.safeParse(process.env);-- if (!parsed.success) {- throw new Error(- "Slack app environment variables are not configured properly.",- );- }-- env = parsed.data;-- return env;-};diff --git a/apps/web/lib/integrations/slack/install.ts b/apps/web/lib/integrations/slack/install.tsdeleted file mode 100644index 2e237312c1..0000000000--- a/apps/web/lib/integrations/slack/install.ts+++ /dev/null@@ -1,22 +0,0 @@-import { redis } from "@/lib/upstash";-import { APP_DOMAIN_WITH_NGROK, nanoid } from "@dub/utils";-import { getSlackEnv } from "./env";--// Get the installation URL for Slack-export const getSlackInstallationUrl = async (workspaceId: string) => {- const env = getSlackEnv();-- const state = nanoid(16);- await redis.set(`slack:install:state:${state}`, workspaceId, {- ex: 30 * 60,- });-- const url = new URL(env.SLACK_APP_INSTALL_URL);- url.searchParams.set(- "redirect_uri",- `${APP_DOMAIN_WITH_NGROK}/api/slack/callback`,- );- url.searchParams.set("state", state);-- return url.toString();-};diff --git a/apps/web/lib/integrations/slack/oauth.ts b/apps/web/lib/integrations/slack/oauth.tsnew file mode 100644index 0000000000..97a9250a6a--- /dev/null+++ b/apps/web/lib/integrations/slack/oauth.ts@@ -0,0 +1,63 @@+import { DubApiError } from "@/lib/api/errors";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import { InstalledIntegration } from "@prisma/client";+import { OAuthProvider, OAuthProviderConfig } from "../oauth-provider";+import { SlackAuthToken } from "../types";+import { slackAuthTokenSchema } from "./schema";++class SlackOAuthProvider extends OAuthProvider<typeof slackAuthTokenSchema> {+ constructor(provider: OAuthProviderConfig) {+ super(provider);+ }++ async uninstall(installation: InstalledIntegration) {+ const credentials = installation.credentials as SlackAuthToken;++ const response = await fetch("https://slack.com/api/apps.uninstall", {+ method: "POST",+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: new URLSearchParams({+ token: credentials.accessToken,+ client_id: process.env.SLACK_CLIENT_ID!,+ client_secret: process.env.SLACK_CLIENT_SECRET!,+ }),+ });++ const data = await response.json();++ if (!data.ok) {+ console.error("[Slack]", data);++ throw new DubApiError({+ code: "bad_request",+ message: "Failed to remove the app from the Slack workspace.",+ });+ }+ }+}++export const slackOAuthProvider = new SlackOAuthProvider({+ name: "Slack",+ clientId: process.env.SLACK_CLIENT_ID!,+ clientSecret: process.env.SLACK_CLIENT_SECRET!,+ authUrl: "https://slack.com/oauth/v2/authorize",+ tokenUrl: "https://slack.com/api/oauth.v2.access",+ redirectUri: `${APP_DOMAIN_WITH_NGROK}/api/slack/callback`,+ redisStatePrefix: "slack:oauth:state",+ scopes: [+ "chat:write",+ "commands",+ "im:write",+ "channels:join",+ "chat:write.customize",+ "links:write",+ "users.profile:read",+ "users:read.email",+ "users:read",+ "incoming-webhook",+ ].join(","),+ tokenSchema: slackAuthTokenSchema,+ tokenRequestStyle: "formdata",+});diff --git a/apps/web/lib/integrations/slack/schema.ts b/apps/web/lib/integrations/slack/schema.tsnew file mode 100644index 0000000000..7c34a7724a--- /dev/null+++ b/apps/web/lib/integrations/slack/schema.ts@@ -0,0 +1,29 @@+import z from "@/lib/zod";++export const slackAuthTokenSchema = z.object({+ app_id: z.string(),+ bot_user_id: z.string(),+ scope: z.string(),+ access_token: z.string(),+ token_type: z.string(),+ authed_user: z.object({+ id: z.string(),+ }),+ team: z.object({+ id: z.string(),+ name: z.string(),+ }),+ incoming_webhook: z.object({+ channel: z.string(),+ channel_id: z.string(),+ url: z.string(),+ }),+});++export const slackSlashCommandSchema = z.object({+ api_app_id: z.string(),+ team_id: z.string(),+ user_id: z.string(),+ text: z.string().transform((text) => text.trim().split(" ")),+ command: z.enum(["/shorten"]),+});\ No newline at end of filediff --git a/apps/web/lib/integrations/slack/type.ts b/apps/web/lib/integrations/slack/type.tsdeleted file mode 100644index d8cc22502a..0000000000--- a/apps/web/lib/integrations/slack/type.ts+++ /dev/null@@ -1,13 +0,0 @@-export type SlackCredential = {- appId: string;- botUserId: string;- scope: string;- accessToken: string;- tokenType: string;- authUser: { id: string };- team: { id: string; name: string };- incomingWebhook: {- channel: string;- channelId: string;- };-};diff --git a/apps/web/lib/integrations/slack/uninstall.ts b/apps/web/lib/integrations/slack/uninstall.tsdeleted file mode 100644index f427b8448d..0000000000--- a/apps/web/lib/integrations/slack/uninstall.ts+++ /dev/null@@ -1,36 +0,0 @@-import { DubApiError } from "@/lib/api/errors";-import { InstalledIntegration } from "@dub/prisma/client";-import { getSlackEnv } from "./env";-import { SlackCredential } from "./type";--export const uninstallSlackIntegration = async ({- installation,-}: {- installation: InstalledIntegration;-}) => {- const env = getSlackEnv();- const credentials = installation.credentials as SlackCredential;-- const response = await fetch("https://slack.com/api/apps.uninstall", {- method: "POST",- headers: {- "Content-Type": "application/x-www-form-urlencoded",- },- body: new URLSearchParams({- token: credentials.accessToken,- client_id: env.SLACK_CLIENT_ID,- client_secret: env.SLACK_CLIENT_SECRET,- }),- });-- const data = await response.json();-- if (!data.ok) {- console.error("[Slack App]", data);-- throw new DubApiError({- code: "bad_request",- message: "Failed to remove the app from the Slack workspace.",- });- }-};diff --git a/apps/web/lib/integrations/slack/verify-request.ts b/apps/web/lib/integrations/slack/verify-request.tsindex 19f39f6a63..c36a7477b0 100644--- a/apps/web/lib/integrations/slack/verify-request.ts+++ b/apps/web/lib/integrations/slack/verify-request.ts@@ -1,5 +1,4 @@import { createHmac } from "crypto";-import { getSlackEnv } from "./env";interface SlackRequestVerificationOptions {signingSecret: string;@@ -13,10 +12,8 @@ interface SlackRequestVerificationOptions {// Verifies the signature of an incoming request from Slack.export const verifySlackSignature = async (req: Request, body: string) => {- const env = getSlackEnv();-const options: SlackRequestVerificationOptions = {- signingSecret: env.SLACK_SIGNING_SECRET,+ signingSecret: process.env.SLACK_SIGNING_SECRET!,body: body,headers: {"x-slack-signature": req.headers.get("x-slack-signature") ?? "",diff --git a/apps/web/lib/integrations/types.ts b/apps/web/lib/integrations/types.tsnew file mode 100644index 0000000000..35a25157ce--- /dev/null+++ b/apps/web/lib/integrations/types.ts@@ -0,0 +1,26 @@+import { z } from "zod";+import { hubSpotAuthTokenSchema, hubSpotContactSchema } from "./hubspot/schema";++export type HubSpotAuthToken = z.infer<typeof hubSpotAuthTokenSchema>;++export type HubSpotContact = z.infer<typeof hubSpotContactSchema>;++export type SlackAuthToken = {+ appId: string;+ botUserId: string;+ scope: string;+ accessToken: string;+ tokenType: string;+ authUser: {+ id: string;+ };+ team: {+ id: string;+ name: string;+ };+ incomingWebhook: {+ channel: string;+ channelId: string;++ };+};diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex d6112714d1..16f00836f4 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -24,6 +24,10 @@ import {FOLDER_PERMISSIONS,FOLDER_WORKSPACE_ACCESS,} from "./folder/constants";+import {+ hubSpotAuthTokenSchema,+ hubSpotContactSchema,+} from "./integrations/hubspot/schema";import { WEBHOOK_TRIGGER_DESCRIPTIONS } from "./webhook/constants";import {BountyListSchema,@@ -605,4 +609,4 @@ export type BountySubmissionsQueryFilters = z.infer<typeof getBountySubmissionsQuerySchema>;-export type Message = z.infer<typeof MessageSchema>;+export type Message = z.infer<typeof MessageSchema>;\ No newline at end of filediff --git a/apps/web/scripts/create-integration.ts b/apps/web/scripts/create-integration.tsindex 7e3171aa66..915d97400d 100644--- a/apps/web/scripts/create-integration.ts+++ b/apps/web/scripts/create-integration.ts@@ -7,9 +7,9 @@ async function main() {const integration = await prisma.integration.create({data: {id: createId({ prefix: "int_" }),- name: "HubSpot",- slug: "hubspot",- description: "Track HubSpot events with Dub.",+ name: "Slack",+ slug: "slack",+ description: "Slack",developer: "Dub",website: "https://dub.co",verified: true,