Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

21.6 KB
Raw Blame
/**
 * Slack Integration Service
 *
 * Simplified service that properly uses the official Slack SDK libraries:
 * - @slack/oauth InstallProvider for OAuth flow management
 * - @slack/web-api WebClient for Slack API operations
 * - Metadata-based project-to-team mapping
 */

import { WebClient } from "@slack/web-api";
import { InstallProvider } from "@slack/oauth";
import { logger } from "../logger";
import { env } from "../../env";
import { prisma, type SlackIntegration } from "../../db";
import { encrypt, decrypt } from "../../encryption";
import { isSlackActionConfig } from "../../domain/automations";

/**
 * Error thrown by SlackService when a Slack API call fails.
 * Preserves the Slack error code so callers can provide user-friendly messages.
 */
export class SlackApiError extends Error {
  constructor(
    message: string,
    public readonly slackErrorCode?: string,
  ) {
    super(message);
    this.name = "SlackApiError";
  }
}

/** OAuth scopes requested when installing the Slack app. */
export const SLACK_BOT_SCOPES = [
  "channels:read", // read public channels
  "groups:read", // read private channels that the bot is a member of
  "chat:write", // send messages to channels the bot is a member of
  "chat:write.public", // send messages to public channels that the bot is not a member of
] as const;

// Types for Slack integration
export interface SlackChannel {
  id: string;
  name: string;
  isPrivate?: boolean;
  isMember?: boolean;
}

export interface GetChannelsResult {
  channels: SlackChannel[];
  nextCursor?: string;
}

/** Same text as Slack's own channel_not_found, so private channels the viewer can't use look non-existent. */
export const SLACK_CHANNEL_NOT_FOUND_MESSAGE =
  'Channel not found. The channel may not exist or is a private channel the bot has not been invited to. For private channels, invite the app with "/invite @Langfuse" in that channel.';

const SLACK_LOOKUP_TIMEOUT_MS = 5_000;

/**
 * getPrivateChannelViewerSlackUserId returns the installer's Slack user id when
 * the Langfuse user is the installer. Only they may see or use private channels.
 */
export function getPrivateChannelViewerSlackUserId(
  integration: Pick<
    SlackIntegration,
    "installerUserId" | "installerSlackUserId"
  >,
  userId: string,
) {
  return integration.installerUserId === userId
    ? integration.installerSlackUserId
    : null;
}

/**
 * getViewablePrivateSlackChannelIds returns the saved private channels the user
 * may see: only the installer, and only channels they are still a member of.
 * Fails closed (nothing viewable) if Slack can't be reached.
 */
export async function getViewablePrivateSlackChannelIds(params: {
  projectId: string;
  userId: string;
  actions: { config: unknown }[];
}): Promise<Set<string>> {
  const hasPrivateChannel = params.actions.some(
    ({ config }) => isSlackActionConfig(config) && config.isPrivate,
  );
  if (!hasPrivateChannel) return new Set();

  const integration = await prisma.slackIntegration.findUnique({
    where: { projectId: params.projectId },
    select: { installerUserId: true, installerSlackUserId: true },
  });
  const viewerSlackUserId =
    integration &&
    getPrivateChannelViewerSlackUserId(integration, params.userId);
  if (!viewerSlackUserId) return new Set();

  try {
    return await withSlackLookupTimeout(
      (async () => {
        const slackService = SlackService.getInstance();
        const client = await slackService.getWebClientForProject(
          params.projectId,
        );
        const { channels } = await slackService.getPrivateChannels(client, {
          slackUserId: viewerSlackUserId,
          includeArchived: true,
        });
        return new Set(channels.map((channel) => channel.id));
      })(),
    );
  } catch (error) {
    logger.warn("Failed to resolve viewable private Slack channels", {
      error,
      projectId: params.projectId,
    });
    return new Set();
  }
}

/**
 * withSlackLookupTimeout rejects after 5s. The Slack client retries for up to
 * 90s, so access lookups would otherwise hold requests; callers fail closed.
 */
