Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: make several improvements to slack integration

Marc Seitzbe892c5d789f
diff --git a/app/api/integrations/slack/oauth/callback/route.ts b/app/api/integrations/slack/oauth/callback/route.ts
index b2fed780..1590aaa1 100644
--- a/app/api/integrations/slack/oauth/callback/route.ts
+++ b/app/api/integrations/slack/oauth/callback/route.ts
@@ -25,12 +25,12 @@ const oAuthCallbackSchema = z.object({
export const GET = async (req: Request) => {
const env = getSlackEnv();
- let workspace: Pick<Team, "id" | "plan"> | null = null;
+ let team: Pick<Team, "id" | "plan"> | null = null;
try {
const session = await getServerSession(authOptions);
if (!session) {
- throw new Error("Unauthorized");
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const userId = (session.user as CustomUser).id;
@@ -38,15 +38,22 @@ export const GET = async (req: Request) => {
const { code, state } = oAuthCallbackSchema.parse(getSearchParams(req.url));
// Find workspace that initiated the Stripe app install
- const teamId = await redis.get<string>(`slack:install:state:${state}`);
+ const stateKey = `slack:install:state:${state}`;
+ const teamId = await redis.get<string>(stateKey);
if (!teamId) {
- throw new Error("Unknown state");
+ return NextResponse.json({ error: "Invalid state" }, { status: 400 });
}
+ await redis.del(stateKey);
- workspace = await prisma.team.findUniqueOrThrow({
+ team = await prisma.team.findUniqueOrThrow({
where: {
id: teamId,
+ users: {
+ some: {
+ userId,
+ },
+ },
},
select: {
id: true,
@@ -54,23 +61,35 @@ 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",
- `${process.env.NEXT_PUBLIC_BASE_URL}/api/integrations/slack/oauth/callback`,
- );
+ if (!team) {
+ return NextResponse.json({ error: "Access denied" }, { status: 403 });
+ }
+ const body = new URLSearchParams({
+ code,
+ client_id: env.SLACK_CLIENT_ID,
+ client_secret: env.SLACK_CLIENT_SECRET,
+ redirect_uri: `${process.env.NEXT_PUBLIC_BASE_URL}/api/integrations/slack/oauth/callback`,
+ });
+ const ac = new AbortController();
+ const to = setTimeout(() => ac.abort(), 10000);
const response = await fetch("https://slack.com/api/oauth.v2.access", {
method: "POST",
- body: formData,
- });
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ Accept: "application/json",
+ },
+ body: body.toString(),
+ signal: ac.signal,
+ }).finally(() => clearTimeout(to));
const data = await response.json();
-
- console.log("data", data);
+ if (!data?.ok) {
+ return NextResponse.json(
+ { error: `Slack OAuth error: ${data?.error || "unknown"}` },
+ { status: 400 },
+ );
+ }
const credentials: SlackCredential = {
appId: data.app_id,
diff --git a/lib/integrations/install.ts b/lib/integrations/install.ts
index f1d4b8c0..791dcd3a 100644
--- a/lib/integrations/install.ts
+++ b/lib/integrations/install.ts
@@ -80,7 +80,7 @@ export const installIntegration = async ({
test: process.env.NODE_ENV === "development",
subject: `The "${integration.name}" integration has been added to your team`,
react: IntegrationInstalled({
- email: email!,
+ email: email,
team: {
name: team.name,
},
diff --git a/lib/integrations/slack/client.ts b/lib/integrations/slack/client.ts
index 7e9b9631..20e260a8 100644
--- a/lib/integrations/slack/client.ts
+++ b/lib/integrations/slack/client.ts
@@ -143,6 +143,9 @@ export class SlackClient {
async getChannels(accessToken: string): Promise<SlackChannel[]> {
const decryptedToken = decryptSlackToken(accessToken);
+ if (!decryptedToken) {
+ throw new Error("Missing Slack access token");
+ }
const channels: SlackChannel[] = [];
let cursor: string | undefined = undefined;
@@ -154,12 +157,21 @@ export class SlackClient {
if (cursor) url.searchParams.set("cursor", cursor);
const requestUrl = url.toString();
+ const ac = new AbortController();
+ const to = setTimeout(() => ac.abort(), 10000);
const resp = await fetch(requestUrl, {
headers: {
Authorization: `Bearer ${decryptedToken}`,
"Content-Type": "application/json",
},
- });
+ signal: ac.signal,
+ }).finally(() => clearTimeout(to));
+ // Basic 429 handling
+ if (resp.status === 429) {
+ const retry = Number(resp.headers.get("retry-after") || 1);
+ await new Promise((r) => setTimeout(r, retry * 1000));
+ continue;
+ }
if (!resp.ok)
throw new Error(
`Failed to get channels: ${resp.status} ${resp.statusText}`,
@@ -189,6 +201,9 @@ export class SlackClient {
message: SlackMessage,
): Promise<{ ok: boolean; ts?: string; error?: string }> {
const decryptedToken = decryptSlackToken(accessToken);
+ if (!decryptedToken) {
+ throw new Error("Missing Slack access token");
+ }
const requestUrl = `${this.baseUrl}/chat.postMessage`;
const response = await fetch(requestUrl, {
@@ -220,5 +235,9 @@ export class SlackClient {
}
}
-// Export singleton instance
-export const slackClient = new SlackClient();
+// Lazily instantiate
+let _slackClient: SlackClient | null = null;
+export function getSlackClient(): SlackClient {
+ if (!_slackClient) _slackClient = new SlackClient();
+ return _slackClient;
+}
diff --git a/lib/integrations/slack/env.ts b/lib/integrations/slack/env.ts
index 2e00b82b..f94aaa72 100644
--- a/lib/integrations/slack/env.ts
+++ b/lib/integrations/slack/env.ts
@@ -1,4 +1,4 @@
-import z from "zod";
+import { z } from "zod";
export const envSchema = z.object({
SLACK_APP_INSTALL_URL: z.string(),
diff --git a/lib/integrations/slack/events.ts b/lib/integrations/slack/events.ts
index 60373bae..7196aa04 100644
--- a/lib/integrations/slack/events.ts
+++ b/lib/integrations/slack/events.ts
@@ -25,6 +25,8 @@ export class SlackEventManager {
},
select: {
enabled: true,
+ credentials: true,
+ configuration: true,
},
});
diff --git a/lib/integrations/slack/templates.ts b/lib/integrations/slack/templates.ts
index e01c8430..eb2231ef 100644
--- a/lib/integrations/slack/templates.ts
+++ b/lib/integrations/slack/templates.ts
@@ -2,6 +2,20 @@ import prisma from "@/lib/prisma";
import { SlackEventData, SlackMessage } from "./types";
+/**
+ * Helper function to safely reference a link with fallback handling
+ * @param link - The link object that may have undefined or null properties
+ * @returns Safe link reference string
+ */
+function linkRef(
+ link: { name?: string | null; id?: string } | null | undefined,
+): string {
+ if (link?.name) {
+ return `"${link.name}"`;
+ }
+ return `"Link ${link?.id?.slice(0, 5) ?? "unknown"}"`;
+}
+
export async function createSlackMessage(
eventData: SlackEventData,
): Promise<SlackMessage | null> {
@@ -45,10 +59,8 @@ async function createDocumentViewMessage(
let accessContext = "";
if (eventData.dataroomId && dataroom) {
accessContext = `in dataroom "${dataroom.name}"`;
- } else if (link?.name) {
- accessContext = `via shared link "${link.name}"`;
} else {
- accessContext = `via shared link "Link ${link?.id.slice(0, 5)}"`;
+ accessContext = `via shared link ${linkRef(link)}`;
}
return {
@@ -99,9 +111,7 @@ async function createDocumentViewMessage(
type: "mrkdwn",
text: eventData.dataroomId
? `Viewed document in dataroom "${dataroom?.name || "Unknown"}"`
- : link?.name
- ? `Viewed document via shared link "${link.name}"`
- : `Viewed document via shared link "Link ${link?.id.slice(0, 5)}"`,
+ : `Viewed document via shared link ${linkRef(link)}`,
},
],
},
@@ -142,9 +152,7 @@ async function createDataroomAccessMessage(
? `<mailto:${eventData.viewerEmail}|${viewerDisplay}>`
: viewerDisplay;
- const accessContext = link?.name
- ? `via shared link "${link.name}"`
- : `via shared link "Link ${link?.id.slice(0, 5)}"`;
+ const accessContext = `via shared link ${linkRef(link)}`;
return {
text: `Your dataroom has been viewed: ${dataroom?.name || "Unknown dataroom"} by ${viewerDisplay} ${accessContext}`,
@@ -199,9 +207,7 @@ async function createDataroomAccessMessage(
elements: [
{
type: "mrkdwn",
- text: link?.name
- ? `Dataroom accessed via shared link "${link.name}"`
- : `Dataroom accessed via shared link "Link ${link?.id.slice(0, 5)}"`,
+ text: `Dataroom accessed via shared link ${linkRef(link)}`,
},
],
},
@@ -261,10 +267,8 @@ async function createDocumentDownloadMessage(
downloadContext = `"${folderName}" (${documentCount} documents)`;
} else if (dataroom) {
downloadContext = `from dataroom "${dataroom.name}"`;
- } else if (link?.name) {
- downloadContext = `via shared link "${link.name}"`;
} else {
- downloadContext = `via shared link "Link ${link?.id.slice(0, 5)}"`;
+ downloadContext = `via shared link ${linkRef(link)}`;
}
return {
@@ -319,9 +323,7 @@ async function createDocumentDownloadMessage(
? `Bulk dataroom download`
: isFolderDownload
? `Folder download`
- : link?.name
- ? `Document download via shared link "${link.name}"`
- : `Document download via shared link "Link ${link?.id.slice(0, 5)}"`,
+ : `Document download via shared link ${linkRef(link)}`,
},
],
},
diff --git a/lib/integrations/slack/types.ts b/lib/integrations/slack/types.ts
index 63d973a4..2af387e1 100644
--- a/lib/integrations/slack/types.ts
+++ b/lib/integrations/slack/types.ts
@@ -10,6 +10,10 @@ export type SlackCredential = {
team: { id: string; name: string };
};
+export type SlackCredentialPublic = {
+ team: { id: string; name: string };
+};
+
export type SlackConfiguration = {
enabledChannels: Record<string, SlackChannelConfig>;
};
@@ -27,7 +31,7 @@ export type SlackIntegration = Omit<
InstalledIntegration,
"credentials" | "configuration"
> & {
- credentials: SlackCredential;
+ credentials: SlackCredentialPublic;
configuration: SlackConfiguration | null;
};
@@ -42,7 +46,7 @@ export interface SlackMessage {
export interface SlackEventData {
teamId: string;
- eventType: string;
+ eventType: SlackNotificationType;
documentId?: string;
dataroomId?: string;
viewId?: string;
diff --git a/lib/integrations/slack/uninstall.ts b/lib/integrations/slack/uninstall.ts
index b3ce6a21..06483cf7 100644
--- a/lib/integrations/slack/uninstall.ts
+++ b/lib/integrations/slack/uninstall.ts
@@ -2,6 +2,7 @@ import { InstalledIntegration } from "@prisma/client";
import { getSlackEnv } from "./env";
import { SlackCredential } from "./types";
+import { decryptSlackToken } from "./utils";
export const uninstallSlackIntegration = async ({
installation,
@@ -11,21 +12,23 @@ export const uninstallSlackIntegration = async ({
const env = getSlackEnv();
const credentials = installation.credentials as SlackCredential;
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10_000);
const response = await fetch("https://slack.com/api/apps.uninstall", {
method: "POST",
- headers: {
- "Content-Type": "application/x-www-form-urlencoded",
- },
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
- token: credentials.accessToken,
+ token: decryptSlackToken(credentials.accessToken),
client_id: env.SLACK_CLIENT_ID,
client_secret: env.SLACK_CLIENT_SECRET,
}),
+ signal: controller.signal,
});
+ clearTimeout(timeout);
const data = await response.json();
- if (!data.ok) {
+ if (!response.ok || !data.ok) {
console.error("[Slack App]", data);
throw new Error("Failed to remove the app from the Slack workspace.");
}
diff --git a/lib/integrations/slack/utils.ts b/lib/integrations/slack/utils.ts
index 6eda18dd..af0489be 100644
--- a/lib/integrations/slack/utils.ts
+++ b/lib/integrations/slack/utils.ts
@@ -1,11 +1,45 @@
import crypto from "crypto";
+/**
+ * Derives a 32-byte encryption key from the environment variable using SHA-256
+ * @param keyMaterial - The raw key material from environment
+ * @returns 32-byte Buffer for AES-256
+ */
+function deriveKey(keyMaterial: string): Buffer {
+ return crypto.createHash("sha256").update(keyMaterial, "utf8").digest();
+}
+
+/**
+ * Checks if a token is already encrypted by detecting the encrypted format
+ * @param token - Token to check
+ * @returns true if already encrypted
+ */
+function isTokenEncrypted(token: string): boolean {
+ if (!token) return false;
+
+ // Check for encrypted format (iv:encrypted:authTag - 3 parts, all hex)
+ const parts = token.split(":");
+ if (parts.length === 3) {
+ const [iv, encrypted, authTag] = parts;
+ // New format: 24-char hex IV (12 bytes), hex encrypted data, 32-char hex authTag (16 bytes)
+ return (
+ /^[0-9a-f]{24}$/.test(iv) &&
+ /^[0-9a-f]+$/.test(encrypted) &&
+ /^[0-9a-f]{32}$/.test(authTag)
+ );
+ }
+
+ return false;
+}
+
export function encryptSlackToken(token: string): string {
if (!token) return "";
- const textParts: string[] = token.split(":");
- if (textParts.length === 2) {
+
+ // Avoid double-encryption with improved detection
+ if (isTokenEncrypted(token)) {
return token;
}
+
const encryptionKey = process.env.NEXT_PRIVATE_SLACK_ENCRYPTION_KEY;
if (!encryptionKey) {
throw new Error(
@@ -13,18 +47,24 @@ export function encryptSlackToken(token: string): string {
);
}
- const encryptedKey: string = crypto
- .createHash("sha256")
- .update(String(encryptionKey))
- .digest("base64")
- .substring(0, 32);
+ // Derive key using raw SHA-256 digest Buffer
+ const key = deriveKey(encryptionKey);
- const IV: Buffer = crypto.randomBytes(16);
- const cipher = crypto.createCipheriv("aes-256-ctr", encryptedKey, IV);
- let encryptedText: string = cipher.update(token, "utf8", "hex");
- encryptedText += cipher.final("hex");
+ // Use 12-byte IV for GCM (recommended size)
+ const iv = crypto.randomBytes(12);
- return IV.toString("hex") + ":" + encryptedText;
+ // Create AES-256-GCM cipher
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
+
+ // Encrypt the token
+ let encrypted = cipher.update(token, "utf8", "hex");
+ encrypted += cipher.final("hex");
+
+ // Get authentication tag
+ const authTag = cipher.getAuthTag();
+
+ // Format: iv:encrypted:authTag (all hex-encoded)
+ return `${iv.toString("hex")}:${encrypted}:${authTag.toString("hex")}`;
}
export function decryptSlackToken(encryptedToken: string): string {
@@ -37,22 +77,46 @@ export function decryptSlackToken(encryptedToken: string): string {
);
}
- const encryptedKey: string = crypto
- .createHash("sha256")
- .update(String(encryptionKey))
- .digest("base64")
- .substring(0, 32);
+ // Derive key using raw SHA-256 digest Buffer
+ const key = deriveKey(encryptionKey);
- const textParts: string[] = encryptedToken.split(":");
- if (!textParts || textParts.length !== 2) {
- return encryptedToken;
- }
+ const parts = encryptedToken.split(":");
+
+ // Handle new GCM format: iv:encrypted:authTag
+ if (parts.length === 3) {
+ try {
+ const [ivHex, encryptedHex, authTagHex] = parts;
- const IV: Buffer = Buffer.from(textParts[0], "hex");
- const encryptedText: string = textParts[1];
- const decipher = crypto.createDecipheriv("aes-256-ctr", encryptedKey, IV);
- let decrypted: string = decipher.update(encryptedText, "hex", "utf8");
- decrypted += decipher.final("utf8");
+ // Parse components
+ const iv = Buffer.from(ivHex, "hex");
+ const encrypted = Buffer.from(encryptedHex, "hex");
+ const authTag = Buffer.from(authTagHex, "hex");
+
+ // Validate sizes
+ if (iv.length !== 12) {
+ throw new Error("Invalid IV length for GCM");
+ }
+ if (authTag.length !== 16) {
+ throw new Error("Invalid auth tag length for GCM");
+ }
+
+ // Create decipher and set auth tag
+ const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
+ decipher.setAuthTag(authTag);
+
+ // Decrypt
+ let decrypted = decipher.update(encrypted, undefined, "utf8");
+ decrypted += decipher.final("utf8");
+
+ return decrypted;
+ } catch (error) {
+ // Surface authentication failures as decryption errors
+ throw new Error(
+ `Token decryption failed: ${error instanceof Error ? error.message : "Unknown error"}`,
+ );
+ }
+ }
- return decrypted;
+ // If not in expected format, return as-is (might be plaintext)
+ return encryptedToken;
}
diff --git a/pages/api/links/download/dataroom-document.ts b/pages/api/links/download/dataroom-document.ts
index 0e4d5b04..3532e2ac 100644
--- a/pages/api/links/download/dataroom-document.ts
+++ b/pages/api/links/download/dataroom-document.ts
@@ -1,6 +1,7 @@
import { NextApiRequest, NextApiResponse } from "next";
import { ItemType, ViewType } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
import { getFile } from "@/lib/files/get-file";
import { notifyDocumentDownload } from "@/lib/integrations/slack/events";
@@ -168,18 +169,16 @@ export default async function handle(
});
if (view.link.teamId) {
- try {
- await notifyDocumentDownload({
+ waitUntil(
+ notifyDocumentDownload({
teamId: view.link.teamId,
documentId,
dataroomId: view.dataroom.id,
linkId,
viewerEmail: view.viewerEmail ?? undefined,
viewerId: view.viewerId ?? undefined,
- });
- } catch (error) {
- console.error("Error sending Slack notification:", error);
- }
+ }),
+ );
} else {
console.log("No teamId found, skipping Slack notification");
}
diff --git a/pages/api/links/download/dataroom-folder.ts b/pages/api/links/download/dataroom-folder.ts
index 1ffab18e..885319a0 100644
--- a/pages/api/links/download/dataroom-folder.ts
+++ b/pages/api/links/download/dataroom-folder.ts
@@ -297,23 +297,21 @@ export default async function handler(
}
if (view.link.teamId) {
- try {
- await notifyDocumentDownload({
- teamId: view.link.teamId,
- documentId: undefined,
- dataroomId,
- linkId,
- viewerEmail: view.viewerEmail ?? undefined,
- viewerId: undefined,
- metadata: {
- folderName: rootFolder.name,
- documentCount: allDocuments.length,
- isFolderDownload: true,
- },
- });
- } catch (error) {
+ void notifyDocumentDownload({
+ teamId: view.link.teamId,
+ documentId: undefined,
+ dataroomId,
+ linkId,
+ viewerEmail: view.viewerEmail ?? undefined,
+ viewerId: undefined,
+ metadata: {
+ folderName: rootFolder.name,
+ documentCount: allDocuments.length,
+ isFolderDownload: true,
+ },
+ }).catch((error) => {
console.error("Error sending Slack notification:", error);
- }
+ });
}
// Get team-specific storage configuration
diff --git a/pages/api/teams/[teamId]/integrations/slack/channels.ts b/pages/api/teams/[teamId]/integrations/slack/channels.ts
index 4133a2b1..d1867bea 100644
--- a/pages/api/teams/[teamId]/integrations/slack/channels.ts
+++ b/pages/api/teams/[teamId]/integrations/slack/channels.ts
@@ -2,8 +2,9 @@ import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth/next";
+import { z } from "zod";
-import { slackClient } from "@/lib/integrations/slack/client";
+import { getSlackClient } from "@/lib/integrations/slack/client";
import { getSlackEnv } from "@/lib/integrations/slack/env";
import { SlackCredential } from "@/lib/integrations/slack/types";
import prisma from "@/lib/prisma";
@@ -55,6 +56,7 @@ export default async function handler(
}
try {
+ const slackClient = getSlackClient();
const channels = await slackClient.getChannels(
(integration.credentials as SlackCredential).accessToken,
);
@@ -90,7 +92,10 @@ export default async function handler(
"Invalid Slack access token. Please reconnect your Slack integration.",
});
}
- return res.status(200).json({ channels: [] });
+ console.error("Unexpected Slack error:", slackError);
+ return res
+ .status(502)
+ .json({ error: "Failed to fetch Slack channels" });
}
} catch (error) {
console.error("Error fetching Slack channels:", error);
@@ -100,11 +105,24 @@ export default async function handler(
if (req.method === "PUT") {
try {
- const { enabledChannels } = req.body;
-
- if (!enabledChannels) {
- return res.status(400).json({ error: "enabledChannels is required" });
+ const updateChannelsSchema = z.object({
+ enabledChannels: z.record(
+ z.string(),
+ z.object({
+ id: z.string(),
+ name: z.string(),
+ enabled: z.boolean(),
+ notificationTypes: z.array(z.string()),
+ }),
+ ),
+ });
+ const parsed = updateChannelsSchema.safeParse(req.body);
+ if (!parsed.success) {
+ return res
+ .status(400)
+ .json({ error: "Invalid enabledChannels format" });
}
+ const { enabledChannels } = parsed.data;
await prisma.installedIntegration.update({
where: {
diff --git a/pages/api/teams/[teamId]/integrations/slack/index.ts b/pages/api/teams/[teamId]/integrations/slack/index.ts
index e45408bd..e421371d 100644
--- a/pages/api/teams/[teamId]/integrations/slack/index.ts
+++ b/pages/api/teams/[teamId]/integrations/slack/index.ts
@@ -5,12 +5,25 @@ import { getServerSession } from "next-auth/next";
import { z } from "zod";
import { getSlackEnv } from "@/lib/integrations/slack/env";
+import {
+ SlackCredential,
+ SlackCredentialPublic,
+} from "@/lib/integrations/slack/types";
+import { uninstallSlackIntegration } from "@/lib/integrations/slack/uninstall";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
+const channelConfigSchema = z.object({
+ enabled: z.boolean(),
+ notificationTypes: z
+ .array(z.enum(["document_view", "document_download", "dataroom_access"]))
+ .default([]),
+ name: z.string().optional(),
+ id: z.string().optional(),
+});
const slackIntegrationUpdateSchema = z.object({
enabled: z.boolean().optional(),
- enabledChannels: z.record(z.string(), z.boolean()).optional(),
+ enabledChannels: z.record(z.string(), channelConfigSchema).optional(),
});
export default async function handler(
@@ -60,7 +73,7 @@ async function handleGet(
console.log("env", env);
try {
- const integration = await prisma.installedIntegration.findUnique({
+ const integrationFullData = await prisma.installedIntegration.findUnique({
where: {
teamId_integrationId: {
teamId,
@@ -77,12 +90,17 @@ async function handleGet(
},
});
- console.log("integration", integration);
-
- if (!integration) {
+ if (!integrationFullData) {
return res.status(404).json({ error: "Slack integration not found" });
}
+ const integration = {
+ ...integrationFullData,
+ credentials: {
+ team: (integrationFullData.credentials as SlackCredential)?.team,
+ },
+ };
+
return res.status(200).json(integration);
} catch (error) {
console.error("Error fetching Slack integration:", error);
@@ -126,20 +144,15 @@ async function handleUpdate(
});
}
- const updateData: {
- enabled?: boolean;
- enabledChannels?: Record<string, boolean>;
- } = {};
-
+ const updateData: any = {};
if (enabled !== undefined) updateData.enabled = enabled;
-
- if (enabledChannels) updateData.enabledChannels = enabledChannels;
+ if (enabledChannels) updateData.configuration = { enabledChannels };
if (Object.keys(updateData).length === 0) {
return res.status(400).json({ error: "No fields to update" });
}
- const updatedIntegration = await prisma.installedIntegration.update({
+ const updatedIntegrationData = await prisma.installedIntegration.update({
where: {
teamId_integrationId: {
teamId,
@@ -157,6 +170,13 @@ async function handleUpdate(
},
});
+ const updatedIntegration = {
+ ...updatedIntegrationData,
+ credentials: {
+ team: (updatedIntegrationData.credentials as SlackCredential)?.team,
+ },
+ };
+
return res.status(200).json(updatedIntegration);
} catch (error) {
console.error("Error updating Slack integration:", error);
@@ -184,6 +204,10 @@ async function handleDelete(
return res.status(404).json({ error: "Slack integration not found" });
}
+ // Uninstall the Slack integration from the Slack workspace
+ await uninstallSlackIntegration({ installation: integration });
+
+ // Delete the Slack integration from the database
await prisma.installedIntegration.delete({
where: {
teamId_integrationId: {
diff --git a/pages/settings/slack.tsx b/pages/settings/slack.tsx
index dcb305a0..7d181b81 100644
--- a/pages/settings/slack.tsx
+++ b/pages/settings/slack.tsx
@@ -38,7 +38,7 @@ export default function SlackSettings() {
const router = useRouter();
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
- const { isFeatureEnabled } = useFeatureFlags();
+ const { features, isLoading } = useFeatureFlags();
const [connecting, setConnecting] = useState(false);
const [isChannelPopoverOpen, setIsChannelPopoverOpen] = useState(false);
const [pendingChannelUpdate, setPendingChannelUpdate] = useState(false);
@@ -120,11 +120,12 @@ export default function SlackSettings() {
// Redirect if Slack feature is not enabled
useEffect(() => {
- if (!isFeatureEnabled("slack")) {
- router.push("/settings/general");
+ if (isLoading) return;
+ if (features && !features.slack) {
+ router.replace("/settings/general");
toast.error("This feature is not available for your team");
}
- }, [isFeatureEnabled, router]);
+ }, [features?.slack, isLoading, router]);
const handleConnect = async () => {
if (!teamId) return;