Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): add Slack API client helpers

Richie McIlroy91d31c230aba
diff --git a/apps/web/__tests__/unit/slack-client.test.ts b/apps/web/__tests__/unit/slack-client.test.ts
new file mode 100644
index 000000000..6adfe71ae
--- /dev/null
+++ b/apps/web/__tests__/unit/slack-client.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ buildSlackInstallUrl,
+ exchangeSlackOAuthCode,
+ SLACK_BOT_SCOPES,
+ sendSlackUnfurl,
+} from "@/lib/slack/client";
+
+const config = {
+ clientId: "client-id",
+ clientSecret: "client-secret",
+ signingSecret: "signing-secret",
+ redirectUrl: "https://cap.so/api/integrations/slack/callback",
+};
+
+const slackResponse = (scope = SLACK_BOT_SCOPES.join(",")) =>
+ new Response(
+ JSON.stringify({
+ ok: true,
+ access_token: "xoxb-token",
+ scope,
+ bot_user_id: "B123",
+ team: {
+ id: "T123",
+ name: "Cap",
+ },
+ enterprise: null,
+ }),
+ {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ },
+ );
+
+describe("Slack API client", () => {
+ it("builds an install URL with only the required bot scopes", () => {
+ const url = new URL(
+ buildSlackInstallUrl({ config, state: "signed-state" }),
+ );
+
+ expect(url.origin).toBe("https://slack.com");
+ expect(url.pathname).toBe("/oauth/v2/authorize");
+ expect(url.searchParams.get("client_id")).toBe("client-id");
+ expect(url.searchParams.get("scope")).toBe(SLACK_BOT_SCOPES.join(","));
+ expect(url.searchParams.get("redirect_uri")).toBe(config.redirectUrl);
+ expect(url.searchParams.get("state")).toBe("signed-state");
+ });
+
+ it("accepts a complete OAuth response and preserves the workspace identity", async () => {
+ const fetchImpl = vi.fn(async () => slackResponse());
+ const result = await exchangeSlackOAuthCode({
+ code: "oauth-code",
+ config,
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ });
+
+ expect(result).toEqual({
+ accessToken: "xoxb-token",
+ scope: SLACK_BOT_SCOPES.join(","),
+ botUserId: "B123",
+ teamId: "T123",
+ teamName: "Cap",
+ enterpriseId: null,
+ });
+ expect(fetchImpl).toHaveBeenCalledOnce();
+ });
+
+ it("rejects OAuth responses that omit a required unfurl scope", async () => {
+ const fetchImpl = vi.fn(async () =>
+ slackResponse("links:read,links:write"),
+ );
+
+ await expect(
+ exchangeSlackOAuthCode({
+ code: "oauth-code",
+ config,
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ }),
+ ).rejects.toThrow("missing required unfurl scopes");
+ });
+
+ it("retries transient unfurl failures with the stable event locator", async () => {
+ const fetchImpl = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ ok: false, error: "ratelimited" }), {
+ status: 429,
+ headers: {
+ "Content-Type": "application/json",
+ "Retry-After": "1",
+ },
+ }),
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ ok: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ const sleepImpl = vi.fn(async () => undefined);
+
+ await sendSlackUnfurl({
+ token: "xoxb-token",
+ event: {
+ channel: "C123",
+ messageTs: "123.456",
+ unfurlId: "U123",
+ source: "conversations_history",
+ },
+ unfurls: {
+ "https://cap.so/s/abc123": {
+ blocks: [{ type: "video" }],
+ },
+ },
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ sleepImpl,
+ });
+
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ expect(sleepImpl).toHaveBeenCalledWith(1000);
+ const request = fetchImpl.mock.calls[1]?.[1] as RequestInit;
+ expect(JSON.parse(String(request.body))).toMatchObject({
+ unfurl_id: "U123",
+ source: "conversations_history",
+ });
+ });
+});
diff --git a/apps/web/lib/slack/client.ts b/apps/web/lib/slack/client.ts
new file mode 100644
index 000000000..bcda56492
--- /dev/null
+++ b/apps/web/lib/slack/client.ts
@@ -0,0 +1,214 @@
+import { serverEnv } from "@cap/env";
+
+export const SLACK_BOT_SCOPES = [
+ "links:read",
+ "links:write",
+ "links.embed:write",
+] as const;
+
+type SlackConfig = {
+ clientId: string;
+ clientSecret: string;
+ signingSecret: string;
+ redirectUrl: string;
+};
+
+export type SlackOAuthResult = {
+ accessToken: string;
+ scope: string;
+ botUserId: string | null;
+ teamId: string;
+ teamName: string;
+ enterpriseId: string | null;
+};
+
+type SlackApiResponse = {
+ ok?: boolean;
+ error?: string;
+};
+
+const sleep = (durationMs: number) =>
+ new Promise<void>((resolve) => setTimeout(resolve, durationMs));
+
+const parseSlackResponse = async (response: Response) => {
+ let value: unknown;
+ try {
+ value = await response.json();
+ } catch {
+ throw new Error(`Slack returned an invalid response (${response.status})`);
+ }
+ if (!value || typeof value !== "object") {
+ throw new Error(`Slack returned an invalid response (${response.status})`);
+ }
+ return value as SlackApiResponse & Record<string, unknown>;
+};
+
+export const getSlackConfig = (): SlackConfig | null => {
+ const env = serverEnv();
+ if (
+ !env.SLACK_CLIENT_ID ||
+ !env.SLACK_CLIENT_SECRET ||
+ !env.SLACK_SIGNING_SECRET
+ ) {
+ return null;
+ }
+
+ return {
+ clientId: env.SLACK_CLIENT_ID,
+ clientSecret: env.SLACK_CLIENT_SECRET,
+ signingSecret: env.SLACK_SIGNING_SECRET,
+ redirectUrl: new URL(
+ "/api/integrations/slack/callback",
+ env.WEB_URL,
+ ).toString(),
+ };
+};
+
+export const isSlackIntegrationConfigured = () =>
+ getSlackConfig() !== null &&
+ /^[0-9a-f]{64}$/i.test(serverEnv().DATABASE_ENCRYPTION_KEY ?? "");
+
+export const buildSlackInstallUrl = ({
+ config,
+ state,
+}: {
+ config: SlackConfig;
+ state: string;
+}) => {
+ const url = new URL("https://slack.com/oauth/v2/authorize");
+ url.searchParams.set("client_id", config.clientId);
+ url.searchParams.set("scope", SLACK_BOT_SCOPES.join(","));
+ url.searchParams.set("redirect_uri", config.redirectUrl);
+ url.searchParams.set("state", state);
+ return url.toString();
+};
+
+export const exchangeSlackOAuthCode = async ({
+ code,
+ config,
+ fetchImpl = fetch,
+}: {
+ code: string;
+ config: SlackConfig;
+ fetchImpl?: typeof fetch;
+}): Promise<SlackOAuthResult> => {
+ const response = await fetchImpl("https://slack.com/api/oauth.v2.access", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ body: new URLSearchParams({
+ client_id: config.clientId,
+ client_secret: config.clientSecret,
+ code,
+ redirect_uri: config.redirectUrl,
+ }),
+ signal: AbortSignal.timeout(10_000),
+ });
+ const body = await parseSlackResponse(response);
+ if (!response.ok || body.ok !== true) {
+ throw new Error(
+ `Slack OAuth failed: ${typeof body.error === "string" ? body.error : response.status}`,
+ );
+ }
+
+ const accessToken = body.access_token;
+ const grantedScopes =
+ typeof body.scope === "string"
+ ? body.scope
+ .split(",")
+ .map((scope) => scope.trim())
+ .filter(Boolean)
+ : [];
+ const team = body.team;
+ const enterprise = body.enterprise;
+ if (
+ typeof accessToken !== "string" ||
+ !team ||
+ typeof team !== "object" ||
+ typeof (team as { id?: unknown }).id !== "string" ||
+ typeof (team as { name?: unknown }).name !== "string"
+ ) {
+ throw new Error("Slack OAuth response is missing workspace credentials");
+ }
+ if (!SLACK_BOT_SCOPES.every((scope) => grantedScopes.includes(scope))) {
+ throw new Error("Slack OAuth response is missing required unfurl scopes");
+ }
+
+ return {
+ accessToken,
+ scope: grantedScopes.join(","),
+ botUserId: typeof body.bot_user_id === "string" ? body.bot_user_id : null,
+ teamId: (team as { id: string }).id,
+ teamName: (team as { name: string }).name,
+ enterpriseId:
+ enterprise &&
+ typeof enterprise === "object" &&
+ typeof (enterprise as { id?: unknown }).id === "string"
+ ? (enterprise as { id: string }).id
+ : null,
+ };
+};
+
+export const sendSlackUnfurl = async ({
+ token,
+ event,
+ unfurls,
+ fetchImpl = fetch,
+ sleepImpl = sleep,
+}: {
+ token: string;
+ event: {
+ channel: string;
+ messageTs: string;
+ unfurlId?: string;
+ source?: string;
+ };
+ unfurls: Record<string, { blocks: unknown[] }>;
+ fetchImpl?: typeof fetch;
+ sleepImpl?: (durationMs: number) => Promise<void>;
+}) => {
+ const locator =
+ event.unfurlId && event.source
+ ? { unfurl_id: event.unfurlId, source: event.source }
+ : { channel: event.channel, ts: event.messageTs };
+ for (let attempt = 1; attempt <= 3; attempt++) {
+ try {
+ const response = await fetchImpl("https://slack.com/api/chat.unfurl", {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/json; charset=utf-8",
+ },
+ body: JSON.stringify({
+ ...locator,
+ unfurls,
+ }),
+ signal: AbortSignal.timeout(10_000),
+ });
+ const body = await parseSlackResponse(response);
+ if (response.ok && body.ok === true) return;
+
+ const retryable = response.status === 429 || response.status >= 500;
+ if (!retryable || attempt === 3) {
+ throw new Error(
+ `Slack unfurl failed: ${typeof body.error === "string" ? body.error : response.status}`,
+ );
+ }
+ const retryAfterSeconds = Number(response.headers.get("Retry-After"));
+ const retryAfterMs =
+ Number.isFinite(retryAfterSeconds) && retryAfterSeconds > 0
+ ? retryAfterSeconds * 1000
+ : attempt * 250;
+ await sleepImpl(Math.min(retryAfterMs, 2000));
+ } catch (error) {
+ if (
+ attempt === 3 ||
+ (error instanceof Error && error.message.startsWith("Slack unfurl"))
+ ) {
+ throw error;
+ }
+ await sleepImpl(attempt * 250);
+ }
+ }
+};