import { ServerResponse } from "http" ; import { IncomingMessage } from "http" ; import crypto from "crypto" ; import { SLACK_SIGNING_SECRET } from "../util/secrets" ; import { WebClient } from "@slack/web-api" ; import { UserModel } from "../models/UserModel" ; import { OrganizationInterface } from "../../types/organization" ; const web = new WebClient ( ) ; export function verifySlackRequestSignature ( req , res , buf ) { console . log ( req . headers ) ; const rawTimestamp = req . headers [ "x-slack-request-timestamp" ] ; if ( ! rawTimestamp || typeof rawTimestamp !== "string" ) { throw new Error ( "Missing or Invalid timestamp" ) ; } const timestamp = parseInt ( rawTimestamp ) ; if ( Math . abs ( timestamp - Date . now ( ) / 1000 ) > 60 * 5 ) { throw new Error ( "Invalid timestamp" ) ; } const str = "v0:" + timestamp + ":" + buf . toString ( ) ; const sig = "v0=" + crypto . createHmac ( "sha256" , SLACK_SIGNING_SECRET ) . update ( str ) . digest ( "hex" ) ; const slackSignature = req . headers [ "x-slack-signature" ] as string ; if ( ! crypto . timingSafeEqual ( Buffer . from ( sig ) , Buffer . from ( slackSignature ) ) ) { throw new Error ( "Signatures do not match" ) ; } } export async function getUserInfoBySlackId ( slackUserId , organization ) { try { const res = await web . users . info ( { token : organization ?. connections ?. slack ?. token , user : slackUserId , } ) ; const slackUser = res . user as { real_name ? : string ; profile ? : { email ? : string ; } ; } ; const email = slackUser ?. profile ?. email ; let id = null ; if ( email ) { const user = await UserModel . findOne ( { email } ) ; if ( user ) { if ( organization . members . map ( ( m ) => m . id ) . includes ( user . id ) ) { id = user . id ; } } } return { id , name : slackUser . real_name || null , } ; } catch ( e ) { return { id : null , name : null , } ; } } export function formatTextResponse ( markdown ) { return { text : markdown , mrkdwn : true , } ; }