upstash / qstash-js

Message queue for serverless
https://docs.upstash.com/qstash
MIT License
135 stars 12 forks source link

Unable to signatures for message outside the UI #15

Closed antoniomdk closed 1 year ago

antoniomdk commented 1 year ago

Hi,

I've been trying to verify the signature using a custom express middleware for next-connect. The problem is that if I send a request through the QStash UI it works fine, but if I try to schedule it from code, the signature verification fails. This is my current code:

import { Receiver } from "@upstash/qstash";
import Boom from '@hapi/boom'
import { json, buffer } from 'micro';

export const verifySignature = async (req: AuthenticatedRequest, res: NextApiResponse, next: () => Promise<void>) => {
  let isValid = false

  const signature = req.headers['upstash-signature'] as string
  const body = await buffer(req)

  try {
    isValid = await qstashReceiver.verify({ signature, body })
  } catch {}

  if (!isValid) {
    throw Boom.unauthorized()
  }

  try {
    if (req.headers["content-type"] === "application/json") {
      req.body = await json(req)
    } else {
      req.body = body
    }
  } catch {
    req.body = body
  }

  await next()
}

Basically, I have an endpoint that is called on a schedule from QStash and that same endpoint schedules several other tasks:

  const alertTasks = alertIds.map(id => client.publishJSON({
    url: `${HOST}/api/v1/queue/checkUserAlert`,
    body: {
      alertId: id
    }
  }))

But the secondary checkUserAlert endpoint is unable to verify the signature although both endpoints use the same middleware.

Any suggestion?

Thanks in advance

chronark commented 1 year ago

I'll check in an hour. But I'm pretty sure it's a body format thing. Maybe an added newline or something.

Our UI calls the same Api as you do

What's your error message?

antoniomdk commented 1 year ago

Hi @chronark,

I really appreciate the quick reply. I just found it was a QSTASH_TOKEN issue, I had a old token, so QStash was generating a wrong signature. It is working fine now!

I'm closing this issue.

Thanks a lot!