import { WebClient } from "@slack/web-api"; import { pino } from "pino"; import { withSpan } from "../telemetry.ts"; import { verifySlackSignature } from "./signature.ts"; export interface SlackClient { sendMessage(args: { msg: string; channel: string; thread_ts?: string }): Promise; inviteUser(args: { email: string }): Promise; getThreadParent(args: { channel: string; thread_ts: string }): Promise<{ text: string }>; verifySignature(args: { timestamp: string; rawBody: string; signature: string; onReject?: (reason: string) => void; }): boolean; } export interface SlackClientDeps { botToken: string; adminToken: string; signingSecret: string; } // Standalone logger: the slack client is constructed before the fastify app // (and its logger) exists. Matches fastify's default pino JSON output. const log = pino(); export function makeSlackClient({ botToken, adminToken, signingSecret, }: SlackClientDeps): SlackClient { const client = new WebClient(botToken); return { async sendMessage({ msg, channel, thread_ts }): Promise { await withSpan( "slack.sendMessage", { "slack.channel": channel, "slack.thread_ts": thread_ts }, () => client.chat.postMessage({ channel, markdown_text: msg, thread_ts }), ); }, // WebClient can't be used here because it's a user-auth'd admin request, not // a bot-auth'd request like the rest. async inviteUser({ email }): Promise { await withSpan("slack.inviteUser", { "slack.invite.email": email }, async () => { log.info({ email }, "slack: inviting user"); const url = `https://devict.slack.com/api/users.admin.invite?t=${Date.now()}`; const resp = await fetch(url, { method: "POST", body: new URLSearchParams({ email, token: adminToken, _attempts: "1" }), }); if (!resp.ok) { throw new Error(`Slack request failed (${resp.status}): ${await resp.text()}`); } const respBody = (await resp.json()) as { ok: boolean; error?: string }; if (!respBody.ok) { throw new Error(`Invite failed: ${respBody.error}`); } }); }, async getThreadParent({ channel, thread_ts }): Promise<{ text: string }> { return withSpan( "slack.getThreadParent", { "slack.channel": channel, "slack.thread_ts": thread_ts }, async () => { const resp = await client.conversations.replies({ channel, ts: thread_ts }); const parent = resp.messages?.find((m) => m.ts === thread_ts); if (!parent?.text) { throw new Error(`thread parent not found for ${channel}/${thread_ts}`); } return { text: parent.text }; }, ); }, verifySignature({ timestamp, rawBody, signature, onReject }): boolean { return verifySlackSignature({ signingSecret, timestamp, rawBody, signature, onReject }); }, }; }