Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

verify the request signature

Kiran Kf9b9e23b2ad3
diff --git a/apps/web/.env.example b/apps/web/.env.example
index f8333b77a5..c9a3e622fc 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -118,4 +118,5 @@ PANGEA_API_KEY=
# Slack integration
SLACK_APP_INSTALL_URL=
SLACK_CLIENT_ID=
-SLACK_CLIENT_SECRET=
\ No newline at end of file
+SLACK_CLIENT_SECRET=
+SLACK_SIGNING_SECRET=
\ No newline at end of file
diff --git a/apps/web/lib/integrations/slack/env.ts b/apps/web/lib/integrations/slack/env.ts
index 420b451533..c5511a2117 100644
--- a/apps/web/lib/integrations/slack/env.ts
+++ b/apps/web/lib/integrations/slack/env.ts
@@ -4,16 +4,27 @@ export const envSchema = z.object({
SLACK_APP_INSTALL_URL: z.string(),
SLACK_CLIENT_ID: z.string(),
SLACK_CLIENT_SECRET: z.string(),
+ SLACK_SIGNING_SECRET: z.string(),
});
+type SlackEnv = z.infer<typeof envSchema>;
+
+let env: SlackEnv | undefined;
+
export const getSlackEnv = () => {
- const env = envSchema.safeParse(process.env);
+ if (env) {
+ return env;
+ }
- if (!env.success) {
+ const parsed = envSchema.safeParse(process.env);
+
+ if (!parsed.success) {
throw new Error(
"Slack app environment variables are not configured properly.",
);
}
- return env.data;
+ env = parsed.data;
+
+ return env;
};
diff --git a/apps/web/lib/integrations/slack/slash-commands.ts b/apps/web/lib/integrations/slack/slash-commands.ts
index e87bb37f13..2f65ea866f 100644
--- a/apps/web/lib/integrations/slack/slash-commands.ts
+++ b/apps/web/lib/integrations/slack/slash-commands.ts
@@ -4,6 +4,7 @@ import { WorkspaceProps } from "@/lib/types";
import z from "@/lib/zod";
import { createLinkBodySchema } from "@/lib/zod/schemas/links";
import { InstalledIntegration } from "@prisma/client";
+import { verifySlackSignature } from "./verify-request";
const schema = z.object({
api_app_id: z.string(),
@@ -16,9 +17,13 @@ const schema = z.object({
export const handleSlashCommand = async (
req: Request,
): Promise<{ text: string }> => {
- const formData = await req.formData();
- const rawFormData = Object.fromEntries(formData.entries());
- const parsedInput = schema.safeParse(rawFormData);
+ const body = await req.text();
+
+ await verifySlackSignature(req, body);
+
+ const rawFormData = new URLSearchParams(body);
+ const formData = Object.fromEntries(rawFormData.entries());
+ const parsedInput = schema.safeParse(formData);
if (!parsedInput.success) {
return {
diff --git a/apps/web/lib/integrations/slack/uninstall.ts b/apps/web/lib/integrations/slack/uninstall.ts
index 6d935afbf1..fd270b084a 100644
--- a/apps/web/lib/integrations/slack/uninstall.ts
+++ b/apps/web/lib/integrations/slack/uninstall.ts
@@ -19,7 +19,7 @@ export const uninstallSlackIntegration = async ({
},
body: new URLSearchParams({
token: credentials.accessToken,
- client_id: env.SLACK_CLIENT_SECRET,
+ client_id: env.SLACK_CLIENT_ID,
client_secret: env.SLACK_CLIENT_SECRET,
}),
});
@@ -27,6 +27,8 @@ export const uninstallSlackIntegration = async ({
const data = await response.json();
if (!data.ok) {
+ console.error("[Slack App]", data);
+
throw new DubApiError({
code: "bad_request",
message: "Failed to remove the app from the Slack workspace.",
diff --git a/apps/web/lib/integrations/slack/verify-request.ts b/apps/web/lib/integrations/slack/verify-request.ts
new file mode 100644
index 0000000000..19f39f6a63
--- /dev/null
+++ b/apps/web/lib/integrations/slack/verify-request.ts
@@ -0,0 +1,68 @@
+import { createHmac } from "crypto";
+import { getSlackEnv } from "./env";
+
+interface SlackRequestVerificationOptions {
+ signingSecret: string;
+ body: string;
+ nowMilliseconds?: number;
+ headers: {
+ "x-slack-signature": string;
+ "x-slack-request-timestamp": number;
+ };
+}
+
+// Verifies the signature of an incoming request from Slack.
+export const verifySlackSignature = async (req: Request, body: string) => {
+ const env = getSlackEnv();
+
+ const options: SlackRequestVerificationOptions = {
+ signingSecret: env.SLACK_SIGNING_SECRET,
+ body: body,
+ headers: {
+ "x-slack-signature": req.headers.get("x-slack-signature") ?? "",
+ "x-slack-request-timestamp": Number(
+ req.headers.get("x-slack-request-timestamp"),
+ ),
+ },
+ };
+
+ const verifyErrorPrefix = "Failed to verify authenticity";
+ const requestTimestampSec = options.headers["x-slack-request-timestamp"];
+ const signature = options.headers["x-slack-signature"];
+
+ if (Number.isNaN(requestTimestampSec)) {
+ throw new Error(
+ `${verifyErrorPrefix}: header x-slack-request-timestamp did not have the expected type (${requestTimestampSec})`,
+ );
+ }
+
+ // Calculate time-dependent values
+ const nowMs = options.nowMilliseconds ?? Date.now();
+ const requestTimestampMaxDeltaMin = 5;
+ const fiveMinutesAgoSec =
+ Math.floor(nowMs / 1000) - 60 * requestTimestampMaxDeltaMin;
+
+ // Rule 1: Check staleness
+ if (requestTimestampSec < fiveMinutesAgoSec) {
+ throw new Error(
+ `${verifyErrorPrefix}: x-slack-request-timestamp must differ from system time by no more than ${requestTimestampMaxDeltaMin} minutes or request is stale`,
+ );
+ }
+
+ // Rule 2: Check signature
+ const [signatureVersion, signatureHash] = signature.split("=");
+
+ // Only handle known versions
+ if (signatureVersion !== "v0") {
+ throw new Error(`${verifyErrorPrefix}: unknown signature version`);
+ }
+
+ // Compute our own signature hash
+ const hmac = createHmac("sha256", options.signingSecret);
+ hmac.update(`${signatureVersion}:${requestTimestampSec}:${options.body}`);
+ const expectedSignature = hmac.digest("hex");
+
+ if (!signatureHash || signatureHash !== expectedSignature) {
+ throw new Error(`${verifyErrorPrefix}: signature mismatch`);
+ }
+};