2022-05-03 23:40:01 +00:00
|
|
|
import { createHmac } from "crypto";
|
2022-06-28 20:40:58 +00:00
|
|
|
import dayjs from "@calcom/dayjs";
|
2022-05-03 23:40:01 +00:00
|
|
|
import { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
import { stringify } from "querystring";
|
|
|
|
|
2022-06-11 21:30:52 +00:00
|
|
|
import { getSlackAppKeys } from "./utils";
|
2022-05-03 23:40:01 +00:00
|
|
|
|
|
|
|
export default async function slackVerify(req: NextApiRequest, res: NextApiResponse) {
|
|
|
|
const timeStamp = req.headers["x-slack-request-timestamp"] as string; // Always returns a string and not a string[]
|
|
|
|
const slackSignature = req.headers["x-slack-signature"] as string;
|
|
|
|
const currentTime = dayjs().unix();
|
2022-06-11 21:30:52 +00:00
|
|
|
const { signing_secret: signingSecret } = await getSlackAppKeys();
|
|
|
|
const [version, hash] = slackSignature.split("=");
|
2022-05-03 23:40:01 +00:00
|
|
|
|
|
|
|
if (!timeStamp) {
|
|
|
|
return res.status(400).json({ message: "Missing X-Slack-Request-Timestamp header" });
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!signingSecret) {
|
|
|
|
return res.status(400).json({ message: "Missing Slack's signing_secret" });
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Math.abs(currentTime - parseInt(timeStamp)) > 60 * 5) {
|
|
|
|
return res.status(400).json({ message: "Request is too old" });
|
|
|
|
}
|
|
|
|
|
2022-06-11 21:30:52 +00:00
|
|
|
const hmac = createHmac("sha256", signingSecret);
|
|
|
|
|
|
|
|
hmac.update(`${version}:${timeStamp}:${stringify(req.body)}`);
|
2022-05-03 23:40:01 +00:00
|
|
|
|
2022-06-11 21:30:52 +00:00
|
|
|
const signed_sig = hmac.digest("hex");
|
|
|
|
console.log({ signed_sig, hash, match: signed_sig === hash });
|
|
|
|
if (signed_sig !== hash) {
|
|
|
|
throw new Error("Hashes do not match ");
|
2022-05-03 23:40:01 +00:00
|
|
|
}
|
|
|
|
}
|