0

我正在为 subs 集成 Twitch API,并且在获取对中间件函数的 webhook 回调响应时遇到问题,它应该检查标头并验证签名。

我收到了正确的回应!然而,它就停在那里!我检查了路线的顺序,但我不确定我错过了什么

我正在关注https://dev.twitch.tv/docs/eventsub

app.post('/createWebhook/:broadcasterId', (req, res) => {
  const createWebHookParams = {
    host: "api.twitch.tv",
    path: "helix/eventsub/subscriptions",
    method: 'POST',
    headers: {
      "Content-Type": "application/json",
      "Client-ID": clientId,
      "Authorization": "Bearer " + authToken
    }
  }

  const createWebHookBody = {
    "type": "channel.follow",
    "version": "1",
    "condition": {
      "broadcaster_user_id": req.params.broadcasterId
    },
    "transport": {
      "method": "webhook",
      "callback": "ngrokURL/notification",
      "secret": webhookSecret // 
    }
  }

  let responseData = ""
  const webhookReq = https.request(createWebHookParams, (result) => {
    result.setEncoding('utf8')
    result.on('data', (d) => {
        responseData = responseData + d
      })
      .on('end', (result) => {
        const responseBody = JSON.parse(responseData) // json
        console.log(responseBody)
        res.send(responseBody)
      })
  })
  webhookReq.on('error', (e) => {
    console.log("Error")
  })

  webhookReq.write(JSON.stringify(createWebHookBody))
  webhookReq.end()

});

// middlewsre ---> // not triggered!!!

app.use(express.json({
  verify: verifyTwitchSignature
}));

// making post to receeive the notification.

app.post('/notification', (req, res) => {
  console.log("incoming notificatin", req.body)
  
  res.status(200).end();
})


// the middleware verifing the signature
const crypto = require("crypto");

const twitchSigningSecret = process.env.SECRET;

const verifyTwitchSignature = (req, res, buf, encoding)=>{
const messageId = req.header("Twitch-Eventsub-Message-Id");
const timeStamp = req.header("Twitch-Eventsub-Message-Timestamp")
const messageSignature = req.header("Twitch-Eventsub-Message-Signature")

console.log(`Message ${messageId} Signature: `,messageSignature)


if (!twitchSigningSecret){
  console.log(`Twitch signing secret is empty`);
  throw new Error ("Twitch signing secret is empty.");

}


const computedSignature = "sha256=" + crypto.createHmac("sha256", twitchSigningSecret).update(messageId + timeStamp + buf).digist("hex");
console.log(`Message ${messageId} Computed Signature: `, computedSignature)

if (messageSignature !== computedSignature) {
  throw new Error("Invalid Signature.");
}else {
  
  console.log("Verification Successful");
}

}

module.exports = verifyTwitchSignature
4

1 回答 1

0

我相信您的verifyTwitchSignature函数需要next作为参数之一传递,并且在传递 call 时需要在 else 语句中传递next();

这是我的观察。

如果您正在使用中间件,则始终必须与和next一起传递。是调用队列中的下一个中间件或函数。reqresnext

于 2021-04-03T21:16:37.313 回答