async function withSlackLookupTimeout<T>(lookup: Promise<T>): Promise<T> {
  let timer: NodeJS.Timeout | undefined;
  const timeout = new Promise<never>((_, reject) => {
    timer = setTimeout(
      () => reject(new Error("Slack lookup timed out")),
      SLACK_LOOKUP_TIMEOUT_MS,
    );
  });
  try {
    return await Promise.race([lookup, timeout]);
  } finally {
    clearTimeout(timer);
  }
}

/**
 * maskPrivateSlackChannel hides the name of a saved private channel from users
 * who may not see it. The channel id stays intact so unchanged saves keep working.
 */
export function maskPrivateSlackChannel<T extends { config: unknown }>(
  action: T,
  viewablePrivateChannelIds: Set<string>,
): T {
  const { config } = action;
  if (
    !isSlackActionConfig(config) ||
    !config.isPrivate ||
    viewablePrivateChannelIds.has(config.channelId)
  ) {
    return action;
  }
  return {
    ...action,
    config: {
      ...config,
      channelName: `Private Channel (…${config.channelId.slice(-3)})`,
    },
  };
}

/** SlackMessage is the Block Kit payload sent to Slack. */
export interface SlackMessage {
  blocks: any[];
  text?: string;
  attachments?: { color: string; fallback?: string; blocks?: any[] }[];
}

export interface SlackMessageParams extends SlackMessage {
  client: WebClient;
  channelId: string;
}

/** escapeSlackMrkdwn escapes Slack mrkdwn special characters to prevent injection. */
export function escapeSlackMrkdwn(text: string): string {
  return text
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;");
}

export interface SlackMessageResponse {
  messageTs: string;
  channel: string;
}

// Interface for Slack installation metadata
export interface SlackInstallationMetadata {
  projectId: string;
  /** Langfuse user who started the install */
  userId?: string;
}

/**
 * Type guard to validate Slack installation metadata
 */
function isSlackInstallationMetadata(
  metadata: unknown,
): metadata is SlackInstallationMetadata {
  return (
    typeof metadata === "object" &&
    metadata !== null &&
    "projectId" in metadata &&
    typeof metadata.projectId === "string" &&
    metadata.projectId.length > 0 &&
    (!("userId" in metadata) || typeof metadata.userId === "string")
  );
}

/**
 * Helper function to safely parse and validate Slack installation metadata
 */
export function parseSlackInstallationMetadata(
  metadata: unknown,
): SlackInstallationMetadata {
  if (typeof metadata !== "string") {
    throw new Error("Installation metadata must be a string");
  }

  let parsedMetadata: unknown;
  try {
    parsedMetadata = JSON.parse(metadata);
  } catch {
    throw new Error("Failed to parse installation metadata as JSON");
  }

  if (!isSlackInstallationMetadata(parsedMetadata)) {
    throw new Error(
      "Invalid installation metadata: missing or invalid projectId",
    );
  }

  return parsedMetadata;
}

/**
 * Slack Service Class
 *
 * Uses InstallProvider for OAuth flow and metadata-based project mapping.
 * Much simpler than the previous implementation while maintaining all functionality.
 */
export class SlackService {
  private static instance: SlackService | null = null;
  private readonly installer: InstallProvider;

