🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(slack): add Slack marketplace install flow (#14350)
Tobias Wochingercee3cac641a4
diff --git a/packages/shared/prisma/migrations/20260617000000_slack_integrations_pending_columns/migration.sql b/packages/shared/prisma/migrations/20260617000000_slack_integrations_pending_columns/migration.sqlnew file mode 100644index 0000000000..ef1df4322f--- /dev/null+++ b/packages/shared/prisma/migrations/20260617000000_slack_integrations_pending_columns/migration.sql@@ -0,0 +1,15 @@+-- Make project_id nullable so a Slack installation can exist before being linked+-- to a project (Marketplace install-then-link flow). The existing unique index+-- on project_id keeps mapping linked projects 1:1; Postgres treats NULLs as+-- distinct, so multiple unlinked (pending) rows can coexist.+ALTER TABLE "slack_integrations" ALTER COLUMN "project_id" DROP NOT NULL;++-- Pending-only columns (NULL once the install is linked to a project).+ALTER TABLE "slack_integrations" ADD COLUMN "expires_at" TIMESTAMP(3);++-- One-time claim token hash: the raw token is carried only by the onboarding+-- URL and is required before a pending install can be linked to a project.+ALTER TABLE "slack_integrations" ADD COLUMN "claim_token_hash" TEXT;++-- Index to purge expired pending installs efficiently.+CREATE INDEX "slack_integrations_expires_at_idx" ON "slack_integrations"("expires_at");diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex fb6b88e804..94b3ddc986 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -1762,9 +1762,15 @@ model Monitor {// Slack Integration: Stores centralized Slack workspace connection for each project// One project can connect to one Slack workspace, supporting multiple channel automationsmodel SlackIntegration {- id String @id @default(cuid())- projectId String @unique @map("project_id")- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ id String @id @default(cuid())++ // projectId is NULL for a "pending" Marketplace installation that has not yet+ // been linked to a project (the Direct Install URL must 302 straight to OAuth,+ // so the token is issued before the user picks a project). Once linked it is+ // set to the chosen project. NULLs are distinct under @unique, so multiple+ // pending rows can coexist; a linked project still maps 1:1.+ projectId String? @unique @map("project_id")+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)// Installation details (encrypted using shared encryption utilities)teamId String @map("team_id") // Slack workspace ID@@ -1772,10 +1778,16 @@ model SlackIntegration {botToken String @map("bot_token") // Encrypted bot token for API callsbotUserId String @map("bot_user_id") // Bot user ID for workspace+ // Pending-only fields (NULL once linked): when an unlinked pending install is+ // purged, and the hashed one-time claim token required to link it.+ expiresAt DateTime? @map("expires_at")+ claimTokenHash String? @map("claim_token_hash")+createdAt DateTime @default(now()) @map("created_at")updatedAt DateTime @default(now()) @updatedAt @map("updated_at")@@index([teamId])+ @@index([expiresAt])@@map("slack_integrations")}diff --git a/packages/shared/src/server/services/SlackService.ts b/packages/shared/src/server/services/SlackService.tsindex 0ff0af8534..1defe14998 100644--- a/packages/shared/src/server/services/SlackService.ts+++ b/packages/shared/src/server/services/SlackService.ts@@ -7,6 +7,7 @@* - Metadata-based project-to-team mapping*/+import { createHash, randomBytes } from "node:crypto";import { WebClient } from "@slack/web-api";import { InstallProvider } from "@slack/oauth";import { logger } from "../logger";@@ -36,6 +37,19 @@ export const SLACK_BOT_SCOPES = ["chat:write.public", // send messages to public channels that the bot is not a member of] as const;+/**+ * How long an unlinked Marketplace installation is held before being purged.+ * Short because the row holds a bot token; the user links it to a project in the+ * onboarding flow within this window.+ */+export const SLACK_PENDING_INSTALL_TTL_MS = 15 * 60 * 1000; // 15 minutes++const generatePendingInstallClaimToken = () =>+ randomBytes(32).toString("base64url");++export const hashSlackPendingInstallClaimToken = (claimToken: string) =>+ createHash("sha256").update(claimToken).digest("hex");+// Types for Slack integrationexport interface SlackChannel {id: string;@@ -120,6 +134,44 @@ export function parseSlackInstallationMetadata(return parsedMetadata;}+/**+ * Lenient variant of parseSlackInstallationMetadata. Returns the projectId when+ * the OAuth metadata carries one (in-app "Connect" flow), or undefined for+ * Marketplace installs that complete OAuth before a project is chosen.+ */+export function tryGetProjectIdFromMetadata(+ metadata: unknown,+): string | undefined {+ if (typeof metadata !== "string" || metadata.length === 0) return undefined;+ try {+ const parsed = JSON.parse(metadata);+ return isSlackInstallationMetadata(parsed) ? parsed.projectId : undefined;+ } catch {+ return undefined;+ }+}++/**+ * Column set shared by the two paths that link a Slack workspace to a project:+ * the in-app "Connect" install and the Marketplace link step. botToken must+ * already be encrypted.+ */+function projectInstallationFields(params: {+ teamId: string;+ teamName: string;+ encryptedBotToken: string;+ botUserId: string;+}) {+ return {+ teamId: params.teamId,+ teamName: params.teamName,+ botToken: params.encryptedBotToken,+ botUserId: params.botUserId,+ expiresAt: null,+ claimTokenHash: null,+ };+}+/*** Slack Service Class*@@ -128,52 +180,114 @@ export function parseSlackInstallationMetadata(*/export class SlackService {private static instance: SlackService | null = null;- private readonly installer: InstallProvider;+ // Lazily constructed: building an InstallProvider requires the Slack OAuth+ // env vars (clientId/clientSecret/stateSecret) and throws without them. The+ // pending-install DB helpers below are pure Prisma and must work even when+ // Slack OAuth is not configured (e.g. the test environment), so we only+ // build the provider on first OAuth use via getInstaller().+ private installer: InstallProvider | null = null;- private constructor() {- this.installer = new InstallProvider({+ private constructor() {}++ private buildInstaller(): InstallProvider {+ return new InstallProvider({clientId: env.SLACK_CLIENT_ID!,clientSecret: env.SLACK_CLIENT_SECRET!,stateSecret: env.SLACK_STATE_SECRET!,+ // 302 straight to Slack's authorize URL (Marketplace "Direct Install URL"+ // behavior) instead of rendering an intermediate "Add to Slack" page. Both+ // flows go through handleInstallPath, which sets the OAuth state cookie+ // that handleCallback verifies.+ directInstall: true,installUrlOptions: {scopes: SLACK_BOT_SCOPES as unknown as string[],},installationStore: {storeInstallation: async (installation) => {try {- const metadata = parseSlackInstallationMetadata(+ const projectId = tryGetProjectIdFromMetadata(installation.metadata,);- const projectId = metadata.projectId;-- logger.info("Storing Slack installation for project", {- projectId,- teamId: installation.team?.id,- teamName: installation.team?.name,- });+ const teamId = installation.team?.id;+ const teamName = installation.team?.name;+ const botToken = installation.bot?.token;+ const botUserId = installation.bot?.userId;++ if (!teamId || !teamName || !botToken || !botUserId) {+ throw new Error(+ "Incomplete Slack installation payload (missing team or bot details)",+ );+ }- // Store by projectId (one integration per project)- await prisma.slackIntegration.upsert({- where: { projectId },- create: {+ if (projectId) {+ // In-app "Connect" flow: the project is known up front (passed via+ // OAuth metadata), so link directly. One integration per project.+ const fields = projectInstallationFields({+ teamId,+ teamName,+ encryptedBotToken: encrypt(botToken),+ botUserId,+ });+ await prisma.slackIntegration.upsert({+ where: { projectId },+ create: { projectId, ...fields },+ update: fields,+ });++ logger.info("Slack installation stored for project", {projectId,- teamId: installation.team?.id!,- teamName: installation.team?.name!,- botToken: encrypt(installation.bot?.token!),- botUserId: installation.bot?.userId!,- },- update: {- teamId: installation.team?.id!,- teamName: installation.team?.name!,- botToken: encrypt(installation.bot?.token!),- botUserId: installation.bot?.userId!,- },- });-- logger.info("Slack installation stored successfully", {- projectId,- teamId: installation.team?.id,- });+ teamId,+ });+ } else {+ // Marketplace flow: no project yet (the Direct Install URL must+ // 302 straight to OAuth). Hold the install as a pending row until+ // the onboarding flow links it to a project.+ //+ // Latest-wins: drop any prior pending install for this workspace+ // (projectId: null guards linked rows), then store the fresh one.+ // Serializable so two concurrent installs of the SAME workspace+ // can't both pass the delete (each seeing no rows) and then both+ // insert, leaving duplicate pending rows; under contention one+ // transaction is aborted and the install can be retried.+ await prisma.$transaction(+ async (tx) => {+ await tx.slackIntegration.deleteMany({+ where: { teamId, projectId: null },+ });+ await tx.slackIntegration.create({+ data: {+ projectId: null,+ teamId,+ teamName,+ botToken: encrypt(botToken),+ botUserId,+ expiresAt: new Date(+ Date.now() + SLACK_PENDING_INSTALL_TTL_MS,+ ),+ },+ });+ },+ { isolationLevel: "Serializable" },+ );++ // Opportunistically purge other workspaces' expired pending rows+ // so abandoned installs can't accumulate (no dedicated cron; reads+ // also filter on expiry). Best-effort: the install already+ // committed above, so a cleanup failure must not surface as a+ // failed install (reads filter on expiry anyway).+ try {+ await this.deleteExpiredPendingInstallations();+ } catch (cleanupError) {+ logger.warn(+ "Opportunistic purge of expired pending Slack installs failed",+ { error: cleanupError },+ );+ }++ logger.info("Slack installation stored as pending (no project)", {+ teamId,+ });+ }} catch (error) {logger.error("Failed to store Slack installation", { error });throw error;@@ -192,6 +306,9 @@ export class SlackService {const integration = await prisma.slackIntegration.findFirst({where: {+ // Only resolve linked installations; a pending (unlinked) row+ // must never be returned as an active integration.+ projectId: { not: null },OR: [{ teamId: lookupId }, // Actual team ID lookup{ projectId: lookupId }, // Project ID lookup (our custom usage)@@ -270,6 +387,9 @@ export class SlackService {* Get the configured InstallProvider instance for OAuth handling*/getInstaller(): InstallProvider {+ if (!this.installer) {+ this.installer = this.buildInstaller();+ }return this.installer;}@@ -285,11 +405,12 @@ export class SlackService {*/async deleteIntegration(projectId: string): Promise<void> {try {- if (!this.installer.installationStore?.deleteInstallation) {+ const installer = this.getInstaller();+ if (!installer.installationStore?.deleteInstallation) {throw new Error("Installation store not configured");}- await this.installer.installationStore.deleteInstallation({+ await installer.installationStore.deleteInstallation({teamId: projectId,isEnterpriseInstall: false,enterpriseId: undefined,@@ -304,13 +425,160 @@ export class SlackService {}}+ /**+ * Get the current (non-expired) pending installation for a Slack workspace.+ * Used by the Marketplace onboarding flow to show which workspace is being+ * linked. Returns null if there is no pending install or it has expired.+ */+ async getPendingInstallation(teamId: string): Promise<{+ teamId: string;+ teamName: string;+ expiresAt: Date | null;+ } | null> {+ return prisma.slackIntegration.findFirst({+ where: { teamId, projectId: null, expiresAt: { gt: new Date() } },+ orderBy: { createdAt: "desc" },+ select: { teamId: true, teamName: true, expiresAt: true },+ });+ }++ /**+ * Get pending installation details only when the caller presents the one-time+ * claim token issued by the OAuth callback.+ */+ async getClaimedPendingInstallation(+ teamId: string,+ claimToken: string,+ ): Promise<{+ teamId: string;+ teamName: string;+ expiresAt: Date | null;+ } | null> {+ // Enforce the claim in the query: a workspace can have several pending+ // installs (multiple people in the same org), so match on teamId AND the+ // claim hash to return the right row, rather than fetching the latest and+ // comparing the hash in app code. A null claimTokenHash never matches.+ return prisma.slackIntegration.findFirst({+ where: {+ teamId,+ projectId: null,+ expiresAt: { gt: new Date() },+ claimTokenHash: hashSlackPendingInstallClaimToken(claimToken),+ },+ orderBy: { createdAt: "desc" },+ select: {+ teamId: true,+ teamName: true,+ expiresAt: true,+ },+ });+ }++ /**+ * Issue a one-time claim token for the latest active pending installation.+ * Only the hash is stored; the raw token is carried by the onboarding URL and+ * required when the user links the install to a project.+ */+ async issuePendingInstallationClaim(teamId: string): Promise<string | null> {+ const pending = await prisma.slackIntegration.findFirst({+ where: { teamId, projectId: null, expiresAt: { gt: new Date() } },+ orderBy: { createdAt: "desc" },+ select: { id: true },+ });+ if (!pending) return null;++ const claimToken = generatePendingInstallClaimToken();+ await prisma.slackIntegration.update({+ where: { id: pending.id },+ data: {+ claimTokenHash: hashSlackPendingInstallClaimToken(claimToken),+ },+ });++ return claimToken;+ }++ /**+ * Link a pending (unlinked) Marketplace installation to a project. Moves the+ * pending row in place: sets projectId and clears the pending-only fields. If+ * the project already has an integration it is replaced (the new install+ * wins). Returns the linked integration, or null if no valid pending install+ * exists for the workspace.+ */+ async linkPendingInstallation(+ teamId: string,+ projectId: string,+ claimToken: string,+ ): Promise<{ id: string; teamId: string; teamName: string } | null> {+ const linked = await prisma.$transaction(async (tx) => {+ // Resolve the pending row inside the transaction so the claim + expiry are+ // validated atomically with the link — no TOCTOU window where the row+ // could expire or be purged between the check and the write. Enforced in+ // the query (see getClaimedPendingInstallation): match on teamId AND the+ // claim hash so the right row is linked even when several exist.+ const pending = await tx.slackIntegration.findFirst({+ where: {+ teamId,+ projectId: null,+ expiresAt: { gt: new Date() },+ claimTokenHash: hashSlackPendingInstallClaimToken(claimToken),+ },+ orderBy: { createdAt: "desc" },+ });+ if (!pending) return null;++ // Upsert the integration for the project (same shape as the in-app+ // "Connect" path), copying the already-encrypted token from the pending+ // row, then consume all pending rows for this workspace.+ const fields = projectInstallationFields({+ teamId: pending.teamId,+ teamName: pending.teamName,+ encryptedBotToken: pending.botToken,+ botUserId: pending.botUserId,+ });+ const result = await tx.slackIntegration.upsert({+ where: { projectId },+ create: { projectId, ...fields },+ update: fields,+ });+ await tx.slackIntegration.deleteMany({+ where: { teamId, projectId: null },+ });+ return result;+ });++ if (!linked) return null;++ logger.info("Linked pending Slack installation to project", {+ teamId,+ projectId,+ });+ return { id: linked.id, teamId: linked.teamId, teamName: linked.teamName };+ }++ /**+ * Purge expired pending (unlinked) installations. The projectId IS NULL guard+ * is mandatory so this can never delete a linked integration.+ */+ async deleteExpiredPendingInstallations(+ now: Date = new Date(),+ ): Promise<number> {+ const { count } = await prisma.slackIntegration.deleteMany({+ where: { projectId: null, expiresAt: { lt: now } },+ });+ if (count > 0) {+ logger.info("Purged expired pending Slack installations", { count });+ }+ return count;+ }+/*** 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({+ const auth = await this.getInstaller().authorize({teamId: projectId,isEnterpriseInstall: false,enterpriseId: undefined,diff --git a/web/src/__tests__/server/slack-marketplace-router.servertest.ts b/web/src/__tests__/server/slack-marketplace-router.servertest.tsnew file mode 100644index 0000000000..8190a4ca98--- /dev/null+++ b/web/src/__tests__/server/slack-marketplace-router.servertest.ts@@ -0,0 +1,323 @@+import { prisma } from "@langfuse/shared/src/db";+import { encrypt } from "@langfuse/shared/encryption";+import type { Session } from "next-auth";+import { TRPCError } from "@trpc/server";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { appRouter } from "@/src/server/api/root";+import {+ createOrgProjectAndApiKey,+ hashSlackPendingInstallClaimToken,+} from "@langfuse/shared/src/server";+import { PENDING_INSTALL_CLAIM_COOKIE } from "@/src/features/slack/server/pendingInstallClaimCookie";++// These tests exercise the real SlackService + prisma (no mock), so they live in+// their own file — the existing slack-integration.servertest.ts mocks SlackService+// at the module level.++type SessionProject = { id: string; name: string; role: string };++function buildSession(+ org: { id: string; name: string },+ projects: SessionProject[],+): Session {+ return {+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: org.id,+ name: org.name,+ role: "MEMBER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ metadata: {},+ projects: projects.map((p) => ({+ id: p.id,+ role: p.role,+ retentionDays: 30,+ deletedAt: null,+ name: p.name,+ metadata: {},+ })),+ },+ ],+ featureFlags: { excludeClickhouseRead: false, templateFlag: true },+ // not an instance admin, so project RBAC is actually enforced+ admin: false,+ },+ environment: {+ enableExperimentalFeatures: false,+ selfHostedInstancePlan: "cloud:hobby",+ },+ } as unknown as Session;+}++function callerFor(session: Session, headers: Record<string, string> = {}) {+ const ctx = createInnerTRPCContext({ session, headers });+ return appRouter.createCaller({ ...ctx, prisma });+}++// The OAuth callback delivers the claim as an httpOnly cookie bound to the+// workspace; the procedures read it from the request headers. Build that header+// the same way so the tests drive the real cookie path.+function claimCookie(teamId: string, claim: string): Record<string, string> {+ return {+ cookie: `${PENDING_INSTALL_CLAIM_COOKIE}=${encodeURIComponent(+ JSON.stringify({ teamId, claim }),+ )}`,+ };+}++let teamCounter = 0;+const uniqueTeamId = (label: string) =>+ `T-router-${Date.now()}-${teamCounter++}-${label}`;+const CLAIM_TOKEN = "router-claim-token";++async function createPendingRow(+ teamId: string,+ teamName = "Test Workspace",+ claimToken = CLAIM_TOKEN,+) {+ return prisma.slackIntegration.create({+ data: {+ projectId: null,+ teamId,+ teamName,+ botToken: encrypt("xoxb-test"),+ botUserId: "U-test",+ expiresAt: new Date(Date.now() + 60 * 60 * 1000),+ claimTokenHash: hashSlackPendingInstallClaimToken(claimToken),+ },+ });+}++describe("slack marketplace tRPC router", () => {+ describe("getPendingInstallation", () => {+ it("returns isPending false when none exists", async () => {+ const { project, org } = await createOrgProjectAndApiKey();+ const teamId = uniqueTeamId("none");+ const caller = callerFor(+ buildSession(org, [+ { id: project.id, name: project.name, role: "ADMIN" },+ ]),+ claimCookie(teamId, CLAIM_TOKEN),+ );++ const res = await caller.slack.getPendingInstallation({ teamId });+ expect(res.isPending).toBe(false);+ expect(res.teamName).toBeNull();+ });++ it("returns the pending workspace when the claim cookie matches", async () => {+ const { project, org } = await createOrgProjectAndApiKey();+ const teamId = uniqueTeamId("exists");+ await createPendingRow(teamId, "Acme Inc");+ const caller = callerFor(+ buildSession(org, [+ { id: project.id, name: project.name, role: "ADMIN" },+ ]),+ claimCookie(teamId, CLAIM_TOKEN),+ );++ const res = await caller.slack.getPendingInstallation({ teamId });+ expect(res).toEqual({ isPending: true, teamId, teamName: "Acme Inc" });+ });++ it("does not expose the pending workspace when the claim cookie does not match", async () => {+ const { project, org } = await createOrgProjectAndApiKey();+ const teamId = uniqueTeamId("wrong-claim");+ await createPendingRow(teamId, "Acme Inc");+ const caller = callerFor(+ buildSession(org, [+ { id: project.id, name: project.name, role: "ADMIN" },+ ]),+ claimCookie(teamId, "wrong-claim"),+ );++ const res = await caller.slack.getPendingInstallation({ teamId });+ expect(res).toEqual({ isPending: false, teamId: null, teamName: null });+ });++ it("does not expose the pending workspace without a claim cookie", async () => {+ const { project, org } = await createOrgProjectAndApiKey();+ const teamId = uniqueTeamId("no-cookie");+ await createPendingRow(teamId, "Acme Inc");+ const caller = callerFor(+ buildSession(org, [+ { id: project.id, name: project.name, role: "ADMIN" },+ ]),+ );++ const res = await caller.slack.getPendingInstallation({ teamId });+ expect(res).toEqual({ isPending: false, teamId: null, teamName: null });+ });+ });++ describe("getConnectableProjects", () => {+ it("returns CUD projects with connection status and excludes non-CUD projects", async () => {+ const { project: connectedProject, org } =+ await createOrgProjectAndApiKey();+ // second project in the same org, no Slack integration+ const unconnectedProject = await prisma.project.create({+ data: { name: `proj-${Date.now()}`, orgId: org.id },+ });+ // already-connected integration for the first project+ await prisma.slackIntegration.create({+ data: {+ projectId: connectedProject.id,+ teamId: uniqueTeamId("connected"),+ teamName: "Connected WS",+ botToken: encrypt("xoxb"),+ botUserId: "U1",+ },+ });++ const caller = callerFor(+ buildSession(org, [+ {+ id: connectedProject.id,+ name: connectedProject.name,+ role: "ADMIN",+ },+ {+ id: unconnectedProject.id,+ name: unconnectedProject.name,+ role: "ADMIN",+ },+ // VIEWER lacks automations:CUD -> must be excluded+ { id: "viewer-project-id", name: "viewer", role: "VIEWER" },+ ]),+ );++ const res = await caller.slack.getConnectableProjects();+ const orgEntry = res.find((o) => o.orgId === org.id);+ expect(orgEntry).toBeDefined();++ const byId = new Map(orgEntry!.projects.map((p) => [p.projectId, p]));+ expect(byId.get(connectedProject.id)?.isConnected).toBe(true);+ expect(byId.get(unconnectedProject.id)?.isConnected).toBe(false);+ expect(byId.has("viewer-project-id")).toBe(false);+ });+ });++ describe("linkPendingInstallation", () => {+ it("links a pending install to the project", async () => {+ const { project, org } = await createOrgProjectAndApiKey();+ const teamId = uniqueTeamId("link");+ await createPendingRow(teamId, "Linked WS");+ const caller = callerFor(+ buildSession(org, [+ { id: project.id, name: project.name, role: "ADMIN" },+ ]),+ claimCookie(teamId, CLAIM_TOKEN),+ );++ const res = await caller.slack.linkPendingInstallation({+ projectId: project.id,+ teamId,+ });+ expect(res).toEqual({ success: true, teamId, teamName: "Linked WS" });++ const row = await prisma.slackIntegration.findUnique({+ where: { projectId: project.id },+ });+ expect(row?.teamId).toBe(teamId);+ expect(row?.expiresAt).toBeNull();+ });++ it("throws NOT_FOUND when there is no pending install", async () => {+ const { project, org } = await createOrgProjectAndApiKey();+ const teamId = uniqueTeamId("missing");+ const caller = callerFor(+ buildSession(org, [+ { id: project.id, name: project.name, role: "ADMIN" },+ ]),+ claimCookie(teamId, CLAIM_TOKEN),+ );++ await expect(+ caller.slack.linkPendingInstallation({+ projectId: project.id,+ teamId,+ }),+ ).rejects.toMatchObject({ code: "NOT_FOUND" });+ });++ it("throws NOT_FOUND when the claim cookie does not match", async () => {+ const { project, org } = await createOrgProjectAndApiKey();+ const teamId = uniqueTeamId("wrong-link-claim");+ await createPendingRow(teamId);+ const caller = callerFor(+ buildSession(org, [+ { id: project.id, name: project.name, role: "ADMIN" },+ ]),+ claimCookie(teamId, "wrong-claim"),+ );++ await expect(+ caller.slack.linkPendingInstallation({+ projectId: project.id,+ teamId,+ }),+ ).rejects.toMatchObject({ code: "NOT_FOUND" });++ const row = await prisma.slackIntegration.findUnique({+ where: { projectId: project.id },+ });+ expect(row).toBeNull();+ });++ it("throws NOT_FOUND without a claim cookie", async () => {+ const { project, org } = await createOrgProjectAndApiKey();+ const teamId = uniqueTeamId("no-cookie-link");+ await createPendingRow(teamId);+ const caller = callerFor(+ buildSession(org, [+ { id: project.id, name: project.name, role: "ADMIN" },+ ]),+ );++ await expect(+ caller.slack.linkPendingInstallation({+ projectId: project.id,+ teamId,+ }),+ ).rejects.toMatchObject({ code: "NOT_FOUND" });++ const row = await prisma.slackIntegration.findUnique({+ where: { projectId: project.id },+ });+ expect(row).toBeNull();+ });++ it("denies users without automations:CUD on the project", async () => {+ const { project, org } = await createOrgProjectAndApiKey();+ const teamId = uniqueTeamId("denied");+ await createPendingRow(teamId);+ // VIEWER role -> automations:read only, no CUD. A valid claim cookie is+ // present, so this proves RBAC gates the link before the claim is read.+ const caller = callerFor(+ buildSession(org, [+ { id: project.id, name: project.name, role: "VIEWER" },+ ]),+ claimCookie(teamId, CLAIM_TOKEN),+ );++ await expect(+ caller.slack.linkPendingInstallation({+ projectId: project.id,+ teamId,+ }),+ ).rejects.toBeInstanceOf(TRPCError);++ // nothing was linked+ const row = await prisma.slackIntegration.findUnique({+ where: { projectId: project.id },+ });+ expect(row).toBeNull();+ });+ });+});diff --git a/web/src/__tests__/server/slack-pending-installation.servertest.ts b/web/src/__tests__/server/slack-pending-installation.servertest.tsnew file mode 100644index 0000000000..6ed135d0a6--- /dev/null+++ b/web/src/__tests__/server/slack-pending-installation.servertest.ts@@ -0,0 +1,183 @@+import { prisma } from "@langfuse/shared/src/db";+import { encrypt } from "@langfuse/shared/encryption";+import {+ SlackService,+ createOrgProjectAndApiKey,+ hashSlackPendingInstallClaimToken,+} from "@langfuse/shared/src/server";++const CLAIM_TOKEN = "test-claim-token";+const futureExpiry = () => new Date(Date.now() + 60 * 60 * 1000);+const pastExpiry = () => new Date(Date.now() - 60 * 1000);++/** Unique team id per call so parallel/repeat runs don't collide. */+let teamCounter = 0;+const uniqueTeamId = (label: string) =>+ `T-${Date.now()}-${teamCounter++}-${label}`;++async function createPendingRow(+ teamId: string,+ opts?: { expiresAt?: Date; teamName?: string; claimToken?: string },+) {+ return prisma.slackIntegration.create({+ data: {+ projectId: null,+ teamId,+ teamName: opts?.teamName ?? "Test Workspace",+ botToken: encrypt("xoxb-test-token"),+ botUserId: "U-test",+ expiresAt: opts?.expiresAt ?? futureExpiry(),+ claimTokenHash: hashSlackPendingInstallClaimToken(+ opts?.claimToken ?? CLAIM_TOKEN,+ ),+ },+ });+}++describe("SlackService pending installations", () => {+ let svc: SlackService;++ beforeAll(() => {+ svc = SlackService.getInstance();+ });++ it("getPendingInstallation returns active pending, null when expired or absent", async () => {+ const teamId = uniqueTeamId("get");+ expect(await svc.getPendingInstallation(teamId)).toBeNull();++ await createPendingRow(teamId, { teamName: "Acme" });+ expect((await svc.getPendingInstallation(teamId))?.teamName).toBe("Acme");++ const expiredTeam = uniqueTeamId("get-expired");+ await createPendingRow(expiredTeam, { expiresAt: pastExpiry() });+ expect(await svc.getPendingInstallation(expiredTeam)).toBeNull();+ });++ it("getClaimedPendingInstallation returns active pending only for the matching claim", async () => {+ const teamId = uniqueTeamId("get-claimed");+ await createPendingRow(teamId, { teamName: "Claimed" });++ expect(+ (await svc.getClaimedPendingInstallation(teamId, CLAIM_TOKEN))?.teamName,+ ).toBe("Claimed");+ expect(+ await svc.getClaimedPendingInstallation(teamId, "wrong-claim"),+ ).toBeNull();+ });++ it("issuePendingInstallationClaim stores a hash and returns the raw token", async () => {+ const teamId = uniqueTeamId("issue-claim");+ await createPendingRow(teamId);++ const claim = await svc.issuePendingInstallationClaim(teamId);+ expect(claim).toEqual(expect.any(String));+ expect(+ await svc.getClaimedPendingInstallation(teamId, claim!),+ ).not.toBeNull();+ });++ it("linkPendingInstallation links the pending install to the project", async () => {+ const { project } = await createOrgProjectAndApiKey();+ const teamId = uniqueTeamId("link");+ await createPendingRow(teamId);++ const linked = await svc.linkPendingInstallation(+ teamId,+ project.id,+ CLAIM_TOKEN,+ );+ expect(linked?.teamId).toBe(teamId);++ const row = await prisma.slackIntegration.findUnique({+ where: { projectId: project.id },+ });+ expect(row?.teamId).toBe(teamId);+ expect(row?.expiresAt).toBeNull();+ expect(row?.claimTokenHash).toBeNull();+ // pending rows for the workspace are consumed+ expect(+ await prisma.slackIntegration.count({+ where: { teamId, projectId: null },+ }),+ ).toBe(0);+ });++ it("linkPendingInstallation replaces an existing integration for the project", async () => {+ const { project } = await createOrgProjectAndApiKey();+ await prisma.slackIntegration.create({+ data: {+ projectId: project.id,+ teamId: uniqueTeamId("old"),+ teamName: "Old",+ botToken: encrypt("x"),+ botUserId: "U1",+ },+ });++ const teamId = uniqueTeamId("link-replace");+ await createPendingRow(teamId, { teamName: "New" });++ const linked = await svc.linkPendingInstallation(+ teamId,+ project.id,+ CLAIM_TOKEN,+ );+ expect(linked?.teamName).toBe("New");++ const rows = await prisma.slackIntegration.findMany({+ where: { projectId: project.id },+ });+ expect(rows).toHaveLength(1);+ expect(rows[0].teamId).toBe(teamId);+ });++ it("linkPendingInstallation returns null when there is no valid pending install", async () => {+ const { project } = await createOrgProjectAndApiKey();+ expect(+ await svc.linkPendingInstallation(+ uniqueTeamId("none"),+ project.id,+ CLAIM_TOKEN,+ ),+ ).toBeNull();+ });++ it("linkPendingInstallation returns null when the claim token is invalid", async () => {+ const { project } = await createOrgProjectAndApiKey();+ const teamId = uniqueTeamId("wrong-claim");+ await createPendingRow(teamId);++ expect(+ await svc.linkPendingInstallation(teamId, project.id, "wrong-claim"),+ ).toBeNull();+ });++ it("deleteExpiredPendingInstallations purges only expired pending rows", async () => {+ const { project } = await createOrgProjectAndApiKey();+ const freshTeam = uniqueTeamId("fresh");+ const expiredTeam = uniqueTeamId("expired");++ await createPendingRow(freshTeam);+ await createPendingRow(expiredTeam, { expiresAt: pastExpiry() });+ await prisma.slackIntegration.create({+ data: {+ projectId: project.id,+ teamId: uniqueTeamId("linked"),+ teamName: "Linked",+ botToken: encrypt("x"),+ botUserId: "U1",+ },+ });++ await svc.deleteExpiredPendingInstallations();++ expect(await svc.getPendingInstallation(freshTeam)).not.toBeNull();+ expect(+ await prisma.slackIntegration.count({ where: { teamId: expiredTeam } }),+ ).toBe(0);+ // Linked integration is never touched by the purge.+ expect(+ await prisma.slackIntegration.count({ where: { projectId: project.id } }),+ ).toBe(1);+ });+});diff --git a/web/src/__tests__/server/unit/slack-marketplace-install-rate-limit.servertest.ts b/web/src/__tests__/server/unit/slack-marketplace-install-rate-limit.servertest.tsnew file mode 100644index 0000000000..4a22174b11--- /dev/null+++ b/web/src/__tests__/server/unit/slack-marketplace-install-rate-limit.servertest.ts@@ -0,0 +1,126 @@+import type { NextApiRequest } from "next";+import { RateLimiterRes } from "rate-limiter-flexible";++import { env } from "@/src/env.mjs";++// Mock the Redis-backed limiter so the test is deterministic and does not depend+// on a live Redis (mirrors web-callout-rate-limit.servertest.ts). We assert how+// the limiter is wired and how allow() maps consume() outcomes to allow/deny,+// not the behavior of rate-limiter-flexible or Redis itself.+const mocks = vi.hoisted(() => ({+ consume: vi.fn(),+ options: [] as Array<Record<string, unknown>>,+}));++vi.mock("rate-limiter-flexible", () => {+ class MockRateLimiterRes {+ constructor(public msBeforeNext = 1000) {}+ }+ class MockRateLimiterRedis {+ consume = mocks.consume;+ constructor(options: Record<string, unknown>) {+ mocks.options.push(options);+ }+ }+ return {+ RateLimiterRedis: MockRateLimiterRedis,+ RateLimiterRes: MockRateLimiterRes,+ };+});++vi.mock("@langfuse/shared/src/server", () => ({+ createNewRedisInstance: vi.fn(),+ logger: { warn: vi.fn(), error: vi.fn(), debug: vi.fn() },+ redisQueueRetryOptions: {},+ // Provided so the shared global teardown (which imports these from the same+ // module) keeps working under this mock.+ redis: null,+ ClickHouseClientManager: {+ getInstance: () => ({ closeAllConnections: vi.fn() }),+ },+}));++import {+ allowSlackMarketplaceInstall,+ SlackMarketplaceInstallRateLimiter,+} from "@/src/features/slack/server/marketplaceInstallRateLimit";++const KEY_PREFIX = "rate-limit:slack-marketplace-install";+const POINTS = 30;+const DURATION_SECONDS = 5 * 60;++function reqWithXff(xff: string): NextApiRequest {+ return {+ headers: { "x-forwarded-for": xff },+ socket: { remoteAddress: "10.0.0.1" },+ } as unknown as NextApiRequest;+}++/** A fake ioredis client that is already "ready" so ensureReady() is a no-op. */+const readyRedis = () =>+ ({ status: "ready", disconnect: vi.fn(), connect: vi.fn() }) as any;++describe("SlackMarketplaceInstallRateLimiter", () => {+ const originalRateLimitsEnabled = env.LANGFUSE_RATE_LIMITS_ENABLED;++ beforeEach(() => {+ (env as any).LANGFUSE_RATE_LIMITS_ENABLED = "true";+ SlackMarketplaceInstallRateLimiter.shutdown();+ mocks.consume.mockReset();+ mocks.consume.mockResolvedValue({});+ mocks.options.length = 0;+ });++ afterEach(() => {+ (env as any).LANGFUSE_RATE_LIMITS_ENABLED = originalRateLimitsEnabled;+ SlackMarketplaceInstallRateLimiter.shutdown();+ });++ it("fails open without ever consuming when Redis is not configured", async () => {+ const limiter = SlackMarketplaceInstallRateLimiter.getInstance(null);+ for (let i = 0; i < POINTS + 5; i++) {+ expect(await limiter.allow(reqWithXff("1.2.3.4"))).toBe(true);+ }+ expect(mocks.consume).not.toHaveBeenCalled();+ expect(mocks.options).toHaveLength(0);+ });++ it("fails open without consuming when rate limiting is disabled", async () => {+ (env as any).LANGFUSE_RATE_LIMITS_ENABLED = "false";+ const limiter =+ SlackMarketplaceInstallRateLimiter.getInstance(readyRedis());+ expect(await limiter.allow(reqWithXff("1.2.3.4"))).toBe(true);+ expect(mocks.consume).not.toHaveBeenCalled();+ });++ it("configures the limiter with the expected window and key prefix", async () => {+ const limiter =+ SlackMarketplaceInstallRateLimiter.getInstance(readyRedis());+ await limiter.allow(reqWithXff("1.2.3.4"));+ expect(mocks.options).toMatchObject([+ { keyPrefix: KEY_PREFIX, points: POINTS, duration: DURATION_SECONDS },+ ]);+ });++ it("allows while consume succeeds and denies when the limiter rejects", async () => {+ const limiter =+ SlackMarketplaceInstallRateLimiter.getInstance(readyRedis());+ expect(await limiter.allow(reqWithXff("1.2.3.4"))).toBe(true);++ mocks.consume.mockRejectedValueOnce(new RateLimiterRes(1000));+ expect(await limiter.allow(reqWithXff("1.2.3.4"))).toBe(false);+ });++ it("fails open when Redis errors (non-RateLimiterRes)", async () => {+ const limiter =+ SlackMarketplaceInstallRateLimiter.getInstance(readyRedis());+ mocks.consume.mockRejectedValueOnce(new Error("redis down"));+ expect(await limiter.allow(reqWithXff("1.2.3.4"))).toBe(true);+ });++ it("keys on the rightmost X-Forwarded-For entry (last trusted proxy hop)", async () => {+ SlackMarketplaceInstallRateLimiter.getInstance(readyRedis());+ await allowSlackMarketplaceInstall(reqWithXff("1.1.1.1, 2.2.2.2, 3.3.3.3"));+ expect(mocks.consume).toHaveBeenCalledWith("3.3.3.3");+ });+});diff --git a/web/src/features/slack/README.md b/web/src/features/slack/README.mdindex a3d45c971c..41a407e914 100644--- a/web/src/features/slack/README.md+++ b/web/src/features/slack/README.md@@ -6,7 +6,7 @@ This guide walks you through setting up and testing the Langfuse Slack integrati- Node.js and pnpm installed- Access to a Slack workspace where you can create apps-- macOS (for mkcert installation)+- A tunneling tool for a public HTTPS URL (ngrok, or VS Code port forwarding)## Setup Steps@@ -36,33 +36,45 @@ This guide walks you through setting up and testing the Langfuse Slack integratiSLACK_STATE_SECRET=your_state_secret_here```-### 4. Set Up HTTPS for Local Development+### 4. Expose your local server over a public HTTPS URL-The Slack OAuth flow requires HTTPS. Set up local certificates:+Slack's OAuth flow (and the Marketplace "Direct Install" flow) only redirects+back to a **publicly reachable HTTPS URL** — `http://localhost:3000` is rejected+with `bad_redirect_uri`. The simplest way to get one in dev is a tunnel:-```bash-# Install mkcert-brew install mkcert+- **ngrok** (`brew install ngrok`):+ ```bash+ ngrok http 3000+ ```+ Use the printed `https://<subdomain>.ngrok-free.app` URL.+- **VS Code port forwarding**: open the **Ports** panel, forward port `3000`,+ and set its visibility to **Public**. Use the printed+ `https://<id>-3000.<region>.devtunnels.ms` URL.-# Install the local CA-mkcert -install+Then point Langfuse and Slack at that URL:-# Generate certificates for localhost-mkcert localhost 127.0.0.1+1. Set `NEXTAUTH_URL` in your `.env` to the tunnel URL (it is used to build the+ OAuth `redirect_uri`):+ ```bash+ NEXTAUTH_URL="https://<your-tunnel-host>"+ ```+2. In your Slack app's **OAuth & Permissions** settings, register the redirect+ URL `https://<your-tunnel-host>/api/public/slack/oauth` (the `app_manifest.json`+ ships the `localhost` URL; replace/add your tunnel host).-# Move certificates to web directory-mv localhost+1*.pem web/-```+> Tunnel hosts usually change each run (unless you have a reserved domain), so+> update both `NEXTAUTH_URL` and the Slack redirect URL whenever it changes.### 5. Start Development ServerFrom the repository root, run:```bash-pnpm run dev:https+pnpm run dev```-This starts the Next.js development server with HTTPS enabled on `https://localhost:3000`.+The tunnel from step 4 terminates TLS and forwards to your local server, so plain+HTTP dev is fine — no local certificates needed.### 6. Test the Integration@@ -76,18 +88,12 @@ This starts the Next.js development server with HTTPS enabled on `https://localh### Common Issues-- **"Invalid redirect URI"**: Ensure your Slack app's OAuth redirect URLs include `https://localhost:3000/api/public/slack/oauth`-- **Certificate errors**: Make sure you've installed the mkcert CA and moved the certificates to the `web/` directory+- **`bad_redirect_uri` / "Invalid redirect URI"**: `NEXTAUTH_URL` and the redirect+ URL registered in your Slack app must both be the exact public HTTPS tunnel+ host (`https://<your-tunnel-host>/api/public/slack/oauth`). A `localhost` or+ `http://` value will be rejected. If your tunnel host changed, update both.- **Environment variables not found**: Verify your `.env` file is in the correct location and contains the Slack credentials-### SSL Certificate Issues--If you encounter SSL certificate warnings in your browser:--1. Make sure you ran `mkcert -install` to install the local CA-2. Try accessing `https://localhost:3000` directly and accept the certificate-3. Restart your development server after certificate changes-## FeaturesThe Slack integration provides:diff --git a/web/src/features/slack/app_manifest.json b/web/src/features/slack/app_manifest.jsonindex 7dec817136..d29191bda0 100644--- a/web/src/features/slack/app_manifest.json+++ b/web/src/features/slack/app_manifest.json@@ -6,6 +6,11 @@"long_description": "The Langfuse Slack App keeps your team in sync by delivering real-time observability and alerts directly to your Slack channels. Whether you’re monitoring AI traces, catching runtime errors, or tracking latency and performance metrics, Langfuse ensures that you’re always in the loop.\r\n\r\nWith flexible configuration per project, you can:\r\n\t•\tGet notified about critical errors and anomalies\r\n\t•\tReceive alerts on trace completions, slow response times, or quality degradations\r\n\t•\tQuickly jump from a Slack message to the exact trace in Langfuse\r\n\t•\tKeep dev, ops, and ML teams aligned without context switching\r\n\r\nStay on top of your LLM applications — without leaving Slack."},"features": {+ "app_home": {+ "home_tab_enabled": false,+ "messages_tab_enabled": false,+ "messages_tab_read_only_enabled": false+ },"bot_user": {"display_name": "Langfuse","always_online": falsediff --git a/web/src/features/slack/server/marketplaceInstallRateLimit.ts b/web/src/features/slack/server/marketplaceInstallRateLimit.tsnew file mode 100644index 0000000000..877dde65d7--- /dev/null+++ b/web/src/features/slack/server/marketplaceInstallRateLimit.ts@@ -0,0 +1,124 @@+import { RateLimiterRedis, RateLimiterRes } from "rate-limiter-flexible";+import { type Cluster, type Redis } from "ioredis";+import { type NextApiRequest } from "next";++import { env } from "@/src/env.mjs";+import { env as sharedEnv } from "@langfuse/shared/src/env";+import {+ createNewRedisInstance,+ logger,+ redisQueueRetryOptions,+} from "@langfuse/shared/src/server";++const KEY_PREFIX = "rate-limit:slack-marketplace-install";+const POINTS = 30; // requests per window, per client IP+const DURATION_SECONDS = 5 * 60;++function getClientIp(req: NextApiRequest): string {+ const forwarded = req.headers["x-forwarded-for"];+ // Use the rightmost X-Forwarded-For entry: it is appended by the last trusted+ // proxy hop and cannot be forged by the client. The leftmost entry is+ // client-supplied and trivially spoofable to rotate IPs and dodge the limit.+ const last =+ typeof forwarded === "string"+ ? forwarded.split(",").at(-1)+ : Array.isArray(forwarded)+ ? forwarded.at(-1)+ : undefined;+ return last?.trim() || req.socket.remoteAddress || "unknown";+}++/**+ * Per-IP rate limit for the public Slack marketplace install endpoint.+ *+ * Fails open: when rate limiting is disabled, Redis isn't configured, or Redis+ * is unavailable, requests are allowed. The endpoint is a DB-free redirect, so+ * this is defense-in-depth against floods rather than protection of an expensive+ * resource — better to let installs through than to block them on an infra blip.+ *+ * Redis is injectable via getInstance(redis) (pass null to disable), which makes+ * the limiter unit-testable without reaching into module internals.+ */+export class SlackMarketplaceInstallRateLimiter {+ private static instance: SlackMarketplaceInstallRateLimiter | null = null;++ private readonly redis: Redis | Cluster | null;+ private readonly limiter: RateLimiterRedis | null;+ private connectPromise: Promise<void> | null = null;++ private constructor(redis: Redis | Cluster | null) {+ this.redis = redis;+ this.limiter = redis+ ? new RateLimiterRedis({+ storeClient: redis,+ keyPrefix: KEY_PREFIX,+ points: POINTS,+ duration: DURATION_SECONDS,+ rejectIfRedisNotReady: true,+ })+ : null;+ }++ static getInstance(+ redis?: Redis | Cluster | null,+ ): SlackMarketplaceInstallRateLimiter {+ if (+ SlackMarketplaceInstallRateLimiter.instance === null ||+ redis !== undefined+ ) {+ const client =+ redis !== undefined+ ? redis+ : createNewRedisInstance({+ keyPrefix: sharedEnv.REDIS_KEY_PREFIX ?? undefined,+ enableAutoPipelining: false,+ enableOfflineQueue: false,+ lazyConnect: true,+ ...redisQueueRetryOptions,+ });+ SlackMarketplaceInstallRateLimiter.instance =+ new SlackMarketplaceInstallRateLimiter(client);+ }+ return SlackMarketplaceInstallRateLimiter.instance;+ }++ /** Disconnect Redis and drop the cached instance (graceful shutdown / tests). */+ static shutdown(): void {+ const instance = SlackMarketplaceInstallRateLimiter.instance;+ if (instance?.redis && instance.redis.status !== "end") {+ instance.redis.disconnect();+ }+ SlackMarketplaceInstallRateLimiter.instance = null;+ }++ /** True if the request may proceed, false if it should be rejected with 429. */+ async allow(req: NextApiRequest): Promise<boolean> {+ if (env.LANGFUSE_RATE_LIMITS_ENABLED === "false") return true;+ if (!this.limiter || !this.redis) return true;++ try {+ await this.ensureReady(this.redis);+ await this.limiter.consume(getClientIp(req));+ return true;+ } catch (error) {+ if (error instanceof RateLimiterRes) return false;+ // Redis unavailable / unexpected -> fail open.+ logger.warn("Slack marketplace install rate limiter unavailable", {+ error: error instanceof Error ? error.message : "Unknown error",+ });+ return true;+ }+ }++ private async ensureReady(client: Redis | Cluster): Promise<void> {+ if (client.status === "ready") return;+ this.connectPromise ??= client.connect().finally(() => {+ this.connectPromise = null;+ });+ await this.connectPromise;+ }+}++/** Convenience wrapper used by the route handler. */+export const allowSlackMarketplaceInstall = (req: NextApiRequest) =>+ SlackMarketplaceInstallRateLimiter.getInstance().allow(req);diff --git a/web/src/features/slack/server/oauth-handlers.ts b/web/src/features/slack/server/oauth-handlers.tsindex bbe51b87ae..e965361691 100644--- a/web/src/features/slack/server/oauth-handlers.ts+++ b/web/src/features/slack/server/oauth-handlers.ts@@ -2,13 +2,14 @@ import { type NextApiRequest, type NextApiResponse } from "next";import {SlackService,SLACK_BOT_SCOPES,- parseSlackInstallationMetadata,+ tryGetProjectIdFromMetadata,} from "@langfuse/shared/src/server";import { logger } from "@langfuse/shared/src/server";import { env } from "@/src/env.mjs";import { getServerAuthSession } from "@/src/server/auth";import { auditLog } from "@/src/features/audit-logs/auditLog";import { prisma } from "@langfuse/shared/src/db";+import { setPendingInstallClaimCookie } from "@/src/features/slack/server/pendingInstallClaimCookie";/*** SlackOAuthHandlers@@ -25,24 +26,15 @@ export async function handleInstallPath(projectId: string,) {try {- // Use InstallProvider's handleInstallPath method to render the installation page- // This method will:- // 1. Generate the OAuth URL with proper state parameter- // 2. Set session cookies for state validation- // 3. Render the installation page with "Add to Slack" button+ // handleInstallPath generates the OAuth URL with a signed state parameter,+ // sets the state cookie, and (directInstall) 302-redirects straight to+ // Slack's authorize URL.const installOptions = {scopes: [...SLACK_BOT_SCOPES],metadata: JSON.stringify({ projectId: projectId }),redirectUri: `${env.NEXTAUTH_URL}/api/public/slack/oauth`,};- // hack because nextjs dev server support for https is experimental- if (env.NODE_ENV === "development") {- installOptions.redirectUri = installOptions.redirectUri?.replace(- "http://",- "https://",- );- }return await SlackService.getInstance().getInstaller().handleInstallPath(req, res, undefined, installOptions);@@ -64,23 +56,62 @@ export async function handleCallback(.getInstaller().handleCallback(req, res, {success: async (installation) => {- const metadata = parseSlackInstallationMetadata(- installation?.metadata,- );- const projectId = metadata.projectId;+ const projectId = tryGetProjectIdFromMetadata(installation?.metadata);+ const teamId = installation.team?.id;+ const teamName = installation.team?.name;logger.info("OAuth callback successful", {projectId,- teamId: installation.team?.id,- teamName: installation.team?.name,+ teamId,+ teamName,});- // Create audit log for the Slack integration- // The session should still be valid from when the user initiated the install+ if (!teamId || !teamName) {+ // storeInstallation already rejects installs missing team/bot+ // details, so this is defensive; treat it as a failed install.+ // Guarding both here also narrows teamName to a string below.+ logger.error(+ "Slack OAuth callback completed without a team id or name",+ { projectId, teamId },+ );+ res.redirect("/slack/direct-setup");+ return;+ }++ // Marketplace flow: no project chosen yet (the Direct Install URL+ // redirects straight to OAuth). storeInstallation already saved a+ // pending row; send the user to onboarding to link it to a project.+ if (!projectId) {+ const claimToken =+ await SlackService.getInstance().issuePendingInstallationClaim(+ teamId,+ );+ if (!claimToken) {+ logger.error("Slack OAuth callback could not issue claim token", {+ teamId,+ });+ res.redirect("/slack/direct-setup");+ return;+ }+ // Deliver the claim as an httpOnly cookie bound to this browser+ // rather than a URL parameter — it is a bearer credential for a+ // live bot token and must not land in history/Referer. The link+ // procedures read it server-side. team_id/team_name stay in the URL+ // (not secret) for display.+ setPendingInstallClaimCookie(res, teamId, claimToken);+ const onboardingUrl = `/slack/direct-setup?team_id=${encodeURIComponent(+ teamId,+ )}&team_name=${encodeURIComponent(teamName)}`;+ res.redirect(onboardingUrl);+ return;+ }++ // In-app "Connect" flow: the install is already linked to the project.+ // Create an audit log; the session is still valid from when the user+ // initiated the install.try {const session = await getServerAuthSession({ req, res });if (session?.user?.id) {- // Find the integration that was just createdconst integration = await prisma.slackIntegration.findUnique({where: { projectId },select: {@@ -90,7 +121,9 @@ export async function handleCallback(},});- if (integration) {+ // project is non-null here (the row was just linked by projectId),+ // but the relation is optional in the schema, so guard it.+ if (integration?.project) {await auditLog({userId: session.user.id,orgId: integration.project.orgId,@@ -98,10 +131,7 @@ export async function handleCallback(resourceType: "slackIntegration",resourceId: integration.id,action: "create",- after: {- teamId: installation.team?.id,- teamName: installation.team?.name,- },+ after: { teamId, teamName },});}}@@ -114,7 +144,7 @@ export async function handleCallback(}// Redirect to project-specific Slack settings page- const redirectUrl = `/project/${projectId}/settings/integrations/slack?success=true&team_name=${encodeURIComponent(installation.team?.name || "")}`;+ const redirectUrl = `/project/${projectId}/settings/integrations/slack?success=true&team_name=${encodeURIComponent(teamName)}`;res.redirect(redirectUrl);},diff --git a/web/src/features/slack/server/pendingInstallClaimCookie.ts b/web/src/features/slack/server/pendingInstallClaimCookie.tsnew file mode 100644index 0000000000..12c836706e--- /dev/null+++ b/web/src/features/slack/server/pendingInstallClaimCookie.ts@@ -0,0 +1,91 @@+import { type NextApiResponse } from "next";+import { SLACK_PENDING_INSTALL_TTL_MS } from "@langfuse/shared/src/server";+import { getCookieOptions } from "@/src/server/utils/cookies";++/**+ * httpOnly cookie carrying the one-time claim that authorizes linking a pending+ * Marketplace install to a project. Delivered as a cookie rather than a URL+ * parameter so that someone who intercepts the onboarding URL (browser history,+ * bookmarks, Referer) can't replay the claim to connect another person's Slack+ * workspace to their own Langfuse project. Set on the OAuth callback and read+ * server-side by the slack tRPC procedures.+ */+export const PENDING_INSTALL_CLAIM_COOKIE = "slack_pending_install_claim";++// Match the pending-install TTL so the cookie can't outlive the row it unlocks.+const MAX_AGE_SECONDS = Math.floor(SLACK_PENDING_INSTALL_TTL_MS / 1000);++// Bind the claim to its workspace so a stale cookie from a previous install+// can't be applied to a different team_id.+type ClaimCookiePayload = { teamId: string; claim: string };++export function setPendingInstallClaimCookie(+ res: NextApiResponse,+ teamId: string,+ claim: string,+): void {+ const value = encodeURIComponent(+ JSON.stringify({ teamId, claim } satisfies ClaimCookiePayload),+ );+ // Reuse the shared cookie defaults (same as the project cookie / next-auth)+ // so secure/domain/path behave consistently — notably `secure` is set on+ // Vercel deploys where NEXTAUTH_URL omits the protocol.+ const options = getCookieOptions();+ const parts = [+ `${PENDING_INSTALL_CLAIM_COOKIE}=${value}`,+ `Path=${options.path}`,+ "SameSite=Lax",+ `Max-Age=${MAX_AGE_SECONDS}`,+ ];+ if (options.domain) parts.push(`Domain=${options.domain}`);+ if (options.httpOnly) parts.push("HttpOnly");+ if (options.secure) parts.push("Secure");+ appendSetCookie(res, parts.join("; "));+}++/**+ * Read and validate the claim cookie for a given workspace. Returns the raw+ * claim only when the cookie is present and bound to the same team_id.+ */+export function readPendingInstallClaimCookie(+ cookieHeader: string | undefined,+ teamId: string,+): string | null {+ const raw = parseCookie(cookieHeader, PENDING_INSTALL_CLAIM_COOKIE);+ if (!raw) return null;+ try {+ const payload = JSON.parse(decodeURIComponent(raw)) as ClaimCookiePayload;+ if (payload.teamId !== teamId || !payload.claim) return null;+ return payload.claim;+ } catch {+ return null;+ }+}++// res.setHeader overwrites; @slack/oauth's handleCallback already sets a+// Set-Cookie (clearing the OAuth state cookie), so append rather than clobber.+function appendSetCookie(res: NextApiResponse, cookie: string): void {+ const existing = res.getHeader("Set-Cookie");+ const cookies = Array.isArray(existing)+ ? existing.map(String)+ : existing+ ? [String(existing)]+ : [];+ cookies.push(cookie);+ res.setHeader("Set-Cookie", cookies);+}++function parseCookie(+ cookieHeader: string | undefined,+ name: string,+): string | null {+ if (!cookieHeader) return null;+ for (const part of cookieHeader.split(";")) {+ const index = part.indexOf("=");+ if (index === -1) continue;+ if (part.slice(0, index).trim() === name) {+ return part.slice(index + 1).trim();+ }+ }+ return null;+}diff --git a/web/src/features/slack/server/router.ts b/web/src/features/slack/server/router.tsindex 83cd660156..2b98a4f229 100644--- a/web/src/features/slack/server/router.ts+++ b/web/src/features/slack/server/router.ts@@ -1,14 +1,21 @@import {createTRPCRouter,+ authenticatedProcedure,+ protectedProcedureWithoutTracing,protectedProjectProcedure,+ protectedProjectProcedureWithoutTracing,} from "@/src/server/api/trpc";import { z } from "zod";import { SlackService, SlackApiError } from "@langfuse/shared/src/server";-import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import {+ hasProjectAccess,+ throwIfNoProjectAccess,+} from "@/src/features/rbac/utils/checkProjectAccess";import { logger } from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";import { auditLog } from "@/src/features/audit-logs/auditLog";import { env } from "@/src/env.mjs";+import { readPendingInstallClaimCookie } from "@/src/features/slack/server/pendingInstallClaimCookie";export const slackRouter = createTRPCRouter({/**@@ -374,4 +381,159 @@ export const slackRouter = createTRPCRouter({});}}),++ /**+ * Get the pending (unlinked) Marketplace installation for a Slack workspace.+ * Used by the /slack/direct-setup onboarding page to show which workspace is being+ * linked. Authenticated but not project-scoped: the install isn't owned by a+ * project yet. Returns null if there is no pending install or it has expired.+ */+ // The claim is a bearer token for a live bot token: it is delivered as an+ // httpOnly cookie (never a URL param or tRPC input) and read server-side+ // here. Non-traced so the cookie-derived claim never reaches input telemetry.+ getPendingInstallation: protectedProcedureWithoutTracing+ .input(z.object({ teamId: z.string() }))+ .query(async ({ input, ctx }) => {+ const claim = readPendingInstallClaimCookie(+ ctx.headers.cookie,+ input.teamId,+ );+ const pending = claim+ ? await SlackService.getInstance().getClaimedPendingInstallation(+ input.teamId,+ claim,+ )+ : null;++ return {+ isPending: pending !== null,+ teamId: pending?.teamId ?? null,+ teamName: pending?.teamName ?? null,+ };+ }),++ /**+ * Drives the /slack/direct-setup onboarding page: the user's projects grouped by+ * organization, limited to those the user can configure automations on (the+ * same scope linkPendingInstallation enforces), each flagged with whether+ * Slack is already connected. Scoped to the user's own session, so it never+ * leaks other tenants' projects or connection status.+ */+ getConnectableProjects: authenticatedProcedure.query(async ({ ctx }) => {+ const orgs = (ctx.session.user?.organizations ?? [])+ .map((org) => ({+ orgId: org.id,+ orgName: org.name,+ projects: org.projects.filter(+ (project) =>+ !project.deletedAt &&+ hasProjectAccess({+ session: ctx.session,+ projectId: project.id,+ scope: "automations:CUD",+ }),+ ),+ }))+ .filter((org) => org.projects.length > 0);++ const projectIds = orgs.flatMap((org) =>+ org.projects.map((project) => project.id),+ );+ if (projectIds.length === 0) return [];++ const connectedRows = await ctx.prisma.slackIntegration.findMany({+ where: { projectId: { in: projectIds } },+ select: { projectId: true },+ });+ const connectedSet = new Set(connectedRows.map((row) => row.projectId));++ return orgs.map((org) => ({+ orgId: org.orgId,+ orgName: org.orgName,+ projects: org.projects.map((project) => ({+ projectId: project.id,+ projectName: project.name,+ isConnected: connectedSet.has(project.id),+ })),+ }));+ }),++ /**+ * Link a pending Marketplace installation to a project. Requires+ * automations:CUD on the chosen project. Moves the pending install in place;+ * replaces any existing integration for the project.+ */+ // The claim arrives as an httpOnly cookie (see getPendingInstallation), read+ // server-side — never a tRPC input. Non-traced for the same reason.+ linkPendingInstallation: protectedProjectProcedureWithoutTracing+ .input(+ z.object({+ projectId: z.string(),+ teamId: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "automations:CUD",+ });++ const claim = readPendingInstallClaimCookie(+ ctx.headers.cookie,+ input.teamId,+ );+ const linked = claim+ ? await SlackService.getInstance().linkPendingInstallation(+ input.teamId,+ input.projectId,+ claim,+ )+ : null;++ if (!linked) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message:+ "This Slack installation has expired or was not found. Please reinstall the app from Slack.",+ });+ }++ // The link already committed (the pending row is consumed). Don't let an+ // audit-log failure reject the mutation — a retry would then hit+ // NOT_FOUND and wrongly tell the user to reinstall. Mirrors the in-app+ // Connect flow in oauth-handlers.ts.+ try {+ await auditLog({+ session: ctx.session,+ resourceType: "slackIntegration",+ resourceId: linked.id,+ action: "create",+ after: {+ teamId: linked.teamId,+ teamName: linked.teamName,+ linkedFromMarketplace: true,+ },+ });+ } catch (auditError) {+ logger.warn(+ "Failed to create audit log for linked Slack installation",+ {+ error: auditError,+ projectId: input.projectId,+ },+ );+ }++ logger.info("Linked pending Slack installation to project", {+ projectId: input.projectId,+ teamId: linked.teamId,+ });++ return {+ success: true,+ teamId: linked.teamId,+ teamName: linked.teamName,+ };+ }),});diff --git a/web/src/pages/api/public/slack/marketplace-install/index.ts b/web/src/pages/api/public/slack/marketplace-install/index.tsnew file mode 100644index 0000000000..dd7a967fcb--- /dev/null+++ b/web/src/pages/api/public/slack/marketplace-install/index.ts@@ -0,0 +1,60 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import {+ SlackService,+ SLACK_BOT_SCOPES,+ logger,+} from "@langfuse/shared/src/server";+import { LangfuseNotFoundError } from "@langfuse/shared";+import { env } from "@/src/env.mjs";+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";+import { allowSlackMarketplaceInstall } from "@/src/features/slack/server/marketplaceInstallRateLimit";++/**+ * Slack Marketplace "Direct Install URL" entry point.+ *+ * Slack requires the Marketplace install link to HTTP 302 redirect straight to+ * the OAuth authorize URL, with no project context — the person installing may+ * not even have a Langfuse account yet. We generate a stateless install URL+ * (signed with the state secret, carrying no projectId metadata) and redirect.+ *+ * The shared OAuth callback then stores a pending installation and sends the+ * user to /slack/direct-setup to link it to a project. Unauthenticated by design:+ * anyone viewing the Marketplace listing can start an install. Method dispatch,+ * CORS, and error handling are handled by withMiddlewares.+ */+export default withMiddlewares({+ GET: async (req: NextApiRequest, res: NextApiResponse) => {+ // Guard all three vars the InstallProvider needs (buildInstaller+ // non-null-asserts each). A partial config would otherwise pass this check+ // and surface as a generic 500 from @slack/oauth instead of this 404.+ if (+ !env.SLACK_CLIENT_ID ||+ !env.SLACK_CLIENT_SECRET ||+ !env.SLACK_STATE_SECRET+ ) {+ throw new LangfuseNotFoundError("Slack integration is not configured");+ }++ // Per-IP rate limit (fails open if Redis is down / disabled).+ if (!(await allowSlackMarketplaceInstall(req))) {+ res+ .status(429)+ .json({ error: "Too many requests. Please try again later." });+ return;+ }++ const redirectUri = `${env.NEXTAUTH_URL}/api/public/slack/oauth`;++ logger.info("Slack marketplace install initiated");+ // handleInstallPath sets the OAuth state cookie that handleCallback+ // verifies, then (directInstall) 302s to Slack's authorize URL. Calling+ // generateInstallUrl directly would skip that cookie -> invalid_state.+ await SlackService.getInstance()+ .getInstaller()+ .handleInstallPath(req, res, undefined, {+ scopes: [...SLACK_BOT_SCOPES],+ redirectUri,+ // No metadata: the project is chosen after OAuth in /slack/direct-setup.+ });+ },+});diff --git a/web/src/pages/slack/direct-setup.tsx b/web/src/pages/slack/direct-setup.tsxnew file mode 100644index 0000000000..8e627deea3--- /dev/null+++ b/web/src/pages/slack/direct-setup.tsx@@ -0,0 +1,178 @@+import { useRouter } from "next/router";+import { useSession } from "next-auth/react";+import { api } from "@/src/utils/api";+import ContainerPage from "@/src/components/layouts/container-page";+import Header from "@/src/components/layouts/header";+import {+ Card,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+} from "@/src/components/ui/card";+import { Button } from "@/src/components/ui/button";+import { CheckCircle } from "lucide-react";++/**+ * Marketplace onboarding page.+ *+ * Landing point after a user installs the Langfuse app from the Slack+ * Marketplace (the OAuth callback redirects here when no project was chosen up+ * front). Lets the signed-in user link the pending Slack installation to one of+ * their projects. Mirrors the organizations overview page layout. Unauthenticated+ * users are redirected to sign in / sign up by the global AppLayout auth guard.+ */+export default function SlackDirectSetupPage() {+ const router = useRouter();+ const session = useSession();++ const teamId =+ typeof router.query.team_id === "string" ? router.query.team_id : "";+ const teamNameFromQuery =+ typeof router.query.team_name === "string" ? router.query.team_name : "";++ // The claim is delivered as an httpOnly cookie (set on the OAuth callback) and+ // read server-side by the procedures below — it is never in the URL or+ // readable here, so the page only needs team_id to drive the queries.+ const pending = api.slack.getPendingInstallation.useQuery(+ { teamId },+ { enabled: !!teamId && session.status === "authenticated" },+ );++ const connectableProjects = api.slack.getConnectableProjects.useQuery(+ undefined,+ { enabled: session.status === "authenticated" },+ );++ const linkMutation = api.slack.linkPendingInstallation.useMutation({+ onSuccess: (data, variables) => {+ router.push(+ `/project/${variables.projectId}/settings/integrations/slack?success=true&team_name=${encodeURIComponent(+ data.teamName ?? "",+ )}`,+ );+ },+ });++ // While the session resolves, show a loading state. Truly unauthenticated+ // users are redirected to sign in by the global AppLayout auth guard before+ // this page renders, so this branch only covers the brief loading window.+ if (session.status !== "authenticated") {+ return (+ <ContainerPage headerProps={{ title: "Connect Slack" }}>+ <p className="text-muted-foreground text-sm">Loading…</p>+ </ContainerPage>+ );+ }++ const workspaceName =+ pending.data?.teamName || teamNameFromQuery || "your Slack workspace";++ // No teamId, or the pending install was not found / has expired (which also+ // covers a missing/expired claim cookie, since the query then returns+ // isPending: false).+ const installInvalid =+ !teamId || (pending.isSuccess && !pending.data.isPending);++ const orgs = connectableProjects.data ?? [];++ return (+ <ContainerPage+ headerProps={{+ title: "Connect Slack",+ help: {+ description:+ "Choose which Langfuse project should receive alerts in this Slack workspace.",+ },+ }}+ >+ {installInvalid ? (+ <Card>+ <CardHeader>+ <CardTitle>Installation expired</CardTitle>+ <CardDescription>+ We could not find an active Slack installation to link. Please+ reinstall the Langfuse app from Slack and try again.+ </CardDescription>+ </CardHeader>+ </Card>+ ) : (+ <>+ <p className="text-muted-foreground mb-6 text-sm">+ Connect the Slack workspace <strong>{workspaceName}</strong> to a+ Langfuse project. Alerts and prompt notifications for that project+ will post to channels you choose.+ </p>++ {linkMutation.error ? (+ <p className="text-destructive mb-4 text-sm">+ {linkMutation.error.message}+ </p>+ ) : null}++ {connectableProjects.isLoading ? (+ <p className="text-muted-foreground text-sm">Loading projects…</p>+ ) : orgs.length === 0 ? (+ <Card>+ <CardHeader>+ <CardTitle>No eligible projects</CardTitle>+ <CardDescription>+ You need a project where you can configure automations to+ connect Slack. Ask an organization admin for access, or create+ a project first.+ </CardDescription>+ </CardHeader>+ </Card>+ ) : (+ orgs.map((org, index) => (+ <div key={org.orgId} className={index > 0 ? "mt-8" : ""}>+ <Header title={org.orgName} className="truncate" />+ <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">+ {org.projects.map((project) => {+ const isLinking =+ linkMutation.isPending &&+ linkMutation.variables?.projectId === project.projectId;++ return (+ <Card key={project.projectId}>+ <CardHeader>+ <CardTitle className="flex items-center gap-2 text-base">+ <span className="min-w-0 truncate">+ {project.projectName}+ </span>+ {project.isConnected ? (+ <CheckCircle+ className="h-4 w-4 shrink-0 text-green-600 dark:text-green-500"+ aria-label="Connected to Slack"+ />+ ) : null}+ </CardTitle>+ </CardHeader>+ <CardFooter>+ <Button+ className="w-full"+ variant="secondary"+ loading={isLinking}+ disabled={linkMutation.isPending}+ onClick={() =>+ linkMutation.mutate({+ projectId: project.projectId,+ teamId,+ })+ }+ >+ {project.isConnected ? "Reconnect" : "Connect"}+ </Button>+ </CardFooter>+ </Card>+ );+ })}+ </div>+ </div>+ ))+ )}+ </>+ )}+ </ContainerPage>+ );+}