Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687import { 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<void>; inviteUser(args: { email: string }): Promise<void>; 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<void> { 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<void> { 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 }); }, };}