  private constructor() {
    this.installer = new InstallProvider({
      clientId: env.SLACK_CLIENT_ID!,
      clientSecret: env.SLACK_CLIENT_SECRET!,
      stateSecret: env.SLACK_STATE_SECRET!,
      directInstall: false,
      installUrlOptions: {
        scopes: SLACK_BOT_SCOPES as unknown as string[],
      },
      installationStore: {
        storeInstallation: async (installation) => {
          try {
            const metadata = parseSlackInstallationMetadata(
              installation.metadata,
            );
            const projectId = metadata.projectId;

            logger.info("Storing Slack installation for project", {
              projectId,
              teamId: installation.team?.id,
              teamName: installation.team?.name,
            });

            // Store by projectId (one integration per project)
            await prisma.slackIntegration.upsert({
              where: { projectId },
              create: {
                projectId,
                teamId: installation.team?.id!,
                teamName: installation.team?.name!,
                botToken: encrypt(installation.bot?.token!),
                botUserId: installation.bot?.userId!,
                installerUserId: metadata.userId ?? null,
                installerSlackUserId: installation.user?.id ?? null,
              },
              update: {
                teamId: installation.team?.id!,
                teamName: installation.team?.name!,
                botToken: encrypt(installation.bot?.token!),
                botUserId: installation.bot?.userId!,
                installerUserId: metadata.userId ?? null,
                installerSlackUserId: installation.user?.id ?? null,
              },
            });

            logger.info("Slack installation stored successfully", {
              projectId,
              teamId: installation.team?.id,
            });
          } catch (error) {
            logger.error("Failed to store Slack installation", { error });
            throw error;
          }
        },

        fetchInstallation: async (installQuery) => {
          try {
            // Handle both teamId and projectId lookups
            // When SDK calls with teamId, we treat it as projectId
            const lookupId = installQuery.teamId;

            if (!lookupId) {
              throw new Error("No lookup ID provided");
            }

            const integration = await prisma.slackIntegration.findFirst({
              where: {
                OR: [
                  { teamId: lookupId }, // Actual team ID lookup
                  { projectId: lookupId }, // Project ID lookup (our custom usage)
                ],
              },
            });

            if (!integration) {
              throw new Error("Slack integration not found");
            }

            // Return full Installation interface as expected by SDK
            return {
              team: {
                id: integration.teamId,
                name: integration.teamName,
              },
              bot: {
                id: integration.botUserId,
                token: decrypt(integration.botToken),
                userId: integration.botUserId,
                scopes: [],
              },
              enterprise: undefined,
              user: {
                token: undefined,
                refreshToken: undefined,
                expiresAt: undefined,
                scopes: undefined,
                id: integration.botUserId,
              },
            };
          } catch (error) {
            logger.error("Failed to fetch Slack installation", { error });
            throw error;
          }
        },

        deleteInstallation: async (installQuery) => {
          try {
            const lookupId = installQuery.teamId;

            if (!lookupId) {
              throw new Error("No lookup ID provided for deletion");
            }

            await prisma.slackIntegration.deleteMany({
              where: {
                OR: [{ teamId: lookupId }, { projectId: lookupId }],
              },
            });

            logger.info("Slack installation deleted successfully", {
              lookupId,
            });
          } catch (error) {
            logger.error("Failed to delete Slack installation", { error });
            throw error;
          }
        },
      },
    });
  }

  /**
   * Get singleton instance of SlackService
   */
  static getInstance(): SlackService {
    if (!SlackService.instance) {
      SlackService.instance = new SlackService();
    }
    return SlackService.instance;
  }

  /**
   * Get the configured InstallProvider instance for OAuth handling
   */
  getInstaller(): InstallProvider {
    return this.installer;
  }

  /**
   * Reset the singleton instance (useful for testing)
   */
  static resetInstance(): void {
    SlackService.instance = null;
  }

  /**
   * Delete Slack integration for a project
   */
  async deleteIntegration(projectId: string): Promise<void> {
    try {
      if (!this.installer.installationStore?.deleteInstallation) {
        throw new Error("Installation store not configured");
      }

      await this.installer.installationStore.deleteInstallation({
        teamId: projectId,
        isEnterpriseInstall: false,
        enterpriseId: undefined,
      });

      logger.info("Slack integration deleted for project", { projectId });
    } catch (error) {
      logger.error("Failed to delete Slack integration", { error, projectId });
      throw new Error(
        `Failed to delete integration: ${error instanceof Error ? error.message : "Unknown error"}`,
      );
    }
  }

  /**
   * Get WebClient for a specific project
   */
  async getWebClientForProject(projectId: string): Promise<WebClient> {
    try {
      // Use projectId as the teamId parameter (handled by our fetchInstallation)
      const auth = await this.installer.authorize({
        teamId: projectId,
        isEnterpriseInstall: false,
        enterpriseId: undefined,
      });

      if (!auth.botToken) {
        throw new Error("No bot token found for project");
      }

      const client = new WebClient(auth.botToken, {
        retryConfig: { retries: 3, maxRetryTime: 90_000 },
      });
      logger.debug("Created WebClient for project", { projectId });

      return client;
    } catch (error) {
      logger.error("Failed to create WebClient for project", {
        error,
        projectId,
      });
      throw new Error(
        `Failed to create WebClient: ${error instanceof Error ? error.message : "Unknown error"}`,
      );
    }
  }

  /**
   * Fetch one page of channels accessible to the bot.
   * Uses cursor-based pagination defined by Slack API https://api.slack.com/apis/pagination.
   */
  private async getChannelsPage(
    client: WebClient,
    channelTypes = "public_channel,private_channel",
    cursor?: string,
  ): Promise<Omit<GetChannelsResult, "hasPrivateChannelAccess">> {
    try {
      const result = await client.conversations.list({
        exclude_archived: true,
        types: channelTypes,
        limit: env.SLACK_PAGE_SIZE,
        cursor: cursor,
      });

      if (!result.ok) {
        throw new Error(`Slack API error: ${result.error}`);
      }

      const channels: SlackChannel[] = (result.channels || []).map(
        (channel) => ({
          id: channel.id!,
          name: channel.name!,
          isPrivate: channel.is_private || false,
          isMember: channel.is_member || false,
        }),
      );

      const nextCursor = result.response_metadata?.next_cursor;
      return {
        channels,
        nextCursor: nextCursor || undefined,
      };
    } catch (error) {
      logger.error("Failed to fetch Slack channels page", { error, cursor });
      throw error;
    }
  }

  /**
   * Get one page of public channels. Private channels come from getPrivateChannels:
   * the bot token lists every private channel it was invited to, including ones
   * the viewer isn't a member of.
   */
  async getChannels(
    client: WebClient,
    cursor?: string,
  ): Promise<GetChannelsResult> {
    try {
      const { channels, nextCursor } = await this.getChannelsPage(
        client,
        "public_channel",
        cursor,
      );

      logger.debug("Retrieved channels from Slack", {
        channelCount: channels.length,
        hasNextPage: Boolean(nextCursor),
      });

      return { channels, nextCursor };
    } catch (error) {
      logger.error("Failed to fetch channels", { error });
      throw new Error(
        `Failed to fetch channels: ${error instanceof Error ? error.message : "Unknown error"}`,
      );
    }
  }

  /**
   * Get all private channels the bot is in, or with `slackUserId` only those that
   * user is also a member of. `hasPrivateChannelAccess` is false for installs
   * predating the `groups:read` scope.
   */
  async getPrivateChannels(
    client: WebClient,
    options: { slackUserId?: string; includeArchived?: boolean } = {},
  ) {
    const channels: SlackChannel[] = [];
    let cursor: string | undefined;
    try {
      do {
        const result = await client.users.conversations({
          types: "private_channel",
          exclude_archived: !options.includeArchived,
          limit: env.SLACK_PAGE_SIZE,
          cursor,
          ...(options.slackUserId ? { user: options.slackUserId } : {}),
        });
        for (const channel of result.channels ?? []) {
          channels.push({
            id: channel.id!,
            name: channel.name!,
            isPrivate: true,
            isMember: true,
          });
        }
        cursor = result.response_metadata?.next_cursor || undefined;
      } while (cursor);
    } catch (error: any) {
      if (error?.data?.error === "missing_scope") {
        return { channels: [], hasPrivateChannelAccess: false };
      }
      logger.error("Failed to fetch private Slack channels", { error });
      throw new SlackApiError(
        `Failed to fetch private channels: ${error instanceof Error ? error.message : "Unknown error"}`,
        error?.data?.error,
      );
    }
    return { channels, hasPrivateChannelAccess: true };
  }

