Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

Nick: monitoring slack fixes

Nicolasc32699f74154
diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts
index 00eaec077..0ce129200 100644
--- a/apps/api/src/config.ts
+++ b/apps/api/src/config.ts
@@ -242,7 +242,7 @@ const configSchema = z.object({
SLACK_OAUTH_SCOPES: z
.string()
.default(
- "chat:write,chat:write.public,commands,channels:read,groups:read,team:read",
+ "chat:write,chat:write.public,commands,channels:read,groups:read,team:read,incoming-webhook",
),
// Absolute URL Slack redirects back to after authorize. Must exactly match a
// Redirect URL configured on the Slack app (e.g.
diff --git a/apps/api/src/controllers/v2/slack.ts b/apps/api/src/controllers/v2/slack.ts
index 49afd9d6b..c63900aad 100644
--- a/apps/api/src/controllers/v2/slack.ts
+++ b/apps/api/src/controllers/v2/slack.ts
@@ -24,6 +24,9 @@ const logger = _logger.child({ module: "slack-controller" });
const startBodySchema = z.object({
redirectPath: z.string().max(512).optional(),
+ // When present, the install is tied to this monitor so we can auto-enable
+ // Slack notifications on it once the user picks a channel during install.
+ monitorId: z.string().uuid().optional(),
});
// Builds an absolute dashboard URL for post-OAuth browser redirects.
@@ -47,11 +50,13 @@ export async function slackOAuthStartController(
const body = startBodySchema.safeParse(req.body ?? {});
const redirectPath = body.success ? body.data.redirectPath : undefined;
+ const monitorId = body.success ? body.data.monitorId : undefined;
try {
const { url } = await createAuthorizeUrl({
teamId: req.auth.team_id,
redirectPath,
+ monitorId,
});
return res.status(200).json({ success: true, url });
} catch (error) {
@@ -131,6 +136,10 @@ export async function slackStatusController(
scope: installation.scope,
authedUserId: installation.authed_user_id,
installedAt: installation.created_at,
+ defaultChannelId: installation.incoming_webhook?.channel_id ?? null,
+ defaultChannelName: installation.incoming_webhook?.channel
+ ? installation.incoming_webhook.channel.replace(/^#/, "")
+ : null,
}
: { connected: false };
diff --git a/apps/api/src/services/integrations/slack/oauth.ts b/apps/api/src/services/integrations/slack/oauth.ts
index 60d775382..40e34ee29 100644
--- a/apps/api/src/services/integrations/slack/oauth.ts
+++ b/apps/api/src/services/integrations/slack/oauth.ts
@@ -6,6 +6,7 @@ import { exchangeOAuthCode } from "./client";
import { encryptSlackToken } from "./crypto";
import { sanitizeRedirectPath } from "./redirect";
import { upsertSlackInstallation } from "./store";
+import { getMonitorForUpdate, updateMonitor } from "../../monitoring/store";
import type { SlackInstallationRow } from "./types";
const logger = _logger.child({ module: "slack-oauth" });
@@ -18,6 +19,9 @@ const AUTHORIZE_ENDPOINT = "https://slack.com/oauth/v2/authorize";
type SlackOAuthStatePayload = {
teamId: string;
redirectPath: string;
+ // When the install was started from a specific monitor, we wire that monitor
+ // up to the channel the user picked during install so it can post right away.
+ monitorId?: string;
};
export function isSlackConfigured(): boolean {
@@ -35,6 +39,7 @@ export function isSlackConfigured(): boolean {
export async function createAuthorizeUrl(params: {
teamId: string;
redirectPath?: string;
+ monitorId?: string;
}): Promise<{ url: string; state: string }> {
if (!isSlackConfigured()) {
throw new Error("slack_not_configured");
@@ -44,6 +49,7 @@ export async function createAuthorizeUrl(params: {
const payload: SlackOAuthStatePayload = {
teamId: params.teamId,
redirectPath: sanitizeRedirectPath(params.redirectPath),
+ ...(params.monitorId ? { monitorId: params.monitorId } : {}),
};
await redisEvictConnection.set(
`${STATE_PREFIX}${state}`,
@@ -75,12 +81,42 @@ async function consumeState(
return {
teamId: parsed.teamId,
redirectPath: sanitizeRedirectPath(parsed.redirectPath),
+ monitorId:
+ typeof parsed.monitorId === "string" ? parsed.monitorId : undefined,
};
} catch {
return null;
}
}
+// Best-effort: turn on Slack notifications for the monitor the install was
+// started from, pointing at the channel the user picked during install. Scoped
+// by team, so an install can only touch that team's own monitors.
+async function attachSlackChannelToMonitor(params: {
+ teamId: string;
+ monitorId: string;
+ channelId: string;
+ channelName: string | null;
+}): Promise<void> {
+ const existing = await getMonitorForUpdate(params.teamId, params.monitorId);
+ if (!existing) return;
+ const currentNotification = existing.notification ?? {};
+ await updateMonitor({
+ teamId: params.teamId,
+ monitorId: params.monitorId,
+ input: {
+ notification: {
+ ...currentNotification,
+ slack: {
+ enabled: true,
+ channelId: params.channelId,
+ channelName: params.channelName ?? undefined,
+ },
+ },
+ },
+ });
+}
+
type SlackOAuthCallbackResult =
| {
ok: true;
@@ -120,6 +156,20 @@ export async function handleOAuthCallback(params: {
};
}
+ // Encrypt first so a misconfigured SLACK_TOKEN_ENCRYPTION_KEY reports a
+ // distinct reason instead of the opaque "persist_failed".
+ let botToken: string;
+ try {
+ botToken = encryptSlackToken(result.access_token);
+ } catch (error) {
+ logger.error("Failed to encrypt Slack bot token", { error });
+ return {
+ ok: false,
+ error: "token_encrypt_failed",
+ redirectPath: statePayload.redirectPath,
+ };
+ }
+
try {
const installation = await upsertSlackInstallation({
teamId: statePayload.teamId,
@@ -127,7 +177,7 @@ export async function handleOAuthCallback(params: {
slackTeamName: result.team.name ?? null,
slackEnterpriseId: result.enterprise?.id ?? null,
botUserId: result.bot_user_id ?? null,
- botToken: encryptSlackToken(result.access_token),
+ botToken,
scope: result.scope ?? null,
authedUserId: result.authed_user?.id ?? null,
appId: result.app_id ?? null,
@@ -139,6 +189,26 @@ export async function handleOAuthCallback(params: {
slackTeamId: result.team.id,
});
+ // If the install was kicked off from a specific monitor, wire that monitor
+ // to the channel the user selected during install so alerts flow right away.
+ const installChannelId = installation.incoming_webhook?.channel_id;
+ if (statePayload.monitorId && installChannelId) {
+ const channelName = installation.incoming_webhook?.channel
+ ? installation.incoming_webhook.channel.replace(/^#/, "")
+ : null;
+ await attachSlackChannelToMonitor({
+ teamId: statePayload.teamId,
+ monitorId: statePayload.monitorId,
+ channelId: installChannelId,
+ channelName,
+ }).catch(error => {
+ logger.warn("Failed to attach Slack channel to monitor after install", {
+ error,
+ monitorId: statePayload.monitorId,
+ });
+ });
+ }
+
return {
ok: true,
teamId: statePayload.teamId,
diff --git a/apps/api/src/services/integrations/slack/types.ts b/apps/api/src/services/integrations/slack/types.ts
index c67bc7fa6..c2e2a8aba 100644
--- a/apps/api/src/services/integrations/slack/types.ts
+++ b/apps/api/src/services/integrations/slack/types.ts
@@ -54,4 +54,8 @@ export type SlackConnectionStatus =
scope: string | null;
authedUserId: string | null;
installedAt: string;
+ // Channel chosen during install (incoming-webhook), used as the default
+ // target when enabling Slack on a monitor.
+ defaultChannelId: string | null;
+ defaultChannelName: string | null;
};