/** * Slack incoming-webhook notifications for security and referral fraud events. * Each channel uses its own webhook URL; SLACK_WEBHOOK_URL is a legacy fallback. */ import { config } from '../config'; export type SlackChannel = 'security' | 'referral'; export type SlackMessageBlock = { type: 'section' | 'header'; text?: { type: 'mrkdwn' | 'plain_text'; text: string }; }; export type SlackWebhookConfig = { securityWebhookUrl?: string; referralWebhookUrl?: string; fallbackWebhookUrl?: string; }; /** Resolves the webhook URL for a Slack channel (pure, testable). */ export function resolveSlackWebhookUrl( channel: SlackChannel, urls: SlackWebhookConfig ): string { const fallback = urls.fallbackWebhookUrl?.trim() ?? ''; if (channel === 'security') { return urls.securityWebhookUrl?.trim() || fallback; } return urls.referralWebhookUrl?.trim() || fallback; } function webhookConfigFromEnv(): SlackWebhookConfig { return { securityWebhookUrl: config.slack.securityWebhookUrl, referralWebhookUrl: config.slack.referralWebhookUrl, fallbackWebhookUrl: config.slack.webhookUrl, }; } export function getSlackWebhookUrl(channel: SlackChannel): string { return resolveSlackWebhookUrl(channel, webhookConfigFromEnv()); } export function isSlackChannelConfigured(channel: SlackChannel): boolean { return Boolean(getSlackWebhookUrl(channel)); } /** True when at least one Slack channel webhook is configured. */ export function isSlackConfigured(): boolean { return isSlackChannelConfigured('security') || isSlackChannelConfigured('referral'); } export function isReferralSlackAlertType(alertType: string): boolean { return alertType.startsWith('referral_'); } function slackChannelLabel(channel: SlackChannel): string { return channel === 'referral' ? '#referral-fraud' : '#security'; } /** Posts a message to a Slack webhook. Failures are logged, not thrown. */ export async function postSlackMessage(input: { webhookUrl: string; text: string; blocks?: SlackMessageBlock[]; }): Promise { const url = input.webhookUrl.trim(); if (!url) return false; try { const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: input.text, blocks: input.blocks, }), }); if (!res.ok) { const body = await res.text().catch(() => ''); console.error(`[slack] Webhook failed (${res.status}): ${body.slice(0, 200)}`); return false; } return true; } catch (e) { console.error('[slack] Webhook error:', e); return false; } } export async function postSlackAlert(input: { channel: SlackChannel; title: string; severity: string; alertType: string; details?: string; userId?: string | null; metadata?: Record; }): Promise { const webhookUrl = getSlackWebhookUrl(input.channel); if (!webhookUrl) return; const emoji = input.severity === 'critical' || input.severity === 'high' ? ':rotating_light:' : input.severity === 'medium' ? ':warning:' : ':information_source:'; const lines = [ `*${input.title}*`, `Channel: \`${slackChannelLabel(input.channel)}\` · Type: \`${input.alertType}\` · Severity: *${input.severity}*`, input.details ? input.details : null, input.userId ? `User: \`${input.userId}\`` : null, ].filter(Boolean); if (input.metadata && Object.keys(input.metadata).length > 0) { lines.push(`\`\`\`${JSON.stringify(input.metadata, null, 2).slice(0, 800)}\`\`\``); } await postSlackMessage({ webhookUrl, text: `${emoji} ${input.title}`, blocks: [{ type: 'section', text: { type: 'mrkdwn', text: lines.join('\n') } }], }); } /** @deprecated Use postSlackAlert({ channel: 'security', ... }) */ export async function postSlackSecurityAlert(input: { title: string; severity: string; alertType: string; details?: string; userId?: string | null; metadata?: Record; }): Promise { await postSlackAlert({ channel: 'security', ...input }); }