Skip to content

Jose 6.x does not work in Cloudflare Worker #765

@tripodsan

Description

@tripodsan

What happened?

Exporting a key in a cloudflare worker causes problems with the CF provided crypto classes:

TypeError: Key must be one of type CryptoKey, KeyObject, or Uint8Array. Received an instance of CryptoKey
    at keyToJWK (index.js:97:11)
    at exportJWK (index.js:107:10)
    at Object.handleRequest [as fetch] (index.js:204:29)

(see example below)

the problem seems to be this check:

function isCryptoKey(key) {
  return key?.[Symbol.toStringTag] === "CryptoKey";
}

this returns CryptoKey in NodeJS, but undefined in the worker.
I think this is mainly problem of the provided crypto library of cloudflare.

maybe this can be improved to also check actual.constructor?.name ?

for example:

function isCryptoKey(key) {
  return (key?.[Symbol.toStringTag] ?? key.constructor?.name) === "CryptoKey";
}

Version

6.0.8

Runtime

Cloudflare Workers

Runtime Details

compatibility 2024-03-21

Code to reproduce

import { exportJWK, generateKeyPair } from 'jose';

const handleRequest = async (req, env/* , ctx */) => {
  try {
    const keyPair = await generateKeyPair('RS256', { extractable: true });
    const publicKey = await exportJWK(keyPair.publicKey);

    return new Response(publicKey, {
      status: 200,
    });
  } catch (err) {
    console.error(err);
    return new Response(err.stack, { status: 500 });
  }
};

export default {
  fetch: handleRequest,
};

Required

  • I have searched the issues tracker and discussions for similar topics and couldn't find anything related.
  • I agree to follow this project's Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions