nearform / fast-jwt

Fast JSON Web Token implementation

Home Page:https://nearform.github.io/fast-jwt/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Change in signer return type on changing key from string to function was surprising

autopulated opened this issue · comments

I don't know if this is really a bug, feature request, or just something for documentation:

The return type of the signer function changes based on whether the key argument to the signer is a function or a string, and this caught me out - the returned promise happily serialises as a string, and I only noticed when trying to verify the resulting "[object Promise]" string as a token..

Maybe it would be safer to have a separate createAsyncSigner (which always returns a function returning a promise, regardless of whether key is supplied as a string)?

If you are using callbacks instead of promises this is ok, because the signer does not accept a callback unless key is a function, so this problem is limited to using promises.

(I was actually using this module via fastify-jwt, and the change in return value leaks through that API as well)

hi @autopulated, this is already covered in the README

The signer is a function which accepts a payload and returns the token.

The payload must be an object.

If the key option is a function, the signer will also accept a Node style callback and will return a promise, supporting therefore both callback and async/await styles.

There's also a code sample there that demonstrates the same thing:

// Sync style
const signSync = createSigner({ key: 'secret' })
const token = signSync({ a: 1, b: 2, c: 3 })
// => eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJjIjozLCJpYXQiOjE1Nzk1MjEyMTJ9.mIcxteEVjbh2MnKQ3EQlojZojGSyA_guqRBYHQURcfnCSSBTT2OShF8lo9_ogjAv-5oECgmCur_cDWB7x3X53g

// Callback style
const signWithCallback = createSigner({ key: (callback) => callback(null, 'secret') })

signWithCallback({ a: 1, b: 2, c: 3 }, (err, token) => {
  // token === eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJjIjozLCJpYXQiOjE1Nzk1MjEyMTJ9.mIcxteEVjbh2MnKQ3EQlojZojGSyA_guqRBYHQURcfnCSSBTT2OShF8lo9_ogjAv-5oECgmCur_cDWB7x3X53g
})

// Promise style - Note that the key function style and the signer function style are unrelated
async function test() {
  const signWithPromise = createSigner({ key: async () => 'secret' })

  const token = await signWithPromise({ a: 1, b: 2, c: 3 })
  // => eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhIjoxLCJiIjoyLCJjIjozLCJpYXQiOjE1Nzk1MjEyMTJ9.mIcxteEVjbh2MnKQ3EQlojZojGSyA_guqRBYHQURcfnCSSBTT2OShF8lo9_ogjAv-5oECgmCur_cDWB7x3X53g
}