jose

repository·main·Indexed 27 days ago

https://github.com/panva/jose

A lightweight, zero-dependency JavaScript library for implementing JSON Object Signing and Encryption (JOSE) standards, including JWA, JWS, JWE, JWT, JWK, and JWKS. It is designed for universal use across Node.js, browsers, and web-interoperable runtimes such as Cloudflare Workers, Deno, and Bun.

Tokens
41.1K
Snippets
44
Records
306
Agent score
92%

What's inside jose

  1. Overview of jose capabilities

    main

    The jose module provides comprehensive support for the following JOSE (JSON Object Signing and Encryption) standards:

    • JSON Web Tokens (JWT): Signing, verifying, and claims set validation.
    • JSON Web Encryption (JWE): Encrypting and decrypting tokens.
    • JSON Web Signature (JWS): Signing and verifying messages with arbitrary payloads in Compact, Flattened JSON, and General JSON formats.
    • JSON Web Encryption (JWE): Encrypting and decrypting messages in Compact, Flattened JSON, and General JSON formats.
    • Key Management: Importing, exporting, and generating keys (JWK, SPKI, X.509, PKCS #8) and secrets.
    • JSON Web Key (JWK): Thumbprint and thumbprint URI calculations.
  2. Import cryptographic keys using jose

    main
    The jose library provides several functions to import cryptographic keys from various formats into a CryptoKey (Web Crypto API) or KeyObject (Node.js crypto module) format. This allows you to use keys for signing, verifying, encrypting, or decrypting operations within the library.
  3. Use Unsecured JSON Web Tokens (JWT)

    main
    Unsecured JWTs are JSON Web Tokens that are neither signed nor encrypted. They consist only of a header and a payload, with no signature to verify authenticity. Use the UnsecuredJWT class to create or work with these tokens when security (integrity and confidentiality) is not required.
  4. Use Base64URL encoding and decoding utilities

    main
    The util/base64url module provides functions for encoding data into Base64URL format and decoding Base64URL strings back into their original form. This is useful for handling data in formats required by JOSE (JSON Object Signing and Encryption) specifications.
  5. Explore jose type definitions

    main
    The jose library provides comprehensive TypeScript definitions for all its core concepts, including JSON Web Keys (JWK), JSON Web Signatures (JWS), JSON Web Encryption (JWE), and JSON Web Tokens (JWT). You can explore these types to understand the structure of headers, payloads, and options required for cryptographic operations.
  6. Export cryptographic keys to JWK, PKCS#8, or SPKI formats

    main

    The jose library provides utility functions to export cryptographic keys into standard formats:

    • JWK (JSON Web Key): Use exportJWK to export a key as a JSON object following the RFC 7517 specification.
    • PKCS#8: Use exportPKCS8 to export a private key in the PKCS#8 format (typically used for private keys).
    • SPKI (Subject Public Key Info): Use exportSPKI to export a public key in the SPKI format (typically used for public keys).

    These functions are used to transform internal cryptographic key objects into portable, standardized formats for storage or transmission.

  7. Use the UnsecuredJWT class

    main

    The UnsecuredJWT class is a utility for creating and decoding Unsecured JWTs (JSON Web Tokens with { "alg": "none" }). It can be imported from the main 'jose' module or the subpath 'jose/jwt/unsecured'.

    // Encoding
    const unsecuredJwt = new jose.UnsecuredJWT({ 'urn:example:claim': true })
      .setIssuedAt()
      .setIssuer('urn:example:issuer')
      .setAudience('urn:example:audience')
      .setExpirationTime('2h')
      .encode()
    
    console.log(unsecuredJwt)
    
    // Decoding
    const payload = jose.UnsecuredJWT.decode(unsecuredJwt, {
      issuer: 'urn:example:issuer',
      audience: 'urn:example:audience',
    })
    
    console.log(payload)
  8. Generate symmetric keys with generateSecret()

    main

    Use the generateSecret function to create a cryptographically strong symmetric key. This is useful for algorithms like HMAC (used in JWT signing) or AES (used in JWE encryption).

    Refer to the GenerateSecretOptions interface for configuration details.

  9. Sign JSON Web Signature (JWS) using Flattened JSON Serialization

    main
    You can sign JSON Web Signatures (JWS) using the Flattened JSON Serialization format by using the FlattenedSign class. This format is useful when you want to represent the JWS components (header, payload, and signature) as separate fields in a JSON object rather than a single compact string.
  10. Handle multiple matching keys in createRemoteJWKSet()

    main

    By default, createRemoteJWKSet() expects only a single public key to match the selection process. If multiple keys match, it may throw an error with the code ERR_JWKS_MULTIPLE_MATCHING_KEYS.

    You can opt-in to an iterative verification approach by catching this specific error and iterating over the matched keys provided by the error object.

    const options = {
      issuer: 'urn:example:issuer',
      audience: 'urn:example:audience',
    }
    const { payload, protectedHeader } = await jose
      .jwtVerify(jwt, JWKS, options)
      .catch(async (error) => {
        if (error?.code === 'ERR_JWKS_MULTIPLE_MATCHING_KEYS') {
          for await (const publicKey of error) {
            try {
              return await jose.jwtVerify(jwt, publicKey, options)
            } catch (innerError) {
              if (innerError?.code === 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED') {
                continue
              }
              throw innerError
            }
          }
          throw new jose.errors.JWSSignatureVerificationFailed()
        }
    
        throw error
      })
    console.log(protectedHeader)
    console.log(payload)
  11. Encrypt data using FlattenedEncrypt

    main

    The FlattenedEncrypt class is used to build and encrypt Flattened JWE (JSON Web Encryption) objects. It can be imported from the main 'jose' module or from the subpath 'jose/jwe/flattened/encrypt'.

    To use it, instantiate the class with a Uint8Array representing your plaintext, configure the headers and additional authenticated data (AAD) using the provided setter methods, and finally call .encrypt(key) with the appropriate encryption key.

    const jwe = await new jose.FlattenedEncrypt(
      new TextEncoder().encode('It\u2019s a dangerous business, Frodo, going out your door.'),
    )
      .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM' })
      .setAdditionalAuthenticatedData(encoder.encode('The Fellowship of the Ring'))
      .encrypt(publicKey)
    
    console.log(jwe)
  12. Verify a JWS using a JWK embedded in the header

    main
    The EmbeddedJWK utility allows for the verification of a JSON Web Signature (JWS) when the required JSON Web Key (JWK) is provided directly within the JWS header itself. This is useful for scenarios where the key is part of the message payload.