tsndr / cloudflare-worker-jwt

A lightweight JWT implementation with ZERO dependencies for Cloudflare Workers.
MIT License
649 stars 51 forks source link

Unable to use RSA 512 key pair #44

Closed roguesherlock closed 11 months ago

roguesherlock commented 11 months ago

Hey so I've a simple nextjs app where I want to sign/verify jwt in the middleware as well as during request phase. I am trying to use RS512 to sign/verify tokens but it seems like it's not supported in node.js ? Can you help me debug this? Thanks!,

DOMException [NotSupportedError]: Unable to import RSA key with format raw
    at new DOMException (node:internal/per_context/domexception:53:5)
    at __node_internal_ (node:internal/util:663:10)
    at Object.rsaImportKey (node:internal/crypto/rsa:287:13)
    at SubtleCrypto.importKey (node:internal/crypto/webcrypto:616:10)
    at Object.sign (webpack-internal:///(action-browser)/./node_modules/.pnpm/@tsndr+cloudflare-worker-jwt@2.2.5/node_modules/@tsndr/cloudflare-worker-jwt/index.js:154:37)
    at Object.create (webpack-internal:///(action-browser)/./app/lib/auth/session.ts:55:94)
    at login (webpack-internal:///(action-browser)/./app/(auth)/login/actions.ts:27:60)

Can you help me debug this?

Here's what my session file looks like,

/**
 * Creates a new session token with provided information
 *
 * @example
 * ```js
 * Session.create({
 *   type: "user",
 *   properties: {
 *     userID: "123"
 *   }
 * })
 * ```
 */
async function create<T extends keyof SessionTypes>(input: {
  type: T
  properties: SessionTypes[T]
  options?: Partial<JwtPayload>
}) {
  const secret = env.AUTH_PRIVATE_KEY
  const token = await jwt.sign(
    {
      ...input.options,
      type: input.type,
      properties: input.properties,
    },
    secret,
    { algorithm: "RS512" },
  )
  cookies().set("auth_token", token)
  return token as string
}

/**
 * Verifies a session token and returns the session data
 *
 * @example
 * ```js
 * Session.verify()
 * ```
 */
async function verify<T = SessionValue>(token: string) {
  if (token) {
    try {
      const isValid = await jwt.verify(token, env.AUTH_PUBLIC_KEY, {
        algorithm: "RS512",
      })
      if (!isValid) throw new Error("Invalid token")
      const { payload } = jwt.decode(token)
      return payload as T
    } catch (e) {}
  }
  return {
    type: "public",
    properties: {},
  }
}
roguesherlock commented 11 months ago

Sorry my bad, I was setting the environment incorrectly! The key was incomplete. I've now fixed it and it seems to be working!

roguesherlock commented 11 months ago

Sorry actually I'm getting this error during verify now,

 [TypeError: Failed to execute 'importKey' on 'SubtleCrypto': 2nd argument is not instance of ArrayBuffer, Buffer, TypedArray, or DataView.] {
  code: 'ERR_INVALID_ARG_TYPE'
}
tsndr commented 11 months ago

Are you sure that env.AUTH_PUBLIC_KEY is defined?

roguesherlock commented 11 months ago

Are you sure that env.AUTH_PUBLIC_KEY is defined?

Yep. I specifically double checked that it had the correct value. I also use a library that'll fail during bundling if the env isn't specified.

roguesherlock commented 11 months ago

I did some debugging and it looks like it's getting the key as well as converting to array buffer I think. still not sure what goes wrong, Here's some output,

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmQmGcpQpL1achUFUTsUo
QKDj39LTdyk71eaB2ECiVRJH5jB76ZPQNZBWfyTcL/aK4iQc23osXcU0o/RqXGGY
gb1VpsLOYx5xqTyj9gjmEJcRNf/8Ebp0ZZP+Quk55bgFT76/WwVE6sE9dMZ/3t4o
r5HrypjnboWTe2ga0pf9opqHoVO0HPX9H2HjqLiM04GCueP1i60/gZMNFuC/8FL3
TZRbJABKKxZ1r1Y3V0M8L1SB+8NhCiVONl6Z7rW4jazNy5iOGgWNhPwjgeDE3pgx
W3yGwwHX1DfJijLZQc1191uv20mUB80AwhxHsErpxcTmWaaCYLJy6sVS+uBybXjw
ewIDAQAB
-----END PUBLIC KEY-----
‚0‚b 0‚"*†H†÷
à¿ðR÷M”[$J+u¯V7WC</TûÃaßÒÓw);ÕæØ@¢UGæ0{é“Ð5V$Ü/öŠâ$Ûz,]Å4£ôj\a˜½U¦ÂÎcq©<£æ—5ÿüºte“þBé9å¸O¾¿[DêÁ=tÆÞÞ(¯‘ëʘçn…“{hҗý¢š‡¡S´õýa㨸ŒÓ‚¹ãõ‹?“
%N6^™îµ¸¬Í˘Ž„ü#àÄޘ1[|†Ã×Ô7Ɋ2ÙAÍu÷[¯ÛI”ÍÂG°JéÅÄæY¦‚`²rêÅRúàrmxð{
bufView Uint8Array(294) [
  48,
  130,
  1,
  34,
  48,
  13,
  6,
  9,
  42,
  134,
  72,
  134,
  247,
  13,
  1,
  1,
  1,
  5,
  0,
  3,
  130,
  1,
  15,
  0,
  48,
  130,
  1,
  10,
  2,
  130,
  1,
  1,
  0,
  153,
  9,
  134,
  114,
  148,
  41,
  47,
  86,
  156,
  133,
  65,
  84,
  78,
  197,
  40,
  64,
  160,
  227,
  223,
  210,
  211,
  119,
  41,
  59,
  213,
  230,
  129,
  216,
  64,
  162,
  85,
  18,
  71,
  230,
  48,
  123,
  233,
  147,
  208,
  53,
  144,
  86,
  127,
  36,
  220,
  47,
  246,
  138,
  226,
  36,
  28,
  219,
  122,
  44,
  93,
  197,
  52,
  163,
  244,
  106,
  92,
  97,
  152,
  129,
  189,
  85,
  166,
  194,
  206,
  99,
  30,
  113,
  169,
  60,
  163,
  246,
  8,
  230,
  16,
  151,
  17,
  53,
  255,
  252,
  17,
  186,
  116,
  101,
  147,
  254,
  66,
  233,
  57,
  229,
  184,
  5,
  79,
  190,
  191,
  91,
  5,
  68,
  234,
  193,
  61,
  116,
  198,
  127,
  222,
  222,
  40,
  175,
  145,
  235,
  202,
  152,
  231,
  110,
  133,
  147,
  123,
  104,
  26,
  210,
  151,
  253,
  162,
  154,
  135,
  161,
  83,
  180,
  28,
  245,
  253,
  31,
  97,
  227,
  168,
  184,
  140,
  211,
  129,
  130,
  185,
  227,
  245,
  139,
  173,
  63,
  129,
  147,
  13,
  22,
  224,
  191,
  240,
  82,
  247,
  77,
  148,
  91,
  36,
  0,
  74,
  43,
  22,
  117,
  175,
  86,
  55,
  87,
  67,
  60,
  47,
  84,
  129,
  251,
  195,
  97,
  10,
  37,
  78,
  54,
  94,
  153,
  238,
  181,
  184,
  141,
  172,
  205,
  203,
  152,
  142,
  26,
  5,
  141,
  132,
  252,
  35,
  129,
  224,
  196,
  222,
  152,
  49,
  91,
  124,
  134,
  195,
  1,
  215,
  212,
  55,
  201,
  138,
  50,
  217,
  65,
  205,
  117,
  247,
  91,
  175,
  219,
  73,
  148,
  7,
  205,
  0,
  194,
  28,
  71,
  176,
  74,
  233,
  197,
  196,
  230,
  89,
  166,
  130,
  96,
  178,
  114,
  234,
  197,
  82,
  250,
  224,
  114,
  109,
  120,
  240,
  123,
  2,
  3,
  1,
  0,
  1
]
buf ArrayBuffer {  }
keyData ArrayBuffer {  }
typeof keyData object
 [TypeError: Failed to execute 'importKey' on 'SubtleCrypto': 2nd argument is not instance of ArrayBuffer, Buffer, TypedArray, or DataView.] {
  code: 'ERR_INVALID_ARG_TYPE'
}
roguesherlock commented 11 months ago

Hey I had to use encryption for the token so I had to switch to another library for now. I think we're good with this. Thanks!