Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): add Slack events webhook route

Richie McIlroybd0212ca83eb
diff --git a/apps/web/__tests__/unit/slack-events-route.test.ts b/apps/web/__tests__/unit/slack-events-route.test.ts
new file mode 100644
index 000000000..c7060c884
--- /dev/null
+++ b/apps/web/__tests__/unit/slack-events-route.test.ts
@@ -0,0 +1,22 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+describe("Slack Events route contract", () => {
+ it("verifies the raw request before parsing and acknowledges through waitUntil", () => {
+ const route = readFileSync(
+ join(process.cwd(), "app/api/integrations/slack/events/route.ts"),
+ "utf8",
+ );
+ const bodyRead = route.indexOf("yield* request.text");
+ const signatureCheck = route.indexOf("verifySlackSignature({", bodyRead);
+ const jsonParse = route.indexOf("JSON.parse(body)", signatureCheck);
+ const deferredWork = route.indexOf("waitUntil(", jsonParse);
+
+ expect(bodyRead).toBeGreaterThan(-1);
+ expect(signatureCheck).toBeGreaterThan(bodyRead);
+ expect(jsonParse).toBeGreaterThan(signatureCheck);
+ expect(deferredWork).toBeGreaterThan(jsonParse);
+ expect(route).toContain("HttpServerRequest.withMaxBodySize");
+ });
+});
diff --git a/apps/web/app/api/integrations/slack/events/route.ts b/apps/web/app/api/integrations/slack/events/route.ts
new file mode 100644
index 000000000..58fa876f7
--- /dev/null
+++ b/apps/web/app/api/integrations/slack/events/route.ts
@@ -0,0 +1,96 @@
+import { serverEnv } from "@cap/env";
+import {
+ HttpApi,
+ HttpApiBuilder,
+ HttpApiEndpoint,
+ HttpApiGroup,
+ HttpServerRequest,
+ HttpServerResponse,
+} from "@effect/platform";
+import { waitUntil } from "@vercel/functions";
+import { Effect, Layer, Option } from "effect";
+import { apiToHandler } from "@/lib/server";
+import { getSlackConfig } from "@/lib/slack/client";
+import { verifySlackSignature } from "@/lib/slack/signature";
+import { parseSlackEventPayload, processSlackEvent } from "@/lib/slack/unfurl";
+
+const MAX_BODY_BYTES = 1_000_000;
+
+class Api extends HttpApi.make("CapSlackEventsApi").add(
+ HttpApiGroup.make("root").add(
+ HttpApiEndpoint.post("receiveSlackEvent")`/api/integrations/slack/events`,
+ ),
+) {}
+
+const jsonResponse = (body: unknown, status = 200) =>
+ HttpServerResponse.text(JSON.stringify(body), {
+ status,
+ contentType: "application/json; charset=utf-8",
+ headers: {
+ "Cache-Control": "private, no-store",
+ "X-Content-Type-Options": "nosniff",
+ },
+ });
+
+const ApiLive = HttpApiBuilder.api(Api).pipe(
+ Layer.provide(
+ HttpApiBuilder.group(Api, "root", (handlers) =>
+ handlers.handle("receiveSlackEvent", () =>
+ Effect.gen(function* () {
+ const config = getSlackConfig();
+ if (!config) {
+ return jsonResponse({ error: "Slack is not configured" }, 503);
+ }
+ const request = yield* HttpServerRequest.HttpServerRequest;
+ const body = yield* request.text.pipe(
+ HttpServerRequest.withMaxBodySize(Option.some(MAX_BODY_BYTES)),
+ Effect.catchAll(() => Effect.succeed("")),
+ );
+ if (
+ !verifySlackSignature({
+ body,
+ timestamp: request.headers["x-slack-request-timestamp"],
+ signature: request.headers["x-slack-signature"],
+ signingSecret: config.signingSecret,
+ })
+ ) {
+ return jsonResponse({ error: "Invalid signature" }, 401);
+ }
+
+ let value: unknown;
+ try {
+ value = JSON.parse(body);
+ } catch {
+ return jsonResponse({ error: "Invalid request body" }, 400);
+ }
+ const payload = parseSlackEventPayload(value);
+ if (!payload) {
+ return jsonResponse({ error: "Unsupported Slack event" }, 400);
+ }
+ if (payload.type === "url_verification") {
+ return jsonResponse({ challenge: payload.challenge });
+ }
+
+ yield* Effect.sync(() =>
+ waitUntil(
+ processSlackEvent({
+ payload,
+ webUrl: serverEnv().WEB_URL,
+ }).catch((error: unknown) => {
+ console.error(
+ "[slack-unfurl] Failed to process event",
+ error instanceof Error ? error.message : "Unknown error",
+ );
+ }),
+ ),
+ );
+ return jsonResponse({ ok: true });
+ }),
+ ),
+ ),
+ ),
+);
+
+const handler = apiToHandler(ApiLive);
+
+export const POST = handler;