Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. πŸ”₯

(feat/slack) Slack App (#3934)

Nicolas67462ee0f7d5
diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts
index 3daa1ce54..00eaec077 100644
--- a/apps/api/src/config.ts
+++ b/apps/api/src/config.ts
@@ -231,6 +231,26 @@ const configSchema = z.object({
SLACK_WEBHOOK_URL: z.string().optional(),
SLACK_ADMIN_WEBHOOK_URL: z.string().optional(),
DISABLE_WEBHOOK_DELIVERY: z.stringbool().optional(),
+
+ // Slack integration ("Add to Slack" for monitor notifications + /monitor
+ // slash command). Credentials come from the Firecrawl Slack app.
+ SLACK_CLIENT_ID: z.string().optional(),
+ SLACK_CLIENT_SECRET: z.string().optional(),
+ SLACK_SIGNING_SECRET: z.string().optional(),
+ // Bot scopes requested during install. Override only if the Slack app manifest
+ // changes; keep in sync with slack-app-manifest.json.
+ SLACK_OAUTH_SCOPES: z
+ .string()
+ .default(
+ "chat:write,chat:write.public,commands,channels:read,groups:read,team:read",
+ ),
+ // Absolute URL Slack redirects back to after authorize. Must exactly match a
+ // Redirect URL configured on the Slack app (e.g.
+ // https://api.firecrawl.dev/v2/slack/oauth/callback).
+ SLACK_OAUTH_REDIRECT_URL: z.string().optional(),
+ // 32-byte key (hex or base64) used to AES-256-GCM encrypt stored bot tokens.
+ // If unset, tokens are stored with a `plain:` prefix (self-hosted only).
+ SLACK_TOKEN_ENCRYPTION_KEY: z.string().optional(),
ALLOW_LOCAL_WEBHOOKS: z.stringbool().optional(),
WEBHOOK_USE_RABBITMQ: z.stringbool().optional(),
diff --git a/apps/api/src/controllers/v2/slack.ts b/apps/api/src/controllers/v2/slack.ts
new file mode 100644
index 000000000..49afd9d6b
--- /dev/null
+++ b/apps/api/src/controllers/v2/slack.ts
@@ -0,0 +1,296 @@
+import { Request, Response } from "express";
+import { z } from "zod";
+import { config } from "../../config";
+import { logger as _logger } from "../../lib/logger";
+import { RequestWithAuth } from "./types";
+import {
+ createAuthorizeUrl,
+ handleOAuthCallback,
+ isSlackConfigured,
+} from "../../services/integrations/slack/oauth";
+import {
+ deleteSlackInstallationByTeam,
+ deleteSlackInstallationsBySlackTeam,
+ getSlackInstallationByTeam,
+ getSlackInstallationBySlackTeam,
+} from "../../services/integrations/slack/store";
+import { decryptSlackToken } from "../../services/integrations/slack/crypto";
+import { listChannels } from "../../services/integrations/slack/client";
+import { verifySlackSignature } from "../../services/integrations/slack/signature";
+import { handleSlashCommand } from "../../services/integrations/slack/commands";
+import type { SlackConnectionStatus } from "../../services/integrations/slack/types";
+
+const logger = _logger.child({ module: "slack-controller" });
+
+const startBodySchema = z.object({
+ redirectPath: z.string().max(512).optional(),
+});
+
+// Builds an absolute dashboard URL for post-OAuth browser redirects.
+function dashboardRedirect(path: string, params: Record<string, string>): string {
+ const url = new URL(path, config.FIRECRAWL_DASHBOARD_URL);
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
+ return url.toString();
+}
+
+// POST /v2/slack/oauth/start (auth) β€” returns the Slack authorize URL for the
+// caller's team. The dashboard redirects the browser to it.
+export async function slackOAuthStartController(
+ req: RequestWithAuth<{}, any, unknown>,
+ res: Response,
+) {
+ if (!isSlackConfigured()) {
+ return res
+ .status(503)
+ .json({ success: false, error: "Slack integration is not configured" });
+ }
+
+ const body = startBodySchema.safeParse(req.body ?? {});
+ const redirectPath = body.success ? body.data.redirectPath : undefined;
+
+ try {
+ const { url } = await createAuthorizeUrl({
+ teamId: req.auth.team_id,
+ redirectPath,
+ });
+ return res.status(200).json({ success: true, url });
+ } catch (error) {
+ logger.error("Failed to build Slack authorize URL", { error });
+ return res
+ .status(500)
+ .json({ success: false, error: "Failed to start Slack connection" });
+ }
+}
+
+// GET /v2/slack/oauth/callback (public) β€” Slack redirects here after the user
+// approves. We exchange the code and bounce the browser back to the dashboard.
+export async function slackOAuthCallbackController(req: Request, res: Response) {
+ const code = typeof req.query.code === "string" ? req.query.code : undefined;
+ const state =
+ typeof req.query.state === "string" ? req.query.state : undefined;
+ const slackError =
+ typeof req.query.error === "string" ? req.query.error : undefined;
+
+ if (slackError) {
+ return res.redirect(
+ dashboardRedirect("/app/monitoring", { slack: "error", reason: slackError }),
+ );
+ }
+
+ if (!code || !state) {
+ return res.redirect(
+ dashboardRedirect("/app/monitoring", {
+ slack: "error",
+ reason: "missing_params",
+ }),
+ );
+ }
+
+ // This handler lands in the user's browser, so it must never surface a 500 via
+ // wrap() β€” any failure (Redis in consumeState, network in the token exchange,
+ // etc.) should bounce them back to the dashboard with an error.
+ try {
+ const result = await handleOAuthCallback({ code, state });
+ if (!result.ok) {
+ return res.redirect(
+ dashboardRedirect(result.redirectPath, {
+ slack: "error",
+ reason: result.error,
+ }),
+ );
+ }
+
+ return res.redirect(
+ dashboardRedirect(result.redirectPath, { slack: "connected" }),
+ );
+ } catch (error) {
+ // redirectPath from the OAuth state isn't recoverable here, so fall back to
+ // the monitoring root.
+ logger.error("Slack OAuth callback failed", { error });
+ return res.redirect(
+ dashboardRedirect("/app/monitoring", {
+ slack: "error",
+ reason: "callback_failed",
+ }),
+ );
+ }
+}
+
+// GET /v2/slack/status (auth) β€” connection status for the team.
+export async function slackStatusController(
+ req: RequestWithAuth<{}, any, unknown>,
+ res: Response,
+) {
+ const installation = await getSlackInstallationByTeam(req.auth.team_id);
+ const status: SlackConnectionStatus = installation
+ ? {
+ connected: true,
+ slackTeamId: installation.slack_team_id,
+ slackTeamName: installation.slack_team_name,
+ botUserId: installation.bot_user_id,
+ scope: installation.scope,
+ authedUserId: installation.authed_user_id,
+ installedAt: installation.created_at,
+ }
+ : { connected: false };
+
+ return res.status(200).json({
+ success: true,
+ configured: isSlackConfigured(),
+ data: status,
+ });
+}
+
+// GET /v2/slack/channels (auth) β€” channels the bot can post to.
+export async function slackChannelsController(
+ req: RequestWithAuth<{}, any, unknown>,
+ res: Response,
+) {
+ const installation = await getSlackInstallationByTeam(req.auth.team_id);
+ if (!installation) {
+ return res
+ .status(404)
+ .json({ success: false, error: "Slack is not connected" });
+ }
+
+ let token: string;
+ try {
+ token = decryptSlackToken(installation.bot_token);
+ } catch (error) {
+ logger.error("Failed to decrypt Slack token for channel list", { error });
+ return res
+ .status(500)
+ .json({ success: false, error: "Slack token unavailable" });
+ }
+
+ const result = await listChannels({ token });
+ if (!result.ok) {
+ return res.status(502).json({
+ success: false,
+ error: result.error ?? "Failed to list Slack channels",
+ });
+ }
+
+ return res.status(200).json({ success: true, data: result.channels });
+}
+
+// DELETE /v2/slack/installation (auth) β€” disconnect the workspace.
+export async function slackDisconnectController(
+ req: RequestWithAuth<{}, any, unknown>,
+ res: Response,
+) {
+ await deleteSlackInstallationByTeam(req.auth.team_id);
+ return res.status(200).json({ success: true });
+}
+
+// POST /v2/slack/commands (public, signature-verified) β€” the /monitor slash
+// command. Slack expects a 200 with a JSON message within 3 seconds.
+export async function slackCommandsController(req: Request, res: Response) {
+ const rawBody = (req as Request & { rawBody?: Buffer }).rawBody;
+ const valid = verifySlackSignature({
+ signature: req.headers["x-slack-signature"] as string | undefined,
+ timestamp: req.headers["x-slack-request-timestamp"] as string | undefined,
+ rawBody: rawBody ?? "",
+ });
+ if (!valid) {
+ return res.status(401).send("invalid signature");
+ }
+
+ const body = (req.body ?? {}) as Record<string, string>;
+
+ // Slack pings this endpoint with ssl_check when you save the URL.
+ if (body.ssl_check === "1") {
+ return res.status(200).send("");
+ }
+
+ const slackTeamId = body.team_id;
+ if (!slackTeamId) {
+ return res.status(200).json({
+ response_type: "ephemeral",
+ text: "Missing workspace context.",
+ });
+ }
+
+ const installation = await getSlackInstallationBySlackTeam(slackTeamId);
+ if (!installation) {
+ return res.status(200).json({
+ response_type: "ephemeral",
+ text: `This workspace isn't linked to Firecrawl yet. Connect it from the dashboard: ${config.FIRECRAWL_DASHBOARD_URL}/app/monitoring`,
+ });
+ }
+
+ try {
+ const response = await handleSlashCommand({
+ installation,
+ text: body.text ?? "",
+ channelId: body.channel_id ?? "",
+ channelName: body.channel_name ?? "this channel",
+ userId: body.user_id ?? "",
+ });
+ return res.status(200).json(response);
+ } catch (error) {
+ logger.error("Slack slash command failed", { error, slackTeamId });
+ return res.status(200).json({
+ response_type: "ephemeral",
+ text: "Something went wrong handling that command.",
+ });
+ }
+}
+
+// POST /v2/slack/events (public, signature-verified) β€” URL verification during
+// setup + lifecycle events (uninstall / token revocation) for cleanup.
+export async function slackEventsController(req: Request, res: Response) {
+ const rawBody = (req as Request & { rawBody?: Buffer }).rawBody;
+ const body = (req.body ?? {}) as Record<string, any>;
+
+ // URL verification challenge is also signed; verify before responding.
+ const valid = verifySlackSignature({
+ signature: req.headers["x-slack-signature"] as string | undefined,
+ timestamp: req.headers["x-slack-request-timestamp"] as string | undefined,
+ rawBody: rawBody ?? "",
+ });
+ if (!valid) {
+ return res.status(401).send("invalid signature");
+ }
+
+ if (body.type === "url_verification") {
+ return res.status(200).json({ challenge: body.challenge });
+ }
+
+ if (body.type === "event_callback" && body.event?.type) {
+ const event = body.event as {
+ type?: string;
+ tokens?: { bot?: unknown[]; oauth?: unknown[] };
+ };
+ const eventType = event.type;
+ const slackTeamId = (body.team_id as string) || undefined;
+
+ // Only tear down the installation on a full uninstall, or when the BOT
+ // token itself is revoked. `tokens_revoked` also fires for user-token-only
+ // revocations (`event.tokens.oauth`), which leave the bot token β€” the one
+ // the integration actually uses β€” valid, so those must be ignored.
+ const botTokenRevoked =
+ eventType === "tokens_revoked" &&
+ Array.isArray(event.tokens?.bot) &&
+ event.tokens.bot.length > 0;
+ const shouldDisconnect =
+ eventType === "app_uninstalled" || botTokenRevoked;
+
+ if (shouldDisconnect && slackTeamId) {
+ try {
+ await deleteSlackInstallationsBySlackTeam(slackTeamId);
+ logger.info("Removed Slack installation after lifecycle event", {
+ eventType,
+ slackTeamId,
+ });
+ } catch (error) {
+ logger.warn("Failed to clean up Slack installation", {
+ error,
+ slackTeamId,
+ });
+ }
+ }
+ }
+
+ return res.status(200).send("");
+}
diff --git a/apps/api/src/db/schema/public.ts b/apps/api/src/db/schema/public.ts
index e5981cd93..1e42f8686 100644
--- a/apps/api/src/db/schema/public.ts
+++ b/apps/api/src/db/schema/public.ts
@@ -387,6 +387,23 @@ export const monitors = pgTable("monitors", {
judge_enabled: boolean("judge_enabled").notNull().default(false),
});
+export const slack_installations = pgTable("slack_installations", {
+ id: uuid("id").notNull().defaultRandom(),
+ team_id: uuid("team_id").notNull(),
+ slack_team_id: text("slack_team_id").notNull(),
+ slack_team_name: text("slack_team_name"),
+ slack_enterprise_id: text("slack_enterprise_id"),
+ bot_user_id: text("bot_user_id"),
+ bot_token: text("bot_token").notNull(),
+ scope: text("scope"),
+ authed_user_id: text("authed_user_id"),
+ app_id: text("app_id"),
+ incoming_webhook: jsonb("incoming_webhook"),
+ revoked_at: ts("revoked_at"),
+ created_at: ts("created_at").notNull().defaultNow(),
+ updated_at: ts("updated_at").notNull().defaultNow(),
+});
+
export const notification_preferences = pgTable("notification_preferences", {
id: uuid("id").notNull().defaultRandom(),
user_id: uuid("user_id").notNull(),
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 3aca6f20b..650a4a0f9 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -63,8 +63,21 @@ global.isProduction = config.IS_PRODUCTION;
setSentryServiceTag("api");
-app.use(bodyParser.urlencoded({ extended: true }));
-app.use(bodyParser.json({ limit: "10mb" }));
+// Capture the exact request bytes so integrations that sign the raw payload
+// (e.g. Slack's X-Slack-Signature) can verify it after body parsing. Typed with
+// the node http types body-parser's `verify` hook expects.
+const captureRawBody = (
+ req: http.IncomingMessage,
+ _res: http.ServerResponse,
+ buf: Buffer,
+) => {
+ if (buf && buf.length) {
+ (req as http.IncomingMessage & { rawBody?: Buffer }).rawBody = buf;
+ }
+};
+
+app.use(bodyParser.urlencoded({ extended: true, verify: captureRawBody }));
+app.use(bodyParser.json({ limit: "10mb", verify: captureRawBody }));
app.use(cors()); // Add this line to enable CORS
diff --git a/apps/api/src/routes/v2.ts b/apps/api/src/routes/v2.ts
index 0cfcb5211..f45bb0a68 100644
--- a/apps/api/src/routes/v2.ts
+++ b/apps/api/src/routes/v2.ts
@@ -78,6 +78,15 @@ import {
unsubscribeMonitorEmailController,
updateMonitorController,
} from "../controllers/v2/monitor";
+import {
+ slackChannelsController,
+ slackCommandsController,
+ slackDisconnectController,
+ slackEventsController,
+ slackOAuthCallbackController,
+ slackOAuthStartController,
+ slackStatusController,
+} from "../controllers/v2/slack";
export const v2Router = express.Router();
expressWs(express()).applyTo(v2Router);
@@ -469,6 +478,33 @@ v2Router.get(
wrap(getMonitorCheckController),
);
+// Slack integration ("Add to Slack" + /monitor slash command).
+// Public endpoints (OAuth callback, slash command, events) authenticate via the
+// OAuth state nonce / Slack request signature rather than a Firecrawl API key.
+v2Router.post(
+ "/slack/oauth/start",
+ authMiddleware(RateLimiterMode.CrawlStatus),
+ wrap(slackOAuthStartController),
+);
+v2Router.get("/slack/oauth/callback", wrap(slackOAuthCallbackController));
+v2Router.get(
+ "/slack/status",
+ authMiddleware(RateLimiterMode.CrawlStatus),
+ wrap(slackStatusController),
+);
+v2Router.get(
+ "/slack/channels",
+ authMiddleware(RateLimiterMode.CrawlStatus),
+ wrap(slackChannelsController),
+);
+v2Router.delete(
+ "/slack/installation",
+ authMiddleware(RateLimiterMode.CrawlStatus),
+ wrap(slackDisconnectController),
+);
+v2Router.post("/slack/commands", wrap(slackCommandsController));
+v2Router.post("/slack/events", wrap(slackEventsController));
+
v2Router.post(
["/browser", "/interact"],
authMiddleware(RateLimiterMode.Browser),
diff --git a/apps/api/src/services/integrations/slack/client.ts b/apps/api/src/services/integrations/slack/client.ts
new file mode 100644
index 000000000..271e6c153
--- /dev/null
+++ b/apps/api/src/services/integrations/slack/client.ts
@@ -0,0 +1,174 @@
+import { config } from "../../../config";
+import { logger as _logger } from "../../../lib/logger";
+import type { SlackChannel, SlackOAuthResult } from "./types";
+
+const logger = _logger.child({ module: "slack-client" });
+
+const SLACK_API_BASE = "https://slack.com/api";
+
+type SlackApiResponse = {
+ ok: boolean;
+ error?: string;
+ warning?: string;
+ [key: string]: unknown;
+};
+
+async function slackPost<T extends SlackApiResponse>(
+ method: string,
+ token: string,
+ body: Record<string, unknown>,
+): Promise<T> {
+ const res = await fetch(`${SLACK_API_BASE}/${method}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json; charset=utf-8",
+ Authorization: `Bearer ${token}`,
+ },
+ body: JSON.stringify(body),
+ });
+ const json = (await res.json()) as T;
+ if (!json.ok) {
+ logger.warn("Slack API call failed", { method, error: json.error });
+ }
+ return json;
+}
+
+async function slackGet<T extends SlackApiResponse>(
+ method: string,
+ token: string,
+ params: Record<string, string>,
+): Promise<T> {
+ const url = new URL(`${SLACK_API_BASE}/${method}`);
+ for (const [key, value] of Object.entries(params)) {
+ url.searchParams.set(key, value);
+ }
+ const res = await fetch(url.toString(), {
+ method: "GET",
+ headers: { Authorization: `Bearer ${token}` },
+ });
+ const json = (await res.json()) as T;
+ if (!json.ok) {
+ logger.warn("Slack API call failed", { method, error: json.error });
+ }
+ return json;
+}
+
+// Exchanges an OAuth authorization code for a bot token. Sends the client
+// credentials as form-encoded params per Slack's oauth.v2.access contract.
+export async function exchangeOAuthCode(params: {
+ code: string;
+ redirectUri: string;
+}): Promise<SlackOAuthResult> {
+ const clientId = config.SLACK_CLIENT_ID;
+ const clientSecret = config.SLACK_CLIENT_SECRET;
+ if (!clientId || !clientSecret) {
+ return { ok: false, error: "slack_not_configured" };
+ }
+
+ const form = new URLSearchParams({
+ client_id: clientId,
+ client_secret: clientSecret,
+ code: params.code,
+ redirect_uri: params.redirectUri,
+ });
+
+ const res = await fetch(`${SLACK_API_BASE}/oauth.v2.access`, {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: form.toString(),
+ });
+ const json = (await res.json()) as SlackOAuthResult;
+ if (!json.ok) {
+ logger.warn("Slack oauth.v2.access failed", { error: json.error });
+ }
+ return json;
+}
+
+export async function postSlackMessage(params: {
+ token: string;
+ channel: string;
+ text: string;
+ blocks?: unknown[];
+ threadTs?: string;
+}): Promise<{ ok: boolean; error?: string; ts?: string }> {
+ const res = await slackPost<
+ SlackApiResponse & { ts?: string; channel?: string }
+ >("chat.postMessage", params.token, {
+ channel: params.channel,
+ text: params.text,
+ blocks: params.blocks,
+ thread_ts: params.threadTs,
+ unfurl_links: false,
+ unfurl_media: false,
+ });
+ return { ok: res.ok, error: res.error, ts: res.ts };
+}
+
+// Public channels can be auto-joined by the bot; private channels require a
+// manual invite (surfaced to the user as an error).
+export async function joinChannel(params: {
+ token: string;
+ channel: string;
+}): Promise<{ ok: boolean; error?: string }> {
+ const res = await slackPost<SlackApiResponse>(
+ "conversations.join",
+ params.token,
+ { channel: params.channel },
+ );
+ return { ok: res.ok, error: res.error };
+}
+
+type SlackConversation = {
+ id: string;
+ name?: string;
+ is_private?: boolean;
+ is_member?: boolean;
+ is_archived?: boolean;
+};
+
+// Lists channels the workspace exposes to the bot, paging through Slack's
+// cursor pagination up to a sane cap so we don't hammer the API for huge orgs.
+export async function listChannels(params: {
+ token: string;
+ limit?: number;
+}): Promise<{ ok: boolean; error?: string; channels: SlackChannel[] }> {
+ const channels: SlackChannel[] = [];
+ let cursor: string | undefined;
+ const hardCap = params.limit ?? 1000;
+
+ for (let page = 0; page < 10; page++) {
+ const query: Record<string, string> = {
+ types: "public_channel,private_channel",
+ exclude_archived: "true",
+ limit: "200",
+ };
+ if (cursor) query.cursor = cursor;
+
+ const res = await slackGet<
+ SlackApiResponse & {
+ channels?: SlackConversation[];
+ response_metadata?: { next_cursor?: string };
+ }
+ >("conversations.list", params.token, query);
+
+ if (!res.ok) {
+ return { ok: false, error: res.error, channels };
+ }
+
+ for (const ch of res.channels ?? []) {
+ if (ch.is_archived) continue;
+ channels.push({
+ id: ch.id,
+ name: ch.name ?? ch.id,
+ isPrivate: Boolean(ch.is_private),
+ isMember: Boolean(ch.is_member),
+ });
+ }
+
+ cursor = res.response_metadata?.next_cursor || undefined;
+ if (!cursor || channels.length >= hardCap) break;
+ }
+
+ channels.sort((a, b) => a.name.localeCompare(b.name));
+ return { ok: true, channels };
+}
diff --git a/apps/api/src/services/integrations/slack/commands.ts b/apps/api/src/services/integrations/slack/commands.ts
new file mode 100644
index 000000000..5d19f03d3
--- /dev/null
+++ b/apps/api/src/services/integrations/slack/commands.ts
@@ -0,0 +1,260 @@
+import { z } from "zod";
+import { config } from "../../../config";
+import { logger as _logger } from "../../../lib/logger";
+import {
+ createMonitor,
+ listMonitors,
+ getMonitorForUpdate,
+ updateMonitor,
+} from "../../monitoring/store";
+import { validateMonitorCron } from "../../monitoring/cron";
+import { createMonitorSchema } from "../../monitoring/types";
+import type { SlackInstallationRow } from "./types";
+import { escapeSlackText, slackLink } from "./messages";
+
+const logger = _logger.child({ module: "slack-commands" });
+
+type SlackCommandResponse = {
+ response_type: "ephemeral" | "in_channel";
+ text: string;
+ blocks?: unknown[];
+};
+
+type SlackSlashCommandInput = {
+ installation: SlackInstallationRow;
+ text: string;
+ channelId: string;
+ channelName: string;
+ userId: string;
+};
+
+const DEFAULT_WATCH_CRON = "0 9 * * *"; // daily at 09:00 UTC
+
+function dashboardUrl(path: string): string {
+ return new URL(path, config.FIRECRAWL_DASHBOARD_URL).toString();
+}
+
+function ephemeral(text: string, blocks?: unknown[]): SlackCommandResponse {
+ return { response_type: "ephemeral", text, blocks };
+}
+
+function helpResponse(): SlackCommandResponse {
+ const lines = [
+ "*Firecrawl monitor commands*",
+ "`/monitor watch <url>` β€” start monitoring a page and post changes to this channel",
+ "`/monitor list` β€” list your team's monitors",
+ "`/monitor cancel <monitor-id>` β€” pause a monitor",
+ "`/monitor status` β€” show this workspace's Firecrawl connection",
+ "`/monitor help` β€” show this help",
+ "",
+ `Manage everything in the ${slackLink(dashboardUrl("/app/monitoring"), "dashboard")}.`,
+ ];
+ return ephemeral(lines.join("\n"));
+}
+
+function statusResponse(
+ installation: SlackInstallationRow,
+): SlackCommandResponse {
+ const workspace = installation.slack_team_name ?? installation.slack_team_id;
+ return ephemeral(
+ [
+ `:white_check_mark: This Slack workspace (*${escapeSlackText(workspace)}*) is linked to your Firecrawl account.`,
+ "Monitors created here bill your team's API key automatically β€” no key to paste.",
+ `Open the ${slackLink(dashboardUrl("/app/monitoring"), "monitoring dashboard")} to configure more.`,
+ ].join("\n"),
+ );
+}
+
+async function listResponse(
+ installation: SlackInstallationRow,
+): Promise<SlackCommandResponse> {
+ const monitors = await listMonitors({
+ teamId: installation.team_id,
+ limit: 20,
+ offset: 0,
+ });
+
+ if (monitors.length === 0) {
+ return ephemeral(
+ `You don't have any monitors yet. Try \`/monitor watch https://example.com\` or open the ${slackLink(
+ dashboardUrl("/app/monitoring/new"),
+ "dashboard",
+ )}.`,
+ );
+ }
+
+ const lines = monitors.map(m => {
+ const statusEmoji = m.status === "active" ? ":green_circle:" : ":pause_button:";
+ const slackOn =
+ (m.notification as { slack?: { enabled?: boolean } } | null)?.slack
+ ?.enabled === true
+ ? " Β· Slack on"
+ : "";
+ return `${statusEmoji} *${escapeSlackText(m.name)}* β€” \`${m.id}\`${slackOn}`;
+ });
+
+ return ephemeral(
+ [`*Your monitors (${monitors.length}):*`, ...lines].join("\n"),
+ );
+}
+
+async function watchResponse(
+ input: SlackSlashCommandInput,
+ rawUrl: string,
+): Promise<SlackCommandResponse> {
+ let url: string;
+ try {
+ const parsed = new URL(rawUrl.trim());
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
+ throw new Error("bad protocol");
+ }
+ url = parsed.toString();
+ } catch {
+ return ephemeral(
+ `\`${escapeSlackText(rawUrl)}\` doesn't look like a valid URL. Try \`/monitor watch https://example.com\`.`,
+ );
+ }
+
+ let host: string;
+ try {
+ host = new URL(url).hostname;
+ } catch {
+ host = url;
+ }
+
+ try {
+ const parsedInput = createMonitorSchema.parse({
+ name: `Slack: ${host}`,
+ schedule: { cron: DEFAULT_WATCH_CRON, timezone: "UTC" },
+ targets: [
+ {
+ type: "scrape",
+ urls: [url],
+ scrapeOptions: { formats: ["markdown"] },
+ },
+ ],
+ notification: {
+ slack: {
+ enabled: true,
+ channelId: input.channelId,
+ channelName: input.channelName,
+ },
+ },
+ origin: "slack",
+ });
+
+ const schedule = validateMonitorCron(
+ parsedInput.schedule.cron,
+ parsedInput.schedule.timezone,
+ );
+
+ const monitor = await createMonitor({
+ teamId: input.installation.team_id,
+ input: parsedInput,
+ nextRunAt: schedule.nextRunAt,
+ intervalMs: schedule.intervalMs,
+ });
+
+ return ephemeral(
+ [
+ `:fire: Now monitoring ${slackLink(url)} β€” changes will be posted to *#${escapeSlackText(
+ input.channelName,
+ )}*.`,
+ `Runs daily. Manage it in the ${slackLink(
+ dashboardUrl(`/app/monitoring/${monitor.id}`),
+ "dashboard",
+ )} (\`${monitor.id}\`).`,
+ `_Tip: if you don't see alerts in a private channel, invite the bot with \`/invite @Firecrawl\`._`,
+ ].join("\n"),
+ );
+ } catch (error) {
+ logger.warn("Failed to create monitor from slash command", {
+ error,
+ teamId: input.installation.team_id,
+ });
+ return ephemeral(
+ "Sorry, I couldn't create that monitor. Please try again from the dashboard.",
+ );
+ }
+}
+
+async function cancelResponse(
+ installation: SlackInstallationRow,
+ monitorId: string,
+): Promise<SlackCommandResponse> {
+ const trimmed = monitorId.trim();
+
+ // Validate the id shape first: a non-UUID arg gets a friendly message and
+ // avoids hitting the DB with an invalid uuid cast (which would throw).
+ if (!z.uuid().safeParse(trimmed).success) {
+ return ephemeral(
+ `\`${escapeSlackText(trimmed)}\` isn't a valid monitor id. Use \`/monitor list\` to find it.`,
+ );
+ }
+
+ // No catch here on purpose: a valid-but-missing id returns null, while real
+ // backend errors propagate to the command handler's try/catch so we don't
+ // disguise a failure as "not found".
+ const existing = await getMonitorForUpdate(installation.team_id, trimmed);
+ if (!existing) {
+ return ephemeral(
+ `I couldn't find a monitor with id \`${escapeSlackText(trimmed)}\` on your team.`,
+ );
+ }
+
+ const updated = await updateMonitor({
+ teamId: installation.team_id,
+ monitorId: trimmed,
+ input: { status: "paused" },
+ });
+
+ if (!updated) {
+ return ephemeral("Sorry, I couldn't pause that monitor. Try the dashboard.");
+ }
+
+ return ephemeral(
+ `:pause_button: Paused *${escapeSlackText(updated.name)}* (\`${updated.id}\`). Resume it anytime from the ${slackLink(
+ dashboardUrl(`/app/monitoring/${updated.id}`),
+ "dashboard",
+ )}.`,
+ );
+}
+
+// Routes a parsed /monitor invocation to the right sub-handler.
+export async function handleSlashCommand(
+ input: SlackSlashCommandInput,
+): Promise<SlackCommandResponse> {
+ const text = input.text.trim();
+ const [subcommand, ...rest] = text.split(/\s+/);
+ const arg = rest.join(" ").trim();
+
+ switch ((subcommand || "help").toLowerCase()) {
+ case "":
+ case "help":
+ return helpResponse();
+ case "status":
+ return statusResponse(input.installation);
+ case "list":
+ case "ls":
+ return listResponse(input.installation);
+ case "watch":
+ case "add":
+ if (!arg) {
+ return ephemeral("Usage: `/monitor watch <url>`");
+ }
+ return watchResponse(input, arg);
+ case "cancel":
+ case "pause":
+ case "stop":
+ if (!arg) {
+ return ephemeral("Usage: `/monitor cancel <monitor-id>`");
+ }
+ return cancelResponse(input.installation, arg);
+ default:
+ // Bare `/monitor <url>` is a convenient alias for watch.
+ if (/^https?:\/\//i.test(text)) {
+ return watchResponse(input, text);
+ }
+ return helpResponse();
+ }
+}
diff --git a/apps/api/src/services/integrations/slack/crypto.ts b/apps/api/src/services/integrations/slack/crypto.ts
new file mode 100644
index 000000000..a86b0b528
--- /dev/null
+++ b/apps/api/src/services/integrations/slack/crypto.ts
@@ -0,0 +1,84 @@
+import crypto from "crypto";
+import { config } from "../../../config";
+
+const PLAINTEXT_PREFIX = "plain:";
+const GCM_PREFIX = "gcm:";
+
+// Accepts a 32-byte key as hex (64 chars) or base64. Returns null ONLY when the
+// key is unset (self-hosted plaintext fallback). A key that is set but malformed
+// throws, so a misconfiguration never silently downgrades to plaintext storage.
+function getKey(): Buffer | null {
+ const raw = config.SLACK_TOKEN_ENCRYPTION_KEY?.trim();
+ if (!raw) return null;
+
+ let key: Buffer | null = null;
+ if (/^[0-9a-fA-F]{64}$/.test(raw)) {
+ key = Buffer.from(raw, "hex");
+ } else {
+ try {
+ const decoded = Buffer.from(raw, "base64");
+ if (decoded.length === 32) key = decoded;
+ } catch {
+ key = null;
+ }
+ }
+
+ if (!key || key.length !== 32) {
+ // A configured-but-invalid key is operator error. Fail loudly rather than
+ // silently downgrading to plaintext token storage.
+ throw new Error(
+ "SLACK_TOKEN_ENCRYPTION_KEY is set but is not a valid 32-byte hex or base64 value",
+ );
+ }
+ return key;
+}
+
+// Encrypts a Slack bot token for storage. When no encryption key is configured
+// the token is stored with a `plain:` marker (self-hosted only).
+export function encryptSlackToken(token: string): string {
+ const key = getKey();
+ if (!key) {
+ return `${PLAINTEXT_PREFIX}${token}`;
+ }
+ const iv = crypto.randomBytes(12);
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
+ const ciphertext = Buffer.concat([
+ cipher.update(token, "utf8"),
+ cipher.final(),
+ ]);
+ const tag = cipher.getAuthTag();
+ return `${GCM_PREFIX}${iv.toString("base64")}:${tag.toString("base64")}:${ciphertext.toString("base64")}`;
+}
+
+// Reverses encryptSlackToken. Throws when a ciphertext requires a key that is
+// missing or invalid so we never silently post with a broken token.
+export function decryptSlackToken(stored: string): string {
+ if (stored.startsWith(PLAINTEXT_PREFIX)) {
+ return stored.slice(PLAINTEXT_PREFIX.length);
+ }
+ if (stored.startsWith(GCM_PREFIX)) {
+ const key = getKey();
+ if (!key) {
+ throw new Error(
+ "Slack token is encrypted but SLACK_TOKEN_ENCRYPTION_KEY is missing/invalid",
+ );
+ }
+ const [ivB64, tagB64, ctB64] = stored.slice(GCM_PREFIX.length).split(":");
+ if (!ivB64 || !tagB64 || !ctB64) {
+ throw new Error("Malformed encrypted Slack token");
+ }
+ const decipher = crypto.createDecipheriv(
+ "aes-256-gcm",
+ key,
+ Buffer.from(ivB64, "base64"),
+ );
+ decipher.setAuthTag(Buffer.from(tagB64, "base64"));
+ const plaintext = Buffer.concat([
+ decipher.update(Buffer.from(ctB64, "base64")),
+ decipher.final(),
+ ]);
+ return plaintext.toString("utf8");
+ }
+ // Legacy/unknown format: assume it's a raw token.
+ return stored;
+}
diff --git a/apps/api/src/services/integrations/slack/messages.ts b/apps/api/src/services/integrations/slack/messages.ts
new file mode 100644
index 000000000..573eb654a
--- /dev/null
+++ b/apps/api/src/services/integrations/slack/messages.ts
@@ -0,0 +1,163 @@
+export type MonitorSlackPage = {
+ url: string;
+ status: string;
+ judgment?: {
+ meaningful: boolean;
+ reason: string;
+ } | null;
+};
+
+type MonitorSlackPayload = {
+ monitorName: string;
+ dashboardUrl: string;
+ checkId: string;
+ summary: {
+ changed: number;
+ new: number;
+ removed: number;
+ error: number;
+ totalPages: number;
+ };
+ pages: MonitorSlackPage[];
+ creditsUsed: number | null;
+};
+
+const MAX_PAGE_BLOCKS = 8;
+// Slack caps a section block's `text` at 3000 chars; exceeding it makes the whole
+// chat.postMessage fail (invalid_blocks), dropping the alert. URLs are the only
+// unbounded input we render, so bound them and clamp the assembled line.
+const SECTION_TEXT_LIMIT = 3000;
+const MAX_LINK_URL_LEN = 2000;
+
+// Slack mrkdwn requires these three characters escaped in text spans.
+export function escapeSlackText(input: string): string {
+ return input.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+}
+
+export function slackLink(url: string, label?: string): string {
+ // Strip the angle brackets that delimit a link, and percent-encode the pipe:
+ // inside `<...>` Slack treats the first `|` as the URL/label separator, so an
+ // unescaped `|` in a user-controlled URL can spoof the displayed link text.
+ const safeUrl = url.replace(/[<>]/g, "").replace(/\|/g, "%7C");
+ if (!label) return `<${safeUrl}>`;
+ return `<${safeUrl}|${escapeSlackText(label)}>`;
+}
+
+// Renders a page URL for a section: clickable when short enough, otherwise a
+// truncated, non-clickable, escaped string so a pathological URL can't blow past
+// Slack's section text limit and drop the whole alert.
+function boundedPageLink(url: string): string {
+ if (url.length <= MAX_LINK_URL_LEN) return slackLink(url);
+ return escapeSlackText(truncate(url, MAX_LINK_URL_LEN));
+}
+
+// Builds the change-detection alert posted to a channel. Returns both a
+// fallback `text` (for notifications/screen readers) and rich Block Kit blocks.
+export function buildMonitorAlertMessage(payload: MonitorSlackPayload): {
+ text: string;
+ blocks: unknown[];
+} {
+ const { summary } = payload;
+
+ const judged = payload.pages.filter(p => p.judgment);
+ const meaningful = judged.filter(p => p.judgment!.meaningful).length;
+ const changedLine =
+ judged.length > 0
+ ? `*Changed:* ${summary.changed} (${meaningful} meaningful)`
+ : `*Changed:* ${summary.changed}`;
+
+ const summaryLines = [
+ changedLine,
+ `*New:* ${summary.new}`,
+ `*Removed:* ${summary.removed}`,
+ `*Errors:* ${summary.error}`,
+ `*Pages checked:* ${summary.totalPages}`,
+ ].join("\n");
+
+ const blocks: unknown[] = [
+ {
+ type: "header",
+ text: {
+ type: "plain_text",
+ text: `πŸ”₯ ${truncate(payload.monitorName, 140)}`,
+ emoji: true,
+ },
+ },
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `Your Firecrawl monitor detected activity.\n${summaryLines}`,
+ },
+ },
+ ];
+
+ const sortedPages = [...payload.pages].sort((a, b) => {
+ const aM = a.judgment?.meaningful === true ? 0 : 1;
+ const bM = b.judgment?.meaningful === true ? 0 : 1;
+ return aM - bM;
+ });
+
+ const shownPages = sortedPages.slice(0, MAX_PAGE_BLOCKS);
+ if (shownPages.length > 0) {
+ blocks.push({ type: "divider" });
+ for (const page of shownPages) {
+ let line = `*${escapeSlackText(page.status)}* ${boundedPageLink(page.url)}`;
+ if (page.judgment) {
+ line += page.judgment.meaningful
+ ? " :large_orange_diamond: _meaningful_"
+ : " :white_circle: _noise_";
+ if (page.judgment.reason) {
+ line += `\n_${escapeSlackText(truncate(page.judgment.reason, 240))}_`;
+ }
+ }
+ blocks.push({
+ type: "section",
+ // Final safety net: never emit a section over Slack's hard limit.
+ text: { type: "mrkdwn", text: truncate(line, SECTION_TEXT_LIMIT) },
+ });
+ }
+ const remaining = sortedPages.length - shownPages.length;
+ if (remaining > 0) {
+ blocks.push({
+ type: "context",
+ elements: [
+ { type: "mrkdwn", text: `…and ${remaining} more page(s).` },
+ ],
+ });
+ }
+ }
+
+ blocks.push({
+ type: "actions",
+ elements: [
+ {
+ type: "button",
+ text: { type: "plain_text", text: "View in dashboard", emoji: true },
+ url: payload.dashboardUrl,
+ style: "primary",
+ },
+ ],
+ });
+
+ blocks.push({
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: `Check \`${escapeSlackText(payload.checkId)}\`${
+ payload.creditsUsed != null ? ` β€’ ${payload.creditsUsed} credits` : ""
+ }`,
+ },
+ ],
+ });
+
+ const text = `Monitor "${payload.monitorName}" detected activity: ${summary.changed} changed, ${summary.new} new, ${summary.removed} removed, ${summary.error} errors.`;
+
+ return { text, blocks };
+}
+
+function truncate(input: string, max: number): string {
+ if (input.length <= max) return input;
+ return input.slice(0, Math.max(0, max - 1)) + "…";
+}
diff --git a/apps/api/src/services/integrations/slack/oauth.ts b/apps/api/src/services/integrations/slack/oauth.ts
new file mode 100644
index 000000000..60d775382
--- /dev/null
+++ b/apps/api/src/services/integrations/slack/oauth.ts
@@ -0,0 +1,156 @@
+import crypto from "crypto";
+import { config } from "../../../config";
+import { logger as _logger } from "../../../lib/logger";
+import { redisEvictConnection } from "../../redis";
+import { exchangeOAuthCode } from "./client";
+import { encryptSlackToken } from "./crypto";
+import { sanitizeRedirectPath } from "./redirect";
+import { upsertSlackInstallation } from "./store";
+import type { SlackInstallationRow } from "./types";
+
+const logger = _logger.child({ module: "slack-oauth" });
+
+const STATE_TTL_SECONDS = 60 * 10; // 10 minutes to complete the flow
+const STATE_PREFIX = "slack-oauth-state:";
+
+const AUTHORIZE_ENDPOINT = "https://slack.com/oauth/v2/authorize";
+
+type SlackOAuthStatePayload = {
+ teamId: string;
+ redirectPath: string;
+};
+
+export function isSlackConfigured(): boolean {
+ return Boolean(
+ config.SLACK_CLIENT_ID &&
+ config.SLACK_CLIENT_SECRET &&
+ config.SLACK_OAUTH_REDIRECT_URL,
+ );
+}
+
+// Creates a signed-ish random state, stashes the team mapping in Redis, and
+// returns the Slack authorize URL the browser should be sent to. State lives in
+// Redis (not a signed cookie) because the callback lands on the API, which may
+// be a different host than the dashboard that started the flow.
+export async function createAuthorizeUrl(params: {
+ teamId: string;
+ redirectPath?: string;
+}): Promise<{ url: string; state: string }> {
+ if (!isSlackConfigured()) {
+ throw new Error("slack_not_configured");
+ }
+
+ const state = crypto.randomBytes(24).toString("hex");
+ const payload: SlackOAuthStatePayload = {
+ teamId: params.teamId,
+ redirectPath: sanitizeRedirectPath(params.redirectPath),
+ };
+ await redisEvictConnection.set(
+ `${STATE_PREFIX}${state}`,
+ JSON.stringify(payload),
+ "EX",
+ STATE_TTL_SECONDS,
+ );
+
+ const url = new URL(AUTHORIZE_ENDPOINT);
+ url.searchParams.set("client_id", config.SLACK_CLIENT_ID!);
+ url.searchParams.set("scope", config.SLACK_OAUTH_SCOPES);
+ url.searchParams.set("redirect_uri", config.SLACK_OAUTH_REDIRECT_URL!);
+ url.searchParams.set("state", state);
+
+ return { url: url.toString(), state };
+}
+
+async function consumeState(
+ state: string,
+): Promise<SlackOAuthStatePayload | null> {
+ const key = `${STATE_PREFIX}${state}`;
+ const raw = await redisEvictConnection.get(key);
+ if (!raw) return null;
+ // One-time use.
+ await redisEvictConnection.del(key);
+ try {
+ const parsed = JSON.parse(raw) as SlackOAuthStatePayload;
+ if (!parsed?.teamId) return null;
+ return {
+ teamId: parsed.teamId,
+ redirectPath: sanitizeRedirectPath(parsed.redirectPath),
+ };
+ } catch {
+ return null;
+ }
+}
+
+type SlackOAuthCallbackResult =
+ | {
+ ok: true;
+ teamId: string;
+ redirectPath: string;
+ installation: SlackInstallationRow;
+ }
+ | {
+ ok: false;
+ error: string;
+ redirectPath: string;
+ };
+
+// Handles the Slack redirect: validates state, exchanges the code, encrypts the
+// bot token, and upserts the installation for the team.
+export async function handleOAuthCallback(params: {
+ code: string;
+ state: string;
+}): Promise<SlackOAuthCallbackResult> {
+ const statePayload = await consumeState(params.state);
+ if (!statePayload) {
+ logger.warn("Slack OAuth callback with invalid/expired state");
+ return { ok: false, error: "invalid_state", redirectPath: "/app/monitoring" };
+ }
+
+ const result = await exchangeOAuthCode({
+ code: params.code,
+ redirectUri: config.SLACK_OAUTH_REDIRECT_URL!,
+ });
+
+ if (!result.ok || !result.access_token || !result.team?.id) {
+ logger.warn("Slack OAuth exchange failed", { error: result.error });
+ return {
+ ok: false,
+ error: result.error ?? "oauth_exchange_failed",
+ redirectPath: statePayload.redirectPath,
+ };
+ }
+
+ try {
+ const installation = await upsertSlackInstallation({
+ teamId: statePayload.teamId,
+ slackTeamId: result.team.id,
+ slackTeamName: result.team.name ?? null,
+ slackEnterpriseId: result.enterprise?.id ?? null,
+ botUserId: result.bot_user_id ?? null,
+ botToken: encryptSlackToken(result.access_token),
+ scope: result.scope ?? null,
+ authedUserId: result.authed_user?.id ?? null,
+ appId: result.app_id ?? null,
+ incomingWebhook: result.incoming_webhook ?? null,
+ });
+
+ logger.info("Slack installation stored", {
+ teamId: statePayload.teamId,
+ slackTeamId: result.team.id,
+ });
+
+ return {
+ ok: true,
+ teamId: statePayload.teamId,
+ redirectPath: statePayload.redirectPath,
+ installation,
+ };
+ } catch (error) {
+ logger.error("Failed to persist Slack installation", { error });
+ return {
+ ok: false,
+ error: "persist_failed",
+ redirectPath: statePayload.redirectPath,
+ };
+ }
+}
diff --git a/apps/api/src/services/integrations/slack/redirect.ts b/apps/api/src/services/integrations/slack/redirect.ts
new file mode 100644
index 000000000..7a1f04b9e
--- /dev/null
+++ b/apps/api/src/services/integrations/slack/redirect.ts
@@ -0,0 +1,22 @@
+import { config } from "../../../config";
+
+const DEFAULT_REDIRECT_PATH = "/app/monitoring";
+
+export function sanitizeRedirectPath(path?: string | null): string {
+ if (!path || typeof path !== "string") return DEFAULT_REDIRECT_PATH;
+ if (!path.startsWith("/")) return DEFAULT_REDIRECT_PATH;
+ if (path.startsWith("//") || path.startsWith("/\\")) {
+ return DEFAULT_REDIRECT_PATH;
+ }
+ if (/[\u0000-\u001f\u007f]/.test(path)) return DEFAULT_REDIRECT_PATH;
+
+ try {
+ const base = new URL(config.FIRECRAWL_DASHBOARD_URL);
+ const resolved = new URL(path, base);
+ if (resolved.origin !== base.origin) return DEFAULT_REDIRECT_PATH;
+ // Return only the on-origin path so nothing host-like survives.
+ return resolved.pathname + resolved.search + resolved.hash;
+ } catch {
+ return DEFAULT_REDIRECT_PATH;
+ }
+}
diff --git a/apps/api/src/services/integrations/slack/signature.ts b/apps/api/src/services/integrations/slack/signature.ts
new file mode 100644
index 000000000..bceaa4aa2
--- /dev/null
+++ b/apps/api/src/services/integrations/slack/signature.ts
@@ -0,0 +1,41 @@
+import crypto from "crypto";
+import { config } from "../../../config";
+
+const FIVE_MINUTES_SECONDS = 60 * 5;
+
+// Verifies the X-Slack-Signature header per
+// https://api.slack.com/authentication/verifying-requests-from-slack
+// The rawBody MUST be the exact bytes Slack sent (captured before body parsing).
+export function verifySlackSignature(params: {
+ signature: string | undefined;
+ timestamp: string | undefined;
+ rawBody: string | Buffer;
+ signingSecret?: string;
+}): boolean {
+ const signingSecret = params.signingSecret ?? config.SLACK_SIGNING_SECRET;
+ if (!signingSecret) return false;
+ if (!params.signature || !params.timestamp) return false;
+
+ const timestampSeconds = Number(params.timestamp);
+ if (!Number.isFinite(timestampSeconds)) return false;
+
+ // Guard against replay attacks with stale timestamps.
+ const nowSeconds = Math.floor(Date.now() / 1000);
+ if (Math.abs(nowSeconds - timestampSeconds) > FIVE_MINUTES_SECONDS) {
+ return false;
+ }
+
+ const body =
+ typeof params.rawBody === "string"
+ ? params.rawBody
+ : params.rawBody.toString("utf8");
+ const base = `v0:${params.timestamp}:${body}`;
+ const expected =
+ "v0=" +
+ crypto.createHmac("sha256", signingSecret).update(base).digest("hex");
+
+ const a = Buffer.from(expected);
+ const b = Buffer.from(params.signature);
+ if (a.length !== b.length) return false;
+ return crypto.timingSafeEqual(a, b);
+}
diff --git a/apps/api/src/services/integrations/slack/slack.test.ts b/apps/api/src/services/integrations/slack/slack.test.ts
new file mode 100644
index 000000000..2e3b9b24f
--- /dev/null
+++ b/apps/api/src/services/integrations/slack/slack.test.ts
@@ -0,0 +1,228 @@
+import crypto from "crypto";
+import { describe, it, expect, afterEach } from "vitest";
+import { config } from "../../../config";
+import { encryptSlackToken, decryptSlackToken } from "./crypto";
+import { verifySlackSignature } from "./signature";
+import { buildMonitorAlertMessage, escapeSlackText, slackLink } from "./messages";
+import { sanitizeRedirectPath } from "./redirect";
+
+const ORIGINAL_ENCRYPTION_KEY = config.SLACK_TOKEN_ENCRYPTION_KEY;
+const ORIGINAL_SIGNING_SECRET = config.SLACK_SIGNING_SECRET;
+
+afterEach(() => {
+ config.SLACK_TOKEN_ENCRYPTION_KEY = ORIGINAL_ENCRYPTION_KEY;
+ config.SLACK_SIGNING_SECRET = ORIGINAL_SIGNING_SECRET;
+});
+
+describe("slack token crypto", () => {
+ it("round-trips a token with AES-256-GCM when a key is configured", () => {
+ config.SLACK_TOKEN_ENCRYPTION_KEY = crypto
+ .randomBytes(32)
+ .toString("hex");
+ // Opaque placeholder β€” the crypto layer treats the token as bytes, and we
+ // avoid real Slack bot-token shapes so secret scanners don't flag it.
+ const token = "slack-bot-token-placeholder";
+ const stored = encryptSlackToken(token);
+ expect(stored.startsWith("gcm:")).toBe(true);
+ expect(stored).not.toContain(token);
+ expect(decryptSlackToken(stored)).toBe(token);
+ });
+
+ it("falls back to a plaintext marker when no key is set", () => {
+ config.SLACK_TOKEN_ENCRYPTION_KEY = undefined;
+ const token = "self-hosted-token-placeholder";
+ const stored = encryptSlackToken(token);
+ expect(stored).toBe(`plain:${token}`);
+ expect(decryptSlackToken(stored)).toBe(token);
+ });
+
+ it("throws when a GCM token is read without its key", () => {
+ config.SLACK_TOKEN_ENCRYPTION_KEY = crypto
+ .randomBytes(32)
+ .toString("hex");
+ const stored = encryptSlackToken("bot-token-placeholder");
+ config.SLACK_TOKEN_ENCRYPTION_KEY = undefined;
+ expect(() => decryptSlackToken(stored)).toThrow();
+ });
+
+ it("throws on a configured-but-invalid key instead of storing plaintext", () => {
+ config.SLACK_TOKEN_ENCRYPTION_KEY = "invalid-key";
+ expect(() => encryptSlackToken("bot-token-placeholder")).toThrow();
+ });
+});
+
+describe("slack signature verification", () => {
+ // Arbitrary non-secret string used only as the HMAC key for these tests.
+ const secret = "test-slack-signing-secret";
+
+ function sign(body: string, timestamp: string): string {
+ return (
+ "v0=" +
+ crypto
+ .createHmac("sha256", secret)
+ .update(`v0:${timestamp}:${body}`)
+ .digest("hex")
+ );
+ }
+
+ it("accepts a correctly signed, fresh request", () => {
+ const body = "token=abc&command=%2Fmonitor&text=list";
+ const timestamp = String(Math.floor(Date.now() / 1000));
+ expect(
+ verifySlackSignature({
+ signature: sign(body, timestamp),
+ timestamp,
+ rawBody: body,
+ signingSecret: secret,
+ }),
+ ).toBe(true);
+ });
+
+ it("rejects a tampered body", () => {
+ const timestamp = String(Math.floor(Date.now() / 1000));
+ const signature = sign("original", timestamp);
+ expect(
+ verifySlackSignature({
+ signature,
+ timestamp,
+ rawBody: "tampered",
+ signingSecret: secret,
+ }),
+ ).toBe(false);
+ });
+
+ it("rejects a stale timestamp (replay guard)", () => {
+ const body = "text=list";
+ const staleTs = String(Math.floor(Date.now() / 1000) - 60 * 10);
+ expect(
+ verifySlackSignature({
+ signature: sign(body, staleTs),
+ timestamp: staleTs,
+ rawBody: body,
+ signingSecret: secret,
+ }),
+ ).toBe(false);
+ });
+
+ it("rejects when no signing secret is available", () => {
+ config.SLACK_SIGNING_SECRET = undefined;
+ const timestamp = String(Math.floor(Date.now() / 1000));
+ expect(
+ verifySlackSignature({
+ signature: "v0=deadbeef",
+ timestamp,
+ rawBody: "x",
+ }),
+ ).toBe(false);
+ });
+});
+
+describe("slack link escaping", () => {
+ it("percent-encodes the pipe so a URL can't spoof the display label", () => {
+ // Without encoding, Slack would render this as a link to external.example labeled
+ // "firecrawl.dev".
+ expect(slackLink("https://external.example?x=y|firecrawl.dev")).toBe(
+ "<https://external.example?x=y%7Cfirecrawl.dev>",
+ );
+ });
+
+ it("strips angle brackets from the URL", () => {
+ expect(slackLink("https://x.com/<a>")).toBe("<https://x.com/a>");
+ });
+
+ it("preserves the real separator for an explicit label while neutralizing URL pipes", () => {
+ expect(slackLink("https://external.example?x=y|z", "Homepage")).toBe(
+ "<https://external.example?x=y%7Cz|Homepage>",
+ );
+ });
+});
+
+describe("slack message builder", () => {
+ it("escapes Slack mrkdwn control characters", () => {
+ expect(escapeSlackText("a & b < c > d")).toBe("a &amp; b &lt; c &gt; d");
+ });
+
+ it("builds an alert with a header, summary, page rows and a dashboard button", () => {
+ const { text, blocks } = buildMonitorAlertMessage({
+ monitorName: "Pricing <watch>",
+ dashboardUrl: "https://www.firecrawl.dev/app/monitoring/m1?checkId=c1",
+ checkId: "c1",
+ summary: { changed: 2, new: 1, removed: 0, error: 0, totalPages: 5 },
+ pages: [
+ {
+ url: "https://example.com/pricing",
+ status: "changed",
+ judgment: { meaningful: true, reason: "Price changed" },
+ },
+ ],
+ creditsUsed: 7,
+ });
+
+ expect(text).toContain("Pricing <watch>");
+ const serialized = JSON.stringify(blocks);
+ expect(serialized).toContain("header");
+ expect(serialized).toContain("View in dashboard");
+ expect(serialized).toContain("example.com/pricing");
+ // Header text is plain_text; the monitor name is not escaped there but the
+ // fallback text keeps it readable.
+ expect(serialized).toContain("meaningful");
+ });
+
+ it("bounds long page URLs so section blocks stay within Slack's 3000-char limit", () => {
+ const longUrl = "https://example.com/" + "a".repeat(6000);
+ const { blocks } = buildMonitorAlertMessage({
+ monitorName: "m",
+ dashboardUrl: "https://www.firecrawl.dev/app/monitoring/m1?checkId=c1",
+ checkId: "c1",
+ summary: { changed: 1, new: 0, removed: 0, error: 0, totalPages: 1 },
+ pages: [
+ {
+ url: longUrl,
+ status: "changed",
+ judgment: { meaningful: true, reason: "r".repeat(500) },
+ },
+ ],
+ creditsUsed: 1,
+ });
+
+ const sections = (blocks as Array<Record<string, any>>).filter(
+ b => b.type === "section" && b.text?.type === "mrkdwn",
+ );
+ expect(sections.length).toBeGreaterThan(0);
+ for (const section of sections) {
+ expect(section.text.text.length).toBeLessThanOrEqual(3000);
+ }
+ });
+});
+
+describe("slack redirect sanitization", () => {
+ it("allows same-origin dashboard paths", () => {
+ expect(sanitizeRedirectPath("/app/monitoring/123")).toBe(
+ "/app/monitoring/123",
+ );
+ expect(sanitizeRedirectPath("/app/monitoring?tab=slack")).toBe(
+ "/app/monitoring?tab=slack",
+ );
+ });
+
+ it("falls back for missing or non-absolute input", () => {
+ expect(sanitizeRedirectPath(undefined)).toBe("/app/monitoring");
+ expect(sanitizeRedirectPath(null)).toBe("/app/monitoring");
+ expect(sanitizeRedirectPath("")).toBe("/app/monitoring");
+ expect(sanitizeRedirectPath("app/monitoring")).toBe("/app/monitoring");
+ });
+
+ it("blocks open-redirect vectors", () => {
+ const vectors = [
+ "//external.example",
+ "/\\external.example", // "/\external.example" β€” URL parser rewrites \ to / for http(s)
+ "/\\/external.example",
+ "https://external.example",
+ "/\t/external.example",
+ "/\n//external.example",
+ ];
+ for (const vector of vectors) {
+ expect(sanitizeRedirectPath(vector)).toBe("/app/monitoring");
+ }
+ });
+});
diff --git a/apps/api/src/services/integrations/slack/store.ts b/apps/api/src/services/integrations/slack/store.ts
new file mode 100644
index 000000000..a6305dca5
--- /dev/null
+++ b/apps/api/src/services/integrations/slack/store.ts
@@ -0,0 +1,116 @@
+import { and, desc, eq, isNull } from "drizzle-orm";
+import { db } from "../../../db/connection";
+import * as schema from "../../../db/schema";
+import type { SlackIncomingWebhook, SlackInstallationRow } from "./types";
+
+function toRow(row: typeof schema.slack_installations.$inferSelect): SlackInstallationRow {
+ return {
+ id: row.id,
+ team_id: row.team_id,
+ slack_team_id: row.slack_team_id,
+ slack_team_name: row.slack_team_name,
+ slack_enterprise_id: row.slack_enterprise_id,
+ bot_user_id: row.bot_user_id,
+ bot_token: row.bot_token,
+ scope: row.scope,
+ authed_user_id: row.authed_user_id,
+ app_id: row.app_id,
+ incoming_webhook: (row.incoming_webhook as SlackIncomingWebhook | null) ?? null,
+ revoked_at: row.revoked_at,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ };
+}
+
+export async function upsertSlackInstallation(params: {
+ teamId: string;
+ slackTeamId: string;
+ slackTeamName?: string | null;
+ slackEnterpriseId?: string | null;
+ botUserId?: string | null;
+ botToken: string;
+ scope?: string | null;
+ authedUserId?: string | null;
+ appId?: string | null;
+ incomingWebhook?: SlackIncomingWebhook | null;
+}): Promise<SlackInstallationRow> {
+ const values = {
+ team_id: params.teamId,
+ slack_team_id: params.slackTeamId,
+ slack_team_name: params.slackTeamName ?? null,
+ slack_enterprise_id: params.slackEnterpriseId ?? null,
+ bot_user_id: params.botUserId ?? null,
+ bot_token: params.botToken,
+ scope: params.scope ?? null,
+ authed_user_id: params.authedUserId ?? null,
+ app_id: params.appId ?? null,
+ incoming_webhook: params.incomingWebhook ?? null,
+ revoked_at: null,
+ };
+
+ const [row] = await db
+ .insert(schema.slack_installations)
+ .values(values)
+ .onConflictDoUpdate({
+ target: schema.slack_installations.team_id,
+ set: {
+ ...values,
+ updated_at: new Date().toISOString(),
+ },
+ })
+ .returning();
+
+ return toRow(row);
+}
+
+export async function getSlackInstallationByTeam(
+ teamId: string,
+): Promise<SlackInstallationRow | null> {
+ const rows = await db
+ .select()
+ .from(schema.slack_installations)
+ .where(
+ and(
+ eq(schema.slack_installations.team_id, teamId),
+ isNull(schema.slack_installations.revoked_at),
+ ),
+ )
+ .limit(1);
+ return rows[0] ? toRow(rows[0]) : null;
+}
+
+// Inbound Slack traffic (slash commands, events) arrives keyed by the Slack
+// workspace id. If two Firecrawl teams share a workspace we take the most
+// recent install; this is a documented edge case.
+export async function getSlackInstallationBySlackTeam(
+ slackTeamId: string,
+): Promise<SlackInstallationRow | null> {
+ const rows = await db
+ .select()
+ .from(schema.slack_installations)
+ .where(
+ and(
+ eq(schema.slack_installations.slack_team_id, slackTeamId),
+ isNull(schema.slack_installations.revoked_at),
+ ),
+ )
+ .orderBy(desc(schema.slack_installations.created_at))
+ .limit(1);
+ return rows[0] ? toRow(rows[0]) : null;
+}
+
+export async function deleteSlackInstallationByTeam(
+ teamId: string,
+): Promise<void> {
+ await db
+ .delete(schema.slack_installations)
+ .where(eq(schema.slack_installations.team_id, teamId));
+}
+
+export async function deleteSlackInstallationsBySlackTeam(
+ slackTeamId: string,
+): Promise<void> {
+ await db
+ .delete(schema.slack_installations)
+ .where(eq(schema.slack_installations.slack_team_id, slackTeamId));
+}
diff --git a/apps/api/src/services/integrations/slack/types.ts b/apps/api/src/services/integrations/slack/types.ts
new file mode 100644
index 000000000..c67bc7fa6
--- /dev/null
+++ b/apps/api/src/services/integrations/slack/types.ts
@@ -0,0 +1,57 @@
+export type SlackIncomingWebhook = {
+ url: string;
+ channel?: string;
+ channel_id?: string;
+ configuration_url?: string;
+};
+
+export type SlackInstallationRow = {
+ id: string;
+ team_id: string;
+ slack_team_id: string;
+ slack_team_name: string | null;
+ slack_enterprise_id: string | null;
+ bot_user_id: string | null;
+ bot_token: string;
+ scope: string | null;
+ authed_user_id: string | null;
+ app_id: string | null;
+ incoming_webhook: SlackIncomingWebhook | null;
+ revoked_at: string | null;
+ created_at: string;
+ updated_at: string;
+};
+
+// Result of exchanging an OAuth code via oauth.v2.access.
+export type SlackOAuthResult = {
+ ok: boolean;
+ error?: string;
+ access_token?: string;
+ token_type?: string;
+ scope?: string;
+ bot_user_id?: string;
+ app_id?: string;
+ team?: { id: string; name?: string };
+ enterprise?: { id: string; name?: string } | null;
+ authed_user?: { id: string };
+ incoming_webhook?: SlackIncomingWebhook;
+};
+
+export type SlackChannel = {
+ id: string;
+ name: string;
+ isPrivate: boolean;
+ isMember: boolean;
+};
+
+export type SlackConnectionStatus =
+ | { connected: false }
+ | {
+ connected: true;
+ slackTeamId: string;
+ slackTeamName: string | null;
+ botUserId: string | null;
+ scope: string | null;
+ authedUserId: string | null;
+ installedAt: string;
+ };
diff --git a/apps/api/src/services/monitoring/runner.ts b/apps/api/src/services/monitoring/runner.ts
index d52f50e55..47b38d5d3 100644
--- a/apps/api/src/services/monitoring/runner.ts
+++ b/apps/api/src/services/monitoring/runner.ts
@@ -32,6 +32,7 @@ import {
import { createWebhookSender, WebhookEvent } from "../webhook";
import { sendMonitorPageWebhook } from "./results";
import { sendMonitoringEmailSummary } from "../notification/monitoring_email";
+import { sendMonitoringSlackSummary } from "../notification/monitoring_slack";
import {
bulkUpsertMonitorPages,
calculateMonitorCheckActualCredits,
@@ -386,7 +387,7 @@ async function sendNotifications(params: {
monitor: MonitorRow;
check: MonitorCheckRow;
pages: PageResult[];
-}): Promise<{ webhook?: unknown; email?: unknown }> {
+}): Promise<{ webhook?: unknown; email?: unknown; slack?: unknown }> {
const payload = {
monitorId: params.monitor.id,
checkId: params.check.id,
@@ -466,9 +467,34 @@ async function sendNotifications(params: {
})),
});
+ let slackStatus: unknown = { attempted: false };
+ try {
+ slackStatus = await sendMonitoringSlackSummary({
+ monitor: params.monitor,
+ check: params.check,
+ pages: nonSamePages.map(page => ({
+ url: page.url,
+ status: page.status,
+ judgment: page.judgment ?? null,
+ })),
+ });
+ } catch (error) {
+ logger.warn("Slack monitor summary threw", {
+ error,
+ monitorId: params.monitor.id,
+ checkId: params.check.id,
+ });
+ slackStatus = {
+ attempted: true,
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+
return {
webhook: webhookStatus,
email: emailStatus,
+ slack: slackStatus,
};
}
@@ -1434,8 +1460,11 @@ export async function reconcileRunningMonitorChecks(
}
if (await claimMonitorNotification(check.id)) {
- let notificationStatus: { webhook?: unknown; email?: unknown } | null =
- null;
+ let notificationStatus: {
+ webhook?: unknown;
+ email?: unknown;
+ slack?: unknown;
+ } | null = null;
try {
const pages = (await listMonitorCheckPages({
teamId: monitor.team_id,
diff --git a/apps/api/src/services/monitoring/types.ts b/apps/api/src/services/monitoring/types.ts
index 54d00ef25..26a6ed883 100644
--- a/apps/api/src/services/monitoring/types.ts
+++ b/apps/api/src/services/monitoring/types.ts
@@ -139,15 +139,35 @@ const monitorScheduleSchema = z
timezone: schedule.timezone,
}));
-const monitorNotificationInner = z.strictObject({
- email: z
- .strictObject({
- enabled: z.boolean().optional().default(false),
- recipients: z.array(z.email()).max(25).optional().default([]),
- includeDiffs: z.boolean().optional().default(false),
- })
- .optional(),
-});
+const monitorNotificationInner = z
+ .strictObject({
+ email: z
+ .strictObject({
+ enabled: z.boolean().optional().default(false),
+ recipients: z.array(z.email()).max(25).optional().default([]),
+ includeDiffs: z.boolean().optional().default(false),
+ })
+ .optional(),
+ // Slack delivery goes to a single channel in the team's connected
+ // workspace. The bot token lives on the slack_installations row, so only
+ // the channel reference is stored on the monitor.
+ slack: z
+ .strictObject({
+ enabled: z.boolean().optional().default(false),
+ channelId: z.string().trim().min(1).max(64).optional(),
+ channelName: z.string().max(128).optional(),
+ })
+ .optional(),
+ })
+ .superRefine((notification, ctx) => {
+ if (notification.slack?.enabled && !notification.slack.channelId) {
+ ctx.addIssue({
+ code: "custom",
+ message: "A Slack channel is required when Slack notifications are enabled",
+ path: ["slack", "channelId"],
+ });
+ }
+ });
// Create defaults a missing notification to {}; the UPDATE schema deliberately does
// not (a default there would materialize {} on a PATCH and wipe the stored email config).
const monitorNotificationSchema = monitorNotificationInner
diff --git a/apps/api/src/services/notification/monitoring_email.test.ts b/apps/api/src/services/notification/monitoring_email.test.ts
index 41c36915e..d096cfa90 100644
--- a/apps/api/src/services/notification/monitoring_email.test.ts
+++ b/apps/api/src/services/notification/monitoring_email.test.ts
@@ -359,6 +359,22 @@ describe("sendMonitoringEmailSummary", () => {
const result = await sendMonitoringEmailSummary(args);
expect(result.attempted).toBe(true);
});
+
+ it("fails open when counters report new/error pages beyond the truncated list", async () => {
+ const args = buildArgs({
+ goal: "track price changes",
+ emailEnabled: true,
+ pages: [
+ { status: "changed", meaningful: false },
+ { status: "changed", meaningful: false },
+ ],
+ });
+ // The visible page list is all noise, but the check aggregates report new
+ // pages that fell outside the 100-page window β€” the email must still fire.
+ (args.check as any).new_count = 5;
+ const result = await sendMonitoringEmailSummary(args);
+ expect(result.attempted).toBe(true);
+ });
});
describe("opt-in gating", () => {
diff --git a/apps/api/src/services/notification/monitoring_email.ts b/apps/api/src/services/notification/monitoring_email.ts
index 2b85e4bc9..dc461ba73 100644
--- a/apps/api/src/services/notification/monitoring_email.ts
+++ b/apps/api/src/services/notification/monitoring_email.ts
@@ -485,9 +485,13 @@ export async function sendMonitoringEmailSummary(params: {
// complete (a missed meaningful alert is worse than a noisy one).
if (params.monitor.judge_enabled && params.monitor.goal) {
const changedPages = params.pages.filter(p => p.status === "changed");
- const nonChangedActivity = params.pages.some(
- p => p.status === "new" || p.status === "removed" || p.status === "error",
- );
+ // Use the authoritative check counters (aggregated over ALL pages), not the
+ // page list β€” the runner caps `pages` at 100, so scanning it can miss
+ // new/removed/error activity beyond the cap and wrongly suppress the email.
+ const nonChangedActivity =
+ params.check.new_count > 0 ||
+ params.check.removed_count > 0 ||
+ params.check.error_count > 0;
const changedListComplete =
changedPages.length >= params.check.changed_count;
if (changedPages.length > 0 && !nonChangedActivity && changedListComplete) {
diff --git a/apps/api/src/services/notification/monitoring_slack.test.ts b/apps/api/src/services/notification/monitoring_slack.test.ts
new file mode 100644
index 000000000..1e4412f5d
--- /dev/null
+++ b/apps/api/src/services/notification/monitoring_slack.test.ts
@@ -0,0 +1,101 @@
+import { describe, it, expect } from "vitest";
+import { shouldSuppressForNoise } from "./monitoring_slack";
+import type { MonitorCheckRow, MonitorRow } from "../monitoring/types";
+
+type Page = {
+ url: string;
+ status: string;
+ judgment?: {
+ meaningful: boolean;
+ confidence: "high" | "medium" | "low";
+ reason: string;
+ } | null;
+};
+
+function monitor(overrides: Partial<MonitorRow> = {}): MonitorRow {
+ return {
+ judge_enabled: true,
+ goal: "track prices",
+ ...overrides,
+ } as MonitorRow;
+}
+
+function check(overrides: Partial<MonitorCheckRow> = {}): MonitorCheckRow {
+ return {
+ changed_count: 0,
+ new_count: 0,
+ removed_count: 0,
+ error_count: 0,
+ ...overrides,
+ } as MonitorCheckRow;
+}
+
+const noise = (url: string): Page => ({
+ url,
+ status: "changed",
+ judgment: { meaningful: false, confidence: "high", reason: "noise" },
+});
+
+describe("shouldSuppressForNoise (slack)", () => {
+ it("suppresses when all changed pages are noise and no other activity", () => {
+ expect(
+ shouldSuppressForNoise(monitor(), check({ changed_count: 2 }), [
+ noise("u1"),
+ noise("u2"),
+ ]),
+ ).toBe(true);
+ });
+
+ it("does NOT suppress when counters report new pages beyond the truncated list", () => {
+ // The 100-page window the runner passes shows only noisy changed pages, but
+ // the authoritative counters report new pages that were truncated out β€” the
+ // alert must still fire.
+ expect(
+ shouldSuppressForNoise(
+ monitor(),
+ check({ changed_count: 2, new_count: 5 }),
+ [noise("u1"), noise("u2")],
+ ),
+ ).toBe(false);
+ });
+
+ it("does not suppress when error activity exists beyond the truncated list", () => {
+ expect(
+ shouldSuppressForNoise(
+ monitor(),
+ check({ changed_count: 2, error_count: 3 }),
+ [noise("u1"), noise("u2")],
+ ),
+ ).toBe(false);
+ });
+
+ it("does not suppress when the changed list is truncated", () => {
+ expect(
+ shouldSuppressForNoise(monitor(), check({ changed_count: 50 }), [
+ noise("u1"),
+ ]),
+ ).toBe(false);
+ });
+
+ it("does not suppress when a changed page is meaningful", () => {
+ expect(
+ shouldSuppressForNoise(monitor(), check({ changed_count: 1 }), [
+ {
+ url: "u1",
+ status: "changed",
+ judgment: { meaningful: true, confidence: "high", reason: "real" },
+ },
+ ]),
+ ).toBe(false);
+ });
+
+ it("does not gate when judging is disabled", () => {
+ expect(
+ shouldSuppressForNoise(
+ monitor({ judge_enabled: false }),
+ check({ changed_count: 1 }),
+ [noise("u1")],
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/apps/api/src/services/notification/monitoring_slack.ts b/apps/api/src/services/notification/monitoring_slack.ts
new file mode 100644
index 000000000..e3fa6aba5
--- /dev/null
+++ b/apps/api/src/services/notification/monitoring_slack.ts
@@ -0,0 +1,172 @@
+import { logger as _logger } from "../../lib/logger";
+import type { MonitorCheckRow, MonitorRow } from "../monitoring/types";
+import { getSlackInstallationByTeam } from "../integrations/slack/store";
+import { decryptSlackToken } from "../integrations/slack/crypto";
+import { joinChannel, postSlackMessage } from "../integrations/slack/client";
+import {
+ buildMonitorAlertMessage,
+ type MonitorSlackPage,
+} from "../integrations/slack/messages";
+import { buildMonitoringCheckDashboardUrl } from "./monitoring_email";
+
+const logger = _logger.child({ module: "monitoring-slack" });
+
+type SlackSummaryPage = {
+ url: string;
+ status: string;
+ judgment?: {
+ meaningful: boolean;
+ confidence: "high" | "medium" | "low";
+ reason: string;
+ } | null;
+};
+
+type SlackSummaryResult = {
+ attempted: boolean;
+ success: boolean;
+ channel?: string;
+ error?: string;
+};
+
+// Mirrors the email judge gate: only suppress when the changed-page list is
+// complete and every changed page is judged noise (a missed alert is worse than
+// a noisy one).
+export function shouldSuppressForNoise(
+ monitor: MonitorRow,
+ check: MonitorCheckRow,
+ pages: SlackSummaryPage[],
+): boolean {
+ if (!monitor.judge_enabled || !monitor.goal) return false;
+ const changedPages = pages.filter(p => p.status === "changed");
+ // Use the authoritative check counters (aggregated over ALL pages), not the
+ // page list β€” the runner caps `pages` at 100, so scanning it can miss
+ // new/removed/error activity beyond the cap and wrongly suppress a real alert.
+ const nonChangedActivity =
+ check.new_count > 0 || check.removed_count > 0 || check.error_count > 0;
+ const changedListComplete = changedPages.length >= check.changed_count;
+ if (changedPages.length > 0 && !nonChangedActivity && changedListComplete) {
+ const anyMeaningful = changedPages.some(
+ p => p.judgment?.meaningful === true || !p.judgment,
+ );
+ return !anyMeaningful;
+ }
+ return false;
+}
+
+export async function sendMonitoringSlackSummary(params: {
+ monitor: MonitorRow;
+ check: MonitorCheckRow;
+ pages: SlackSummaryPage[];
+}): Promise<SlackSummaryResult> {
+ const slackConfig = params.monitor.notification?.slack;
+ if (!slackConfig?.enabled) {
+ return { attempted: false, success: true };
+ }
+
+ const channelId = slackConfig.channelId;
+ if (!channelId) {
+ logger.warn("Slack notifications enabled but no channel configured", {
+ monitorId: params.monitor.id,
+ checkId: params.check.id,
+ });
+ return { attempted: false, success: false, error: "no_channel" };
+ }
+
+ const activity =
+ params.check.changed_count +
+ params.check.new_count +
+ params.check.removed_count +
+ params.check.error_count;
+ if (activity <= 0) {
+ return { attempted: false, success: true, channel: channelId };
+ }
+
+ if (shouldSuppressForNoise(params.monitor, params.check, params.pages)) {
+ logger.info("Skipping Slack summary; all changed pages judged noise", {
+ monitorId: params.monitor.id,
+ checkId: params.check.id,
+ });
+ return { attempted: false, success: true, channel: channelId };
+ }
+
+ const installation = await getSlackInstallationByTeam(params.monitor.team_id);
+ if (!installation) {
+ logger.warn("Slack notifications enabled but workspace not connected", {
+ monitorId: params.monitor.id,
+ teamId: params.monitor.team_id,
+ });
+ return { attempted: false, success: false, error: "not_connected" };
+ }
+
+ let token: string;
+ try {
+ token = decryptSlackToken(installation.bot_token);
+ } catch (error) {
+ logger.error("Failed to decrypt Slack bot token", {
+ error,
+ teamId: params.monitor.team_id,
+ });
+ return { attempted: false, success: false, error: "token_decrypt_failed" };
+ }
+
+ const dashboardUrl = buildMonitoringCheckDashboardUrl({
+ monitorId: params.monitor.id,
+ checkId: params.check.id,
+ });
+
+ const slackPages: MonitorSlackPage[] = params.pages.map(page => ({
+ url: page.url,
+ status: page.status,
+ judgment: page.judgment
+ ? { meaningful: page.judgment.meaningful, reason: page.judgment.reason }
+ : null,
+ }));
+
+ const { text, blocks } = buildMonitorAlertMessage({
+ monitorName: params.monitor.name,
+ dashboardUrl,
+ checkId: params.check.id,
+ summary: {
+ changed: params.check.changed_count,
+ new: params.check.new_count,
+ removed: params.check.removed_count,
+ error: params.check.error_count,
+ totalPages: params.check.total_pages,
+ },
+ pages: slackPages,
+ creditsUsed: params.check.actual_credits,
+ });
+
+ let res = await postSlackMessage({ token, channel: channelId, text, blocks });
+
+ // Public channels: auto-join once and retry so the first alert lands even if
+ // nobody invited the bot. Private channels still require a manual /invite.
+ if (!res.ok && res.error === "not_in_channel") {
+ const joined = await joinChannel({ token, channel: channelId });
+ if (joined.ok) {
+ res = await postSlackMessage({ token, channel: channelId, text, blocks });
+ }
+ }
+
+ if (!res.ok) {
+ logger.warn("Slack monitor summary failed", {
+ monitorId: params.monitor.id,
+ checkId: params.check.id,
+ channel: channelId,
+ error: res.error,
+ });
+ return {
+ attempted: true,
+ success: false,
+ channel: channelId,
+ error: res.error,
+ };
+ }
+
+ logger.info("Slack monitor summary sent", {
+ monitorId: params.monitor.id,
+ checkId: params.check.id,
+ channel: channelId,
+ });
+ return { attempted: true, success: true, channel: channelId };
+}