  /**
   * Resolve whether the viewer may use `channel` (id or `#name`): `public` if it
   * is not a private channel the bot is in, `private` if the viewer shares it,
   * `denied` otherwise. Callers must treat `denied` exactly like a non-existent
   * channel so its existence isn't revealed.
   */
  async checkPrivateChannelAccess(params: {
    client: WebClient;
    channel: string;
    viewerSlackUserId: string | null;
  }): Promise<
    | { access: "public" }
    | { access: "private"; channel: SlackChannel }
    | { access: "denied" }
  > {
    const key = params.channel.trim().replace(/^#/, "");
    // Slack channel names are lowercase but name lookups ignore case.
    const name = key.toLowerCase();
    // Archived channels are included so they can't bypass the check.
    const botChannels = await this.getPrivateChannels(params.client, {
      includeArchived: true,
    });

    // Without groups:read, private channels look like public ones; only accept
    // channels Slack confirms are public.
    if (!botChannels.hasPrivateChannelAccess) {
      const info = params.channel.trim().startsWith("#")
        ? await withSlackLookupTimeout(
            this.findPublicChannelByName(params.client, name),
          ).catch(() => null)
        : await this.getChannelInfo(params.client, key);
      return info && !info.isPrivate
        ? { access: "public" }
        : { access: "denied" };
    }

    const privateChannel = botChannels.channels.find(
      (channel) => channel.id === key || channel.name.toLowerCase() === name,
    );
    if (!privateChannel) return { access: "public" };
    if (!params.viewerSlackUserId) return { access: "denied" };

    const viewerChannels = await this.getPrivateChannels(params.client, {
      slackUserId: params.viewerSlackUserId,
      includeArchived: true,
    });
    return viewerChannels.channels.some(
      (channel) => channel.id === privateChannel.id,
    )
      ? { access: "private", channel: privateChannel }
      : { access: "denied" };
  }

  private async findPublicChannelByName(client: WebClient, name: string) {
    let cursor: string | undefined;
    do {
      const page = await this.getChannels(client, cursor);
      const match = page.channels.find((channel) => channel.name === name);
      if (match) return match;
      cursor = page.nextCursor;
    } while (cursor);
    return null;
  }

  /**
   * Get channel info by ID via conversations.info.
   */
  async getChannelInfo(
    client: WebClient,
    channelId: string,
  ): Promise<SlackChannel | null> {
    try {
      const result = await client.conversations.info({ channel: channelId });
      if (!result.ok || !result.channel) return null;
      return {
        id: result.channel.id!,
        name: result.channel.name!,
        isPrivate: result.channel.is_private || false,
        isMember: result.channel.is_member || false,
      };
    } catch (error) {
      logger.warn("Failed to fetch channel info", { error, channelId });
      return null;
    }
  }

  /**
   * Send a message to a Slack channel
   */
  async sendMessage(params: SlackMessageParams): Promise<SlackMessageResponse> {
    try {
      const result = await params.client.chat.postMessage({
        channel: params.channelId,
        blocks: params.blocks,
        attachments: params.attachments as any,
        text:
          params.text ||
          (params.blocks?.length || params.attachments?.length
            ? undefined
            : "Langfuse Notification"),
        unfurl_links: false,
        unfurl_media: false,
      });

      if (!result.ok) {
        throw new Error(`Failed to send message: ${result.error}`);
      }

      const response = {
        messageTs: result.ts!,
        channel: result.channel!,
      };

      logger.info("Message sent successfully to Slack", {
        channel: params.channelId,
        messageTs: response.messageTs,
      });

      return response;
    } catch (error: any) {
      logger.error("Failed to send message", {
        error,
        channelId: params.channelId,
      });

      const slackErrorCode = error?.data?.error as string | undefined;
      throw new SlackApiError(
        `Failed to send message: ${error instanceof Error ? error.message : "Unknown error"}`,
        slackErrorCode,
      );
    }
  }

  /**
   * Validate a WebClient instance
   */
  async validateClient(client: WebClient): Promise<boolean> {
    try {
      const result = await client.auth.test();
      return result.ok || false;
    } catch (error) {
      logger.warn("Client validation failed", { error });
      return false;
    }
  }
}