diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8184a4e313..513b565716 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,13 @@
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
+## [6.0.1](https://github.com/panva/jose/compare/v6.0.0...v6.0.1) (2025-02-22)
+
+
+### Fixes
+
+* **types:** update build to include extensions in type imports ([9b96672](https://github.com/panva/jose/commit/9b96672ef79aabf07699e0ccafa5b54380f6330c))
+
## [6.0.0](https://github.com/panva/jose/compare/v5.10.0...v6.0.0) (2025-02-22)
diff --git a/dist/deno/README.md b/dist/deno/README.md
new file mode 100644
index 0000000000..52498baa85
--- /dev/null
+++ b/dist/deno/README.md
@@ -0,0 +1,96 @@
+# `jose` API Documentation
+
+`jose` is JavaScript module for JSON Object Signing and Encryption, providing support for JSON Web Tokens (JWT), JSON Web Signature (JWS), JSON Web Encryption (JWE), JSON Web Key (JWK), JSON Web Key Set (JWKS), and more. The module is designed to work across various Web-interoperable runtimes including Node.js, browsers, Cloudflare Workers, Deno, Bun, and others.
+
+## Sponsor
+
+
+
+
+
+
+
+If you want to quickly add JWT authentication to JavaScript apps, feel free to check out Auth0's JavaScript SDK and free plan. [Create an Auth0 account; it's free!][sponsor-auth0]
+
+## [💗 Help the project](https://github.com/sponsors/panva)
+
+Support from the community to continue maintaining and improving this module is welcome. If you find the module useful, please consider supporting the project by [becoming a sponsor](https://github.com/sponsors/panva).
+
+## Available modules
+
+**`example`** Deno import
+```js
+import * as jose from 'https://deno.land/x/jose@v6.0.1/index.ts'
+```
+
+### JSON Web Tokens (JWT)
+
+The `jose` module supports JSON Web Tokens (JWT) and provides functionality for signing and verifying tokens, as well as their JWT Claims Set validation.
+
+- [JWT Claims Set Validation & Signature Verification](https://github.com/panva/jose/blob/v6.0.1/docs/jwt/verify/functions/jwtVerify.md) using the `jwtVerify` function
+ - [Using a remote JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v6.0.1/docs/jwks/remote/functions/createRemoteJWKSet.md)
+ - [Using a local JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v6.0.1/docs/jwks/local/functions/createLocalJWKSet.md)
+- [Signing](https://github.com/panva/jose/blob/v6.0.1/docs/jwt/sign/classes/SignJWT.md) using the `SignJWT` class
+- Utility functions
+ - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v6.0.1/docs/util/decode_protected_header/functions/decodeProtectedHeader.md)
+ - [Decoding JWT Claims Set](https://github.com/panva/jose/blob/v6.0.1/docs/util/decode_jwt/functions/decodeJwt.md) prior to its validation
+
+### Encrypted JSON Web Tokens
+
+The `jose` module supports encrypted JSON Web Tokens and provides functionality for encrypting and decrypting tokens, as well as their JWT Claims Set validation.
+
+- [Decryption & JWT Claims Set Validation](https://github.com/panva/jose/blob/v6.0.1/docs/jwt/decrypt/functions/jwtDecrypt.md) using the `jwtDecrypt` function
+- [Encryption](https://github.com/panva/jose/blob/v6.0.1/docs/jwt/encrypt/classes/EncryptJWT.md) using the `EncryptJWT` class
+- Utility functions
+ - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v6.0.1/docs/util/decode_protected_header/functions/decodeProtectedHeader.md)
+
+### Key Utilities
+
+The `jose` module supports importing, exporting, and generating keys and secrets in various formats, including PEM formats like SPKI, X.509 certificate, and PKCS #8, as well as JSON Web Key (JWK).
+
+- Key Import Functions
+ - [JWK Import](https://github.com/panva/jose/blob/v6.0.1/docs/key/import/functions/importJWK.md)
+ - [Public Key Import (SPKI)](https://github.com/panva/jose/blob/v6.0.1/docs/key/import/functions/importSPKI.md)
+ - [Public Key Import (X.509 Certificate)](https://github.com/panva/jose/blob/v6.0.1/docs/key/import/functions/importX509.md)
+ - [Private Key Import (PKCS #8)](https://github.com/panva/jose/blob/v6.0.1/docs/key/import/functions/importPKCS8.md)
+- Key and Secret Generation Functions
+ - [Asymmetric Key Pair Generation](https://github.com/panva/jose/blob/v6.0.1/docs/key/generate_key_pair/functions/generateKeyPair.md)
+ - [Symmetric Secret Generation](https://github.com/panva/jose/blob/v6.0.1/docs/key/generate_secret/functions/generateSecret.md)
+- Key Export Functions
+ - [JWK Export](https://github.com/panva/jose/blob/v6.0.1/docs/key/export/functions/exportJWK.md)
+ - [Private Key Export](https://github.com/panva/jose/blob/v6.0.1/docs/dkey/export/functions/exportPKCS8.md)
+ - [Public Key Export](https://github.com/panva/jose/blob/v6.0.1/docs/dkey/export/functions/exportSPKI.md)
+
+### JSON Web Signature (JWS)
+
+The `jose` module supports signing and verification of JWS messages with arbitrary payloads in Compact, Flattened JSON, and General JSON serialization syntaxes.
+
+- Signing - [Compact](https://github.com/panva/jose/blob/v6.0.1/docs/jws/compact/sign/classes/CompactSign.md), [Flattened JSON](https://github.com/panva/jose/blob/v6.0.1/docs/jws/flattened/sign/classes/FlattenedSign.md), [General JSON](https://github.com/panva/jose/blob/v6.0.1/docs/jws/general/sign/classes/GeneralSign.md)
+- Verification - [Compact](https://github.com/panva/jose/blob/v6.0.1/docs/jws/compact/verify/functions/compactVerify.md), [Flattened JSON](https://github.com/panva/jose/blob/v6.0.1/docs/jws/flattened/verify/functions/flattenedVerify.md), [General JSON](https://github.com/panva/jose/blob/v6.0.1/docs/jws/general/verify/functions/generalVerify.md)
+ - [Using a remote JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v6.0.1/docs/jwks/remote/functions/createRemoteJWKSet.md)
+ - [Using a local JSON Web Key Set (JWKS)](https://github.com/panva/jose/blob/v6.0.1/docs/jwks/local/functions/createLocalJWKSet.md)
+- Utility functions
+ - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v6.0.1/docs/util/decode_protected_header/functions/decodeProtectedHeader.md)
+
+### JSON Web Encryption (JWE)
+
+The `jose` module supports encryption and decryption of JWE messages with arbitrary plaintext in Compact, Flattened JSON, and General JSON serialization syntaxes.
+
+- Encryption - [Compact](https://github.com/panva/jose/blob/v6.0.1/docs/jwe/compact/encrypt/classes/CompactEncrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v6.0.1/docs/jwe/flattened/encrypt/classes/FlattenedEncrypt.md), [General JSON](https://github.com/panva/jose/blob/v6.0.1/docs/jwe/general/encrypt/classes/GeneralEncrypt.md)
+- Decryption - [Compact](https://github.com/panva/jose/blob/v6.0.1/docs/jwe/compact/decrypt/functions/compactDecrypt.md), [Flattened JSON](https://github.com/panva/jose/blob/v6.0.1/docs/jwe/flattened/decrypt/functions/flattenedDecrypt.md), [General JSON](https://github.com/panva/jose/blob/v6.0.1/docs/jwe/general/decrypt/functions/generalDecrypt.md)
+- Utility functions
+ - [Decoding Token's Protected Header](https://github.com/panva/jose/blob/v6.0.1/docs/util/decode_protected_header/functions/decodeProtectedHeader.md)
+
+### Other
+
+The following are additional features and utilities provided by the `jose` module:
+
+- [Calculating JWK Thumbprint](https://github.com/panva/jose/blob/v6.0.1/docs/jwk/thumbprint/functions/calculateJwkThumbprint.md)
+- [Calculating JWK Thumbprint URI](https://github.com/panva/jose/blob/v6.0.1/docs/jwk/thumbprint/functions/calculateJwkThumbprintUri.md)
+- [Verification using a JWK Embedded in a JWS Header](https://github.com/panva/jose/blob/v6.0.1/docs/jwk/embedded/functions/EmbeddedJWK.md)
+- [Unsecured JWT](https://github.com/panva/jose/blob/v6.0.1/docs/jwt/unsecured/classes/UnsecuredJWT.md)
+- [JOSE Errors](https://github.com/panva/jose/blob/v6.0.1/docs/util/errors/README.md)
+
+[sponsor-auth0]: https://a0.to/signup/panva
+
+[^cjs]: CJS style `let jose = require('jose')` is possible in Node.js versions where `process.features.require_module` is `true` or with the `--experimental-require-module` Node.js CLI flag.
diff --git a/dist/deno/index.ts b/dist/deno/index.ts
new file mode 100644
index 0000000000..ebb52f9568
--- /dev/null
+++ b/dist/deno/index.ts
@@ -0,0 +1,113 @@
+export { compactDecrypt } from './jwe/compact/decrypt.ts'
+export type { CompactDecryptGetKey } from './jwe/compact/decrypt.ts'
+export { flattenedDecrypt } from './jwe/flattened/decrypt.ts'
+export type { FlattenedDecryptGetKey } from './jwe/flattened/decrypt.ts'
+export { generalDecrypt } from './jwe/general/decrypt.ts'
+export type { GeneralDecryptGetKey } from './jwe/general/decrypt.ts'
+export { GeneralEncrypt } from './jwe/general/encrypt.ts'
+export type { Recipient } from './jwe/general/encrypt.ts'
+
+export { compactVerify } from './jws/compact/verify.ts'
+export type { CompactVerifyGetKey } from './jws/compact/verify.ts'
+export { flattenedVerify } from './jws/flattened/verify.ts'
+export type { FlattenedVerifyGetKey } from './jws/flattened/verify.ts'
+export { generalVerify } from './jws/general/verify.ts'
+export type { GeneralVerifyGetKey } from './jws/general/verify.ts'
+
+export { jwtVerify } from './jwt/verify.ts'
+export type { JWTVerifyOptions, JWTVerifyGetKey } from './jwt/verify.ts'
+export { jwtDecrypt } from './jwt/decrypt.ts'
+export type { JWTDecryptOptions, JWTDecryptGetKey } from './jwt/decrypt.ts'
+export type { ProduceJWT } from './jwt/produce.ts'
+
+export { CompactEncrypt } from './jwe/compact/encrypt.ts'
+export { FlattenedEncrypt } from './jwe/flattened/encrypt.ts'
+
+export { CompactSign } from './jws/compact/sign.ts'
+export { FlattenedSign } from './jws/flattened/sign.ts'
+export { GeneralSign } from './jws/general/sign.ts'
+export type { Signature } from './jws/general/sign.ts'
+
+export { SignJWT } from './jwt/sign.ts'
+export { EncryptJWT } from './jwt/encrypt.ts'
+
+export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.ts'
+export { EmbeddedJWK } from './jwk/embedded.ts'
+
+export { createLocalJWKSet } from './jwks/local.ts'
+export { createRemoteJWKSet, jwksCache } from './jwks/remote.ts'
+export type {
+ RemoteJWKSetOptions,
+ JWKSCacheInput,
+ ExportedJWKSCache,
+ customFetch,
+ FetchImplementation,
+} from './jwks/remote.ts'
+
+export { UnsecuredJWT } from './jwt/unsecured.ts'
+export type { UnsecuredResult } from './jwt/unsecured.ts'
+
+export { exportPKCS8, exportSPKI, exportJWK } from './key/export.ts'
+
+export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.ts'
+export type { KeyImportOptions } from './key/import.ts'
+
+export { decodeProtectedHeader } from './util/decode_protected_header.ts'
+export { decodeJwt } from './util/decode_jwt.ts'
+export type { ProtectedHeaderParameters } from './util/decode_protected_header.ts'
+
+export * as errors from './util/errors.ts'
+
+export { generateKeyPair } from './key/generate_key_pair.ts'
+export type { GenerateKeyPairResult, GenerateKeyPairOptions } from './key/generate_key_pair.ts'
+export { generateSecret } from './key/generate_secret.ts'
+export type { GenerateSecretOptions } from './key/generate_secret.ts'
+
+export * as base64url from './util/base64url.ts'
+
+export type {
+ CompactDecryptResult,
+ CompactJWEHeaderParameters,
+ CompactJWSHeaderParameters,
+ CompactVerifyResult,
+ CritOption,
+ CryptoKey,
+ DecryptOptions,
+ EncryptOptions,
+ FlattenedDecryptResult,
+ FlattenedJWE,
+ FlattenedJWS,
+ FlattenedJWSInput,
+ FlattenedVerifyResult,
+ GeneralDecryptResult,
+ GeneralJWE,
+ GeneralJWS,
+ GeneralJWSInput,
+ GeneralVerifyResult,
+ GetKeyFunction,
+ JoseHeaderParameters,
+ JSONWebKeySet,
+ JWEHeaderParameters,
+ JWEKeyManagementHeaderParameters,
+ JWK_EC_Private,
+ JWK_EC_Public,
+ JWK_oct,
+ JWK_OKP_Private,
+ JWK_OKP_Public,
+ JWK_RSA_Private,
+ JWK_RSA_Public,
+ JWK,
+ JWKParameters,
+ JWSHeaderParameters,
+ JWTClaimVerificationOptions,
+ JWTDecryptResult,
+ JWTHeaderParameters,
+ JWTPayload,
+ JWTVerifyResult,
+ KeyObject,
+ ResolvedKey,
+ SignOptions,
+ VerifyOptions,
+} from './types.d.ts'
+
+export const cryptoRuntime = 'WebCryptoAPI'
diff --git a/dist/deno/jwe/compact/decrypt.ts b/dist/deno/jwe/compact/decrypt.ts
new file mode 100644
index 0000000000..03d92e1d41
--- /dev/null
+++ b/dist/deno/jwe/compact/decrypt.ts
@@ -0,0 +1,84 @@
+import { flattenedDecrypt } from '../flattened/decrypt.ts'
+import { JWEInvalid } from '../../util/errors.ts'
+import { decoder } from '../../lib/buffer_utils.ts'
+import type * as types from '../../types.d.ts'
+
+/**
+ * Interface for Compact JWE Decryption dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ */
+export interface CompactDecryptGetKey
+ extends types.GetKeyFunction {}
+
+/**
+ * Decrypts a Compact JWE.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwe/compact/decrypt'`.
+ *
+ * @param jwe Compact JWE.
+ * @param key Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export async function compactDecrypt(
+ jwe: string | Uint8Array,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.DecryptOptions,
+): Promise
+/**
+ * @param jwe Compact JWE.
+ * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export async function compactDecrypt(
+ jwe: string | Uint8Array,
+ getKey: CompactDecryptGetKey,
+ options?: types.DecryptOptions,
+): Promise
+export async function compactDecrypt(
+ jwe: string | Uint8Array,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array | CompactDecryptGetKey,
+ options?: types.DecryptOptions,
+) {
+ if (jwe instanceof Uint8Array) {
+ jwe = decoder.decode(jwe)
+ }
+
+ if (typeof jwe !== 'string') {
+ throw new JWEInvalid('Compact JWE must be a string or Uint8Array')
+ }
+ const {
+ 0: protectedHeader,
+ 1: encryptedKey,
+ 2: iv,
+ 3: ciphertext,
+ 4: tag,
+ length,
+ } = jwe.split('.')
+
+ if (length !== 5) {
+ throw new JWEInvalid('Invalid Compact JWE')
+ }
+
+ const decrypted = await flattenedDecrypt(
+ {
+ ciphertext,
+ iv: iv || undefined,
+ protected: protectedHeader,
+ tag: tag || undefined,
+ encrypted_key: encryptedKey || undefined,
+ },
+ key as Parameters[1],
+ options,
+ )
+
+ const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader! }
+
+ if (typeof key === 'function') {
+ return { ...result, key: decrypted.key }
+ }
+
+ return result
+}
diff --git a/dist/deno/jwe/compact/encrypt.ts b/dist/deno/jwe/compact/encrypt.ts
new file mode 100644
index 0000000000..cb8afa92bf
--- /dev/null
+++ b/dist/deno/jwe/compact/encrypt.ts
@@ -0,0 +1,84 @@
+import type * as types from '../../types.d.ts'
+import { FlattenedEncrypt } from '../flattened/encrypt.ts'
+
+/**
+ * The CompactEncrypt class is used to build and encrypt Compact JWE strings.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwe/compact/encrypt'`.
+ *
+ */
+export class CompactEncrypt {
+ private _flattened: FlattenedEncrypt
+
+ /** @param plaintext Binary representation of the plaintext to encrypt. */
+ constructor(plaintext: Uint8Array) {
+ this._flattened = new FlattenedEncrypt(plaintext)
+ }
+
+ /**
+ * Sets a content encryption key to use, by default a random suitable one is generated for the JWE
+ * enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param cek JWE Content Encryption Key.
+ */
+ setContentEncryptionKey(cek: Uint8Array): this {
+ this._flattened.setContentEncryptionKey(cek)
+ return this
+ }
+
+ /**
+ * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable
+ * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param iv JWE Initialization Vector.
+ */
+ setInitializationVector(iv: Uint8Array): this {
+ this._flattened.setInitializationVector(iv)
+ return this
+ }
+
+ /**
+ * Sets the JWE Protected Header on the CompactEncrypt object.
+ *
+ * @param protectedHeader JWE Protected Header object.
+ */
+ setProtectedHeader(protectedHeader: types.CompactJWEHeaderParameters): this {
+ this._flattened.setProtectedHeader(protectedHeader)
+ return this
+ }
+
+ /**
+ * Sets the JWE Key Management parameters to be used when encrypting the Content Encryption Key.
+ * You do not need to invoke this method, it is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param parameters JWE Key Management parameters.
+ */
+ setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): this {
+ this._flattened.setKeyManagementParameters(parameters)
+ return this
+ }
+
+ /**
+ * Encrypts and resolves the value of the Compact JWE string.
+ *
+ * @param key Public Key or Secret to encrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Encryption options.
+ */
+ async encrypt(
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.EncryptOptions,
+ ): Promise {
+ const jwe = await this._flattened.encrypt(key, options)
+
+ return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.')
+ }
+}
diff --git a/dist/deno/jwe/flattened/decrypt.ts b/dist/deno/jwe/flattened/decrypt.ts
new file mode 100644
index 0000000000..f2df659b12
--- /dev/null
+++ b/dist/deno/jwe/flattened/decrypt.ts
@@ -0,0 +1,245 @@
+import type * as types from '../../types.d.ts'
+import { decode as base64url } from '../../lib/base64url.ts'
+import decrypt from '../../lib/decrypt.ts'
+import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.ts'
+import isDisjoint from '../../lib/is_disjoint.ts'
+import isObject from '../../lib/is_object.ts'
+import decryptKeyManagement from '../../lib/decrypt_key_management.ts'
+import { encoder, decoder, concat } from '../../lib/buffer_utils.ts'
+import generateCek from '../../lib/cek.ts'
+import validateCrit from '../../lib/validate_crit.ts'
+import validateAlgorithms from '../../lib/validate_algorithms.ts'
+import normalizeKey from '../../lib/normalize_key.ts'
+import checkKeyType from '../../lib/check_key_type.ts'
+
+/**
+ * Interface for Flattened JWE Decryption dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ */
+export interface FlattenedDecryptGetKey
+ extends types.GetKeyFunction {}
+
+/**
+ * Decrypts a Flattened JWE.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwe/flattened/decrypt'`.
+ *
+ * @param jwe Flattened JWE.
+ * @param key Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export function flattenedDecrypt(
+ jwe: types.FlattenedJWE,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.DecryptOptions,
+): Promise
+/**
+ * @param jwe Flattened JWE.
+ * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export function flattenedDecrypt(
+ jwe: types.FlattenedJWE,
+ getKey: FlattenedDecryptGetKey,
+ options?: types.DecryptOptions,
+): Promise
+export async function flattenedDecrypt(
+ jwe: types.FlattenedJWE,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array | FlattenedDecryptGetKey,
+ options?: types.DecryptOptions,
+) {
+ if (!isObject(jwe)) {
+ throw new JWEInvalid('Flattened JWE must be an object')
+ }
+
+ if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {
+ throw new JWEInvalid('JOSE Header missing')
+ }
+
+ if (jwe.iv !== undefined && typeof jwe.iv !== 'string') {
+ throw new JWEInvalid('JWE Initialization Vector incorrect type')
+ }
+
+ if (typeof jwe.ciphertext !== 'string') {
+ throw new JWEInvalid('JWE Ciphertext missing or incorrect type')
+ }
+
+ if (jwe.tag !== undefined && typeof jwe.tag !== 'string') {
+ throw new JWEInvalid('JWE Authentication Tag incorrect type')
+ }
+
+ if (jwe.protected !== undefined && typeof jwe.protected !== 'string') {
+ throw new JWEInvalid('JWE Protected Header incorrect type')
+ }
+
+ if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') {
+ throw new JWEInvalid('JWE Encrypted Key incorrect type')
+ }
+
+ if (jwe.aad !== undefined && typeof jwe.aad !== 'string') {
+ throw new JWEInvalid('JWE AAD incorrect type')
+ }
+
+ if (jwe.header !== undefined && !isObject(jwe.header)) {
+ throw new JWEInvalid('JWE Shared Unprotected Header incorrect type')
+ }
+
+ if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) {
+ throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type')
+ }
+
+ let parsedProt!: types.JWEHeaderParameters
+ if (jwe.protected) {
+ try {
+ const protectedHeader = base64url(jwe.protected)
+ parsedProt = JSON.parse(decoder.decode(protectedHeader))
+ } catch {
+ throw new JWEInvalid('JWE Protected Header is invalid')
+ }
+ }
+ if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {
+ throw new JWEInvalid(
+ 'JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint',
+ )
+ }
+
+ const joseHeader: types.JWEHeaderParameters = {
+ ...parsedProt,
+ ...jwe.header,
+ ...jwe.unprotected,
+ }
+
+ validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader)
+
+ if (joseHeader.zip !== undefined) {
+ throw new JOSENotSupported(
+ 'JWE "zip" (Compression Algorithm) Header Parameter is not supported.',
+ )
+ }
+
+ const { alg, enc } = joseHeader
+
+ if (typeof alg !== 'string' || !alg) {
+ throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header')
+ }
+
+ if (typeof enc !== 'string' || !enc) {
+ throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header')
+ }
+
+ const keyManagementAlgorithms =
+ options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms)
+ const contentEncryptionAlgorithms =
+ options &&
+ validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms)
+
+ if (
+ (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||
+ (!keyManagementAlgorithms && alg.startsWith('PBES2'))
+ ) {
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed')
+ }
+
+ if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
+ throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed')
+ }
+
+ let encryptedKey!: Uint8Array
+ if (jwe.encrypted_key !== undefined) {
+ try {
+ encryptedKey = base64url(jwe.encrypted_key!)
+ } catch {
+ throw new JWEInvalid('Failed to base64url decode the encrypted_key')
+ }
+ }
+
+ let resolvedKey = false
+ if (typeof key === 'function') {
+ key = await key(parsedProt, jwe)
+ resolvedKey = true
+ }
+ checkKeyType(alg === 'dir' ? enc : alg, key, 'decrypt')
+
+ const k = await normalizeKey(key, alg)
+ let cek: types.CryptoKey | Uint8Array
+ try {
+ cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options)
+ } catch (err) {
+ if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
+ throw err
+ }
+ // https://www.rfc-editor.org/rfc/rfc7516#section-11.5
+ // To mitigate the attacks described in RFC 3218, the
+ // recipient MUST NOT distinguish between format, padding, and length
+ // errors of encrypted keys. It is strongly recommended, in the event
+ // of receiving an improperly formatted key, that the recipient
+ // substitute a randomly generated CEK and proceed to the next step, to
+ // mitigate timing attacks.
+ cek = generateCek(enc)
+ }
+
+ let iv: Uint8Array | undefined
+ let tag: Uint8Array | undefined
+ if (jwe.iv !== undefined) {
+ try {
+ iv = base64url(jwe.iv)
+ } catch {
+ throw new JWEInvalid('Failed to base64url decode the iv')
+ }
+ }
+ if (jwe.tag !== undefined) {
+ try {
+ tag = base64url(jwe.tag)
+ } catch {
+ throw new JWEInvalid('Failed to base64url decode the tag')
+ }
+ }
+
+ const protectedHeader: Uint8Array = encoder.encode(jwe.protected ?? '')
+ let additionalData: Uint8Array
+
+ if (jwe.aad !== undefined) {
+ additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad))
+ } else {
+ additionalData = protectedHeader
+ }
+
+ let ciphertext: Uint8Array
+ try {
+ ciphertext = base64url(jwe.ciphertext)
+ } catch {
+ throw new JWEInvalid('Failed to base64url decode the ciphertext')
+ }
+ const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData)
+
+ const result: types.FlattenedDecryptResult = { plaintext }
+
+ if (jwe.protected !== undefined) {
+ result.protectedHeader = parsedProt
+ }
+
+ if (jwe.aad !== undefined) {
+ try {
+ result.additionalAuthenticatedData = base64url(jwe.aad!)
+ } catch {
+ throw new JWEInvalid('Failed to base64url decode the aad')
+ }
+ }
+
+ if (jwe.unprotected !== undefined) {
+ result.sharedUnprotectedHeader = jwe.unprotected
+ }
+
+ if (jwe.header !== undefined) {
+ result.unprotectedHeader = jwe.header
+ }
+
+ if (resolvedKey) {
+ return { ...result, key: k }
+ }
+
+ return result
+}
diff --git a/dist/deno/jwe/flattened/encrypt.ts b/dist/deno/jwe/flattened/encrypt.ts
new file mode 100644
index 0000000000..c3c1bfd55e
--- /dev/null
+++ b/dist/deno/jwe/flattened/encrypt.ts
@@ -0,0 +1,288 @@
+import { encode as base64url } from '../../lib/base64url.ts'
+import { unprotected } from '../../lib/private_symbols.ts'
+import encrypt from '../../lib/encrypt.ts'
+import type * as types from '../../types.d.ts'
+import encryptKeyManagement from '../../lib/encrypt_key_management.ts'
+import { JOSENotSupported, JWEInvalid } from '../../util/errors.ts'
+import isDisjoint from '../../lib/is_disjoint.ts'
+import { encoder, decoder, concat } from '../../lib/buffer_utils.ts'
+import validateCrit from '../../lib/validate_crit.ts'
+import normalizeKey from '../../lib/normalize_key.ts'
+import checkKeyType from '../../lib/check_key_type.ts'
+
+/**
+ * The FlattenedEncrypt class is used to build and encrypt Flattened JWE objects.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwe/flattened/encrypt'`.
+ *
+ */
+export class FlattenedEncrypt {
+ private _plaintext: Uint8Array
+
+ private _protectedHeader!: types.JWEHeaderParameters | undefined
+
+ private _sharedUnprotectedHeader!: types.JWEHeaderParameters | undefined
+
+ private _unprotectedHeader!: types.JWEHeaderParameters | undefined
+
+ private _aad!: Uint8Array | undefined
+
+ private _cek!: Uint8Array | undefined
+
+ private _iv!: Uint8Array | undefined
+
+ private _keyManagementParameters!: types.JWEKeyManagementHeaderParameters
+
+ /** @param plaintext Binary representation of the plaintext to encrypt. */
+ constructor(plaintext: Uint8Array) {
+ if (!(plaintext instanceof Uint8Array)) {
+ throw new TypeError('plaintext must be an instance of Uint8Array')
+ }
+ this._plaintext = plaintext
+ }
+
+ /**
+ * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is
+ * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or
+ * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed
+ * and missing.
+ *
+ * @param parameters JWE Key Management parameters.
+ */
+ setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): this {
+ if (this._keyManagementParameters) {
+ throw new TypeError('setKeyManagementParameters can only be called once')
+ }
+ this._keyManagementParameters = parameters
+ return this
+ }
+
+ /**
+ * Sets the JWE Protected Header on the FlattenedEncrypt object.
+ *
+ * @param protectedHeader JWE Protected Header.
+ */
+ setProtectedHeader(protectedHeader: types.JWEHeaderParameters): this {
+ if (this._protectedHeader) {
+ throw new TypeError('setProtectedHeader can only be called once')
+ }
+ this._protectedHeader = protectedHeader
+ return this
+ }
+
+ /**
+ * Sets the JWE Shared Unprotected Header on the FlattenedEncrypt object.
+ *
+ * @param sharedUnprotectedHeader JWE Shared Unprotected Header.
+ */
+ setSharedUnprotectedHeader(sharedUnprotectedHeader: types.JWEHeaderParameters): this {
+ if (this._sharedUnprotectedHeader) {
+ throw new TypeError('setSharedUnprotectedHeader can only be called once')
+ }
+ this._sharedUnprotectedHeader = sharedUnprotectedHeader
+ return this
+ }
+
+ /**
+ * Sets the JWE Per-Recipient Unprotected Header on the FlattenedEncrypt object.
+ *
+ * @param unprotectedHeader JWE Per-Recipient Unprotected Header.
+ */
+ setUnprotectedHeader(unprotectedHeader: types.JWEHeaderParameters): this {
+ if (this._unprotectedHeader) {
+ throw new TypeError('setUnprotectedHeader can only be called once')
+ }
+ this._unprotectedHeader = unprotectedHeader
+ return this
+ }
+
+ /**
+ * Sets the Additional Authenticated Data on the FlattenedEncrypt object.
+ *
+ * @param aad Additional Authenticated Data.
+ */
+ setAdditionalAuthenticatedData(aad: Uint8Array): this {
+ this._aad = aad
+ return this
+ }
+
+ /**
+ * Sets a content encryption key to use, by default a random suitable one is generated for the JWE
+ * enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param cek JWE Content Encryption Key.
+ */
+ setContentEncryptionKey(cek: Uint8Array): this {
+ if (this._cek) {
+ throw new TypeError('setContentEncryptionKey can only be called once')
+ }
+ this._cek = cek
+ return this
+ }
+
+ /**
+ * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable
+ * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param iv JWE Initialization Vector.
+ */
+ setInitializationVector(iv: Uint8Array): this {
+ if (this._iv) {
+ throw new TypeError('setInitializationVector can only be called once')
+ }
+ this._iv = iv
+ return this
+ }
+
+ /**
+ * Encrypts and resolves the value of the Flattened JWE object.
+ *
+ * @param key Public Key or Secret to encrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Encryption options.
+ */
+ async encrypt(
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.EncryptOptions,
+ ): Promise {
+ if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {
+ throw new JWEInvalid(
+ 'either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()',
+ )
+ }
+
+ if (
+ !isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)
+ ) {
+ throw new JWEInvalid(
+ 'JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint',
+ )
+ }
+
+ const joseHeader: types.JWEHeaderParameters = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...this._sharedUnprotectedHeader,
+ }
+
+ validateCrit(JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader)
+
+ if (joseHeader.zip !== undefined) {
+ throw new JOSENotSupported(
+ 'JWE "zip" (Compression Algorithm) Header Parameter is not supported.',
+ )
+ }
+
+ const { alg, enc } = joseHeader
+
+ if (typeof alg !== 'string' || !alg) {
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid')
+ }
+
+ if (typeof enc !== 'string' || !enc) {
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid')
+ }
+
+ let encryptedKey: Uint8Array | undefined
+
+ if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) {
+ throw new TypeError(
+ `setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`,
+ )
+ }
+
+ checkKeyType(alg === 'dir' ? enc : alg, key, 'encrypt')
+
+ let cek: types.CryptoKey | Uint8Array
+ {
+ let parameters: { [propName: string]: unknown } | undefined
+ const k = await normalizeKey(key, alg)
+ ;({ cek, encryptedKey, parameters } = await encryptKeyManagement(
+ alg,
+ enc,
+ k,
+ this._cek,
+ this._keyManagementParameters,
+ ))
+
+ if (parameters) {
+ if (options && unprotected in options) {
+ if (!this._unprotectedHeader) {
+ this.setUnprotectedHeader(parameters)
+ } else {
+ this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters }
+ }
+ } else if (!this._protectedHeader) {
+ this.setProtectedHeader(parameters)
+ } else {
+ this._protectedHeader = { ...this._protectedHeader, ...parameters }
+ }
+ }
+ }
+
+ let additionalData: Uint8Array
+ let protectedHeader: Uint8Array
+ let aadMember: string | undefined
+ if (this._protectedHeader) {
+ protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)))
+ } else {
+ protectedHeader = encoder.encode('')
+ }
+
+ if (this._aad) {
+ aadMember = base64url(this._aad)
+ additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember))
+ } else {
+ additionalData = protectedHeader
+ }
+
+ const { ciphertext, tag, iv } = await encrypt(
+ enc,
+ this._plaintext,
+ cek,
+ this._iv,
+ additionalData,
+ )
+
+ const jwe: types.FlattenedJWE = {
+ ciphertext: base64url(ciphertext),
+ }
+
+ if (iv) {
+ jwe.iv = base64url(iv)
+ }
+
+ if (tag) {
+ jwe.tag = base64url(tag)
+ }
+
+ if (encryptedKey) {
+ jwe.encrypted_key = base64url(encryptedKey)
+ }
+
+ if (aadMember) {
+ jwe.aad = aadMember
+ }
+
+ if (this._protectedHeader) {
+ jwe.protected = decoder.decode(protectedHeader)
+ }
+
+ if (this._sharedUnprotectedHeader) {
+ jwe.unprotected = this._sharedUnprotectedHeader
+ }
+
+ if (this._unprotectedHeader) {
+ jwe.header = this._unprotectedHeader
+ }
+
+ return jwe
+ }
+}
diff --git a/dist/deno/jwe/general/decrypt.ts b/dist/deno/jwe/general/decrypt.ts
new file mode 100644
index 0000000000..66e3e7cbe7
--- /dev/null
+++ b/dist/deno/jwe/general/decrypt.ts
@@ -0,0 +1,78 @@
+import { flattenedDecrypt } from '../flattened/decrypt.ts'
+import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.ts'
+import type * as types from '../../types.d.ts'
+import isObject from '../../lib/is_object.ts'
+
+/**
+ * Interface for General JWE Decryption dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ */
+export interface GeneralDecryptGetKey
+ extends types.GetKeyFunction {}
+
+/**
+ * Decrypts a General JWE.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwe/general/decrypt'`.
+ *
+ * @param jwe General JWE.
+ * @param key Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export function generalDecrypt(
+ jwe: types.GeneralJWE,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.DecryptOptions,
+): Promise
+/**
+ * @param jwe General JWE.
+ * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export function generalDecrypt(
+ jwe: types.GeneralJWE,
+ getKey: GeneralDecryptGetKey,
+ options?: types.DecryptOptions,
+): Promise
+export async function generalDecrypt(
+ jwe: types.GeneralJWE,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array | GeneralDecryptGetKey,
+ options?: types.DecryptOptions,
+) {
+ if (!isObject(jwe)) {
+ throw new JWEInvalid('General JWE must be an object')
+ }
+
+ if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) {
+ throw new JWEInvalid('JWE Recipients missing or incorrect type')
+ }
+
+ if (!jwe.recipients.length) {
+ throw new JWEInvalid('JWE Recipients has no members')
+ }
+
+ for (const recipient of jwe.recipients) {
+ try {
+ return await flattenedDecrypt(
+ {
+ aad: jwe.aad,
+ ciphertext: jwe.ciphertext,
+ encrypted_key: recipient.encrypted_key,
+ header: recipient.header,
+ iv: jwe.iv,
+ protected: jwe.protected,
+ tag: jwe.tag,
+ unprotected: jwe.unprotected,
+ },
+ key as Parameters[1],
+ options,
+ )
+ } catch {
+ //
+ }
+ }
+ throw new JWEDecryptionFailed()
+}
diff --git a/dist/deno/jwe/general/encrypt.ts b/dist/deno/jwe/general/encrypt.ts
new file mode 100644
index 0000000000..d9b6ba6cb2
--- /dev/null
+++ b/dist/deno/jwe/general/encrypt.ts
@@ -0,0 +1,289 @@
+import type * as types from '../../types.d.ts'
+import { FlattenedEncrypt } from '../flattened/encrypt.ts'
+import { unprotected } from '../../lib/private_symbols.ts'
+import { JOSENotSupported, JWEInvalid } from '../../util/errors.ts'
+import generateCek from '../../lib/cek.ts'
+import isDisjoint from '../../lib/is_disjoint.ts'
+import encryptKeyManagement from '../../lib/encrypt_key_management.ts'
+import { encode as base64url } from '../../lib/base64url.ts'
+import validateCrit from '../../lib/validate_crit.ts'
+import normalizeKey from '../../lib/normalize_key.ts'
+import checkKeyType from '../../lib/check_key_type.ts'
+
+export interface Recipient {
+ /**
+ * Sets the JWE Per-Recipient Unprotected Header on the Recipient object.
+ *
+ * @param unprotectedHeader JWE Per-Recipient Unprotected Header.
+ */
+ setUnprotectedHeader(unprotectedHeader: types.JWEHeaderParameters): Recipient
+
+ /** A shorthand for calling addRecipient() on the enclosing GeneralEncrypt instance */
+ addRecipient(...args: Parameters): Recipient
+
+ /** A shorthand for calling encrypt() on the enclosing GeneralEncrypt instance */
+ encrypt(...args: Parameters): Promise
+
+ /** Returns the enclosing GeneralEncrypt */
+ done(): GeneralEncrypt
+}
+
+class IndividualRecipient implements Recipient {
+ private parent: GeneralEncrypt
+ unprotectedHeader?: types.JWEHeaderParameters
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array
+ options: types.CritOption
+
+ constructor(
+ enc: GeneralEncrypt,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options: types.CritOption,
+ ) {
+ this.parent = enc
+ this.key = key
+ this.options = options
+ }
+
+ setUnprotectedHeader(unprotectedHeader: types.JWEHeaderParameters) {
+ if (this.unprotectedHeader) {
+ throw new TypeError('setUnprotectedHeader can only be called once')
+ }
+ this.unprotectedHeader = unprotectedHeader
+ return this
+ }
+
+ addRecipient(...args: Parameters) {
+ return this.parent.addRecipient(...args)
+ }
+
+ encrypt(...args: Parameters) {
+ return this.parent.encrypt(...args)
+ }
+
+ done() {
+ return this.parent
+ }
+}
+
+/**
+ * The GeneralEncrypt class is used to build and encrypt General JWE objects.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwe/general/encrypt'`.
+ *
+ */
+export class GeneralEncrypt {
+ private _plaintext: Uint8Array
+
+ private _recipients: IndividualRecipient[] = []
+
+ private _protectedHeader!: types.JWEHeaderParameters
+
+ private _unprotectedHeader!: types.JWEHeaderParameters
+
+ private _aad!: Uint8Array
+
+ /** @param plaintext Binary representation of the plaintext to encrypt. */
+ constructor(plaintext: Uint8Array) {
+ this._plaintext = plaintext
+ }
+
+ /**
+ * Adds an additional recipient for the General JWE object.
+ *
+ * @param key Public Key or Secret to encrypt the Content Encryption Key for the recipient with.
+ * See {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Encryption options.
+ */
+ addRecipient(
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.CritOption,
+ ): Recipient {
+ const recipient = new IndividualRecipient(this, key, { crit: options?.crit })
+ this._recipients.push(recipient)
+ return recipient
+ }
+
+ /**
+ * Sets the JWE Protected Header on the GeneralEncrypt object.
+ *
+ * @param protectedHeader JWE Protected Header object.
+ */
+ setProtectedHeader(protectedHeader: types.JWEHeaderParameters): this {
+ if (this._protectedHeader) {
+ throw new TypeError('setProtectedHeader can only be called once')
+ }
+ this._protectedHeader = protectedHeader
+ return this
+ }
+
+ /**
+ * Sets the JWE Shared Unprotected Header on the GeneralEncrypt object.
+ *
+ * @param sharedUnprotectedHeader JWE Shared Unprotected Header object.
+ */
+ setSharedUnprotectedHeader(sharedUnprotectedHeader: types.JWEHeaderParameters): this {
+ if (this._unprotectedHeader) {
+ throw new TypeError('setSharedUnprotectedHeader can only be called once')
+ }
+ this._unprotectedHeader = sharedUnprotectedHeader
+ return this
+ }
+
+ /**
+ * Sets the Additional Authenticated Data on the GeneralEncrypt object.
+ *
+ * @param aad Additional Authenticated Data.
+ */
+ setAdditionalAuthenticatedData(aad: Uint8Array): this {
+ this._aad = aad
+ return this
+ }
+
+ /** Encrypts and resolves the value of the General JWE object. */
+ async encrypt(): Promise {
+ if (!this._recipients.length) {
+ throw new JWEInvalid('at least one recipient must be added')
+ }
+
+ if (this._recipients.length === 1) {
+ const [recipient] = this._recipients
+
+ const flattened = await new FlattenedEncrypt(this._plaintext)
+ .setAdditionalAuthenticatedData(this._aad)
+ .setProtectedHeader(this._protectedHeader)
+ .setSharedUnprotectedHeader(this._unprotectedHeader)
+ .setUnprotectedHeader(recipient.unprotectedHeader!)
+ .encrypt(recipient.key, { ...recipient.options })
+
+ const jwe: types.GeneralJWE = {
+ ciphertext: flattened.ciphertext,
+ iv: flattened.iv,
+ recipients: [{}],
+ tag: flattened.tag,
+ }
+
+ if (flattened.aad) jwe.aad = flattened.aad
+ if (flattened.protected) jwe.protected = flattened.protected
+ if (flattened.unprotected) jwe.unprotected = flattened.unprotected
+ if (flattened.encrypted_key) jwe.recipients![0].encrypted_key = flattened.encrypted_key
+ if (flattened.header) jwe.recipients![0].header = flattened.header
+
+ return jwe
+ }
+
+ let enc!: string
+ for (let i = 0; i < this._recipients.length; i++) {
+ const recipient = this._recipients[i]
+ if (
+ !isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)
+ ) {
+ throw new JWEInvalid(
+ 'JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint',
+ )
+ }
+
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...recipient.unprotectedHeader,
+ }
+
+ const { alg } = joseHeader
+
+ if (typeof alg !== 'string' || !alg) {
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid')
+ }
+
+ if (alg === 'dir' || alg === 'ECDH-ES') {
+ throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient')
+ }
+
+ if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) {
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid')
+ }
+
+ if (!enc) {
+ enc = joseHeader.enc
+ } else if (enc !== joseHeader.enc) {
+ throw new JWEInvalid(
+ 'JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients',
+ )
+ }
+
+ validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader)
+
+ if (joseHeader.zip !== undefined) {
+ throw new JOSENotSupported(
+ 'JWE "zip" (Compression Algorithm) Header Parameter is not supported.',
+ )
+ }
+ }
+
+ const cek = generateCek(enc)
+
+ const jwe: types.GeneralJWE = {
+ ciphertext: '',
+ iv: '',
+ recipients: [],
+ tag: '',
+ }
+
+ for (let i = 0; i < this._recipients.length; i++) {
+ const recipient = this._recipients[i]
+ const target: Record = {}
+ jwe.recipients!.push(target)
+
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...recipient.unprotectedHeader,
+ }
+
+ const p2c = joseHeader.alg!.startsWith('PBES2') ? 2048 + i : undefined
+
+ if (i === 0) {
+ const flattened = await new FlattenedEncrypt(this._plaintext)
+ .setAdditionalAuthenticatedData(this._aad)
+ .setContentEncryptionKey(cek)
+ .setProtectedHeader(this._protectedHeader)
+ .setSharedUnprotectedHeader(this._unprotectedHeader)
+ .setUnprotectedHeader(recipient.unprotectedHeader!)
+ .setKeyManagementParameters({ p2c })
+ .encrypt(recipient.key, {
+ ...recipient.options,
+ // @ts-expect-error
+ [unprotected]: true,
+ })
+
+ jwe.ciphertext = flattened.ciphertext
+ jwe.iv = flattened.iv
+ jwe.tag = flattened.tag
+
+ if (flattened.aad) jwe.aad = flattened.aad
+ if (flattened.protected) jwe.protected = flattened.protected
+ if (flattened.unprotected) jwe.unprotected = flattened.unprotected
+
+ target.encrypted_key = flattened.encrypted_key!
+ if (flattened.header) target.header = flattened.header
+
+ continue
+ }
+
+ const alg =
+ recipient.unprotectedHeader?.alg! ||
+ this._protectedHeader?.alg! ||
+ this._unprotectedHeader?.alg!
+
+ checkKeyType(alg === 'dir' ? enc : alg, recipient.key, 'encrypt')
+
+ const k = await normalizeKey(recipient.key, alg)
+ const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, { p2c })
+ target.encrypted_key = base64url(encryptedKey!)
+ if (recipient.unprotectedHeader || parameters)
+ target.header = { ...recipient.unprotectedHeader, ...parameters }
+ }
+
+ return jwe as types.GeneralJWE
+ }
+}
diff --git a/dist/deno/jwk/embedded.ts b/dist/deno/jwk/embedded.ts
new file mode 100644
index 0000000000..4dfba96180
--- /dev/null
+++ b/dist/deno/jwk/embedded.ts
@@ -0,0 +1,35 @@
+import type * as types from '../types.d.ts'
+import { importJWK } from '../key/import.ts'
+import isObject from '../lib/is_object.ts'
+import { JWSInvalid } from '../util/errors.ts'
+
+/**
+ * EmbeddedJWK is an implementation of a GetKeyFunction intended to be used with the JWS/JWT verify
+ * operations whenever you need to opt-in to verify signatures with a public key embedded in the
+ * token's "jwk" (JSON Web Key) Header Parameter. It is recommended to combine this with the verify
+ * function's `algorithms` option to define accepted JWS "alg" (Algorithm) Header Parameter values.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwk/embedded'`.
+ *
+ */
+export async function EmbeddedJWK(
+ protectedHeader?: types.JWSHeaderParameters,
+ token?: types.FlattenedJWSInput,
+): Promise {
+ const joseHeader = {
+ ...protectedHeader,
+ ...token?.header,
+ }
+ if (!isObject(joseHeader.jwk)) {
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object')
+ }
+
+ const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg!)
+
+ if (key instanceof Uint8Array || key.type !== 'public') {
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key')
+ }
+
+ return key
+}
diff --git a/dist/deno/jwk/thumbprint.ts b/dist/deno/jwk/thumbprint.ts
new file mode 100644
index 0000000000..3b61cb9502
--- /dev/null
+++ b/dist/deno/jwk/thumbprint.ts
@@ -0,0 +1,102 @@
+import digest from '../lib/digest.ts'
+import { encode as base64url } from '../lib/base64url.ts'
+
+import { JOSENotSupported, JWKInvalid } from '../util/errors.ts'
+import { encoder } from '../lib/buffer_utils.ts'
+import type * as types from '../types.d.ts'
+import isKeyLike from '../lib/is_key_like.ts'
+import { isJWK } from '../lib/is_jwk.ts'
+import { exportJWK } from '../key/export.ts'
+import invalidKeyInput from '../lib/invalid_key_input.ts'
+
+const check = (value: unknown, description: string) => {
+ if (typeof value !== 'string' || !value) {
+ throw new JWKInvalid(`${description} missing or invalid`)
+ }
+}
+
+/**
+ * Calculates a base64url-encoded JSON Web Key (JWK) Thumbprint
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwk/thumbprint'`.
+ *
+ * @param key Key to calculate the thumbprint for.
+ * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is
+ * "sha256".
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7638 RFC7638}
+ */
+export async function calculateJwkThumbprint(
+ key: types.JWK | types.CryptoKey | types.KeyObject,
+ digestAlgorithm?: 'sha256' | 'sha384' | 'sha512',
+): Promise {
+ let jwk: types.JWK
+ if (isJWK(key)) {
+ jwk = key
+ } else if (isKeyLike(key)) {
+ jwk = await exportJWK(key)
+ } else {
+ throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'))
+ }
+
+ digestAlgorithm ??= 'sha256'
+
+ if (
+ digestAlgorithm !== 'sha256' &&
+ digestAlgorithm !== 'sha384' &&
+ digestAlgorithm !== 'sha512'
+ ) {
+ throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"')
+ }
+
+ let components: types.JWK
+ switch (jwk.kty) {
+ case 'EC':
+ check(jwk.crv, '"crv" (Curve) Parameter')
+ check(jwk.x, '"x" (X Coordinate) Parameter')
+ check(jwk.y, '"y" (Y Coordinate) Parameter')
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }
+ break
+ case 'OKP':
+ check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter')
+ check(jwk.x, '"x" (Public Key) Parameter')
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x }
+ break
+ case 'RSA':
+ check(jwk.e, '"e" (Exponent) Parameter')
+ check(jwk.n, '"n" (Modulus) Parameter')
+ components = { e: jwk.e, kty: jwk.kty, n: jwk.n }
+ break
+ case 'oct':
+ check(jwk.k, '"k" (Key Value) Parameter')
+ components = { k: jwk.k, kty: jwk.kty }
+ break
+ default:
+ throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported')
+ }
+
+ const data = encoder.encode(JSON.stringify(components))
+ return base64url(await digest(digestAlgorithm, data))
+}
+
+/**
+ * Calculates a JSON Web Key (JWK) Thumbprint URI
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwk/thumbprint'`.
+ *
+ * @param key Key to calculate the thumbprint for.
+ * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is
+ * "sha256".
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc9278 RFC9278}
+ */
+export async function calculateJwkThumbprintUri(
+ key: types.CryptoKey | types.KeyObject | types.JWK,
+ digestAlgorithm?: 'sha256' | 'sha384' | 'sha512',
+): Promise {
+ digestAlgorithm ??= 'sha256'
+ const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm)
+ return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`
+}
diff --git a/dist/deno/jwks/local.ts b/dist/deno/jwks/local.ts
new file mode 100644
index 0000000000..f61cfeea49
--- /dev/null
+++ b/dist/deno/jwks/local.ts
@@ -0,0 +1,202 @@
+import type * as types from '../types.d.ts'
+import { importJWK } from '../key/import.ts'
+import {
+ JWKSInvalid,
+ JOSENotSupported,
+ JWKSNoMatchingKey,
+ JWKSMultipleMatchingKeys,
+} from '../util/errors.ts'
+import isObject from '../lib/is_object.ts'
+
+function getKtyFromAlg(alg: unknown) {
+ switch (typeof alg === 'string' && alg.slice(0, 2)) {
+ case 'RS':
+ case 'PS':
+ return 'RSA'
+ case 'ES':
+ return 'EC'
+ case 'Ed':
+ return 'OKP'
+ default:
+ throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set')
+ }
+}
+
+interface Cache {
+ [alg: string]: types.CryptoKey
+}
+
+function isJWKSLike(jwks: unknown): jwks is types.JSONWebKeySet {
+ return (
+ jwks &&
+ typeof jwks === 'object' &&
+ // @ts-expect-error
+ Array.isArray(jwks.keys) &&
+ // @ts-expect-error
+ jwks.keys.every(isJWKLike)
+ )
+}
+
+function isJWKLike(key: unknown) {
+ return isObject(key)
+}
+
+function clone(obj: T): T {
+ if (typeof structuredClone === 'function') {
+ return structuredClone(obj)
+ }
+
+ return JSON.parse(JSON.stringify(obj))
+}
+
+class LocalJWKSet {
+ private _jwks?: types.JSONWebKeySet
+
+ private _cached: WeakMap = new WeakMap()
+
+ constructor(jwks: unknown) {
+ if (!isJWKSLike(jwks)) {
+ throw new JWKSInvalid('JSON Web Key Set malformed')
+ }
+
+ this._jwks = clone(jwks)
+ }
+
+ async getKey(
+ protectedHeader?: types.JWSHeaderParameters,
+ token?: types.FlattenedJWSInput,
+ ): Promise {
+ const { alg, kid } = { ...protectedHeader, ...token?.header }
+ const kty = getKtyFromAlg(alg)
+
+ const candidates = this._jwks!.keys.filter((jwk) => {
+ // filter keys based on the mapping of signature algorithms to Key Type
+ let candidate = kty === jwk.kty
+
+ // filter keys based on the JWK Key ID in the header
+ if (candidate && typeof kid === 'string') {
+ candidate = kid === jwk.kid
+ }
+
+ // filter keys based on the key's declared Algorithm
+ if (candidate && typeof jwk.alg === 'string') {
+ candidate = alg === jwk.alg
+ }
+
+ // filter keys based on the key's declared Public Key Use
+ if (candidate && typeof jwk.use === 'string') {
+ candidate = jwk.use === 'sig'
+ }
+
+ // filter keys based on the key's declared Key Operations
+ if (candidate && Array.isArray(jwk.key_ops)) {
+ candidate = jwk.key_ops.includes('verify')
+ }
+
+ // filter out non-applicable curves / sub types
+ if (candidate) {
+ switch (alg) {
+ case 'ES256':
+ candidate = jwk.crv === 'P-256'
+ break
+ case 'ES384':
+ candidate = jwk.crv === 'P-384'
+ break
+ case 'ES512':
+ candidate = jwk.crv === 'P-521'
+ break
+ case 'Ed25519': // Fall through
+ case 'EdDSA':
+ candidate = jwk.crv === 'Ed25519'
+ break
+ }
+ }
+
+ return candidate
+ })
+
+ const { 0: jwk, length } = candidates
+
+ if (length === 0) {
+ throw new JWKSNoMatchingKey()
+ }
+ if (length !== 1) {
+ const error = new JWKSMultipleMatchingKeys()
+
+ const { _cached } = this
+ error[Symbol.asyncIterator] = async function* () {
+ for (const jwk of candidates) {
+ try {
+ yield await importWithAlgCache(_cached, jwk, alg!)
+ } catch {}
+ }
+ }
+
+ throw error
+ }
+
+ return importWithAlgCache(this._cached, jwk, alg!)
+ }
+}
+
+async function importWithAlgCache(cache: WeakMap, jwk: types.JWK, alg: string) {
+ const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk)!
+ if (cached[alg] === undefined) {
+ const key = await importJWK({ ...jwk, ext: true }, alg)
+
+ if (key instanceof Uint8Array || key.type !== 'public') {
+ throw new JWKSInvalid('JSON Web Key Set members must be public keys')
+ }
+
+ cached[alg] = key
+ }
+
+ return cached[alg]
+}
+
+/**
+ * Returns a function that resolves a JWS JOSE Header to a public key object from a locally stored,
+ * or otherwise available, JSON Web Key Set.
+ *
+ * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type),
+ * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if
+ * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key
+ * Operations) Parameters (if they are present on the JWK).
+ *
+ * Only a single public key must match the selection process. As shown in the example below when
+ * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt
+ * verification in an iterative manner.
+ *
+ * Note: The function's purpose is to resolve public keys used for verifying signatures and will not
+ * work for public encryption keys.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwks/local'`.
+ *
+ * @param jwks JSON Web Key Set formatted object.
+ */
+export function createLocalJWKSet(
+ jwks: types.JSONWebKeySet,
+): (
+ protectedHeader?: types.JWSHeaderParameters,
+ token?: types.FlattenedJWSInput,
+) => Promise {
+ const set = new LocalJWKSet(jwks)
+
+ const localJWKSet = async (
+ protectedHeader?: types.JWSHeaderParameters,
+ token?: types.FlattenedJWSInput,
+ ): Promise => set.getKey(protectedHeader, token)
+
+ Object.defineProperties(localJWKSet, {
+ jwks: {
+ // @ts-expect-error
+ value: () => clone(set._jwks),
+ enumerable: true,
+ configurable: false,
+ writable: false,
+ },
+ })
+
+ return localJWKSet
+}
diff --git a/dist/deno/jwks/remote.ts b/dist/deno/jwks/remote.ts
new file mode 100644
index 0000000000..119d5184b5
--- /dev/null
+++ b/dist/deno/jwks/remote.ts
@@ -0,0 +1,469 @@
+import type * as types from '../types.d.ts'
+import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from '../util/errors.ts'
+
+import { createLocalJWKSet } from './local.ts'
+import isObject from '../lib/is_object.ts'
+
+function isCloudflareWorkers() {
+ return (
+ // @ts-ignore
+ typeof WebSocketPair !== 'undefined' ||
+ // @ts-ignore
+ (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
+ // @ts-ignore
+ (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel')
+ )
+}
+
+// An explicit user-agent in browser environment is a trigger for CORS preflight requests which
+// are not needed for our request, so we're omitting setting a default user-agent in browser
+// environments.
+let USER_AGENT: string
+// @ts-ignore
+if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
+ const NAME = 'jose'
+ const VERSION = 'v6.0.1'
+ USER_AGENT = `${NAME}/${VERSION}`
+}
+
+/**
+ * When passed to {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} this allows the resolver
+ * to make use of advanced fetch configurations, HTTP Proxies, retry on network errors, etc.
+ *
+ * import ky from 'ky'
+ *
+ * let logRequest!: (request: Request) => void
+ * let logResponse!: (request: Request, response: Response) => void
+ * let logRetry!: (request: Request, error: Error, retryCount: number) => void
+ *
+ * const JWKS = jose.createRemoteJWKSet(url, {
+ * [jose.customFetch]: (...args) =>
+ * ky(args[0], {
+ * ...args[1],
+ * hooks: {
+ * beforeRequest: [
+ * (request) => {
+ * logRequest(request)
+ * },
+ * ],
+ * beforeRetry: [
+ * ({ request, error, retryCount }) => {
+ * logRetry(request, error, retryCount)
+ * },
+ * ],
+ * afterResponse: [
+ * (request, _, response) => {
+ * logResponse(request, response)
+ * },
+ * ],
+ * },
+ * }),
+ * })
+ * ```
+ *
+ * import * as undici from 'undici'
+ *
+ * // see https://undici.nodejs.org/#/docs/api/EnvHttpProxyAgent
+ * let envHttpProxyAgent = new undici.EnvHttpProxyAgent()
+ *
+ * // @ts-ignore
+ * const JWKS = jose.createRemoteJWKSet(url, {
+ * [jose.customFetch]: (...args) => {
+ * // @ts-ignore
+ * return undici.fetch(args[0], { ...args[1], dispatcher: envHttpProxyAgent }) // prettier-ignore
+ * },
+ * })
+ * ```
+ *
+ * import * as undici from 'undici'
+ *
+ * // see https://undici.nodejs.org/#/docs/api/RetryAgent
+ * let retryAgent = new undici.RetryAgent(new undici.Agent(), {
+ * statusCodes: [],
+ * errorCodes: [
+ * 'ECONNRESET',
+ * 'ECONNREFUSED',
+ * 'ENOTFOUND',
+ * 'ENETDOWN',
+ * 'ENETUNREACH',
+ * 'EHOSTDOWN',
+ * 'UND_ERR_SOCKET',
+ * ],
+ * })
+ *
+ * // @ts-ignore
+ * const JWKS = jose.createRemoteJWKSet(url, {
+ * [jose.customFetch]: (...args) => {
+ * // @ts-ignore
+ * return undici.fetch(args[0], { ...args[1], dispatcher: retryAgent }) // prettier-ignore
+ * },
+ * })
+ * ```
+ *
+ * import * as undici from 'undici'
+ *
+ * // see https://undici.nodejs.org/#/docs/api/MockAgent
+ * let mockAgent = new undici.MockAgent()
+ * mockAgent.disableNetConnect()
+ *
+ * // @ts-ignore
+ * const JWKS = jose.createRemoteJWKSet(url, {
+ * [jose.customFetch]: (...args) => {
+ * // @ts-ignore
+ * return undici.fetch(args[0], { ...args[1], dispatcher: mockAgent }) // prettier-ignore
+ * },
+ * })
+ * ```
+ */
+export const customFetch: unique symbol = Symbol()
+
+export type FetchImplementation = (
+ url: string,
+ options: {
+ headers: Headers
+ method: 'GET'
+ redirect: 'manual'
+ signal: AbortSignal
+ },
+) => Promise
+
+async function fetchJwks(
+ url: string,
+ options: {
+ headers: Headers
+ signal: AbortSignal
+ [customFetch]?: FetchImplementation
+ },
+) {
+ const response = await (options?.[customFetch] || fetch)(url, {
+ method: 'GET',
+ signal: options.signal,
+ redirect: 'manual',
+ headers: options.headers,
+ }).catch((err) => {
+ if (err.name === 'TimeoutError') {
+ throw new JWKSTimeout()
+ }
+
+ throw err
+ })
+
+ if (response.status !== 200) {
+ throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response')
+ }
+
+ try {
+ return await response.json()
+ } catch {
+ throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON')
+ }
+}
+
+/**
+ * DANGER ZONE - This option has security implications that must be understood, assessed for
+ * applicability, and accepted before use. It is critical that the JSON Web Key Set cache only be
+ * writable by your own code.
+ *
+ * This option is intended for cloud computing runtimes that cannot keep an in memory cache between
+ * their code's invocations. Use in runtimes where an in memory cache between requests is available
+ * is not desirable.
+ *
+ * When passed to {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} this allows the passed in
+ * object to:
+ *
+ * - Serve as an initial value for the JSON Web Key Set that the module would otherwise need to
+ * trigger an HTTP request for
+ * - Have the JSON Web Key Set the function optionally ended up triggering an HTTP request for
+ * assigned to it as properties
+ *
+ * The intended use pattern is:
+ *
+ * - Before verifying with {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} you pull the
+ * previously cached object from a low-latency key-value store offered by the cloud computing
+ * runtime it is executed on;
+ * - Default to an empty object `{}` instead when there's no previously cached value;
+ * - Pass it in as {@link RemoteJWKSetOptions[jwksCache]};
+ * - Afterwards, update the key-value storage if the {@link ExportedJWKSCache.uat `uat`} property of
+ * the object has changed.
+ *
+ * // Prerequisites
+ * let url!: URL
+ * let jwt!: string
+ * let getPreviouslyCachedJWKS!: () => Promise
+ * let storeNewJWKScache!: (cache: jose.ExportedJWKSCache) => Promise
+ *
+ * // Load JSON Web Key Set cache
+ * const jwksCache: jose.JWKSCacheInput = (await getPreviouslyCachedJWKS()) || {}
+ * const { uat } = jwksCache
+ *
+ * const JWKS = jose.createRemoteJWKSet(url, {
+ * [jose.jwksCache]: jwksCache,
+ * })
+ *
+ * // Use JSON Web Key Set cache
+ * await jose.jwtVerify(jwt, JWKS)
+ *
+ * if (uat !== jwksCache.uat) {
+ * // Update JSON Web Key Set cache
+ * await storeNewJWKScache(jwksCache)
+ * }
+ * ```
+ */
+export const jwksCache: unique symbol = Symbol()
+
+/** Options for the remote JSON Web Key Set. */
+export interface RemoteJWKSetOptions {
+ /**
+ * Timeout (in milliseconds) for the HTTP request. When reached the request will be aborted and
+ * the verification will fail. Default is 5000 (5 seconds).
+ */
+ timeoutDuration?: number
+
+ /**
+ * Duration (in milliseconds) for which no more HTTP requests will be triggered after a previous
+ * successful fetch. Default is 30000 (30 seconds).
+ */
+ cooldownDuration?: number
+
+ /**
+ * Maximum time (in milliseconds) between successful HTTP requests. Default is 600000 (10
+ * minutes).
+ */
+ cacheMaxAge?: number | typeof Infinity
+
+ /** Headers to be sent with the HTTP request. */
+ headers?: Record
+
+ /** See {@link jwksCache}. */
+ [jwksCache]?: JWKSCacheInput
+
+ /** See {@link customFetch}. */
+ [customFetch]?: FetchImplementation
+}
+
+export interface ExportedJWKSCache {
+ jwks: types.JSONWebKeySet
+ uat: number
+}
+
+export type JWKSCacheInput = ExportedJWKSCache | Record
+
+function isFreshJwksCache(input: unknown, cacheMaxAge: number): input is ExportedJWKSCache {
+ if (typeof input !== 'object' || input === null) {
+ return false
+ }
+
+ if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {
+ return false
+ }
+
+ if (
+ !('jwks' in input) ||
+ !isObject(input.jwks) ||
+ !Array.isArray(input.jwks.keys) ||
+ !Array.prototype.every.call(input.jwks.keys, isObject)
+ ) {
+ return false
+ }
+
+ return true
+}
+
+class RemoteJWKSet {
+ private _url: URL
+
+ private _timeoutDuration: number
+
+ private _cooldownDuration: number
+
+ private _cacheMaxAge: number
+
+ private _jwksTimestamp?: number
+
+ private _pendingFetch?: Promise
+
+ private _options: Pick
+
+ private _local!: ReturnType
+
+ private _cache?: JWKSCacheInput
+
+ constructor(url: unknown, options?: RemoteJWKSetOptions) {
+ if (!(url instanceof URL)) {
+ throw new TypeError('url must be an instance of URL')
+ }
+ this._url = new URL(url.href)
+ this._options = { headers: options?.headers }
+ this._timeoutDuration =
+ typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000
+ this._cooldownDuration =
+ typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000
+ this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000
+
+ if (options?.[jwksCache] !== undefined) {
+ this._cache = options?.[jwksCache]
+ if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) {
+ this._jwksTimestamp = this._cache.uat
+ this._local = createLocalJWKSet(this._cache.jwks)
+ }
+ }
+ }
+
+ coolingDown() {
+ return typeof this._jwksTimestamp === 'number'
+ ? Date.now() < this._jwksTimestamp + this._cooldownDuration
+ : false
+ }
+
+ fresh() {
+ return typeof this._jwksTimestamp === 'number'
+ ? Date.now() < this._jwksTimestamp + this._cacheMaxAge
+ : false
+ }
+
+ async getKey(
+ protectedHeader?: types.JWSHeaderParameters,
+ token?: types.FlattenedJWSInput,
+ ): Promise {
+ if (!this._local || !this.fresh()) {
+ await this.reload()
+ }
+
+ try {
+ return await this._local(protectedHeader, token)
+ } catch (err) {
+ if (err instanceof JWKSNoMatchingKey) {
+ if (this.coolingDown() === false) {
+ await this.reload()
+ return this._local(protectedHeader, token)
+ }
+ }
+ throw err
+ }
+ }
+
+ async reload() {
+ // Do not assume a fetch created in another request reliably resolves
+ // see https://github.com/panva/jose/issues/355 and https://github.com/panva/jose/issues/509
+ if (this._pendingFetch && isCloudflareWorkers()) {
+ this._pendingFetch = undefined
+ }
+
+ const headers = new Headers(this._options.headers)
+ if (USER_AGENT && !headers.has('User-Agent')) {
+ headers.set('User-Agent', USER_AGENT)
+ this._options.headers = Object.fromEntries(headers.entries())
+ }
+
+ if (!headers.has('accept')) {
+ headers.set('accept', 'application/json')
+ headers.append('accept', 'application/jwk-set+json')
+ }
+
+ this._pendingFetch ||= fetchJwks(this._url.href, {
+ headers,
+ signal: AbortSignal.timeout(this._timeoutDuration),
+ })
+ .then((json) => {
+ this._local = createLocalJWKSet(json as unknown as types.JSONWebKeySet)
+ if (this._cache) {
+ this._cache.uat = Date.now()
+ this._cache.jwks = json as unknown as types.JSONWebKeySet
+ }
+ this._jwksTimestamp = Date.now()
+ this._pendingFetch = undefined
+ })
+ .catch((err: Error) => {
+ this._pendingFetch = undefined
+ throw err
+ })
+
+ await this._pendingFetch
+ }
+}
+
+/**
+ * Returns a function that resolves a JWS JOSE Header to a public key object downloaded from a
+ * remote endpoint returning a JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC
+ * jwks_uri. The JSON Web Key Set is fetched when no key matches the selection process but only as
+ * frequently as the `cooldownDuration` option allows to prevent abuse.
+ *
+ * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type),
+ * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if
+ * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key
+ * Operations) Parameters (if they are present on the JWK).
+ *
+ * Only a single public key must match the selection process. As shown in the example below when
+ * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt
+ * verification in an iterative manner.
+ *
+ * Note: The function's purpose is to resolve public keys used for verifying signatures and will not
+ * work for public encryption keys.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwks/remote'`.
+ *
+ * @param url URL to fetch the JSON Web Key Set from.
+ * @param options Options for the remote JSON Web Key Set.
+ */
+export function createRemoteJWKSet(
+ url: URL,
+ options?: RemoteJWKSetOptions,
+): {
+ (
+ protectedHeader?: types.JWSHeaderParameters,
+ token?: types.FlattenedJWSInput,
+ ): Promise
+ /** @ignore */
+ coolingDown: boolean
+ /** @ignore */
+ fresh: boolean
+ /** @ignore */
+ reloading: boolean
+ /** @ignore */
+ reload: () => Promise
+ /** @ignore */
+ jwks: () => types.JSONWebKeySet | undefined
+} {
+ const set = new RemoteJWKSet(url, options)
+
+ const remoteJWKSet = async (
+ protectedHeader?: types.JWSHeaderParameters,
+ token?: types.FlattenedJWSInput,
+ ): Promise => set.getKey(protectedHeader, token)
+
+ Object.defineProperties(remoteJWKSet, {
+ coolingDown: {
+ get: () => set.coolingDown(),
+ enumerable: true,
+ configurable: false,
+ },
+ fresh: {
+ get: () => set.fresh(),
+ enumerable: true,
+ configurable: false,
+ },
+ reload: {
+ value: () => set.reload(),
+ enumerable: true,
+ configurable: false,
+ writable: false,
+ },
+ reloading: {
+ // @ts-expect-error
+ get: () => !!set._pendingFetch,
+ enumerable: true,
+ configurable: false,
+ },
+ jwks: {
+ // @ts-expect-error
+ value: () => set._local?.jwks(),
+ enumerable: true,
+ configurable: false,
+ writable: false,
+ },
+ })
+
+ // @ts-expect-error
+ return remoteJWKSet
+}
diff --git a/dist/deno/jws/compact/sign.ts b/dist/deno/jws/compact/sign.ts
new file mode 100644
index 0000000000..569d4d6288
--- /dev/null
+++ b/dist/deno/jws/compact/sign.ts
@@ -0,0 +1,48 @@
+import type * as types from '../../types.d.ts'
+import { FlattenedSign } from '../flattened/sign.ts'
+
+/**
+ * The CompactSign class is used to build and sign Compact JWS strings.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jws/compact/sign'`.
+ *
+ */
+export class CompactSign {
+ private _flattened: FlattenedSign
+
+ /** @param payload Binary representation of the payload to sign. */
+ constructor(payload: Uint8Array) {
+ this._flattened = new FlattenedSign(payload)
+ }
+
+ /**
+ * Sets the JWS Protected Header on the CompactSign object.
+ *
+ * @param protectedHeader JWS Protected Header.
+ */
+ setProtectedHeader(protectedHeader: types.CompactJWSHeaderParameters): this {
+ this._flattened.setProtectedHeader(protectedHeader)
+ return this
+ }
+
+ /**
+ * Signs and resolves the value of the Compact JWS string.
+ *
+ * @param key Private Key or Secret to sign the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Sign options.
+ */
+ async sign(
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.SignOptions,
+ ): Promise {
+ const jws = await this._flattened.sign(key, options)
+
+ if (jws.payload === undefined) {
+ throw new TypeError('use the flattened module for creating JWS with b64: false')
+ }
+
+ return `${jws.protected}.${jws.payload}.${jws.signature}`
+ }
+}
diff --git a/dist/deno/jws/compact/verify.ts b/dist/deno/jws/compact/verify.ts
new file mode 100644
index 0000000000..ccfc035bca
--- /dev/null
+++ b/dist/deno/jws/compact/verify.ts
@@ -0,0 +1,77 @@
+import type * as types from '../../types.d.ts'
+import { flattenedVerify } from '../flattened/verify.ts'
+import { JWSInvalid } from '../../util/errors.ts'
+import { decoder } from '../../lib/buffer_utils.ts'
+
+/**
+ * Interface for Compact JWS Verification dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ *
+ * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set.
+ */
+export interface CompactVerifyGetKey
+ extends types.GenericGetKeyFunction<
+ types.CompactJWSHeaderParameters,
+ types.FlattenedJWSInput,
+ types.CryptoKey | types.KeyObject | types.JWK | Uint8Array
+ > {}
+
+/**
+ * Verifies the signature and format of and afterwards decodes the Compact JWS.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jws/compact/verify'`.
+ *
+ * @param jws Compact JWS.
+ * @param key Key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export function compactVerify(
+ jws: string | Uint8Array,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.VerifyOptions,
+): Promise
+/**
+ * @param jws Compact JWS.
+ * @param getKey Function resolving a key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export function compactVerify(
+ jws: string | Uint8Array,
+ getKey: CompactVerifyGetKey,
+ options?: types.VerifyOptions,
+): Promise
+export async function compactVerify(
+ jws: string | Uint8Array,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array | CompactVerifyGetKey,
+ options?: types.VerifyOptions,
+) {
+ if (jws instanceof Uint8Array) {
+ jws = decoder.decode(jws)
+ }
+
+ if (typeof jws !== 'string') {
+ throw new JWSInvalid('Compact JWS must be a string or Uint8Array')
+ }
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.')
+
+ if (length !== 3) {
+ throw new JWSInvalid('Invalid Compact JWS')
+ }
+
+ const verified = await flattenedVerify(
+ { payload, protected: protectedHeader, signature },
+ key as Parameters[1],
+ options,
+ )
+
+ const result = { payload: verified.payload, protectedHeader: verified.protectedHeader! }
+
+ if (typeof key === 'function') {
+ return { ...result, key: verified.key }
+ }
+
+ return result
+}
diff --git a/dist/deno/jws/flattened/sign.ts b/dist/deno/jws/flattened/sign.ts
new file mode 100644
index 0000000000..57ea7c7260
--- /dev/null
+++ b/dist/deno/jws/flattened/sign.ts
@@ -0,0 +1,150 @@
+import type * as types from '../../types.d.ts'
+import { encode as base64url } from '../../lib/base64url.ts'
+import sign from '../../lib/sign.ts'
+
+import isDisjoint from '../../lib/is_disjoint.ts'
+import { JWSInvalid } from '../../util/errors.ts'
+import { encoder, decoder, concat } from '../../lib/buffer_utils.ts'
+import checkKeyType from '../../lib/check_key_type.ts'
+import validateCrit from '../../lib/validate_crit.ts'
+import normalizeKey from '../../lib/normalize_key.ts'
+
+/**
+ * The FlattenedSign class is used to build and sign Flattened JWS objects.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jws/flattened/sign'`.
+ *
+ */
+export class FlattenedSign {
+ private _payload: Uint8Array
+
+ private _protectedHeader!: types.JWSHeaderParameters
+
+ private _unprotectedHeader!: types.JWSHeaderParameters
+
+ /** @param payload Binary representation of the payload to sign. */
+ constructor(payload: Uint8Array) {
+ if (!(payload instanceof Uint8Array)) {
+ throw new TypeError('payload must be an instance of Uint8Array')
+ }
+ this._payload = payload
+ }
+
+ /**
+ * Sets the JWS Protected Header on the FlattenedSign object.
+ *
+ * @param protectedHeader JWS Protected Header.
+ */
+ setProtectedHeader(protectedHeader: types.JWSHeaderParameters): this {
+ if (this._protectedHeader) {
+ throw new TypeError('setProtectedHeader can only be called once')
+ }
+ this._protectedHeader = protectedHeader
+ return this
+ }
+
+ /**
+ * Sets the JWS Unprotected Header on the FlattenedSign object.
+ *
+ * @param unprotectedHeader JWS Unprotected Header.
+ */
+ setUnprotectedHeader(unprotectedHeader: types.JWSHeaderParameters): this {
+ if (this._unprotectedHeader) {
+ throw new TypeError('setUnprotectedHeader can only be called once')
+ }
+ this._unprotectedHeader = unprotectedHeader
+ return this
+ }
+
+ /**
+ * Signs and resolves the value of the Flattened JWS object.
+ *
+ * @param key Private Key or Secret to sign the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Sign options.
+ */
+ async sign(
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.SignOptions,
+ ): Promise {
+ if (!this._protectedHeader && !this._unprotectedHeader) {
+ throw new JWSInvalid(
+ 'either setProtectedHeader or setUnprotectedHeader must be called before #sign()',
+ )
+ }
+
+ if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) {
+ throw new JWSInvalid(
+ 'JWS Protected and JWS Unprotected Header Parameter names must be disjoint',
+ )
+ }
+
+ const joseHeader: types.JWSHeaderParameters = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ }
+
+ const extensions = validateCrit(
+ JWSInvalid,
+ new Map([['b64', true]]),
+ options?.crit,
+ this._protectedHeader,
+ joseHeader,
+ )
+
+ let b64 = true
+ if (extensions.has('b64')) {
+ b64 = this._protectedHeader.b64!
+ if (typeof b64 !== 'boolean') {
+ throw new JWSInvalid(
+ 'The "b64" (base64url-encode payload) Header Parameter must be a boolean',
+ )
+ }
+ }
+
+ const { alg } = joseHeader
+
+ if (typeof alg !== 'string' || !alg) {
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid')
+ }
+
+ checkKeyType(alg, key, 'sign')
+
+ let payload = this._payload
+ if (b64) {
+ payload = encoder.encode(base64url(payload))
+ }
+
+ let protectedHeader: Uint8Array
+ if (this._protectedHeader) {
+ protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)))
+ } else {
+ protectedHeader = encoder.encode('')
+ }
+
+ const data = concat(protectedHeader, encoder.encode('.'), payload)
+
+ const k = await normalizeKey(key, alg)
+ const signature = await sign(alg, k, data)
+
+ const jws: types.FlattenedJWS = {
+ signature: base64url(signature),
+ payload: '',
+ }
+
+ if (b64) {
+ jws.payload = decoder.decode(payload)
+ }
+
+ if (this._unprotectedHeader) {
+ jws.header = this._unprotectedHeader
+ }
+
+ if (this._protectedHeader) {
+ jws.protected = decoder.decode(protectedHeader)
+ }
+
+ return jws
+ }
+}
diff --git a/dist/deno/jws/flattened/verify.ts b/dist/deno/jws/flattened/verify.ts
new file mode 100644
index 0000000000..2e428f2e1f
--- /dev/null
+++ b/dist/deno/jws/flattened/verify.ts
@@ -0,0 +1,196 @@
+import type * as types from '../../types.d.ts'
+import { decode as base64url } from '../../lib/base64url.ts'
+import verify from '../../lib/verify.ts'
+
+import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.ts'
+import { concat, encoder, decoder } from '../../lib/buffer_utils.ts'
+import isDisjoint from '../../lib/is_disjoint.ts'
+import isObject from '../../lib/is_object.ts'
+import checkKeyType from '../../lib/check_key_type.ts'
+import validateCrit from '../../lib/validate_crit.ts'
+import validateAlgorithms from '../../lib/validate_algorithms.ts'
+import normalizeKey from '../../lib/normalize_key.ts'
+
+/**
+ * Interface for Flattened JWS Verification dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ *
+ * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set.
+ */
+export interface FlattenedVerifyGetKey
+ extends types.GenericGetKeyFunction<
+ types.JWSHeaderParameters | undefined,
+ types.FlattenedJWSInput,
+ types.CryptoKey | types.KeyObject | types.JWK | Uint8Array
+ > {}
+
+/**
+ * Verifies the signature and format of and afterwards decodes the Flattened JWS.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jws/flattened/verify'`.
+ *
+ * @param jws Flattened JWS.
+ * @param key Key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export function flattenedVerify(
+ jws: types.FlattenedJWSInput,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.VerifyOptions,
+): Promise
+/**
+ * @param jws Flattened JWS.
+ * @param getKey Function resolving a key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export function flattenedVerify(
+ jws: types.FlattenedJWSInput,
+ getKey: FlattenedVerifyGetKey,
+ options?: types.VerifyOptions,
+): Promise
+export async function flattenedVerify(
+ jws: types.FlattenedJWSInput,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array | FlattenedVerifyGetKey,
+ options?: types.VerifyOptions,
+) {
+ if (!isObject(jws)) {
+ throw new JWSInvalid('Flattened JWS must be an object')
+ }
+
+ if (jws.protected === undefined && jws.header === undefined) {
+ throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members')
+ }
+
+ if (jws.protected !== undefined && typeof jws.protected !== 'string') {
+ throw new JWSInvalid('JWS Protected Header incorrect type')
+ }
+
+ if (jws.payload === undefined) {
+ throw new JWSInvalid('JWS Payload missing')
+ }
+
+ if (typeof jws.signature !== 'string') {
+ throw new JWSInvalid('JWS Signature missing or incorrect type')
+ }
+
+ if (jws.header !== undefined && !isObject(jws.header)) {
+ throw new JWSInvalid('JWS Unprotected Header incorrect type')
+ }
+
+ let parsedProt: types.JWSHeaderParameters = {}
+ if (jws.protected) {
+ try {
+ const protectedHeader = base64url(jws.protected)
+ parsedProt = JSON.parse(decoder.decode(protectedHeader))
+ } catch {
+ throw new JWSInvalid('JWS Protected Header is invalid')
+ }
+ }
+ if (!isDisjoint(parsedProt, jws.header)) {
+ throw new JWSInvalid(
+ 'JWS Protected and JWS Unprotected Header Parameter names must be disjoint',
+ )
+ }
+
+ const joseHeader: types.JWSHeaderParameters = {
+ ...parsedProt,
+ ...jws.header,
+ }
+
+ const extensions = validateCrit(
+ JWSInvalid,
+ new Map([['b64', true]]),
+ options?.crit,
+ parsedProt,
+ joseHeader,
+ )
+
+ let b64 = true
+ if (extensions.has('b64')) {
+ b64 = parsedProt.b64!
+ if (typeof b64 !== 'boolean') {
+ throw new JWSInvalid(
+ 'The "b64" (base64url-encode payload) Header Parameter must be a boolean',
+ )
+ }
+ }
+
+ const { alg } = joseHeader
+
+ if (typeof alg !== 'string' || !alg) {
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid')
+ }
+
+ const algorithms = options && validateAlgorithms('algorithms', options.algorithms)
+
+ if (algorithms && !algorithms.has(alg)) {
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed')
+ }
+
+ if (b64) {
+ if (typeof jws.payload !== 'string') {
+ throw new JWSInvalid('JWS Payload must be a string')
+ }
+ } else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {
+ throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance')
+ }
+
+ let resolvedKey = false
+ if (typeof key === 'function') {
+ key = await key(parsedProt, jws)
+ resolvedKey = true
+ }
+
+ checkKeyType(alg, key, 'verify')
+
+ const data = concat(
+ encoder.encode(jws.protected ?? ''),
+ encoder.encode('.'),
+ typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload,
+ )
+ let signature: Uint8Array
+ try {
+ signature = base64url(jws.signature)
+ } catch {
+ throw new JWSInvalid('Failed to base64url decode the signature')
+ }
+
+ const k = await normalizeKey(key, alg)
+ const verified = await verify(alg, k, signature, data)
+
+ if (!verified) {
+ throw new JWSSignatureVerificationFailed()
+ }
+
+ let payload: Uint8Array
+ if (b64) {
+ try {
+ payload = base64url(jws.payload)
+ } catch {
+ throw new JWSInvalid('Failed to base64url decode the payload')
+ }
+ } else if (typeof jws.payload === 'string') {
+ payload = encoder.encode(jws.payload)
+ } else {
+ payload = jws.payload
+ }
+
+ const result: types.FlattenedVerifyResult = { payload }
+
+ if (jws.protected !== undefined) {
+ result.protectedHeader = parsedProt
+ }
+
+ if (jws.header !== undefined) {
+ result.unprotectedHeader = jws.header
+ }
+
+ if (resolvedKey) {
+ return { ...result, key: k }
+ }
+
+ return result
+}
diff --git a/dist/deno/jws/general/sign.ts b/dist/deno/jws/general/sign.ts
new file mode 100644
index 0000000000..4085ecdc94
--- /dev/null
+++ b/dist/deno/jws/general/sign.ts
@@ -0,0 +1,139 @@
+import type * as types from '../../types.d.ts'
+import { FlattenedSign } from '../flattened/sign.ts'
+import { JWSInvalid } from '../../util/errors.ts'
+
+export interface Signature {
+ /**
+ * Sets the JWS Protected Header on the Signature object.
+ *
+ * @param protectedHeader JWS Protected Header.
+ */
+ setProtectedHeader(protectedHeader: types.JWSHeaderParameters): Signature
+
+ /**
+ * Sets the JWS Unprotected Header on the Signature object.
+ *
+ * @param unprotectedHeader JWS Unprotected Header.
+ */
+ setUnprotectedHeader(unprotectedHeader: types.JWSHeaderParameters): Signature
+
+ /** A shorthand for calling addSignature() on the enclosing GeneralSign instance */
+ addSignature(...args: Parameters): Signature
+
+ /** A shorthand for calling encrypt() on the enclosing GeneralSign instance */
+ sign(...args: Parameters): Promise
+
+ /** Returns the enclosing GeneralSign */
+ done(): GeneralSign
+}
+
+class IndividualSignature implements Signature {
+ private parent: GeneralSign
+
+ protectedHeader?: types.JWSHeaderParameters
+ unprotectedHeader?: types.JWSHeaderParameters
+ options?: types.SignOptions
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array
+
+ constructor(
+ sig: GeneralSign,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.SignOptions,
+ ) {
+ this.parent = sig
+ this.key = key
+ this.options = options
+ }
+
+ setProtectedHeader(protectedHeader: types.JWSHeaderParameters) {
+ if (this.protectedHeader) {
+ throw new TypeError('setProtectedHeader can only be called once')
+ }
+ this.protectedHeader = protectedHeader
+ return this
+ }
+
+ setUnprotectedHeader(unprotectedHeader: types.JWSHeaderParameters) {
+ if (this.unprotectedHeader) {
+ throw new TypeError('setUnprotectedHeader can only be called once')
+ }
+ this.unprotectedHeader = unprotectedHeader
+ return this
+ }
+
+ addSignature(...args: Parameters) {
+ return this.parent.addSignature(...args)
+ }
+
+ sign(...args: Parameters) {
+ return this.parent.sign(...args)
+ }
+
+ done() {
+ return this.parent
+ }
+}
+
+/**
+ * The GeneralSign class is used to build and sign General JWS objects.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jws/general/sign'`.
+ *
+ */
+export class GeneralSign {
+ private _payload: Uint8Array
+
+ private _signatures: IndividualSignature[] = []
+
+ /** @param payload Binary representation of the payload to sign. */
+ constructor(payload: Uint8Array) {
+ this._payload = payload
+ }
+
+ /**
+ * Adds an additional signature for the General JWS object.
+ *
+ * @param key Private Key or Secret to sign the individual JWS signature with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Sign options.
+ */
+ addSignature(
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.SignOptions,
+ ): Signature {
+ const signature = new IndividualSignature(this, key, options)
+ this._signatures.push(signature)
+ return signature
+ }
+
+ /** Signs and resolves the value of the General JWS object. */
+ async sign(): Promise {
+ if (!this._signatures.length) {
+ throw new JWSInvalid('at least one signature must be added')
+ }
+
+ const jws: types.GeneralJWS = {
+ signatures: [],
+ payload: '',
+ }
+
+ for (let i = 0; i < this._signatures.length; i++) {
+ const signature = this._signatures[i]
+ const flattened = new FlattenedSign(this._payload)
+
+ flattened.setProtectedHeader(signature.protectedHeader!)
+ flattened.setUnprotectedHeader(signature.unprotectedHeader!)
+
+ const { payload, ...rest } = await flattened.sign(signature.key, signature.options)
+ if (i === 0) {
+ jws.payload = payload
+ } else if (jws.payload !== payload) {
+ throw new JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)')
+ }
+ jws.signatures.push(rest)
+ }
+
+ return jws
+ }
+}
diff --git a/dist/deno/jws/general/verify.ts b/dist/deno/jws/general/verify.ts
new file mode 100644
index 0000000000..370d0e4f65
--- /dev/null
+++ b/dist/deno/jws/general/verify.ts
@@ -0,0 +1,76 @@
+import type * as types from '../../types.d.ts'
+import { flattenedVerify } from '../flattened/verify.ts'
+import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.ts'
+import isObject from '../../lib/is_object.ts'
+
+/**
+ * Interface for General JWS Verification dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ *
+ * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set.
+ */
+export interface GeneralVerifyGetKey
+ extends types.GenericGetKeyFunction<
+ types.JWSHeaderParameters,
+ types.FlattenedJWSInput,
+ types.CryptoKey | types.KeyObject | types.JWK | Uint8Array
+ > {}
+
+/**
+ * Verifies the signature and format of and afterwards decodes the General JWS.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jws/general/verify'`.
+ *
+ * @param jws General JWS.
+ * @param key Key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export function generalVerify(
+ jws: types.GeneralJWSInput,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.VerifyOptions,
+): Promise
+/**
+ * @param jws General JWS.
+ * @param getKey Function resolving a key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export function generalVerify(
+ jws: types.GeneralJWSInput,
+ getKey: GeneralVerifyGetKey,
+ options?: types.VerifyOptions,
+): Promise
+export async function generalVerify(
+ jws: types.GeneralJWSInput,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array | GeneralVerifyGetKey,
+ options?: types.VerifyOptions,
+) {
+ if (!isObject(jws)) {
+ throw new JWSInvalid('General JWS must be an object')
+ }
+
+ if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) {
+ throw new JWSInvalid('JWS Signatures missing or incorrect type')
+ }
+
+ for (const signature of jws.signatures) {
+ try {
+ return await flattenedVerify(
+ {
+ header: signature.header,
+ payload: jws.payload,
+ protected: signature.protected,
+ signature: signature.signature,
+ },
+ key as Parameters[1],
+ options,
+ )
+ } catch {
+ //
+ }
+ }
+ throw new JWSSignatureVerificationFailed()
+}
diff --git a/dist/deno/jwt/decrypt.ts b/dist/deno/jwt/decrypt.ts
new file mode 100644
index 0000000000..97d12d0796
--- /dev/null
+++ b/dist/deno/jwt/decrypt.ts
@@ -0,0 +1,93 @@
+import type * as types from '../types.d.ts'
+import { compactDecrypt } from '../jwe/compact/decrypt.ts'
+import jwtPayload from '../lib/jwt_claims_set.ts'
+import { JWTClaimValidationFailed } from '../util/errors.ts'
+
+/** Combination of JWE Decryption options and JWT Claims Set verification options. */
+export interface JWTDecryptOptions
+ extends types.DecryptOptions,
+ types.JWTClaimVerificationOptions {}
+
+/**
+ * Interface for JWT Decryption dynamic key resolution. No token components have been verified at
+ * the time of this function call.
+ */
+export interface JWTDecryptGetKey
+ extends types.GetKeyFunction {}
+
+/**
+ * Verifies the JWT format (to be a JWE Compact format), decrypts the ciphertext, validates the JWT
+ * Claims Set.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwt/decrypt'`.
+ *
+ * @param jwt JSON Web Token value (encoded as JWE).
+ * @param key Private Key or Secret to decrypt and verify the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWT Decryption and JWT Claims Set validation options.
+ */
+export async function jwtDecrypt(
+ jwt: string | Uint8Array,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: JWTDecryptOptions,
+): Promise>
+/**
+ * @param jwt JSON Web Token value (encoded as JWE).
+ * @param getKey Function resolving Private Key or Secret to decrypt and verify the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWT Decryption and JWT Claims Set validation options.
+ */
+export async function jwtDecrypt(
+ jwt: string | Uint8Array,
+ getKey: JWTDecryptGetKey,
+ options?: JWTDecryptOptions,
+): Promise & types.ResolvedKey>
+export async function jwtDecrypt(
+ jwt: string | Uint8Array,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array | JWTDecryptGetKey,
+ options?: JWTDecryptOptions,
+) {
+ const decrypted = await compactDecrypt(jwt, key as Parameters[1], options)
+ const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options)
+
+ const { protectedHeader } = decrypted
+
+ if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) {
+ throw new JWTClaimValidationFailed(
+ 'replicated "iss" claim header parameter mismatch',
+ payload,
+ 'iss',
+ 'mismatch',
+ )
+ }
+
+ if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) {
+ throw new JWTClaimValidationFailed(
+ 'replicated "sub" claim header parameter mismatch',
+ payload,
+ 'sub',
+ 'mismatch',
+ )
+ }
+
+ if (
+ protectedHeader.aud !== undefined &&
+ JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)
+ ) {
+ throw new JWTClaimValidationFailed(
+ 'replicated "aud" claim header parameter mismatch',
+ payload,
+ 'aud',
+ 'mismatch',
+ )
+ }
+
+ const result = { payload, protectedHeader }
+
+ if (typeof key === 'function') {
+ return { ...result, key: decrypted.key }
+ }
+
+ return result
+}
diff --git a/dist/deno/jwt/encrypt.ts b/dist/deno/jwt/encrypt.ts
new file mode 100644
index 0000000000..1265bb1da3
--- /dev/null
+++ b/dist/deno/jwt/encrypt.ts
@@ -0,0 +1,155 @@
+import type * as types from '../types.d.ts'
+import { CompactEncrypt } from '../jwe/compact/encrypt.ts'
+import { encoder } from '../lib/buffer_utils.ts'
+import { ProduceJWT } from './produce.ts'
+
+/**
+ * The EncryptJWT class is used to build and encrypt Compact JWE formatted JSON Web Tokens.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwt/encrypt'`.
+ *
+ */
+export class EncryptJWT extends ProduceJWT {
+ private _cek!: Uint8Array
+
+ private _iv!: Uint8Array
+
+ private _keyManagementParameters!: types.JWEKeyManagementHeaderParameters
+
+ private _protectedHeader!: types.CompactJWEHeaderParameters
+
+ private _replicateIssuerAsHeader!: boolean
+
+ private _replicateSubjectAsHeader!: boolean
+
+ private _replicateAudienceAsHeader!: boolean
+
+ /**
+ * Sets the JWE Protected Header on the EncryptJWT object.
+ *
+ * @param protectedHeader JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc"
+ * (JWE Encryption Algorithm) properties.
+ */
+ setProtectedHeader(protectedHeader: types.CompactJWEHeaderParameters): this {
+ if (this._protectedHeader) {
+ throw new TypeError('setProtectedHeader can only be called once')
+ }
+ this._protectedHeader = protectedHeader
+ return this
+ }
+
+ /**
+ * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is
+ * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or
+ * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed
+ * and missing.
+ *
+ * @param parameters JWE Key Management parameters.
+ */
+ setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): this {
+ if (this._keyManagementParameters) {
+ throw new TypeError('setKeyManagementParameters can only be called once')
+ }
+ this._keyManagementParameters = parameters
+ return this
+ }
+
+ /**
+ * Sets a content encryption key to use, by default a random suitable one is generated for the JWE
+ * enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param cek JWE Content Encryption Key.
+ */
+ setContentEncryptionKey(cek: Uint8Array): this {
+ if (this._cek) {
+ throw new TypeError('setContentEncryptionKey can only be called once')
+ }
+ this._cek = cek
+ return this
+ }
+
+ /**
+ * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable
+ * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param iv JWE Initialization Vector.
+ */
+ setInitializationVector(iv: Uint8Array): this {
+ if (this._iv) {
+ throw new TypeError('setInitializationVector can only be called once')
+ }
+ this._iv = iv
+ return this
+ }
+
+ /**
+ * Replicates the "iss" (Issuer) Claim as a JWE Protected Header Parameter.
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3}
+ */
+ replicateIssuerAsHeader(): this {
+ this._replicateIssuerAsHeader = true
+ return this
+ }
+
+ /**
+ * Replicates the "sub" (Subject) Claim as a JWE Protected Header Parameter.
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3}
+ */
+ replicateSubjectAsHeader(): this {
+ this._replicateSubjectAsHeader = true
+ return this
+ }
+
+ /**
+ * Replicates the "aud" (Audience) Claim as a JWE Protected Header Parameter.
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3}
+ */
+ replicateAudienceAsHeader(): this {
+ this._replicateAudienceAsHeader = true
+ return this
+ }
+
+ /**
+ * Encrypts and returns the JWT.
+ *
+ * @param key Public Key or Secret to encrypt the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Encryption options.
+ */
+ async encrypt(
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.EncryptOptions,
+ ): Promise {
+ const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload)))
+ if (this._replicateIssuerAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss }
+ }
+ if (this._replicateSubjectAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub }
+ }
+ if (this._replicateAudienceAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud }
+ }
+ enc.setProtectedHeader(this._protectedHeader)
+ if (this._iv) {
+ enc.setInitializationVector(this._iv)
+ }
+ if (this._cek) {
+ enc.setContentEncryptionKey(this._cek)
+ }
+ if (this._keyManagementParameters) {
+ enc.setKeyManagementParameters(this._keyManagementParameters)
+ }
+ return enc.encrypt(key, options)
+ }
+}
diff --git a/dist/deno/jwt/produce.ts b/dist/deno/jwt/produce.ts
new file mode 100644
index 0000000000..20812460b5
--- /dev/null
+++ b/dist/deno/jwt/produce.ts
@@ -0,0 +1,173 @@
+import type * as types from '../types.d.ts'
+import epoch from '../lib/epoch.ts'
+import isObject from '../lib/is_object.ts'
+import secs from '../lib/secs.ts'
+
+function validateInput(label: string, input: number) {
+ if (!Number.isFinite(input)) {
+ throw new TypeError(`Invalid ${label} input`)
+ }
+
+ return input
+}
+
+/** Generic class for JWT producing. */
+export class ProduceJWT {
+ protected _payload!: types.JWTPayload
+
+ /** @param payload The JWT Claims Set object. Defaults to an empty object. */
+ constructor(payload: types.JWTPayload = {}) {
+ if (!isObject(payload)) {
+ throw new TypeError('JWT Claims Set MUST be an object')
+ }
+ this._payload = payload
+ }
+
+ /**
+ * Set the "iss" (Issuer) Claim.
+ *
+ * @param issuer "Issuer" Claim value to set on the JWT Claims Set.
+ */
+ setIssuer(issuer: string): this {
+ this._payload = { ...this._payload, iss: issuer }
+ return this
+ }
+
+ /**
+ * Set the "sub" (Subject) Claim.
+ *
+ * @param subject "sub" (Subject) Claim value to set on the JWT Claims Set.
+ */
+ setSubject(subject: string): this {
+ this._payload = { ...this._payload, sub: subject }
+ return this
+ }
+
+ /**
+ * Set the "aud" (Audience) Claim.
+ *
+ * @param audience "aud" (Audience) Claim value to set on the JWT Claims Set.
+ */
+ setAudience(audience: string | string[]): this {
+ this._payload = { ...this._payload, aud: audience }
+ return this
+ }
+
+ /**
+ * Set the "jti" (JWT ID) Claim.
+ *
+ * @param jwtId "jti" (JWT ID) Claim value to set on the JWT Claims Set.
+ */
+ setJti(jwtId: string): this {
+ this._payload = { ...this._payload, jti: jwtId }
+ return this
+ }
+
+ /**
+ * Set the "nbf" (Not Before) Claim.
+ *
+ * - If a `number` is passed as an argument it is used as the claim directly.
+ * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the
+ * claim.
+ * - If a `string` is passed as an argument it is resolved to a time span, and then added to the
+ * current unix timestamp and used as the claim.
+ *
+ * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1
+ * day".
+ *
+ * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins",
+ * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year",
+ * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an
+ * alias for a year.
+ *
+ * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets
+ * subtracted from the current unix timestamp. A "from now" suffix can also be used for
+ * readability when adding to the current unix timestamp.
+ *
+ * @param input "nbf" (Not Before) Claim value to set on the JWT Claims Set.
+ */
+ setNotBefore(input: number | string | Date): this {
+ if (typeof input === 'number') {
+ this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) }
+ } else if (input instanceof Date) {
+ this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) }
+ } else {
+ this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) }
+ }
+ return this
+ }
+
+ /**
+ * Set the "exp" (Expiration Time) Claim.
+ *
+ * - If a `number` is passed as an argument it is used as the claim directly.
+ * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the
+ * claim.
+ * - If a `string` is passed as an argument it is resolved to a time span, and then added to the
+ * current unix timestamp and used as the claim.
+ *
+ * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1
+ * day".
+ *
+ * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins",
+ * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year",
+ * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an
+ * alias for a year.
+ *
+ * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets
+ * subtracted from the current unix timestamp. A "from now" suffix can also be used for
+ * readability when adding to the current unix timestamp.
+ *
+ * @param input "exp" (Expiration Time) Claim value to set on the JWT Claims Set.
+ */
+ setExpirationTime(input: number | string | Date): this {
+ if (typeof input === 'number') {
+ this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) }
+ } else if (input instanceof Date) {
+ this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) }
+ } else {
+ this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) }
+ }
+ return this
+ }
+
+ /**
+ * Set the "iat" (Issued At) Claim.
+ *
+ * - If no argument is used the current unix timestamp is used as the claim.
+ * - If a `number` is passed as an argument it is used as the claim directly.
+ * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the
+ * claim.
+ * - If a `string` is passed as an argument it is resolved to a time span, and then added to the
+ * current unix timestamp and used as the claim.
+ *
+ * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1
+ * day".
+ *
+ * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins",
+ * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year",
+ * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an
+ * alias for a year.
+ *
+ * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets
+ * subtracted from the current unix timestamp. A "from now" suffix can also be used for
+ * readability when adding to the current unix timestamp.
+ *
+ * @param input "iat" (Expiration Time) Claim value to set on the JWT Claims Set.
+ */
+ setIssuedAt(input?: number | string | Date): this {
+ if (typeof input === 'undefined') {
+ this._payload = { ...this._payload, iat: epoch(new Date()) }
+ } else if (input instanceof Date) {
+ this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) }
+ } else if (typeof input === 'string') {
+ this._payload = {
+ ...this._payload,
+ iat: validateInput('setIssuedAt', epoch(new Date()) + secs(input)),
+ }
+ } else {
+ this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) }
+ }
+ return this
+ }
+}
diff --git a/dist/deno/jwt/sign.ts b/dist/deno/jwt/sign.ts
new file mode 100644
index 0000000000..77b30c1640
--- /dev/null
+++ b/dist/deno/jwt/sign.ts
@@ -0,0 +1,50 @@
+import { CompactSign } from '../jws/compact/sign.ts'
+import { JWTInvalid } from '../util/errors.ts'
+import type * as types from '../types.d.ts'
+import { encoder } from '../lib/buffer_utils.ts'
+import { ProduceJWT } from './produce.ts'
+
+/**
+ * The SignJWT class is used to build and sign Compact JWS formatted JSON Web Tokens.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwt/sign'`.
+ *
+ */
+export class SignJWT extends ProduceJWT {
+ private _protectedHeader!: types.JWTHeaderParameters
+
+ /**
+ * Sets the JWS Protected Header on the SignJWT object.
+ *
+ * @param protectedHeader JWS Protected Header. Must contain an "alg" (JWS Algorithm) property.
+ */
+ setProtectedHeader(protectedHeader: types.JWTHeaderParameters): this {
+ this._protectedHeader = protectedHeader
+ return this
+ }
+
+ /**
+ * Signs and returns the JWT.
+ *
+ * @param key Private Key or Secret to sign the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWT Sign options.
+ */
+ async sign(
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: types.SignOptions,
+ ): Promise {
+ const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)))
+ sig.setProtectedHeader(this._protectedHeader)
+ if (
+ Array.isArray(this._protectedHeader?.crit) &&
+ this._protectedHeader.crit.includes('b64') &&
+ // @ts-expect-error
+ this._protectedHeader.b64 === false
+ ) {
+ throw new JWTInvalid('JWTs MUST NOT use unencoded payload')
+ }
+ return sig.sign(key, options)
+ }
+}
diff --git a/dist/deno/jwt/unsecured.ts b/dist/deno/jwt/unsecured.ts
new file mode 100644
index 0000000000..970084d854
--- /dev/null
+++ b/dist/deno/jwt/unsecured.ts
@@ -0,0 +1,65 @@
+import * as base64url from '../lib/base64url.ts'
+
+import type * as types from '../types.d.ts'
+import { decoder } from '../lib/buffer_utils.ts'
+import { JWTInvalid } from '../util/errors.ts'
+import jwtPayload from '../lib/jwt_claims_set.ts'
+import { ProduceJWT } from './produce.ts'
+
+export interface UnsecuredResult {
+ payload: PayloadType & types.JWTPayload
+ header: types.JWSHeaderParameters
+}
+
+/**
+ * The UnsecuredJWT class is a utility for dealing with `{ "alg": "none" }` Unsecured JWTs.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwt/unsecured'`.
+ *
+ */
+export class UnsecuredJWT extends ProduceJWT {
+ /** Encodes the Unsecured JWT. */
+ encode(): string {
+ const header = base64url.encode(JSON.stringify({ alg: 'none' }))
+ const payload = base64url.encode(JSON.stringify(this._payload))
+
+ return `${header}.${payload}.`
+ }
+
+ /**
+ * Decodes an unsecured JWT.
+ *
+ * @param jwt Unsecured JWT to decode the payload of.
+ * @param options JWT Claims Set validation options.
+ */
+ static decode(
+ jwt: string,
+ options?: types.JWTClaimVerificationOptions,
+ ): UnsecuredResult {
+ if (typeof jwt !== 'string') {
+ throw new JWTInvalid('Unsecured JWT must be a string')
+ }
+ const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.')
+
+ if (length !== 3 || signature !== '') {
+ throw new JWTInvalid('Invalid Unsecured JWT')
+ }
+
+ let header: types.JWSHeaderParameters
+ try {
+ header = JSON.parse(decoder.decode(base64url.decode(encodedHeader)))
+ if (header.alg !== 'none') throw new Error()
+ } catch {
+ throw new JWTInvalid('Invalid Unsecured JWT')
+ }
+
+ const payload = jwtPayload(
+ header,
+ base64url.decode(encodedPayload),
+ options,
+ ) as UnsecuredResult['payload']
+
+ return { payload, header }
+ }
+}
diff --git a/dist/deno/jwt/verify.ts b/dist/deno/jwt/verify.ts
new file mode 100644
index 0000000000..c17eb789f0
--- /dev/null
+++ b/dist/deno/jwt/verify.ts
@@ -0,0 +1,67 @@
+import { compactVerify } from '../jws/compact/verify.ts'
+import type * as types from '../types.d.ts'
+import jwtPayload from '../lib/jwt_claims_set.ts'
+import { JWTInvalid } from '../util/errors.ts'
+
+/** Combination of JWS Verification options and JWT Claims Set verification options. */
+export interface JWTVerifyOptions extends types.VerifyOptions, types.JWTClaimVerificationOptions {}
+
+/**
+ * Interface for JWT Verification dynamic key resolution. No token components have been verified at
+ * the time of this function call.
+ *
+ * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set.
+ */
+export interface JWTVerifyGetKey
+ extends types.GenericGetKeyFunction<
+ types.JWTHeaderParameters,
+ types.FlattenedJWSInput,
+ types.CryptoKey | types.KeyObject | types.JWK | Uint8Array
+ > {}
+
+/**
+ * Verifies the JWT format (to be a JWS Compact format), verifies the JWS signature, validates the
+ * JWT Claims Set.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwt/verify'`.
+ *
+ * @param jwt JSON Web Token value (encoded as JWS).
+ * @param key Key to verify the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWT Decryption and JWT Claims Set validation options.
+ */
+export async function jwtVerify(
+ jwt: string | Uint8Array,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ options?: JWTVerifyOptions,
+): Promise>
+
+/**
+ * @param jwt JSON Web Token value (encoded as JWS).
+ * @param getKey Function resolving a key to verify the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWT Decryption and JWT Claims Set validation options.
+ */
+export async function jwtVerify(
+ jwt: string | Uint8Array,
+ getKey: JWTVerifyGetKey,
+ options?: JWTVerifyOptions,
+): Promise & types.ResolvedKey>
+
+export async function jwtVerify(
+ jwt: string | Uint8Array,
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array | JWTVerifyGetKey,
+ options?: JWTVerifyOptions,
+) {
+ const verified = await compactVerify(jwt, key as Parameters[1], options)
+ if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
+ throw new JWTInvalid('JWTs MUST NOT use unencoded payload')
+ }
+ const payload = jwtPayload(verified.protectedHeader, verified.payload, options)
+ const result = { payload, protectedHeader: verified.protectedHeader }
+ if (typeof key === 'function') {
+ return { ...result, key: verified.key }
+ }
+ return result
+}
diff --git a/dist/deno/key/export.ts b/dist/deno/key/export.ts
new file mode 100644
index 0000000000..33a64e6fc3
--- /dev/null
+++ b/dist/deno/key/export.ts
@@ -0,0 +1,42 @@
+import { toSPKI as exportPublic, toPKCS8 as exportPrivate } from '../lib/asn1.ts'
+import keyToJWK from '../lib/key_to_jwk.ts'
+
+import type * as types from '../types.d.ts'
+
+/**
+ * Exports a public {@link !CryptoKey} or {@link !KeyObject} to a PEM-encoded SPKI string format.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/export'`.
+ *
+ * @param key Key to export to a PEM-encoded SPKI string format.
+ */
+export async function exportSPKI(key: types.CryptoKey | types.KeyObject): Promise {
+ return exportPublic(key)
+}
+
+/**
+ * Exports a private {@link !CryptoKey} or {@link !KeyObject} to a PEM-encoded PKCS8 string format.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/export'`.
+ *
+ * @param key Key to export to a PEM-encoded PKCS8 string format.
+ */
+export async function exportPKCS8(key: types.CryptoKey | types.KeyObject): Promise {
+ return exportPrivate(key)
+}
+
+/**
+ * Exports a {@link !CryptoKey}, {@link !KeyObject}, or {@link !Uint8Array} to a JWK.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/export'`.
+ *
+ * @param key Key to export as JWK.
+ */
+export async function exportJWK(
+ key: types.CryptoKey | types.KeyObject | Uint8Array,
+): Promise {
+ return keyToJWK(key)
+}
diff --git a/dist/deno/key/generate_key_pair.ts b/dist/deno/key/generate_key_pair.ts
new file mode 100644
index 0000000000..0151c29d4c
--- /dev/null
+++ b/dist/deno/key/generate_key_pair.ts
@@ -0,0 +1,149 @@
+import { JOSENotSupported } from '../util/errors.ts'
+
+import type * as types from '../types.d.ts'
+
+export interface GenerateKeyPairResult {
+ /** The generated Private Key. */
+ privateKey: types.CryptoKey
+
+ /** Public Key corresponding to the generated Private Key. */
+ publicKey: types.CryptoKey
+}
+
+export interface GenerateKeyPairOptions {
+ /**
+ * The EC "crv" (Curve) or OKP "crv" (Subtype of Key Pair) value to generate. The curve must be
+ * both supported on the runtime as well as applicable for the given JWA algorithm identifier.
+ */
+ crv?: string
+
+ /**
+ * A hint for RSA algorithms to generate an RSA key of a given `modulusLength` (Key size in bits).
+ * JOSE requires 2048 bits or larger. Default is 2048.
+ */
+ modulusLength?: number
+
+ /**
+ * The value to use as {@link !SubtleCrypto.generateKey} `extractable` argument. Default is false.
+ *
+ */
+ extractable?: boolean
+}
+
+function getModulusLengthOption(options?: GenerateKeyPairOptions) {
+ const modulusLength = options?.modulusLength ?? 2048
+ if (typeof modulusLength !== 'number' || modulusLength < 2048) {
+ throw new JOSENotSupported(
+ 'Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used',
+ )
+ }
+ return modulusLength
+}
+
+/**
+ * Generates a private and a public key for a given JWA algorithm identifier. This can only generate
+ * asymmetric key pairs. For symmetric secrets use the `generateSecret` function.
+ *
+ * Note: The `privateKey` is generated with `extractable` set to `false` by default. See
+ * {@link GenerateKeyPairOptions.extractable} to generate an extractable `privateKey`.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/generate/keypair'`.
+ *
+ * @param alg JWA Algorithm Identifier to be used with the generated key pair. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ * @param options Additional options passed down to the key pair generation.
+ */
+export async function generateKeyPair(
+ alg: string,
+ options?: GenerateKeyPairOptions,
+): Promise {
+ let algorithm: RsaHashedKeyGenParams | EcKeyGenParams | KeyAlgorithm
+ let keyUsages: KeyUsage[]
+
+ switch (alg) {
+ case 'PS256':
+ case 'PS384':
+ case 'PS512':
+ algorithm = {
+ name: 'RSA-PSS',
+ hash: `SHA-${alg.slice(-3)}`,
+ publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
+ modulusLength: getModulusLengthOption(options),
+ }
+ keyUsages = ['sign', 'verify']
+ break
+ case 'RS256':
+ case 'RS384':
+ case 'RS512':
+ algorithm = {
+ name: 'RSASSA-PKCS1-v1_5',
+ hash: `SHA-${alg.slice(-3)}`,
+ publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
+ modulusLength: getModulusLengthOption(options),
+ }
+ keyUsages = ['sign', 'verify']
+ break
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512':
+ algorithm = {
+ name: 'RSA-OAEP',
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
+ publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
+ modulusLength: getModulusLengthOption(options),
+ }
+ keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey']
+ break
+ case 'ES256':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-256' }
+ keyUsages = ['sign', 'verify']
+ break
+ case 'ES384':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-384' }
+ keyUsages = ['sign', 'verify']
+ break
+ case 'ES512':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-521' }
+ keyUsages = ['sign', 'verify']
+ break
+ case 'Ed25519': // Fall through
+ case 'EdDSA': {
+ keyUsages = ['sign', 'verify']
+ algorithm = { name: 'Ed25519' }
+ break
+ }
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW': {
+ keyUsages = ['deriveBits']
+ const crv = options?.crv ?? 'P-256'
+ switch (crv) {
+ case 'P-256':
+ case 'P-384':
+ case 'P-521': {
+ algorithm = { name: 'ECDH', namedCurve: crv }
+ break
+ }
+ case 'X25519':
+ algorithm = { name: 'X25519' }
+ break
+ default:
+ throw new JOSENotSupported(
+ 'Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519',
+ )
+ }
+ break
+ }
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')
+ }
+
+ return crypto.subtle.generateKey(
+ algorithm,
+ options?.extractable ?? false,
+ keyUsages,
+ ) as Promise
+}
diff --git a/dist/deno/key/generate_secret.ts b/dist/deno/key/generate_secret.ts
new file mode 100644
index 0000000000..4522cad988
--- /dev/null
+++ b/dist/deno/key/generate_secret.ts
@@ -0,0 +1,64 @@
+import { JOSENotSupported } from '../util/errors.ts'
+
+import type * as types from '../types.d.ts'
+
+export interface GenerateSecretOptions {
+ /** The value to use as {@link !SubtleCrypto.generateKey} `extractable` argument. Default is false. */
+ extractable?: boolean
+}
+
+/**
+ * Generates a symmetric secret key for a given JWA algorithm identifier.
+ *
+ * Note: The secret key is generated with `extractable` set to `false` by default.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/generate/secret'`.
+ *
+ * @param alg JWA Algorithm Identifier to be used with the generated secret. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ * @param options Additional options passed down to the secret generation.
+ */
+export async function generateSecret(
+ alg: string,
+ options?: GenerateSecretOptions,
+): Promise {
+ let length: number
+ let algorithm: AesKeyGenParams | HmacKeyGenParams
+ let keyUsages: KeyUsage[]
+ switch (alg) {
+ case 'HS256':
+ case 'HS384':
+ case 'HS512':
+ length = parseInt(alg.slice(-3), 10)
+ algorithm = { name: 'HMAC', hash: `SHA-${length}`, length }
+ keyUsages = ['sign', 'verify']
+ break
+ case 'A128CBC-HS256':
+ case 'A192CBC-HS384':
+ case 'A256CBC-HS512':
+ length = parseInt(alg.slice(-3), 10)
+ return crypto.getRandomValues(new Uint8Array(length >> 3))
+ case 'A128KW':
+ case 'A192KW':
+ case 'A256KW':
+ length = parseInt(alg.slice(1, 4), 10)
+ algorithm = { name: 'AES-KW', length }
+ keyUsages = ['wrapKey', 'unwrapKey']
+ break
+ case 'A128GCMKW':
+ case 'A192GCMKW':
+ case 'A256GCMKW':
+ case 'A128GCM':
+ case 'A192GCM':
+ case 'A256GCM':
+ length = parseInt(alg.slice(1, 4), 10)
+ algorithm = { name: 'AES-GCM', length }
+ keyUsages = ['encrypt', 'decrypt']
+ break
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')
+ }
+
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages)
+}
diff --git a/dist/deno/key/import.ts b/dist/deno/key/import.ts
new file mode 100644
index 0000000000..7aeaf7d1d2
--- /dev/null
+++ b/dist/deno/key/import.ts
@@ -0,0 +1,140 @@
+import { decode as decodeBase64URL } from '../lib/base64url.ts'
+import { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.ts'
+import toCryptoKey from '../lib/jwk_to_key.ts'
+
+import { JOSENotSupported } from '../util/errors.ts'
+import isObject from '../lib/is_object.ts'
+import type * as types from '../types.d.ts'
+
+export interface KeyImportOptions {
+ /**
+ * The value to use as {@link !SubtleCrypto.importKey} `extractable` argument. Default is false for
+ * private and secret keys, true otherwise.
+ */
+ extractable?: boolean
+}
+
+/**
+ * Imports a PEM-encoded SPKI string as a {@link !CryptoKey}.
+ *
+ * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in
+ * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption
+ * (1.2.840.113549.1.1.1) instead for all RSA algorithms.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/import'`.
+ *
+ * @param spki PEM-encoded SPKI string
+ * @param alg JSON Web Algorithm identifier to be used with the imported key. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ */
+export async function importSPKI(
+ spki: string,
+ alg: string,
+ options?: KeyImportOptions,
+): Promise {
+ if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {
+ throw new TypeError('"spki" must be SPKI formatted string')
+ }
+ return fromSPKI(spki, alg, options)
+}
+
+/**
+ * Imports the SPKI from an X.509 string certificate as a {@link !CryptoKey}.
+ *
+ * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in
+ * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption
+ * (1.2.840.113549.1.1.1) instead for all RSA algorithms.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/import'`.
+ *
+ * @param x509 X.509 certificate string
+ * @param alg JSON Web Algorithm identifier to be used with the imported key. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ */
+export async function importX509(
+ x509: string,
+ alg: string,
+ options?: KeyImportOptions,
+): Promise {
+ if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {
+ throw new TypeError('"x509" must be X.509 formatted string')
+ }
+ return fromX509(x509, alg, options)
+}
+
+/**
+ * Imports a PEM-encoded PKCS#8 string as a {@link !CryptoKey}.
+ *
+ * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in
+ * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption
+ * (1.2.840.113549.1.1.1) instead for all RSA algorithms.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/import'`.
+ *
+ * @param pkcs8 PEM-encoded PKCS#8 string
+ * @param alg JSON Web Algorithm identifier to be used with the imported key. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ */
+export async function importPKCS8(
+ pkcs8: string,
+ alg: string,
+ options?: KeyImportOptions,
+): Promise {
+ if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {
+ throw new TypeError('"pkcs8" must be PKCS#8 formatted string')
+ }
+ return fromPKCS8(pkcs8, alg, options)
+}
+
+/**
+ * Imports a JWK to a {@link !CryptoKey}. Either the JWK "alg" (Algorithm) Parameter, or the optional
+ * "alg" argument, must be present.
+ *
+ * Note: The JSON Web Key parameters "use", "key_ops", and "ext" are also used in the
+ * {@link !CryptoKey} import process.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/import'`.
+ *
+ * @param jwk JSON Web Key.
+ * @param alg JSON Web Algorithm identifier to be used with the imported key. Default is the "alg"
+ * property on the JWK. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ */
+export async function importJWK(
+ jwk: types.JWK,
+ alg?: string,
+ options?: KeyImportOptions,
+): Promise {
+ if (!isObject(jwk)) {
+ throw new TypeError('JWK must be an object')
+ }
+
+ let ext: boolean | undefined
+
+ alg ??= jwk.alg
+ ext ??= options?.extractable ?? jwk.ext
+
+ switch (jwk.kty) {
+ case 'oct':
+ if (typeof jwk.k !== 'string' || !jwk.k) {
+ throw new TypeError('missing "k" (Key Value) Parameter value')
+ }
+
+ return decodeBase64URL(jwk.k)
+ case 'RSA':
+ if ('oth' in jwk && jwk.oth !== undefined) {
+ throw new JOSENotSupported(
+ 'RSA JWK "oth" (Other Primes Info) Parameter value is not supported',
+ )
+ }
+ case 'EC':
+ case 'OKP':
+ return toCryptoKey({ ...jwk, alg, ext })
+ default:
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value')
+ }
+}
diff --git a/dist/deno/lib/aesgcmkw.ts b/dist/deno/lib/aesgcmkw.ts
new file mode 100644
index 0000000000..395271242c
--- /dev/null
+++ b/dist/deno/lib/aesgcmkw.ts
@@ -0,0 +1,26 @@
+import encrypt from './encrypt.ts'
+import decrypt from './decrypt.ts'
+import { encode as base64url } from '../lib/base64url.ts'
+
+export async function wrap(alg: string, key: unknown, cek: Uint8Array, iv?: Uint8Array) {
+ const jweAlgorithm = alg.slice(0, 7)
+
+ const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0))
+
+ return {
+ encryptedKey: wrapped.ciphertext,
+ iv: base64url(wrapped.iv!),
+ tag: base64url(wrapped.tag!),
+ }
+}
+
+export async function unwrap(
+ alg: string,
+ key: unknown,
+ encryptedKey: Uint8Array,
+ iv: Uint8Array,
+ tag: Uint8Array,
+) {
+ const jweAlgorithm = alg.slice(0, 7)
+ return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0))
+}
diff --git a/dist/deno/lib/aeskw.ts b/dist/deno/lib/aeskw.ts
new file mode 100644
index 0000000000..dd4b697606
--- /dev/null
+++ b/dist/deno/lib/aeskw.ts
@@ -0,0 +1,56 @@
+import type * as types from '../types.d.ts'
+import { checkEncCryptoKey } from './crypto_key.ts'
+
+function checkKeySize(key: types.CryptoKey, alg: string) {
+ if ((key.algorithm as AesKeyAlgorithm).length !== parseInt(alg.slice(1, 4), 10)) {
+ throw new TypeError(`Invalid key size for alg: ${alg}`)
+ }
+}
+
+function getCryptoKey(key: types.CryptoKey | Uint8Array, alg: string, usage: KeyUsage) {
+ if (key instanceof Uint8Array) {
+ return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage])
+ }
+ checkEncCryptoKey(key, alg, usage)
+ return key
+}
+
+export async function wrap(alg: string, key: types.CryptoKey | Uint8Array, cek: Uint8Array) {
+ const cryptoKey = await getCryptoKey(key, alg, 'wrapKey')
+
+ checkKeySize(cryptoKey, alg)
+
+ // algorithm used is irrelevant
+ const cryptoKeyCek = await crypto.subtle.importKey(
+ 'raw',
+ cek,
+ { hash: 'SHA-256', name: 'HMAC' },
+ true,
+ ['sign'],
+ )
+
+ return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW'))
+}
+
+export async function unwrap(
+ alg: string,
+ key: types.CryptoKey | Uint8Array,
+ encryptedKey: Uint8Array,
+) {
+ const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey')
+
+ checkKeySize(cryptoKey, alg)
+
+ // algorithm used is irrelevant
+ const cryptoKeyCek = await crypto.subtle.unwrapKey(
+ 'raw',
+ encryptedKey,
+ cryptoKey,
+ 'AES-KW',
+ { hash: 'SHA-256', name: 'HMAC' },
+ true,
+ ['sign'],
+ )
+
+ return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek))
+}
diff --git a/dist/deno/lib/asn1.ts b/dist/deno/lib/asn1.ts
new file mode 100644
index 0000000000..aa1ee154c2
--- /dev/null
+++ b/dist/deno/lib/asn1.ts
@@ -0,0 +1,276 @@
+import type * as types from '../types.d.ts'
+import invalidKeyInput from './invalid_key_input.ts'
+import { encodeBase64, decodeBase64 } from './base64url.ts'
+import { JOSENotSupported } from '../util/errors.ts'
+import { isCryptoKey, isKeyObject } from './is_key_like.ts'
+
+import type { KeyImportOptions } from '../key/import.ts'
+
+const formatPEM = (b64: string, descriptor: string) => {
+ const newlined = (b64.match(/.{1,64}/g) || []).join('\n')
+ return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`
+}
+
+interface ExportOptions {
+ format: 'pem'
+ type: 'spki' | 'pkcs8'
+}
+
+interface ExtractableKeyObject extends types.KeyObject {
+ export(arg: ExportOptions): string
+}
+
+const genericExport = async (
+ keyType: 'private' | 'public',
+ keyFormat: 'spki' | 'pkcs8',
+ key: unknown,
+) => {
+ if (isKeyObject(key)) {
+ if (key.type !== keyType) {
+ throw new TypeError(`key is not a ${keyType} key`)
+ }
+
+ return (key as ExtractableKeyObject).export({ format: 'pem', type: keyFormat })
+ }
+
+ if (!isCryptoKey(key)) {
+ throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject'))
+ }
+
+ if (!key.extractable) {
+ throw new TypeError('CryptoKey is not extractable')
+ }
+
+ if (key.type !== keyType) {
+ throw new TypeError(`key is not a ${keyType} key`)
+ }
+
+ return formatPEM(
+ encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))),
+ `${keyType.toUpperCase()} KEY`,
+ )
+}
+
+export const toSPKI = (key: unknown): Promise => {
+ return genericExport('public', 'spki', key)
+}
+
+export const toPKCS8 = (key: unknown): Promise => {
+ return genericExport('private', 'pkcs8', key)
+}
+
+const findOid = (keyData: Uint8Array, oid: number[], from = 0): boolean => {
+ if (from === 0) {
+ oid.unshift(oid.length)
+ oid.unshift(0x06)
+ }
+ const i = keyData.indexOf(oid[0], from)
+ if (i === -1) return false
+ const sub = keyData.subarray(i, i + oid.length)
+ if (sub.length !== oid.length) return false
+ return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1)
+}
+
+const getNamedCurve = (keyData: Uint8Array): string | undefined => {
+ switch (true) {
+ case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]):
+ return 'P-256'
+ case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]):
+ return 'P-384'
+ case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]):
+ return 'P-521'
+ default:
+ return undefined
+ }
+}
+
+const genericImport = async (
+ replace: RegExp,
+ keyFormat: 'spki' | 'pkcs8',
+ pem: string,
+ alg: string,
+ options?: KeyImportOptions,
+) => {
+ let algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm
+ let keyUsages: KeyUsage[]
+
+ const keyData = new Uint8Array(
+ atob(pem.replace(replace, ''))
+ .split('')
+ .map((c) => c.charCodeAt(0)),
+ )
+
+ const isPublic = keyFormat === 'spki'
+
+ switch (alg) {
+ case 'PS256':
+ case 'PS384':
+ case 'PS512':
+ algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` }
+ keyUsages = isPublic ? ['verify'] : ['sign']
+ break
+ case 'RS256':
+ case 'RS384':
+ case 'RS512':
+ algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` }
+ keyUsages = isPublic ? ['verify'] : ['sign']
+ break
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512':
+ algorithm = {
+ name: 'RSA-OAEP',
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
+ }
+ keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey']
+ break
+ case 'ES256':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-256' }
+ keyUsages = isPublic ? ['verify'] : ['sign']
+ break
+ case 'ES384':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-384' }
+ keyUsages = isPublic ? ['verify'] : ['sign']
+ break
+ case 'ES512':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-521' }
+ keyUsages = isPublic ? ['verify'] : ['sign']
+ break
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW': {
+ const namedCurve = getNamedCurve(keyData)
+ algorithm = namedCurve?.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: 'X25519' }
+ keyUsages = isPublic ? [] : ['deriveBits']
+ break
+ }
+ case 'Ed25519': // Fall through
+ case 'EdDSA':
+ algorithm = { name: 'Ed25519' }
+ keyUsages = isPublic ? ['verify'] : ['sign']
+ break
+ default:
+ throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value')
+ }
+
+ return crypto.subtle.importKey(
+ keyFormat,
+ keyData,
+ algorithm,
+ options?.extractable ?? (isPublic ? true : false),
+ keyUsages,
+ )
+}
+
+type PEMImportFunction = (
+ pem: string,
+ alg: string,
+ options?: KeyImportOptions,
+) => Promise
+
+export const fromPKCS8: PEMImportFunction = (pem, alg, options?) => {
+ return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options)
+}
+
+export const fromSPKI: PEMImportFunction = (pem, alg, options?) => {
+ return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, 'spki', pem, alg, options)
+}
+
+function getElement(seq: Uint8Array) {
+ const result = []
+ let next = 0
+
+ while (next < seq.length) {
+ const nextPart = parseElement(seq.subarray(next))
+ result.push(nextPart)
+ next += nextPart.byteLength
+ }
+ return result
+}
+
+function parseElement(bytes: Uint8Array) {
+ let position = 0
+
+ // tag
+ let tag = bytes[0] & 0x1f
+ position++
+ if (tag === 0x1f) {
+ tag = 0
+ while (bytes[position] >= 0x80) {
+ tag = tag * 128 + bytes[position] - 0x80
+ position++
+ }
+ tag = tag * 128 + bytes[position] - 0x80
+ position++
+ }
+
+ // length
+ let length = 0
+ if (bytes[position] < 0x80) {
+ length = bytes[position]
+ position++
+ } else if (length === 0x80) {
+ length = 0
+
+ while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) {
+ if (length > bytes.byteLength) {
+ throw new TypeError('invalid indefinite form length')
+ }
+ length++
+ }
+
+ const byteLength = position + length + 2
+ return {
+ byteLength,
+ contents: bytes.subarray(position, position + length),
+ raw: bytes.subarray(0, byteLength),
+ }
+ } else {
+ const numberOfDigits = bytes[position] & 0x7f
+ position++
+ length = 0
+ for (let i = 0; i < numberOfDigits; i++) {
+ length = length * 256 + bytes[position]
+ position++
+ }
+ }
+
+ const byteLength = position + length
+ return {
+ byteLength,
+ contents: bytes.subarray(position, byteLength),
+ raw: bytes.subarray(0, byteLength),
+ }
+}
+
+function spkiFromX509(buf: Uint8Array) {
+ const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents)
+ return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw)
+}
+
+let X509Certificate: any
+function getSPKI(x509: string): string {
+ if (
+ // @ts-ignore
+ (X509Certificate ||= globalThis.process?.getBuiltinModule?.('node:crypto')?.X509Certificate)
+ ) {
+ try {
+ return new X509Certificate(x509).publicKey.export({ format: 'pem', type: 'spki' })
+ } catch {}
+ }
+ const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '')
+ const raw = decodeBase64(pem)
+ return formatPEM(spkiFromX509(raw), 'PUBLIC KEY')
+}
+
+export const fromX509: PEMImportFunction = (pem, alg, options?) => {
+ let spki: string
+ try {
+ spki = getSPKI(pem)
+ } catch (cause) {
+ throw new TypeError('Failed to parse the X.509 certificate', { cause })
+ }
+ return fromSPKI(spki, alg, options)
+}
diff --git a/dist/deno/lib/base64url.ts b/dist/deno/lib/base64url.ts
new file mode 100644
index 0000000000..2cdfdf2211
--- /dev/null
+++ b/dist/deno/lib/base64url.ts
@@ -0,0 +1,45 @@
+import { encoder, decoder, Buffer } from '../lib/buffer_utils.ts'
+
+export function encodeBase64(input: Uint8Array | string): string {
+ if (Buffer) return Buffer.from(input).toString('base64')
+ let unencoded = input
+ if (typeof unencoded === 'string') {
+ unencoded = encoder.encode(unencoded)
+ }
+ const CHUNK_SIZE = 0x8000
+ const arr = []
+ for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {
+ // @ts-expect-error
+ arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)))
+ }
+ return btoa(arr.join(''))
+}
+
+export function encode(input: Uint8Array | string): string {
+ if (Buffer) return Buffer.from(input).toString('base64url')
+ return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')
+}
+
+export function decodeBase64(encoded: string): Uint8Array {
+ if (Buffer) return Buffer.from(encoded, 'base64')
+ const binary = atob(encoded)
+ const bytes = new Uint8Array(binary.length)
+ for (let i = 0; i < binary.length; i++) {
+ bytes[i] = binary.charCodeAt(i)
+ }
+ return bytes
+}
+
+export function decode(input: Uint8Array | string): Uint8Array {
+ let encoded = input
+ if (encoded instanceof Uint8Array) {
+ encoded = decoder.decode(encoded)
+ }
+ if (Buffer) return Buffer.from(encoded, 'base64url')
+ encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '')
+ try {
+ return decodeBase64(encoded)
+ } catch {
+ throw new TypeError('The input to be decoded is not correctly encoded.')
+ }
+}
diff --git a/dist/deno/lib/buffer_utils.ts b/dist/deno/lib/buffer_utils.ts
new file mode 100644
index 0000000000..e2f5bc471a
--- /dev/null
+++ b/dist/deno/lib/buffer_utils.ts
@@ -0,0 +1,43 @@
+export const encoder = new TextEncoder()
+export const decoder = new TextDecoder()
+
+const MAX_INT32 = 2 ** 32
+
+// @ts-expect-error
+const Buffer: any = globalThis.process?.getBuiltinModule?.('node:buffer')?.Buffer
+
+export { Buffer }
+
+export function concat(...buffers: Uint8Array[]): Uint8Array {
+ if (Buffer) return Buffer.concat(buffers)
+ const size = buffers.reduce((acc, { length }) => acc + length, 0)
+ const buf = new Uint8Array(size)
+ let i = 0
+ for (const buffer of buffers) {
+ buf.set(buffer, i)
+ i += buffer.length
+ }
+ return buf
+}
+
+function writeUInt32BE(buf: Uint8Array, value: number, offset?: number) {
+ if (value < 0 || value >= MAX_INT32) {
+ throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`)
+ }
+ buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset)
+}
+
+export function uint64be(value: number) {
+ const high = Math.floor(value / MAX_INT32)
+ const low = value % MAX_INT32
+ const buf = new Uint8Array(8)
+ writeUInt32BE(buf, high, 0)
+ writeUInt32BE(buf, low, 4)
+ return buf
+}
+
+export function uint32be(value: number) {
+ const buf = new Uint8Array(4)
+ writeUInt32BE(buf, value)
+ return buf
+}
diff --git a/dist/deno/lib/cek.ts b/dist/deno/lib/cek.ts
new file mode 100644
index 0000000000..b76c1a7f5f
--- /dev/null
+++ b/dist/deno/lib/cek.ts
@@ -0,0 +1,21 @@
+import { JOSENotSupported } from '../util/errors.ts'
+
+export function bitLength(alg: string) {
+ switch (alg) {
+ case 'A128GCM':
+ return 128
+ case 'A192GCM':
+ return 192
+ case 'A256GCM':
+ case 'A128CBC-HS256':
+ return 256
+ case 'A192CBC-HS384':
+ return 384
+ case 'A256CBC-HS512':
+ return 512
+ default:
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`)
+ }
+}
+export default (alg: string): Uint8Array =>
+ crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3))
diff --git a/dist/deno/lib/check_cek_length.ts b/dist/deno/lib/check_cek_length.ts
new file mode 100644
index 0000000000..5ac4d073c9
--- /dev/null
+++ b/dist/deno/lib/check_cek_length.ts
@@ -0,0 +1,10 @@
+import { JWEInvalid } from '../util/errors.ts'
+
+export default (cek: Uint8Array, expected: number) => {
+ const actual = cek.byteLength << 3
+ if (actual !== expected) {
+ throw new JWEInvalid(
+ `Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`,
+ )
+ }
+}
diff --git a/dist/deno/lib/check_iv_length.ts b/dist/deno/lib/check_iv_length.ts
new file mode 100644
index 0000000000..f6d9fa5f84
--- /dev/null
+++ b/dist/deno/lib/check_iv_length.ts
@@ -0,0 +1,8 @@
+import { JWEInvalid } from '../util/errors.ts'
+import { bitLength } from './iv.ts'
+
+export default (enc: string, iv: Uint8Array) => {
+ if (iv.length << 3 !== bitLength(enc)) {
+ throw new JWEInvalid('Invalid Initialization Vector length')
+ }
+}
diff --git a/dist/deno/lib/check_key_length.ts b/dist/deno/lib/check_key_length.ts
new file mode 100644
index 0000000000..1896427dbd
--- /dev/null
+++ b/dist/deno/lib/check_key_length.ts
@@ -0,0 +1,10 @@
+import type * as types from '../types.d.ts'
+
+export default (alg: string, key: types.CryptoKey) => {
+ if (alg.startsWith('RS') || alg.startsWith('PS')) {
+ const { modulusLength } = key.algorithm as RsaKeyAlgorithm
+ if (typeof modulusLength !== 'number' || modulusLength < 2048) {
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`)
+ }
+ }
+}
diff --git a/dist/deno/lib/check_key_type.ts b/dist/deno/lib/check_key_type.ts
new file mode 100644
index 0000000000..08f9769b5d
--- /dev/null
+++ b/dist/deno/lib/check_key_type.ts
@@ -0,0 +1,161 @@
+import { withAlg as invalidKeyInput } from './invalid_key_input.ts'
+import isKeyLike from './is_key_like.ts'
+import * as jwk from './is_jwk.ts'
+import type * as types from '../types.d.ts'
+
+// @ts-expect-error
+const tag = (key: unknown): string => key?.[Symbol.toStringTag]
+
+const jwkMatchesOp = (alg: string, key: types.JWK, usage: Usage) => {
+ if (key.use !== undefined) {
+ let expected: string
+ switch (usage) {
+ case 'sign':
+ case 'verify':
+ expected = 'sig'
+ break
+ case 'encrypt':
+ case 'decrypt':
+ expected = 'enc'
+ break
+ }
+ if (key.use !== expected) {
+ throw new TypeError(
+ `Invalid key for this operation, its "use" must be "${expected}" when present`,
+ )
+ }
+ }
+
+ if (key.alg !== undefined && key.alg !== alg) {
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`)
+ }
+
+ if (Array.isArray(key.key_ops)) {
+ let expectedKeyOp
+
+ switch (true) {
+ case usage === 'sign' || usage === 'verify': // Fall through
+ case alg === 'dir': // Fall through
+ case alg.includes('CBC-HS'):
+ expectedKeyOp = usage
+ break
+ case alg.startsWith('PBES2'):
+ expectedKeyOp = 'deriveBits'
+ break
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
+ if (!alg.includes('GCM') && alg.endsWith('KW')) {
+ expectedKeyOp = usage === 'encrypt' ? 'wrapKey' : 'unwrapKey'
+ } else {
+ expectedKeyOp = usage
+ }
+ break
+ case usage === 'encrypt' && alg.startsWith('RSA'):
+ expectedKeyOp = 'wrapKey'
+ break
+ case usage === 'decrypt':
+ expectedKeyOp = alg.startsWith('RSA') ? 'unwrapKey' : 'deriveBits'
+ break
+ }
+
+ if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
+ throw new TypeError(
+ `Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`,
+ )
+ }
+ }
+
+ return true
+}
+
+const symmetricTypeCheck = (alg: string, key: unknown, usage: Usage) => {
+ if (key instanceof Uint8Array) return
+
+ if (jwk.isJWK(key)) {
+ if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return
+ throw new TypeError(
+ `JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`,
+ )
+ }
+
+ if (!isKeyLike(key)) {
+ throw new TypeError(
+ invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key', 'Uint8Array'),
+ )
+ }
+
+ if (key.type !== 'secret') {
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`)
+ }
+}
+
+const asymmetricTypeCheck = (alg: string, key: unknown, usage: Usage) => {
+ if (jwk.isJWK(key)) {
+ switch (usage) {
+ case 'decrypt':
+ case 'sign':
+ if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return
+ throw new TypeError(`JSON Web Key for this operation be a private JWK`)
+ case 'encrypt':
+ case 'verify':
+ if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return
+ throw new TypeError(`JSON Web Key for this operation be a public JWK`)
+ }
+ }
+
+ if (!isKeyLike(key)) {
+ throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key'))
+ }
+
+ if (key.type === 'secret') {
+ throw new TypeError(
+ `${tag(key)} instances for asymmetric algorithms must not be of type "secret"`,
+ )
+ }
+
+ if (key.type === 'public') {
+ switch (usage) {
+ case 'sign':
+ throw new TypeError(
+ `${tag(key)} instances for asymmetric algorithm signing must be of type "private"`,
+ )
+ case 'decrypt':
+ throw new TypeError(
+ `${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`,
+ )
+ default:
+ break
+ }
+ }
+
+ if (key.type === 'private') {
+ switch (usage) {
+ case 'verify':
+ throw new TypeError(
+ `${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`,
+ )
+ case 'encrypt':
+ throw new TypeError(
+ `${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`,
+ )
+ default:
+ break
+ }
+ }
+}
+
+type Usage = 'sign' | 'verify' | 'encrypt' | 'decrypt'
+
+export default (alg: string, key: unknown, usage: Usage): void => {
+ const symmetric =
+ alg.startsWith('HS') ||
+ alg === 'dir' ||
+ alg.startsWith('PBES2') ||
+ /^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(alg) ||
+ /^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(alg)
+
+ if (symmetric) {
+ symmetricTypeCheck(alg, key, usage)
+ } else {
+ asymmetricTypeCheck(alg, key, usage)
+ }
+}
diff --git a/dist/deno/lib/crypto_key.ts b/dist/deno/lib/crypto_key.ts
new file mode 100644
index 0000000000..07a548c672
--- /dev/null
+++ b/dist/deno/lib/crypto_key.ts
@@ -0,0 +1,140 @@
+import type * as types from '../types.d.ts'
+
+function unusable(name: string | number, prop = 'algorithm.name') {
+ return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`)
+}
+
+function isAlgorithm(
+ algorithm: KeyAlgorithm,
+ name: string,
+): algorithm is T {
+ return algorithm.name === name
+}
+
+function getHashLength(hash: KeyAlgorithm) {
+ return parseInt(hash.name.slice(4), 10)
+}
+
+function getNamedCurve(alg: string) {
+ switch (alg) {
+ case 'ES256':
+ return 'P-256'
+ case 'ES384':
+ return 'P-384'
+ case 'ES512':
+ return 'P-521'
+ default:
+ throw new Error('unreachable')
+ }
+}
+
+function checkUsage(key: types.CryptoKey, usage?: KeyUsage) {
+ if (usage && !key.usages.includes(usage)) {
+ throw new TypeError(
+ `CryptoKey does not support this operation, its usages must include ${usage}.`,
+ )
+ }
+}
+
+export function checkSigCryptoKey(key: types.CryptoKey, alg: string, usage: KeyUsage) {
+ switch (alg) {
+ case 'HS256':
+ case 'HS384':
+ case 'HS512': {
+ if (!isAlgorithm(key.algorithm, 'HMAC')) throw unusable('HMAC')
+ const expected = parseInt(alg.slice(2), 10)
+ const actual = getHashLength(key.algorithm.hash)
+ if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash')
+ break
+ }
+ case 'RS256':
+ case 'RS384':
+ case 'RS512': {
+ if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))
+ throw unusable('RSASSA-PKCS1-v1_5')
+ const expected = parseInt(alg.slice(2), 10)
+ const actual = getHashLength(key.algorithm.hash)
+ if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash')
+ break
+ }
+ case 'PS256':
+ case 'PS384':
+ case 'PS512': {
+ if (!isAlgorithm(key.algorithm, 'RSA-PSS')) throw unusable('RSA-PSS')
+ const expected = parseInt(alg.slice(2), 10)
+ const actual = getHashLength(key.algorithm.hash)
+ if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash')
+ break
+ }
+ case 'Ed25519': // Fall through
+ case 'EdDSA': {
+ if (!isAlgorithm(key.algorithm, 'Ed25519')) throw unusable('Ed25519')
+ break
+ }
+ case 'ES256':
+ case 'ES384':
+ case 'ES512': {
+ if (!isAlgorithm(key.algorithm, 'ECDSA')) throw unusable('ECDSA')
+ const expected = getNamedCurve(alg)
+ const actual = key.algorithm.namedCurve
+ if (actual !== expected) throw unusable(expected, 'algorithm.namedCurve')
+ break
+ }
+ default:
+ throw new TypeError('CryptoKey does not support this operation')
+ }
+
+ checkUsage(key, usage)
+}
+
+export function checkEncCryptoKey(key: types.CryptoKey, alg: string, usage?: KeyUsage) {
+ switch (alg) {
+ case 'A128GCM':
+ case 'A192GCM':
+ case 'A256GCM': {
+ if (!isAlgorithm(key.algorithm, 'AES-GCM')) throw unusable('AES-GCM')
+ const expected = parseInt(alg.slice(1, 4), 10)
+ const actual = key.algorithm.length
+ if (actual !== expected) throw unusable(expected, 'algorithm.length')
+ break
+ }
+ case 'A128KW':
+ case 'A192KW':
+ case 'A256KW': {
+ if (!isAlgorithm(key.algorithm, 'AES-KW')) throw unusable('AES-KW')
+ const expected = parseInt(alg.slice(1, 4), 10)
+ const actual = key.algorithm.length
+ if (actual !== expected) throw unusable(expected, 'algorithm.length')
+ break
+ }
+ case 'ECDH': {
+ switch (key.algorithm.name) {
+ case 'ECDH':
+ case 'X25519':
+ break
+ default:
+ throw unusable('ECDH or X25519')
+ }
+ break
+ }
+ case 'PBES2-HS256+A128KW':
+ case 'PBES2-HS384+A192KW':
+ case 'PBES2-HS512+A256KW':
+ if (!isAlgorithm(key.algorithm, 'PBKDF2')) throw unusable('PBKDF2')
+ break
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512': {
+ if (!isAlgorithm(key.algorithm, 'RSA-OAEP')) throw unusable('RSA-OAEP')
+ const expected = parseInt(alg.slice(9), 10) || 1
+ const actual = getHashLength(key.algorithm.hash)
+ if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash')
+ break
+ }
+ default:
+ throw new TypeError('CryptoKey does not support this operation')
+ }
+
+ checkUsage(key, usage)
+}
diff --git a/dist/deno/lib/decrypt.ts b/dist/deno/lib/decrypt.ts
new file mode 100644
index 0000000000..4f6c1a9254
--- /dev/null
+++ b/dist/deno/lib/decrypt.ts
@@ -0,0 +1,166 @@
+import { concat, uint64be } from './buffer_utils.ts'
+
+import type * as types from '../types.d.ts'
+import checkIvLength from './check_iv_length.ts'
+import checkCekLength from './check_cek_length.ts'
+import { JOSENotSupported, JWEDecryptionFailed, JWEInvalid } from '../util/errors.ts'
+import { checkEncCryptoKey } from './crypto_key.ts'
+import invalidKeyInput from './invalid_key_input.ts'
+import { isCryptoKey } from './is_key_like.ts'
+
+let timingSafeEqual: (a: Uint8Array, b: Uint8Array) => boolean =
+ // @ts-expect-error
+ globalThis.process?.getBuiltinModule?.('node:crypto')?.timingSafeEqual
+
+timingSafeEqual ||= (a: Uint8Array, b: Uint8Array): boolean => {
+ if (!(a instanceof Uint8Array)) {
+ throw new TypeError('First argument must be a buffer')
+ }
+ if (!(b instanceof Uint8Array)) {
+ throw new TypeError('Second argument must be a buffer')
+ }
+ if (a.length !== b.length) {
+ throw new TypeError('Input buffers must have the same length')
+ }
+
+ const len = a.length
+ let out = 0
+ let i = -1
+ while (++i < len) {
+ out |= a[i] ^ b[i]
+ }
+ return out === 0
+}
+
+async function cbcDecrypt(
+ enc: string,
+ cek: Uint8Array | types.CryptoKey,
+ ciphertext: Uint8Array,
+ iv: Uint8Array,
+ tag: Uint8Array,
+ aad: Uint8Array,
+) {
+ if (!(cek instanceof Uint8Array)) {
+ throw new TypeError(invalidKeyInput(cek, 'Uint8Array'))
+ }
+ const keySize = parseInt(enc.slice(1, 4), 10)
+ const encKey = await crypto.subtle.importKey(
+ 'raw',
+ cek.subarray(keySize >> 3),
+ 'AES-CBC',
+ false,
+ ['decrypt'],
+ )
+ const macKey = await crypto.subtle.importKey(
+ 'raw',
+ cek.subarray(0, keySize >> 3),
+ {
+ hash: `SHA-${keySize << 1}`,
+ name: 'HMAC',
+ },
+ false,
+ ['sign'],
+ )
+
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3))
+ const expectedTag = new Uint8Array(
+ (await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3),
+ )
+
+ let macCheckPassed!: boolean
+ try {
+ macCheckPassed = timingSafeEqual(tag, expectedTag)
+ } catch {
+ //
+ }
+ if (!macCheckPassed) {
+ throw new JWEDecryptionFailed()
+ }
+
+ let plaintext!: Uint8Array
+ try {
+ plaintext = new Uint8Array(
+ await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext),
+ )
+ } catch {
+ //
+ }
+ if (!plaintext) {
+ throw new JWEDecryptionFailed()
+ }
+
+ return plaintext
+}
+
+async function gcmDecrypt(
+ enc: string,
+ cek: Uint8Array | types.CryptoKey,
+ ciphertext: Uint8Array,
+ iv: Uint8Array,
+ tag: Uint8Array,
+ aad: Uint8Array,
+) {
+ let encKey: types.CryptoKey
+ if (cek instanceof Uint8Array) {
+ encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt'])
+ } else {
+ checkEncCryptoKey(cek, enc, 'decrypt')
+ encKey = cek
+ }
+
+ try {
+ return new Uint8Array(
+ await crypto.subtle.decrypt(
+ {
+ additionalData: aad,
+ iv,
+ name: 'AES-GCM',
+ tagLength: 128,
+ },
+ encKey,
+ concat(ciphertext, tag),
+ ),
+ )
+ } catch {
+ throw new JWEDecryptionFailed()
+ }
+}
+
+export default async (
+ enc: string,
+ cek: unknown,
+ ciphertext: Uint8Array,
+ iv: Uint8Array | undefined,
+ tag: Uint8Array | undefined,
+ aad: Uint8Array,
+): Promise => {
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
+ throw new TypeError(
+ invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key'),
+ )
+ }
+
+ if (!iv) {
+ throw new JWEInvalid('JWE Initialization Vector missing')
+ }
+ if (!tag) {
+ throw new JWEInvalid('JWE Authentication Tag missing')
+ }
+
+ checkIvLength(enc, iv)
+
+ switch (enc) {
+ case 'A128CBC-HS256':
+ case 'A192CBC-HS384':
+ case 'A256CBC-HS512':
+ if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(-3), 10))
+ return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad)
+ case 'A128GCM':
+ case 'A192GCM':
+ case 'A256GCM':
+ if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc.slice(1, 4), 10))
+ return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad)
+ default:
+ throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm')
+ }
+}
diff --git a/dist/deno/lib/decrypt_key_management.ts b/dist/deno/lib/decrypt_key_management.ts
new file mode 100644
index 0000000000..8ad622a142
--- /dev/null
+++ b/dist/deno/lib/decrypt_key_management.ts
@@ -0,0 +1,162 @@
+import * as aeskw from './aeskw.ts'
+import * as ecdhes from './ecdhes.ts'
+import * as pbes2kw from './pbes2kw.ts'
+import * as rsaes from './rsaes.ts'
+import * as base64url from '../lib/base64url.ts'
+
+import type * as types from '../types.d.ts'
+import { JOSENotSupported, JWEInvalid } from '../util/errors.ts'
+import { bitLength as cekLength } from '../lib/cek.ts'
+import { importJWK } from '../key/import.ts'
+import isObject from './is_object.ts'
+import { unwrap as aesGcmKw } from './aesgcmkw.ts'
+import { assertCryptoKey } from './is_key_like.ts'
+
+export default async (
+ alg: string,
+ key: types.CryptoKey | Uint8Array,
+ encryptedKey: Uint8Array | undefined,
+ joseHeader: types.JWEHeaderParameters,
+ options?: types.DecryptOptions,
+): Promise => {
+ switch (alg) {
+ case 'dir': {
+ // Direct Encryption
+ if (encryptedKey !== undefined)
+ throw new JWEInvalid('Encountered unexpected JWE Encrypted Key')
+
+ return key
+ }
+ case 'ECDH-ES':
+ // Direct Key Agreement
+ if (encryptedKey !== undefined)
+ throw new JWEInvalid('Encountered unexpected JWE Encrypted Key')
+
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW': {
+ // Direct Key Agreement
+ if (!isObject(joseHeader.epk))
+ throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`)
+
+ assertCryptoKey(key)
+ if (!ecdhes.allowed(key))
+ throw new JOSENotSupported(
+ 'ECDH with the provided key is not allowed or not supported by your javascript runtime',
+ )
+
+ const epk = await importJWK(joseHeader.epk, alg)
+ assertCryptoKey(epk)
+ let partyUInfo!: Uint8Array
+ let partyVInfo!: Uint8Array
+
+ if (joseHeader.apu !== undefined) {
+ if (typeof joseHeader.apu !== 'string')
+ throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`)
+ try {
+ partyUInfo = base64url.decode(joseHeader.apu)
+ } catch {
+ throw new JWEInvalid('Failed to base64url decode the apu')
+ }
+ }
+
+ if (joseHeader.apv !== undefined) {
+ if (typeof joseHeader.apv !== 'string')
+ throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`)
+ try {
+ partyVInfo = base64url.decode(joseHeader.apv)
+ } catch {
+ throw new JWEInvalid('Failed to base64url decode the apv')
+ }
+ }
+
+ const sharedSecret = await ecdhes.deriveKey(
+ epk,
+ key,
+ alg === 'ECDH-ES' ? joseHeader.enc! : alg,
+ alg === 'ECDH-ES' ? cekLength(joseHeader.enc!) : parseInt(alg.slice(-5, -2), 10),
+ partyUInfo,
+ partyVInfo,
+ )
+
+ if (alg === 'ECDH-ES') return sharedSecret
+
+ // Key Agreement with Key Wrapping
+ if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing')
+
+ return aeskw.unwrap(alg.slice(-6), sharedSecret, encryptedKey)
+ }
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512': {
+ // Key Encryption (RSA)
+ if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing')
+ assertCryptoKey(key)
+ return rsaes.decrypt(alg, key, encryptedKey)
+ }
+ case 'PBES2-HS256+A128KW':
+ case 'PBES2-HS384+A192KW':
+ case 'PBES2-HS512+A256KW': {
+ // Key Encryption (PBES2)
+ if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing')
+
+ if (typeof joseHeader.p2c !== 'number')
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`)
+
+ const p2cLimit = options?.maxPBES2Count || 10_000
+
+ if (joseHeader.p2c > p2cLimit)
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`)
+
+ if (typeof joseHeader.p2s !== 'string')
+ throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`)
+
+ let p2s: Uint8Array
+ try {
+ p2s = base64url.decode(joseHeader.p2s)
+ } catch {
+ throw new JWEInvalid('Failed to base64url decode the p2s')
+ }
+ return pbes2kw.unwrap(alg, key, encryptedKey, joseHeader.p2c, p2s)
+ }
+ case 'A128KW':
+ case 'A192KW':
+ case 'A256KW': {
+ // Key Wrapping (AES KW)
+ if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing')
+
+ return aeskw.unwrap(alg, key, encryptedKey)
+ }
+ case 'A128GCMKW':
+ case 'A192GCMKW':
+ case 'A256GCMKW': {
+ // Key Wrapping (AES GCM KW)
+ if (encryptedKey === undefined) throw new JWEInvalid('JWE Encrypted Key missing')
+
+ if (typeof joseHeader.iv !== 'string')
+ throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`)
+
+ if (typeof joseHeader.tag !== 'string')
+ throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`)
+
+ let iv: Uint8Array
+ try {
+ iv = base64url.decode(joseHeader.iv)
+ } catch {
+ throw new JWEInvalid('Failed to base64url decode the iv')
+ }
+ let tag: Uint8Array
+ try {
+ tag = base64url.decode(joseHeader.tag)
+ } catch {
+ throw new JWEInvalid('Failed to base64url decode the tag')
+ }
+
+ return aesGcmKw(alg, key, encryptedKey, iv, tag)
+ }
+ default: {
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')
+ }
+ }
+}
diff --git a/dist/deno/lib/digest.ts b/dist/deno/lib/digest.ts
new file mode 100644
index 0000000000..28fde36e84
--- /dev/null
+++ b/dist/deno/lib/digest.ts
@@ -0,0 +1,7 @@
+export default async (
+ algorithm: 'sha256' | 'sha384' | 'sha512',
+ data: Uint8Array,
+): Promise => {
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data))
+}
diff --git a/dist/deno/lib/ecdhes.ts b/dist/deno/lib/ecdhes.ts
new file mode 100644
index 0000000000..95f40e2720
--- /dev/null
+++ b/dist/deno/lib/ecdhes.ts
@@ -0,0 +1,72 @@
+import type * as types from '../types.d.ts'
+import { encoder, concat, uint32be } from './buffer_utils.ts'
+import { checkEncCryptoKey } from './crypto_key.ts'
+import digest from './digest.ts'
+
+function lengthAndInput(input: Uint8Array) {
+ return concat(uint32be(input.length), input)
+}
+
+async function concatKdf(secret: Uint8Array, bits: number, value: Uint8Array) {
+ const iterations = Math.ceil((bits >> 3) / 32)
+ const res = new Uint8Array(iterations * 32)
+ for (let iter = 0; iter < iterations; iter++) {
+ const buf = new Uint8Array(4 + secret.length + value.length)
+ buf.set(uint32be(iter + 1))
+ buf.set(secret, 4)
+ buf.set(value, 4 + secret.length)
+ res.set(await digest('sha256', buf), iter * 32)
+ }
+ return res.slice(0, bits >> 3)
+}
+
+export async function deriveKey(
+ publicKey: types.CryptoKey,
+ privateKey: types.CryptoKey,
+ algorithm: string,
+ keyLength: number,
+ apu: Uint8Array = new Uint8Array(0),
+ apv: Uint8Array = new Uint8Array(0),
+) {
+ checkEncCryptoKey(publicKey, 'ECDH')
+ checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits')
+
+ const value = concat(
+ lengthAndInput(encoder.encode(algorithm)),
+ lengthAndInput(apu),
+ lengthAndInput(apv),
+ uint32be(keyLength),
+ )
+
+ let length: number
+ if (publicKey.algorithm.name === 'X25519') {
+ length = 256
+ } else {
+ length =
+ Math.ceil(parseInt((publicKey.algorithm as EcKeyAlgorithm).namedCurve.slice(-3), 10) / 8) << 3
+ }
+
+ const sharedSecret = new Uint8Array(
+ await crypto.subtle.deriveBits(
+ {
+ name: publicKey.algorithm.name,
+ public: publicKey,
+ },
+ privateKey,
+ length,
+ ),
+ )
+
+ return concatKdf(sharedSecret, keyLength, value)
+}
+
+export function allowed(key: types.CryptoKey) {
+ switch ((key.algorithm as EcKeyAlgorithm).namedCurve) {
+ case 'P-256':
+ case 'P-384':
+ case 'P-521':
+ return true
+ default:
+ return key.algorithm.name === 'X25519'
+ }
+}
diff --git a/dist/deno/lib/encrypt.ts b/dist/deno/lib/encrypt.ts
new file mode 100644
index 0000000000..eea4b61b46
--- /dev/null
+++ b/dist/deno/lib/encrypt.ts
@@ -0,0 +1,134 @@
+import type * as types from '../types.d.ts'
+import { concat, uint64be } from './buffer_utils.ts'
+import checkIvLength from './check_iv_length.ts'
+import checkCekLength from './check_cek_length.ts'
+import { checkEncCryptoKey } from './crypto_key.ts'
+import invalidKeyInput from './invalid_key_input.ts'
+import generateIv from './iv.ts'
+import { JOSENotSupported } from '../util/errors.ts'
+import { isCryptoKey } from './is_key_like.ts'
+
+async function cbcEncrypt(
+ enc: string,
+ plaintext: Uint8Array,
+ cek: Uint8Array | types.CryptoKey,
+ iv: Uint8Array,
+ aad: Uint8Array,
+) {
+ if (!(cek instanceof Uint8Array)) {
+ throw new TypeError(invalidKeyInput(cek, 'Uint8Array'))
+ }
+ const keySize = parseInt(enc.slice(1, 4), 10)
+ const encKey = await crypto.subtle.importKey(
+ 'raw',
+ cek.subarray(keySize >> 3),
+ 'AES-CBC',
+ false,
+ ['encrypt'],
+ )
+ const macKey = await crypto.subtle.importKey(
+ 'raw',
+ cek.subarray(0, keySize >> 3),
+ {
+ hash: `SHA-${keySize << 1}`,
+ name: 'HMAC',
+ },
+ false,
+ ['sign'],
+ )
+
+ const ciphertext = new Uint8Array(
+ await crypto.subtle.encrypt(
+ {
+ iv,
+ name: 'AES-CBC',
+ },
+ encKey,
+ plaintext,
+ ),
+ )
+
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3))
+ const tag = new Uint8Array(
+ (await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3),
+ )
+
+ return { ciphertext, tag, iv }
+}
+
+async function gcmEncrypt(
+ enc: string,
+ plaintext: Uint8Array,
+ cek: Uint8Array | types.CryptoKey,
+ iv: Uint8Array,
+ aad: Uint8Array,
+) {
+ let encKey: types.CryptoKey
+ if (cek instanceof Uint8Array) {
+ encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt'])
+ } else {
+ checkEncCryptoKey(cek, enc, 'encrypt')
+ encKey = cek
+ }
+
+ const encrypted = new Uint8Array(
+ await crypto.subtle.encrypt(
+ {
+ additionalData: aad,
+ iv,
+ name: 'AES-GCM',
+ tagLength: 128,
+ },
+ encKey,
+ plaintext,
+ ),
+ )
+
+ const tag = encrypted.slice(-16)
+ const ciphertext = encrypted.slice(0, -16)
+
+ return { ciphertext, tag, iv }
+}
+
+export default async (
+ enc: string,
+ plaintext: Uint8Array,
+ cek: unknown,
+ iv: Uint8Array | undefined,
+ aad: Uint8Array,
+): Promise<{
+ ciphertext: Uint8Array
+ tag: Uint8Array | undefined
+ iv: Uint8Array | undefined
+}> => {
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
+ throw new TypeError(
+ invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key'),
+ )
+ }
+
+ if (iv) {
+ checkIvLength(enc, iv)
+ } else {
+ iv = generateIv(enc)
+ }
+
+ switch (enc) {
+ case 'A128CBC-HS256':
+ case 'A192CBC-HS384':
+ case 'A256CBC-HS512':
+ if (cek instanceof Uint8Array) {
+ checkCekLength(cek, parseInt(enc.slice(-3), 10))
+ }
+ return cbcEncrypt(enc, plaintext, cek, iv, aad)
+ case 'A128GCM':
+ case 'A192GCM':
+ case 'A256GCM':
+ if (cek instanceof Uint8Array) {
+ checkCekLength(cek, parseInt(enc.slice(1, 4), 10))
+ }
+ return gcmEncrypt(enc, plaintext, cek, iv, aad)
+ default:
+ throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm')
+ }
+}
diff --git a/dist/deno/lib/encrypt_key_management.ts b/dist/deno/lib/encrypt_key_management.ts
new file mode 100644
index 0000000000..dd4f7c842b
--- /dev/null
+++ b/dist/deno/lib/encrypt_key_management.ts
@@ -0,0 +1,124 @@
+import type * as types from '../types.d.ts'
+import * as aeskw from './aeskw.ts'
+import * as ecdhes from './ecdhes.ts'
+import * as pbes2kw from './pbes2kw.ts'
+import * as rsaes from './rsaes.ts'
+import * as base64url from '../lib/base64url.ts'
+import normalizeKey from './normalize_key.ts'
+
+import type { JWEKeyManagementHeaderParameters, JWEHeaderParameters, JWK } from '../types.d.ts'
+import generateCek, { bitLength as cekLength } from '../lib/cek.ts'
+import { JOSENotSupported } from '../util/errors.ts'
+import { exportJWK } from '../key/export.ts'
+import { wrap as aesGcmKw } from './aesgcmkw.ts'
+import { assertCryptoKey } from './is_key_like.ts'
+
+export default async (
+ alg: string,
+ enc: string,
+ key: types.CryptoKey | Uint8Array,
+ providedCek?: Uint8Array,
+ providedParameters: JWEKeyManagementHeaderParameters = {},
+): Promise<{
+ cek: types.CryptoKey | Uint8Array
+ encryptedKey?: Uint8Array
+ parameters?: JWEHeaderParameters
+}> => {
+ let encryptedKey: Uint8Array | undefined
+ let parameters: (JWEHeaderParameters & { epk?: JWK }) | undefined
+ let cek: types.CryptoKey | Uint8Array
+
+ switch (alg) {
+ case 'dir': {
+ // Direct Encryption
+ cek = key
+ break
+ }
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW': {
+ assertCryptoKey(key)
+ // Direct Key Agreement
+ if (!ecdhes.allowed(key)) {
+ throw new JOSENotSupported(
+ 'ECDH with the provided key is not allowed or not supported by your javascript runtime',
+ )
+ }
+ const { apu, apv } = providedParameters
+ let ephemeralKey: types.CryptoKey
+ if (providedParameters.epk) {
+ ephemeralKey = (await normalizeKey(providedParameters.epk, alg)) as types.CryptoKey
+ } else {
+ ephemeralKey = (
+ await crypto.subtle.generateKey(key.algorithm as EcKeyAlgorithm, true, ['deriveBits'])
+ ).privateKey
+ }
+ const { x, y, crv, kty } = await exportJWK(ephemeralKey!)
+ const sharedSecret = await ecdhes.deriveKey(
+ key,
+ ephemeralKey,
+ alg === 'ECDH-ES' ? enc : alg,
+ alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10),
+ apu,
+ apv,
+ )
+ parameters = { epk: { x, crv, kty } }
+ if (kty === 'EC') parameters.epk!.y = y
+ if (apu) parameters.apu = base64url.encode(apu)
+ if (apv) parameters.apv = base64url.encode(apv)
+
+ if (alg === 'ECDH-ES') {
+ cek = sharedSecret
+ break
+ }
+
+ // Key Agreement with Key Wrapping
+ cek = providedCek || generateCek(enc)
+ const kwAlg = alg.slice(-6)
+ encryptedKey = await aeskw.wrap(kwAlg, sharedSecret, cek)
+ break
+ }
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512': {
+ // Key Encryption (RSA)
+ cek = providedCek || generateCek(enc)
+ assertCryptoKey(key)
+ encryptedKey = await rsaes.encrypt(alg, key, cek)
+ break
+ }
+ case 'PBES2-HS256+A128KW':
+ case 'PBES2-HS384+A192KW':
+ case 'PBES2-HS512+A256KW': {
+ // Key Encryption (PBES2)
+ cek = providedCek || generateCek(enc)
+ const { p2c, p2s } = providedParameters
+ ;({ encryptedKey, ...parameters } = await pbes2kw.wrap(alg, key, cek, p2c, p2s))
+ break
+ }
+ case 'A128KW':
+ case 'A192KW':
+ case 'A256KW': {
+ // Key Wrapping (AES KW)
+ cek = providedCek || generateCek(enc)
+ encryptedKey = await aeskw.wrap(alg, key, cek)
+ break
+ }
+ case 'A128GCMKW':
+ case 'A192GCMKW':
+ case 'A256GCMKW': {
+ // Key Wrapping (AES GCM KW)
+ cek = providedCek || generateCek(enc)
+ const { iv } = providedParameters
+ ;({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv))
+ break
+ }
+ default: {
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')
+ }
+ }
+
+ return { cek, encryptedKey, parameters }
+}
diff --git a/dist/deno/lib/epoch.ts b/dist/deno/lib/epoch.ts
new file mode 100644
index 0000000000..616795a52e
--- /dev/null
+++ b/dist/deno/lib/epoch.ts
@@ -0,0 +1 @@
+export default (date: Date) => Math.floor(date.getTime() / 1000)
diff --git a/dist/deno/lib/get_sign_verify_key.ts b/dist/deno/lib/get_sign_verify_key.ts
new file mode 100644
index 0000000000..5934f485b1
--- /dev/null
+++ b/dist/deno/lib/get_sign_verify_key.ts
@@ -0,0 +1,21 @@
+import type * as types from '../types.d.ts'
+import { checkSigCryptoKey } from './crypto_key.ts'
+import invalidKeyInput from './invalid_key_input.ts'
+
+export default async (alg: string, key: types.CryptoKey | Uint8Array, usage: KeyUsage) => {
+ if (key instanceof Uint8Array) {
+ if (!alg.startsWith('HS')) {
+ throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'))
+ }
+ return crypto.subtle.importKey(
+ 'raw',
+ key,
+ { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' },
+ false,
+ [usage],
+ )
+ }
+
+ checkSigCryptoKey(key, alg, usage)
+ return key
+}
diff --git a/dist/deno/lib/invalid_key_input.ts b/dist/deno/lib/invalid_key_input.ts
new file mode 100644
index 0000000000..d2e29ec503
--- /dev/null
+++ b/dist/deno/lib/invalid_key_input.ts
@@ -0,0 +1,31 @@
+function message(msg: string, actual: unknown, ...types: Array) {
+ types = types.filter(Boolean)
+ if (types.length > 2) {
+ const last = types.pop()
+ msg += `one of type ${types.join(', ')}, or ${last}.`
+ } else if (types.length === 2) {
+ msg += `one of type ${types[0]} or ${types[1]}.`
+ } else {
+ msg += `of type ${types[0]}.`
+ }
+
+ if (actual == null) {
+ msg += ` Received ${actual}`
+ } else if (typeof actual === 'function' && actual.name) {
+ msg += ` Received function ${actual.name}`
+ } else if (typeof actual === 'object' && actual != null) {
+ if (actual.constructor?.name) {
+ msg += ` Received an instance of ${actual.constructor.name}`
+ }
+ }
+
+ return msg
+}
+
+export default (actual: unknown, ...types: string[]) => {
+ return message('Key must be ', actual, ...types)
+}
+
+export function withAlg(alg: string, actual: unknown, ...types: Array) {
+ return message(`Key for the ${alg} algorithm must be `, actual, ...types)
+}
diff --git a/dist/deno/lib/is_disjoint.ts b/dist/deno/lib/is_disjoint.ts
new file mode 100644
index 0000000000..558421c87b
--- /dev/null
+++ b/dist/deno/lib/is_disjoint.ts
@@ -0,0 +1,25 @@
+export default (...headers: Array) => {
+ const sources = headers.filter(Boolean) as object[]
+
+ if (sources.length === 0 || sources.length === 1) {
+ return true
+ }
+
+ let acc!: Set
+ for (const header of sources) {
+ const parameters = Object.keys(header)
+ if (!acc || acc.size === 0) {
+ acc = new Set(parameters)
+ continue
+ }
+
+ for (const parameter of parameters) {
+ if (acc.has(parameter)) {
+ return false
+ }
+ acc.add(parameter)
+ }
+ }
+
+ return true
+}
diff --git a/dist/deno/lib/is_jwk.ts b/dist/deno/lib/is_jwk.ts
new file mode 100644
index 0000000000..22929d35cd
--- /dev/null
+++ b/dist/deno/lib/is_jwk.ts
@@ -0,0 +1,18 @@
+import type * as types from '../types.d.ts'
+import isObject from './is_object.ts'
+
+export function isJWK(key: unknown): key is types.JWK & { kty: string } {
+ return isObject(key) && typeof key.kty === 'string'
+}
+
+export function isPrivateJWK(key: types.JWK & { kty: string }) {
+ return key.kty !== 'oct' && typeof key.d === 'string'
+}
+
+export function isPublicJWK(key: types.JWK & { kty: string }) {
+ return key.kty !== 'oct' && typeof key.d === 'undefined'
+}
+
+export function isSecretJWK(key: types.JWK & { kty: string }) {
+ return key.kty === 'oct' && typeof key.k === 'string'
+}
diff --git a/dist/deno/lib/is_key_like.ts b/dist/deno/lib/is_key_like.ts
new file mode 100644
index 0000000000..7d14c86a89
--- /dev/null
+++ b/dist/deno/lib/is_key_like.ts
@@ -0,0 +1,21 @@
+import type * as types from '../types.d.ts'
+
+export function assertCryptoKey(key: unknown): asserts key is types.CryptoKey {
+ if (!isCryptoKey(key)) {
+ throw new Error('CryptoKey instance expected')
+ }
+}
+
+export function isCryptoKey(key: unknown): key is types.CryptoKey {
+ // @ts-expect-error
+ return key?.[Symbol.toStringTag] === 'CryptoKey'
+}
+
+export function isKeyObject(key: unknown): key is T {
+ // @ts-expect-error
+ return key?.[Symbol.toStringTag] === 'KeyObject'
+}
+
+export default (key: unknown): key is types.CryptoKey | types.KeyObject => {
+ return isCryptoKey(key) || isKeyObject(key)
+}
diff --git a/dist/deno/lib/is_object.ts b/dist/deno/lib/is_object.ts
new file mode 100644
index 0000000000..a2f68b7f45
--- /dev/null
+++ b/dist/deno/lib/is_object.ts
@@ -0,0 +1,17 @@
+function isObjectLike(value: unknown) {
+ return typeof value === 'object' && value !== null
+}
+
+export default (input: unknown): input is T => {
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {
+ return false
+ }
+ if (Object.getPrototypeOf(input) === null) {
+ return true
+ }
+ let proto = input
+ while (Object.getPrototypeOf(proto) !== null) {
+ proto = Object.getPrototypeOf(proto)
+ }
+ return Object.getPrototypeOf(input) === proto
+}
diff --git a/dist/deno/lib/iv.ts b/dist/deno/lib/iv.ts
new file mode 100644
index 0000000000..385a38020d
--- /dev/null
+++ b/dist/deno/lib/iv.ts
@@ -0,0 +1,21 @@
+import { JOSENotSupported } from '../util/errors.ts'
+
+export function bitLength(alg: string) {
+ switch (alg) {
+ case 'A128GCM':
+ case 'A128GCMKW':
+ case 'A192GCM':
+ case 'A192GCMKW':
+ case 'A256GCM':
+ case 'A256GCMKW':
+ return 96
+ case 'A128CBC-HS256':
+ case 'A192CBC-HS384':
+ case 'A256CBC-HS512':
+ return 128
+ default:
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`)
+ }
+}
+export default (alg: string): Uint8Array =>
+ crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3))
diff --git a/dist/deno/lib/jwk_to_key.ts b/dist/deno/lib/jwk_to_key.ts
new file mode 100644
index 0000000000..eda60c3a3a
--- /dev/null
+++ b/dist/deno/lib/jwk_to_key.ts
@@ -0,0 +1,111 @@
+import { JOSENotSupported } from '../util/errors.ts'
+import type * as types from '../types.d.ts'
+
+function subtleMapping(jwk: types.JWK): {
+ algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm
+ keyUsages: KeyUsage[]
+} {
+ let algorithm: RsaHashedImportParams | EcKeyAlgorithm | Algorithm
+ let keyUsages: KeyUsage[]
+
+ switch (jwk.kty) {
+ case 'RSA': {
+ switch (jwk.alg) {
+ case 'PS256':
+ case 'PS384':
+ case 'PS512':
+ algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` }
+ keyUsages = jwk.d ? ['sign'] : ['verify']
+ break
+ case 'RS256':
+ case 'RS384':
+ case 'RS512':
+ algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` }
+ keyUsages = jwk.d ? ['sign'] : ['verify']
+ break
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512':
+ algorithm = {
+ name: 'RSA-OAEP',
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,
+ }
+ keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey']
+ break
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')
+ }
+ break
+ }
+ case 'EC': {
+ switch (jwk.alg) {
+ case 'ES256':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-256' }
+ keyUsages = jwk.d ? ['sign'] : ['verify']
+ break
+ case 'ES384':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-384' }
+ keyUsages = jwk.d ? ['sign'] : ['verify']
+ break
+ case 'ES512':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-521' }
+ keyUsages = jwk.d ? ['sign'] : ['verify']
+ break
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW':
+ algorithm = { name: 'ECDH', namedCurve: jwk.crv! }
+ keyUsages = jwk.d ? ['deriveBits'] : []
+ break
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')
+ }
+ break
+ }
+ case 'OKP': {
+ switch (jwk.alg) {
+ case 'Ed25519': // Fall through
+ case 'EdDSA':
+ algorithm = { name: 'Ed25519' }
+ keyUsages = jwk.d ? ['sign'] : ['verify']
+ break
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW':
+ algorithm = { name: jwk.crv! }
+ keyUsages = jwk.d ? ['deriveBits'] : []
+ break
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')
+ }
+ break
+ }
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value')
+ }
+
+ return { algorithm, keyUsages }
+}
+
+export default async (jwk: types.JWK): Promise => {
+ if (!jwk.alg) {
+ throw new TypeError('"alg" argument is required when "jwk.alg" is not present')
+ }
+
+ const { algorithm, keyUsages } = subtleMapping(jwk)
+
+ const keyData: types.JWK = { ...jwk }
+ delete keyData.alg
+ delete keyData.use
+
+ return crypto.subtle.importKey(
+ 'jwk',
+ keyData,
+ algorithm,
+ jwk.ext ?? (jwk.d ? false : true),
+ (jwk.key_ops as KeyUsage[]) ?? keyUsages,
+ )
+}
diff --git a/dist/deno/lib/jwt_claims_set.ts b/dist/deno/lib/jwt_claims_set.ts
new file mode 100644
index 0000000000..91dae076af
--- /dev/null
+++ b/dist/deno/lib/jwt_claims_set.ts
@@ -0,0 +1,176 @@
+import type * as types from '../types.d.ts'
+import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.ts'
+import { decoder } from './buffer_utils.ts'
+import epoch from './epoch.ts'
+import secs from './secs.ts'
+import isObject from './is_object.ts'
+
+const normalizeTyp = (value: string) => value.toLowerCase().replace(/^application\//, '')
+
+const checkAudiencePresence = (audPayload: unknown, audOption: unknown[]) => {
+ if (typeof audPayload === 'string') {
+ return audOption.includes(audPayload)
+ }
+
+ if (Array.isArray(audPayload)) {
+ // Each principal intended to process the JWT MUST
+ // identify itself with a value in the audience claim
+ return audOption.some(Set.prototype.has.bind(new Set(audPayload)))
+ }
+
+ return false
+}
+
+export default (
+ protectedHeader: types.JWEHeaderParameters | types.JWSHeaderParameters,
+ encodedPayload: Uint8Array,
+ options: types.JWTClaimVerificationOptions = {},
+) => {
+ let payload!: { [propName: string]: unknown }
+ try {
+ payload = JSON.parse(decoder.decode(encodedPayload))
+ } catch {
+ //
+ }
+
+ if (!isObject(payload)) {
+ throw new JWTInvalid('JWT Claims Set must be a top-level JSON object')
+ }
+
+ const { typ } = options
+ if (
+ typ &&
+ (typeof protectedHeader!.typ !== 'string' ||
+ normalizeTyp(protectedHeader!.typ) !== normalizeTyp(typ))
+ ) {
+ throw new JWTClaimValidationFailed(
+ 'unexpected "typ" JWT header value',
+ payload,
+ 'typ',
+ 'check_failed',
+ )
+ }
+
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options
+
+ const presenceCheck = [...requiredClaims]
+
+ if (maxTokenAge !== undefined) presenceCheck.push('iat')
+ if (audience !== undefined) presenceCheck.push('aud')
+ if (subject !== undefined) presenceCheck.push('sub')
+ if (issuer !== undefined) presenceCheck.push('iss')
+
+ for (const claim of new Set(presenceCheck.reverse())) {
+ if (!(claim in payload)) {
+ throw new JWTClaimValidationFailed(
+ `missing required "${claim}" claim`,
+ payload,
+ claim,
+ 'missing',
+ )
+ }
+ }
+
+ if (
+ issuer &&
+ !((Array.isArray(issuer) ? issuer : [issuer]) as unknown[]).includes(payload.iss!)
+ ) {
+ throw new JWTClaimValidationFailed(
+ 'unexpected "iss" claim value',
+ payload,
+ 'iss',
+ 'check_failed',
+ )
+ }
+
+ if (subject && payload.sub !== subject) {
+ throw new JWTClaimValidationFailed(
+ 'unexpected "sub" claim value',
+ payload,
+ 'sub',
+ 'check_failed',
+ )
+ }
+
+ if (
+ audience &&
+ !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)
+ ) {
+ throw new JWTClaimValidationFailed(
+ 'unexpected "aud" claim value',
+ payload,
+ 'aud',
+ 'check_failed',
+ )
+ }
+
+ let tolerance: number
+ switch (typeof options.clockTolerance) {
+ case 'string':
+ tolerance = secs(options.clockTolerance)
+ break
+ case 'number':
+ tolerance = options.clockTolerance
+ break
+ case 'undefined':
+ tolerance = 0
+ break
+ default:
+ throw new TypeError('Invalid clockTolerance option type')
+ }
+
+ const { currentDate } = options
+ const now = epoch(currentDate || new Date())
+
+ if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {
+ throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid')
+ }
+
+ if (payload.nbf !== undefined) {
+ if (typeof payload.nbf !== 'number') {
+ throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid')
+ }
+ if (payload.nbf > now + tolerance) {
+ throw new JWTClaimValidationFailed(
+ '"nbf" claim timestamp check failed',
+ payload,
+ 'nbf',
+ 'check_failed',
+ )
+ }
+ }
+
+ if (payload.exp !== undefined) {
+ if (typeof payload.exp !== 'number') {
+ throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid')
+ }
+ if (payload.exp <= now - tolerance) {
+ throw new JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed')
+ }
+ }
+
+ if (maxTokenAge) {
+ const age = now - payload.iat!
+ const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge)
+
+ if (age - tolerance > max) {
+ throw new JWTExpired(
+ '"iat" claim timestamp check failed (too far in the past)',
+ payload,
+ 'iat',
+ 'check_failed',
+ )
+ }
+
+ if (age < 0 - tolerance) {
+ throw new JWTClaimValidationFailed(
+ '"iat" claim timestamp check failed (it should be in the past)',
+ payload,
+ 'iat',
+ 'check_failed',
+ )
+ }
+ }
+
+ return payload as types.JWTPayload
+}
diff --git a/dist/deno/lib/key_to_jwk.ts b/dist/deno/lib/key_to_jwk.ts
new file mode 100644
index 0000000000..2f3353bd4a
--- /dev/null
+++ b/dist/deno/lib/key_to_jwk.ts
@@ -0,0 +1,38 @@
+import type * as types from '../types.d.ts'
+import invalidKeyInput from './invalid_key_input.ts'
+import { encode as base64url } from './base64url.ts'
+import { isCryptoKey, isKeyObject } from './is_key_like.ts'
+
+interface ExportOptions {
+ format: 'jwk'
+}
+
+interface ExtractableKeyObject extends types.KeyObject {
+ export(arg: ExportOptions): types.JWK
+ export(): Uint8Array
+}
+
+export default async function keyToJWK(key: unknown): Promise {
+ if (isKeyObject(key)) {
+ if (key.type === 'secret') {
+ key = (key as ExtractableKeyObject).export()
+ } else {
+ return (key as ExtractableKeyObject).export({ format: 'jwk' })
+ }
+ }
+ if (key instanceof Uint8Array) {
+ return {
+ kty: 'oct',
+ k: base64url(key),
+ }
+ }
+ if (!isCryptoKey(key)) {
+ throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'Uint8Array'))
+ }
+ if (!key.extractable) {
+ throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK')
+ }
+ const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key)
+
+ return jwk as types.JWK
+}
diff --git a/dist/deno/lib/normalize_key.ts b/dist/deno/lib/normalize_key.ts
new file mode 100644
index 0000000000..6491cbb41c
--- /dev/null
+++ b/dist/deno/lib/normalize_key.ts
@@ -0,0 +1,243 @@
+import type * as types from '../types.d.ts'
+import { isJWK } from './is_jwk.ts'
+import { decode } from './base64url.ts'
+import importJWK from './jwk_to_key.ts'
+import { isCryptoKey, isKeyObject } from './is_key_like.ts'
+
+let cache: WeakMap>
+
+interface ConvertableKeyObject extends types.KeyObject {
+ export(): Uint8Array
+ export(opts: { format: 'jwk' }): types.JWK
+ asymmetricKeyType?: string
+ asymmetricKeyDetails?: { namedCurve?: string }
+ toCryptoKey(
+ alg:
+ | AlgorithmIdentifier
+ | RsaHashedImportParams
+ | EcKeyImportParams
+ | HmacImportParams
+ | AesKeyAlgorithm,
+ extractable: boolean,
+ usages: string[],
+ ): types.CryptoKey
+}
+
+const handleJWK = async (
+ key: types.KeyObject | types.JWK,
+ jwk: types.JWK,
+ alg: string,
+ freeze = false,
+) => {
+ cache ||= new WeakMap()
+ let cached = cache.get(key)
+ if (cached?.[alg]) {
+ return cached[alg]
+ }
+
+ const cryptoKey = await importJWK({ ...jwk, alg })
+ if (freeze) Object.freeze(key)
+ if (!cached) {
+ cache.set(key, { [alg]: cryptoKey })
+ } else {
+ cached[alg] = cryptoKey
+ }
+ return cryptoKey
+}
+
+const handleKeyObject = (keyObject: ConvertableKeyObject, alg: string) => {
+ cache ||= new WeakMap()
+ let cached = cache.get(keyObject)
+ if (cached?.[alg]) {
+ return cached[alg]
+ }
+
+ const isPublic = keyObject.type === 'public'
+ const extractable = isPublic ? true : false
+
+ let cryptoKey: types.CryptoKey | undefined
+ if (keyObject.asymmetricKeyType === 'x25519') {
+ switch (alg) {
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW':
+ break
+
+ default:
+ throw new TypeError('given KeyObject instance cannot be used for this algorithm')
+ }
+
+ cryptoKey = keyObject.toCryptoKey(
+ keyObject.asymmetricKeyType,
+ extractable,
+ isPublic ? [] : ['deriveBits'],
+ )
+ }
+
+ if (keyObject.asymmetricKeyType === 'ed25519') {
+ if (alg !== 'EdDSA' && alg !== 'Ed25519') {
+ throw new TypeError('given KeyObject instance cannot be used for this algorithm')
+ }
+
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
+ isPublic ? 'verify' : 'sign',
+ ])
+ }
+
+ if (keyObject.asymmetricKeyType === 'rsa') {
+ let hash: string
+ switch (alg) {
+ case 'RSA-OAEP':
+ hash = 'SHA-1'
+ break
+ case 'RS256':
+ case 'PS256':
+ case 'RSA-OAEP-256':
+ hash = 'SHA-256'
+ break
+ case 'RS384':
+ case 'PS384':
+ case 'RSA-OAEP-384':
+ hash = 'SHA-384'
+ break
+ case 'RS512':
+ case 'PS512':
+ case 'RSA-OAEP-512':
+ hash = 'SHA-512'
+ break
+
+ default:
+ throw new TypeError('given KeyObject instance cannot be used for this algorithm')
+ }
+
+ if (alg.startsWith('RSA-OAEP')) {
+ return keyObject.toCryptoKey(
+ {
+ name: 'RSA-OAEP',
+ hash,
+ },
+ extractable,
+ isPublic ? ['encrypt'] : ['decrypt'],
+ )
+ }
+
+ cryptoKey = keyObject.toCryptoKey(
+ {
+ name: alg.startsWith('PS') ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5',
+ hash,
+ },
+ extractable,
+ [isPublic ? 'verify' : 'sign'],
+ )
+ }
+
+ if (keyObject.asymmetricKeyType === 'ec') {
+ const nist = new Map([
+ ['prime256v1', 'P-256'],
+ ['secp384r1', 'P-384'],
+ ['secp521r1', 'P-521'],
+ ])
+
+ const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve)
+ if (!namedCurve) {
+ throw new TypeError('given KeyObject instance cannot be used for this algorithm')
+ }
+
+ if (alg === 'ES256' && namedCurve === 'P-256') {
+ cryptoKey = keyObject.toCryptoKey(
+ {
+ name: 'ECDSA',
+ namedCurve,
+ },
+ extractable,
+ [isPublic ? 'verify' : 'sign'],
+ )
+ }
+
+ if (alg === 'ES384' && namedCurve === 'P-384') {
+ cryptoKey = keyObject.toCryptoKey(
+ {
+ name: 'ECDSA',
+ namedCurve,
+ },
+ extractable,
+ [isPublic ? 'verify' : 'sign'],
+ )
+ }
+
+ if (alg === 'ES512' && namedCurve === 'P-521') {
+ cryptoKey = keyObject.toCryptoKey(
+ {
+ name: 'ECDSA',
+ namedCurve,
+ },
+ extractable,
+ [isPublic ? 'verify' : 'sign'],
+ )
+ }
+
+ if (alg.startsWith('ECDH-ES')) {
+ cryptoKey = keyObject.toCryptoKey(
+ {
+ name: 'ECDH',
+ namedCurve,
+ },
+ extractable,
+ isPublic ? [] : ['deriveBits'],
+ )
+ }
+ }
+
+ if (!cryptoKey) {
+ throw new TypeError('given KeyObject instance cannot be used for this algorithm')
+ }
+
+ if (!cached) {
+ cache.set(keyObject, { [alg]: cryptoKey })
+ } else {
+ cached[alg] = cryptoKey
+ }
+ return cryptoKey
+}
+
+export default async (
+ key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array,
+ alg: string,
+): Promise => {
+ if (key instanceof Uint8Array) {
+ return key
+ }
+
+ if (isCryptoKey(key)) {
+ return key
+ }
+
+ if (isKeyObject(key)) {
+ if (key.type === 'secret') {
+ return (key as ConvertableKeyObject).export()
+ }
+
+ if ('toCryptoKey' in key && typeof key.toCryptoKey === 'function') {
+ try {
+ return handleKeyObject(key as ConvertableKeyObject, alg)
+ } catch (err) {
+ if (err instanceof TypeError) {
+ throw err
+ }
+ }
+ }
+
+ let jwk: types.JWK = (key as ConvertableKeyObject).export({ format: 'jwk' })
+ return handleJWK(key, jwk, alg)
+ }
+
+ if (isJWK(key)) {
+ if (key.k) {
+ return decode(key.k)
+ }
+ return handleJWK(key, key, alg, true)
+ }
+
+ throw new Error('unreachable')
+}
diff --git a/dist/deno/lib/pbes2kw.ts b/dist/deno/lib/pbes2kw.ts
new file mode 100644
index 0000000000..daba3065be
--- /dev/null
+++ b/dist/deno/lib/pbes2kw.ts
@@ -0,0 +1,68 @@
+import type * as types from '../types.d.ts'
+import { encode as base64url } from './base64url.ts'
+import * as aeskw from './aeskw.ts'
+import { checkEncCryptoKey } from './crypto_key.ts'
+import { concat, encoder } from './buffer_utils.ts'
+import { JWEInvalid } from '../util/errors.ts'
+
+function getCryptoKey(key: types.CryptoKey | Uint8Array, alg: string) {
+ if (key instanceof Uint8Array) {
+ return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits'])
+ }
+
+ checkEncCryptoKey(key, alg, 'deriveBits')
+ return key
+}
+
+const concatSalt = (alg: string, p2sInput: Uint8Array) =>
+ concat(encoder.encode(alg), new Uint8Array([0]), p2sInput)
+
+async function deriveKey(
+ p2s: Uint8Array,
+ alg: string,
+ p2c: number,
+ key: types.CryptoKey | Uint8Array,
+) {
+ if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
+ throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets')
+ }
+
+ const salt = concatSalt(alg, p2s)
+ const keylen = parseInt(alg.slice(13, 16), 10)
+ const subtleAlg = {
+ hash: `SHA-${alg.slice(8, 11)}`,
+ iterations: p2c,
+ name: 'PBKDF2',
+ salt,
+ }
+
+ const cryptoKey = await getCryptoKey(key, alg)
+
+ return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen))
+}
+
+export async function wrap(
+ alg: string,
+ key: types.CryptoKey | Uint8Array,
+ cek: Uint8Array,
+ p2c = 2048,
+ p2s: Uint8Array = crypto.getRandomValues(new Uint8Array(16)),
+) {
+ const derived = await deriveKey(p2s, alg, p2c, key)
+
+ const encryptedKey = await aeskw.wrap(alg.slice(-6), derived, cek)
+
+ return { encryptedKey, p2c, p2s: base64url(p2s) }
+}
+
+export async function unwrap(
+ alg: string,
+ key: types.CryptoKey | Uint8Array,
+ encryptedKey: Uint8Array,
+ p2c: number,
+ p2s: Uint8Array,
+) {
+ const derived = await deriveKey(p2s, alg, p2c, key)
+
+ return aeskw.unwrap(alg.slice(-6), derived, encryptedKey)
+}
diff --git a/dist/deno/lib/private_symbols.ts b/dist/deno/lib/private_symbols.ts
new file mode 100644
index 0000000000..5cb1e2b394
--- /dev/null
+++ b/dist/deno/lib/private_symbols.ts
@@ -0,0 +1 @@
+export const unprotected = Symbol()
diff --git a/dist/deno/lib/rsaes.ts b/dist/deno/lib/rsaes.ts
new file mode 100644
index 0000000000..32c06911b0
--- /dev/null
+++ b/dist/deno/lib/rsaes.ts
@@ -0,0 +1,32 @@
+import type * as types from '../types.d.ts'
+import { checkEncCryptoKey } from './crypto_key.ts'
+import checkKeyLength from './check_key_length.ts'
+import { JOSENotSupported } from '../util/errors.ts'
+
+const subtleAlgorithm = (alg: string) => {
+ switch (alg) {
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512':
+ return 'RSA-OAEP'
+ default:
+ throw new JOSENotSupported(
+ `alg ${alg} is not supported either by JOSE or your javascript runtime`,
+ )
+ }
+}
+
+export async function encrypt(alg: string, key: types.CryptoKey, cek: Uint8Array) {
+ checkEncCryptoKey(key, alg, 'encrypt')
+ checkKeyLength(alg, key)
+
+ return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek))
+}
+
+export async function decrypt(alg: string, key: types.CryptoKey, encryptedKey: Uint8Array) {
+ checkEncCryptoKey(key, alg, 'decrypt')
+ checkKeyLength(alg, key)
+
+ return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey))
+}
diff --git a/dist/deno/lib/secs.ts b/dist/deno/lib/secs.ts
new file mode 100644
index 0000000000..0abc825f8c
--- /dev/null
+++ b/dist/deno/lib/secs.ts
@@ -0,0 +1,65 @@
+const minute = 60
+const hour = minute * 60
+const day = hour * 24
+const week = day * 7
+const year = day * 365.25
+
+const REGEX =
+ /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i
+
+export default (str: string): number => {
+ const matched = REGEX.exec(str)
+
+ if (!matched || (matched[4] && matched[1])) {
+ throw new TypeError('Invalid time period format')
+ }
+
+ const value = parseFloat(matched[2])
+ const unit = matched[3].toLowerCase()
+
+ let numericDate: number
+
+ switch (unit) {
+ case 'sec':
+ case 'secs':
+ case 'second':
+ case 'seconds':
+ case 's':
+ numericDate = Math.round(value)
+ break
+ case 'minute':
+ case 'minutes':
+ case 'min':
+ case 'mins':
+ case 'm':
+ numericDate = Math.round(value * minute)
+ break
+ case 'hour':
+ case 'hours':
+ case 'hr':
+ case 'hrs':
+ case 'h':
+ numericDate = Math.round(value * hour)
+ break
+ case 'day':
+ case 'days':
+ case 'd':
+ numericDate = Math.round(value * day)
+ break
+ case 'week':
+ case 'weeks':
+ case 'w':
+ numericDate = Math.round(value * week)
+ break
+ // years matched
+ default:
+ numericDate = Math.round(value * year)
+ break
+ }
+
+ if (matched[1] === '-' || matched[4] === 'ago') {
+ return -numericDate
+ }
+
+ return numericDate
+}
diff --git a/dist/deno/lib/sign.ts b/dist/deno/lib/sign.ts
new file mode 100644
index 0000000000..ee257a96cf
--- /dev/null
+++ b/dist/deno/lib/sign.ts
@@ -0,0 +1,16 @@
+import type * as types from '../types.d.ts'
+import subtleAlgorithm from './subtle_dsa.ts'
+
+import checkKeyLength from './check_key_length.ts'
+import getSignKey from './get_sign_verify_key.ts'
+
+export default async (alg: string, key: types.CryptoKey | Uint8Array, data: Uint8Array) => {
+ const cryptoKey = await getSignKey(alg, key, 'sign')
+ checkKeyLength(alg, cryptoKey)
+ const signature = await crypto.subtle.sign(
+ subtleAlgorithm(alg, cryptoKey.algorithm),
+ cryptoKey,
+ data,
+ )
+ return new Uint8Array(signature)
+}
diff --git a/dist/deno/lib/subtle_dsa.ts b/dist/deno/lib/subtle_dsa.ts
new file mode 100644
index 0000000000..c3dafe3de1
--- /dev/null
+++ b/dist/deno/lib/subtle_dsa.ts
@@ -0,0 +1,30 @@
+import { JOSENotSupported } from '../util/errors.ts'
+
+export default (alg: string, algorithm: KeyAlgorithm | EcKeyAlgorithm) => {
+ const hash = `SHA-${alg.slice(-3)}`
+ switch (alg) {
+ case 'HS256':
+ case 'HS384':
+ case 'HS512':
+ return { hash, name: 'HMAC' }
+ case 'PS256':
+ case 'PS384':
+ case 'PS512':
+ return { hash, name: 'RSA-PSS', saltLength: parseInt(alg.slice(-3), 10) >> 3 }
+ case 'RS256':
+ case 'RS384':
+ case 'RS512':
+ return { hash, name: 'RSASSA-PKCS1-v1_5' }
+ case 'ES256':
+ case 'ES384':
+ case 'ES512':
+ return { hash, name: 'ECDSA', namedCurve: (algorithm as EcKeyAlgorithm).namedCurve }
+ case 'Ed25519': // Fall through
+ case 'EdDSA':
+ return { name: 'Ed25519' }
+ default:
+ throw new JOSENotSupported(
+ `alg ${alg} is not supported either by JOSE or your javascript runtime`,
+ )
+ }
+}
diff --git a/dist/deno/lib/validate_algorithms.ts b/dist/deno/lib/validate_algorithms.ts
new file mode 100644
index 0000000000..4c03af43ad
--- /dev/null
+++ b/dist/deno/lib/validate_algorithms.ts
@@ -0,0 +1,14 @@
+export default (option: string, algorithms?: string[]) => {
+ if (
+ algorithms !== undefined &&
+ (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))
+ ) {
+ throw new TypeError(`"${option}" option must be an array of strings`)
+ }
+
+ if (!algorithms) {
+ return undefined
+ }
+
+ return new Set(algorithms)
+}
diff --git a/dist/deno/lib/validate_crit.ts b/dist/deno/lib/validate_crit.ts
new file mode 100644
index 0000000000..56572da261
--- /dev/null
+++ b/dist/deno/lib/validate_crit.ts
@@ -0,0 +1,55 @@
+import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.ts'
+
+interface CritCheckHeader {
+ b64?: boolean
+ crit?: string[]
+ [propName: string]: unknown
+}
+
+export default (
+ Err: typeof JWEInvalid | typeof JWSInvalid,
+ recognizedDefault: Map,
+ recognizedOption: { [propName: string]: boolean } | undefined,
+ protectedHeader: CritCheckHeader | undefined,
+ joseHeader: CritCheckHeader,
+) => {
+ if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected')
+ }
+
+ if (!protectedHeader || protectedHeader.crit === undefined) {
+ return new Set()
+ }
+
+ if (
+ !Array.isArray(protectedHeader.crit) ||
+ protectedHeader.crit.length === 0 ||
+ protectedHeader.crit.some((input: string) => typeof input !== 'string' || input.length === 0)
+ ) {
+ throw new Err(
+ '"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present',
+ )
+ }
+
+ let recognized: Map
+ if (recognizedOption !== undefined) {
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()])
+ } else {
+ recognized = recognizedDefault
+ }
+
+ for (const parameter of protectedHeader.crit) {
+ if (!recognized.has(parameter)) {
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`)
+ }
+
+ if (joseHeader[parameter] === undefined) {
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`)
+ }
+ if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`)
+ }
+ }
+
+ return new Set(protectedHeader.crit)
+}
diff --git a/dist/deno/lib/verify.ts b/dist/deno/lib/verify.ts
new file mode 100644
index 0000000000..641a6ed564
--- /dev/null
+++ b/dist/deno/lib/verify.ts
@@ -0,0 +1,21 @@
+import type * as types from '../types.d.ts'
+import subtleAlgorithm from './subtle_dsa.ts'
+
+import checkKeyLength from './check_key_length.ts'
+import getVerifyKey from './get_sign_verify_key.ts'
+
+export default async (
+ alg: string,
+ key: types.CryptoKey | Uint8Array,
+ signature: Uint8Array,
+ data: Uint8Array,
+) => {
+ const cryptoKey = await getVerifyKey(alg, key, 'verify')
+ checkKeyLength(alg, cryptoKey)
+ const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm)
+ try {
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data)
+ } catch {
+ return false
+ }
+}
diff --git a/dist/deno/types.d.ts b/dist/deno/types.d.ts
new file mode 100644
index 0000000000..c3d0e39610
--- /dev/null
+++ b/dist/deno/types.d.ts
@@ -0,0 +1,694 @@
+/** Generic JSON Web Key Parameters. */
+export interface JWKParameters {
+ /** JWK "kty" (Key Type) Parameter */
+ kty: string
+ /**
+ * JWK "alg" (Algorithm) Parameter
+ *
+ * @see {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}
+ */
+ alg?: string
+ /** JWK "key_ops" (Key Operations) Parameter */
+ key_ops?: string[]
+ /** JWK "ext" (Extractable) Parameter */
+ ext?: boolean
+ /** JWK "use" (Public Key Use) Parameter */
+ use?: string
+ /** JWK "x5c" (X.509 Certificate Chain) Parameter */
+ x5c?: string[]
+ /** JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter */
+ x5t?: string
+ /** JWK "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter */
+ 'x5t#S256'?: string
+ /** JWK "x5u" (X.509 URL) Parameter */
+ x5u?: string
+ /** JWK "kid" (Key ID) Parameter */
+ kid?: string
+}
+
+/** Convenience interface for Public OKP JSON Web Keys */
+export interface JWK_OKP_Public extends JWKParameters {
+ /** OKP JWK "crv" (The Subtype of Key Pair) Parameter */
+ crv: string
+ /** OKP JWK "x" (The public key) Parameter */
+ x: string
+}
+
+/** Convenience interface for Private OKP JSON Web Keys */
+export interface JWK_OKP_Private extends JWK_OKP_Public, JWKParameters {
+ /** OKP JWK "d" (The Private Key) Parameter */
+ d: string
+}
+
+/** Convenience interface for Public EC JSON Web Keys */
+export interface JWK_EC_Public extends JWKParameters {
+ /** EC JWK "crv" (Curve) Parameter */
+ crv: string
+ /** EC JWK "x" (X Coordinate) Parameter */
+ x: string
+ /** EC JWK "y" (Y Coordinate) Parameter */
+ y: string
+}
+
+/** Convenience interface for Private EC JSON Web Keys */
+export interface JWK_EC_Private extends JWK_EC_Public, JWKParameters {
+ /** EC JWK "d" (ECC Private Key) Parameter */
+ d: string
+}
+
+/** Convenience interface for Public RSA JSON Web Keys */
+export interface JWK_RSA_Public extends JWKParameters {
+ /** RSA JWK "e" (Exponent) Parameter */
+ e: string
+ /** RSA JWK "n" (Modulus) Parameter */
+ n: string
+}
+
+/** Convenience interface for Private RSA JSON Web Keys */
+export interface JWK_RSA_Private extends JWK_RSA_Public, JWKParameters {
+ /** RSA JWK "d" (Private Exponent) Parameter */
+ d: string
+ /** RSA JWK "dp" (First Factor CRT Exponent) Parameter */
+ dp: string
+ /** RSA JWK "dq" (Second Factor CRT Exponent) Parameter */
+ dq: string
+ /** RSA JWK "p" (First Prime Factor) Parameter */
+ p: string
+ /** RSA JWK "q" (Second Prime Factor) Parameter */
+ q: string
+ /** RSA JWK "qi" (First CRT Coefficient) Parameter */
+ qi: string
+}
+
+/** Convenience interface for oct JSON Web Keys */
+export interface JWK_oct extends JWKParameters {
+ /** Oct JWK "k" (Key Value) Parameter */
+ k: string
+}
+
+/**
+ * JSON Web Key ({@link https://www.rfc-editor.org/rfc/rfc7517 JWK}). "RSA", "EC", "OKP", and "oct"
+ * key types are supported.
+ *
+ * @see {@link JWK_OKP_Public}
+ * @see {@link JWK_OKP_Private}
+ * @see {@link JWK_EC_Public}
+ * @see {@link JWK_EC_Private}
+ * @see {@link JWK_RSA_Public}
+ * @see {@link JWK_RSA_Private}
+ * @see {@link JWK_oct}
+ */
+export interface JWK extends JWKParameters {
+ /**
+ * - EC JWK "crv" (Curve) Parameter
+ * - OKP JWK "crv" (The Subtype of Key Pair) Parameter
+ */
+ crv?: string
+ /**
+ * - Private RSA JWK "d" (Private Exponent) Parameter
+ * - Private EC JWK "d" (ECC Private Key) Parameter
+ * - Private OKP JWK "d" (The Private Key) Parameter
+ */
+ d?: string
+ /** Private RSA JWK "dp" (First Factor CRT Exponent) Parameter */
+ dp?: string
+ /** Private RSA JWK "dq" (Second Factor CRT Exponent) Parameter */
+ dq?: string
+ /** RSA JWK "e" (Exponent) Parameter */
+ e?: string
+ /** Oct JWK "k" (Key Value) Parameter */
+ k?: string
+ /** RSA JWK "n" (Modulus) Parameter */
+ n?: string
+ /** Private RSA JWK "p" (First Prime Factor) Parameter */
+ p?: string
+ /** Private RSA JWK "q" (Second Prime Factor) Parameter */
+ q?: string
+ /** Private RSA JWK "qi" (First CRT Coefficient) Parameter */
+ qi?: string
+ /**
+ * - EC JWK "x" (X Coordinate) Parameter
+ * - OKP JWK "x" (The public key) Parameter
+ */
+ x?: string
+ /** EC JWK "y" (Y Coordinate) Parameter */
+ y?: string
+}
+
+/**
+ * @private
+ *
+ * @internal
+ */
+export interface GenericGetKeyFunction {
+ /**
+ * Dynamic key resolution function. No token components have been verified at the time of this
+ * function call.
+ *
+ * If you cannot match a key suitable for the token, throw an error instead.
+ *
+ * @param protectedHeader JWE or JWS Protected Header.
+ * @param token The consumed JWE or JWS token.
+ */
+ (protectedHeader: IProtectedHeader, token: IToken): Promise | ReturnKeyTypes
+}
+
+/**
+ * Generic Interface for consuming operations dynamic key resolution.
+ *
+ * @param IProtectedHeader Type definition of the JWE or JWS Protected Header.
+ * @param IToken Type definition of the consumed JWE or JWS token.
+ */
+export interface GetKeyFunction
+ extends GenericGetKeyFunction<
+ IProtectedHeader,
+ IToken,
+ CryptoKey | KeyObject | JWK | Uint8Array
+ > {}
+
+/**
+ * Flattened JWS definition for verify function inputs, allows payload as {@link !Uint8Array} for
+ * detached signature validation.
+ */
+export interface FlattenedJWSInput {
+ /**
+ * The "header" member MUST be present and contain the value JWS Unprotected Header when the JWS
+ * Unprotected Header value is non- empty; otherwise, it MUST be absent. This value is represented
+ * as an unencoded JSON object, rather than as a string. These Header Parameter values are not
+ * integrity protected.
+ */
+ header?: JWSHeaderParameters
+
+ /**
+ * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797
+ * "b64": false is used the value passed may also be a {@link !Uint8Array}.
+ */
+ payload: string | Uint8Array
+
+ /**
+ * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWS Protected
+ * Header)) when the JWS Protected Header value is non-empty; otherwise, it MUST be absent. These
+ * Header Parameter values are integrity protected.
+ */
+ protected?: string
+
+ /** The "signature" member MUST be present and contain the value BASE64URL(JWS Signature). */
+ signature: string
+}
+
+/**
+ * General JWS definition for verify function inputs, allows payload as {@link !Uint8Array} for
+ * detached signature validation.
+ */
+export interface GeneralJWSInput {
+ /**
+ * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When when
+ * JWS Unencoded Payload ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) "b64": false is
+ * used the value passed may also be a {@link !Uint8Array}.
+ */
+ payload: string | Uint8Array
+
+ /**
+ * The "signatures" member value MUST be an array of JSON objects. Each object represents a
+ * signature or MAC over the JWS Payload and the JWS Protected Header.
+ */
+ signatures: Omit[]
+}
+
+/**
+ * Flattened JWS definition. Payload is returned as an empty string when JWS Unencoded Payload
+ * ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used.
+ */
+export interface FlattenedJWS extends Partial {
+ payload: string
+ signature: string
+}
+
+/**
+ * General JWS definition. Payload is returned as an empty string when JWS Unencoded Payload
+ * ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used.
+ */
+export interface GeneralJWS {
+ payload: string
+ signatures: Omit[]
+}
+
+export interface JoseHeaderParameters {
+ /** "kid" (Key ID) Header Parameter */
+ kid?: string
+
+ /** "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter */
+ x5t?: string
+
+ /** "x5c" (X.509 Certificate Chain) Header Parameter */
+ x5c?: string[]
+
+ /** "x5u" (X.509 URL) Header Parameter */
+ x5u?: string
+
+ /** "jku" (JWK Set URL) Header Parameter */
+ jku?: string
+
+ /** "jwk" (JSON Web Key) Header Parameter */
+ jwk?: Pick
+
+ /** "typ" (Type) Header Parameter */
+ typ?: string
+
+ /** "cty" (Content Type) Header Parameter */
+ cty?: string
+}
+
+/** Recognized JWS Header Parameters, any other Header Members may also be present. */
+export interface JWSHeaderParameters extends JoseHeaderParameters {
+ /**
+ * JWS "alg" (Algorithm) Header Parameter
+ *
+ * @see {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}
+ */
+ alg?: string
+
+ /**
+ * This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing
+ * Input computation as per {@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}.
+ */
+ b64?: boolean
+
+ /** JWS "crit" (Critical) Header Parameter */
+ crit?: string[]
+
+ /** Any other JWS Header member. */
+ [propName: string]: unknown
+}
+
+/** Recognized JWE Key Management-related Header Parameters. */
+export interface JWEKeyManagementHeaderParameters {
+ apu?: Uint8Array
+ apv?: Uint8Array
+ /**
+ * @deprecated You should not use this parameter. It is only really intended for test and vector
+ * validation purposes.
+ */
+ p2c?: number
+ /**
+ * @deprecated You should not use this parameter. It is only really intended for test and vector
+ * validation purposes.
+ */
+ p2s?: Uint8Array
+ /**
+ * @deprecated You should not use this parameter. It is only really intended for test and vector
+ * validation purposes.
+ */
+ iv?: Uint8Array
+ /**
+ * @deprecated You should not use this parameter. It is only really intended for test and vector
+ * validation purposes.
+ */
+ epk?: CryptoKey | KeyObject
+}
+
+/** Flattened JWE definition. */
+export interface FlattenedJWE {
+ /**
+ * The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD
+ * value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a
+ * base64url-encoded value to be integrity protected but not encrypted.
+ */
+ aad?: string
+
+ /** The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). */
+ ciphertext: string
+
+ /**
+ * The "encrypted_key" member MUST be present and contain the value BASE64URL(JWE Encrypted Key)
+ * when the JWE Encrypted Key value is non-empty; otherwise, it MUST be absent.
+ */
+ encrypted_key?: string
+
+ /**
+ * The "header" member MUST be present and contain the value JWE Per- Recipient Unprotected Header
+ * when the JWE Per-Recipient Unprotected Header value is non-empty; otherwise, it MUST be absent.
+ * This value is represented as an unencoded JSON object, rather than as a string. These Header
+ * Parameter values are not integrity protected.
+ */
+ header?: JWEHeaderParameters
+
+ /**
+ * The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when
+ * the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent.
+ */
+ iv?: string
+
+ /**
+ * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected
+ * Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These
+ * Header Parameter values are integrity protected.
+ */
+ protected?: string
+
+ /**
+ * The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when
+ * the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent.
+ */
+ tag?: string
+
+ /**
+ * The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header
+ * when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This
+ * value is represented as an unencoded JSON object, rather than as a string. These Header
+ * Parameter values are not integrity protected.
+ */
+ unprotected?: JWEHeaderParameters
+}
+
+export interface GeneralJWE extends Omit {
+ recipients: Pick[]
+}
+
+/** Recognized JWE Header Parameters, any other Header members may also be present. */
+export interface JWEHeaderParameters extends JoseHeaderParameters {
+ /**
+ * JWE "alg" (Algorithm) Header Parameter
+ *
+ * @see {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}
+ */
+ alg?: string
+
+ /**
+ * JWE "enc" (Encryption Algorithm) Header Parameter
+ *
+ * @see {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}
+ */
+ enc?: string
+
+ /** JWE "crit" (Critical) Header Parameter */
+ crit?: string[]
+
+ /**
+ * JWE "zip" (Compression Algorithm) Header Parameter. This parameter is not supported anymore.
+ *
+ * @deprecated Compression of data SHOULD NOT be done before encryption, because such compressed
+ * data often reveals information about the plaintext.
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc8725#name-avoid-compression-of-encryp Avoid Compression of Encryption Inputs}
+ */
+ zip?: string
+
+ /** Any other JWE Header member. */
+ [propName: string]: unknown
+}
+
+/** Shared Interface with a "crit" property for all sign, verify, encrypt and decrypt operations. */
+export interface CritOption {
+ /**
+ * An object with keys representing recognized "crit" (Critical) Header Parameter names. The value
+ * for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity
+ * protected, `false` when it's irrelevant.
+ *
+ * This makes the "Extension Header Parameter "..." is not recognized" error go away.
+ *
+ * Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit"
+ * (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically
+ * correct when provided and that it is optionally integrity protected. It will not process the
+ * Header Parameter in any way or reject the operation if it is missing. You MUST still verify the
+ * Header Parameter was present and process it according to the profile's validation steps after
+ * the operation succeeds.
+ *
+ * The JWS extension Header Parameter `b64` is always recognized and processed properly. No other
+ * registered Header Parameters that need this kind of default built-in treatment are currently
+ * available.
+ */
+ crit?: {
+ [propName: string]: boolean
+ }
+}
+
+/** JWE Decryption options. */
+export interface DecryptOptions extends CritOption {
+ /**
+ * A list of accepted JWE "alg" (Algorithm) Header Parameter values. By default all "alg"
+ * (Algorithm) Header Parameter values applicable for the used key/secret are allowed except for
+ * all PBES2 Key Management Algorithms, these need to be explicitly allowed using this option.
+ */
+ keyManagementAlgorithms?: string[]
+
+ /**
+ * A list of accepted JWE "enc" (Encryption Algorithm) Header Parameter values. By default all
+ * "enc" (Encryption Algorithm) values applicable for the used key/secret are allowed.
+ */
+ contentEncryptionAlgorithms?: string[]
+
+ /**
+ * (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter
+ * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default
+ * this value is set to 10000.
+ */
+ maxPBES2Count?: number
+}
+
+/** JWE Encryption options. */
+export interface EncryptOptions extends CritOption {}
+
+/** JWT Claims Set verification options. */
+export interface JWTClaimVerificationOptions {
+ /**
+ * Expected JWT "aud" (Audience) Claim value(s).
+ *
+ * This option makes the JWT "aud" (Audience) Claim presence required.
+ */
+ audience?: string | string[]
+
+ /**
+ * Clock skew tolerance
+ *
+ * - In seconds when number (e.g. 5)
+ * - Resolved into a number of seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours").
+ *
+ * Used when validating the JWT "nbf" (Not Before) and "exp" (Expiration Time) claims, and when
+ * validating the "iat" (Issued At) claim if the {@link maxTokenAge `maxTokenAge` option} is set.
+ */
+ clockTolerance?: string | number
+
+ /**
+ * Expected JWT "iss" (Issuer) Claim value(s).
+ *
+ * This option makes the JWT "iss" (Issuer) Claim presence required.
+ */
+ issuer?: string | string[]
+
+ /**
+ * Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value.
+ *
+ * - In seconds when number (e.g. 5)
+ * - Resolved into a number of seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours").
+ *
+ * This option makes the JWT "iat" (Issued At) Claim presence required.
+ */
+ maxTokenAge?: string | number
+
+ /**
+ * Expected JWT "sub" (Subject) Claim value.
+ *
+ * This option makes the JWT "sub" (Subject) Claim presence required.
+ */
+ subject?: string
+
+ /**
+ * Expected JWT "typ" (Type) Header Parameter value.
+ *
+ * This option makes the JWT "typ" (Type) Header Parameter presence required.
+ */
+ typ?: string
+
+ /** Date to use when comparing NumericDate claims, defaults to `new Date()`. */
+ currentDate?: Date
+
+ /**
+ * Array of required Claim Names that must be present in the JWT Claims Set. Default is that: if
+ * the {@link issuer `issuer` option} is set, then JWT "iss" (Issuer) Claim must be present; if the
+ * {@link audience `audience` option} is set, then JWT "aud" (Audience) Claim must be present; if
+ * the {@link subject `subject` option} is set, then JWT "sub" (Subject) Claim must be present; if
+ * the {@link maxTokenAge `maxTokenAge` option} is set, then JWT "iat" (Issued At) Claim must be
+ * present.
+ */
+ requiredClaims?: string[]
+}
+
+/** JWS Verification options. */
+export interface VerifyOptions extends CritOption {
+ /**
+ * A list of accepted JWS "alg" (Algorithm) Header Parameter values. By default all "alg"
+ * (Algorithm) values applicable for the used key/secret are allowed.
+ *
+ * Note: Unsecured JWTs (`{ "alg": "none" }`) are never accepted by this API.
+ */
+ algorithms?: string[]
+}
+
+/** JWS Signing options. */
+export interface SignOptions extends CritOption {}
+
+/** Recognized JWT Claims Set members, any other members may also be present. */
+export interface JWTPayload {
+ /**
+ * JWT Issuer
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1 RFC7519#section-4.1.1}
+ */
+ iss?: string
+
+ /**
+ * JWT Subject
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2 RFC7519#section-4.1.2}
+ */
+ sub?: string
+
+ /**
+ * JWT Audience
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3 RFC7519#section-4.1.3}
+ */
+ aud?: string | string[]
+
+ /**
+ * JWT ID
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7 RFC7519#section-4.1.7}
+ */
+ jti?: string
+
+ /**
+ * JWT Not Before
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5 RFC7519#section-4.1.5}
+ */
+ nbf?: number
+
+ /**
+ * JWT Expiration Time
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4 RFC7519#section-4.1.4}
+ */
+ exp?: number
+
+ /**
+ * JWT Issued At
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 RFC7519#section-4.1.6}
+ */
+ iat?: number
+
+ /** Any other JWT Claim Set member. */
+ [propName: string]: unknown
+}
+
+export interface FlattenedDecryptResult {
+ /** JWE AAD. */
+ additionalAuthenticatedData?: Uint8Array
+
+ /** Plaintext. */
+ plaintext: Uint8Array
+
+ /** JWE Protected Header. */
+ protectedHeader?: JWEHeaderParameters
+
+ /** JWE Shared Unprotected Header. */
+ sharedUnprotectedHeader?: JWEHeaderParameters
+
+ /** JWE Per-Recipient Unprotected Header. */
+ unprotectedHeader?: JWEHeaderParameters
+}
+
+export interface GeneralDecryptResult extends FlattenedDecryptResult {}
+
+export interface CompactDecryptResult {
+ /** Plaintext. */
+ plaintext: Uint8Array
+
+ /** JWE Protected Header. */
+ protectedHeader: CompactJWEHeaderParameters
+}
+
+export interface FlattenedVerifyResult {
+ /** JWS Payload. */
+ payload: Uint8Array
+
+ /** JWS Protected Header. */
+ protectedHeader?: JWSHeaderParameters
+
+ /** JWS Unprotected Header. */
+ unprotectedHeader?: JWSHeaderParameters
+}
+
+export interface GeneralVerifyResult extends FlattenedVerifyResult {}
+
+export interface CompactVerifyResult {
+ /** JWS Payload. */
+ payload: Uint8Array
+
+ /** JWS Protected Header. */
+ protectedHeader: CompactJWSHeaderParameters
+}
+
+export interface JWTVerifyResult {
+ /** JWT Claims Set. */
+ payload: PayloadType & JWTPayload
+
+ /** JWS Protected Header. */
+ protectedHeader: JWTHeaderParameters
+}
+
+export interface JWTDecryptResult {
+ /** JWT Claims Set. */
+ payload: PayloadType & JWTPayload
+
+ /** JWE Protected Header. */
+ protectedHeader: CompactJWEHeaderParameters
+}
+
+export interface ResolvedKey {
+ /** Key resolved from the key resolver function. */
+ key: CryptoKey | Uint8Array
+}
+
+/** Recognized Compact JWS Header Parameters, any other Header Members may also be present. */
+export interface CompactJWSHeaderParameters extends JWSHeaderParameters {
+ alg: string
+}
+
+/** Recognized Signed JWT Header Parameters, any other Header Members may also be present. */
+export interface JWTHeaderParameters extends CompactJWSHeaderParameters {
+ b64?: true
+}
+
+/** Recognized Compact JWE Header Parameters, any other Header Members may also be present. */
+export interface CompactJWEHeaderParameters extends JWEHeaderParameters {
+ alg: string
+ enc: string
+}
+
+/** JSON Web Key Set */
+export interface JSONWebKeySet {
+ keys: JWK[]
+}
+
+/**
+ * {@link !KeyObject} is a representation of a key/secret available in the Node.js runtime. You may
+ * use the Node.js runtime APIs {@link !createPublicKey}, {@link !createPrivateKey}, and
+ * {@link !createSecretKey} to obtain a {@link !KeyObject} from your existing key material.
+ */
+export interface KeyObject {
+ type: string
+}
+
+/**
+ * {@link !CryptoKey} is a representation of a key/secret available in all supported runtimes. In
+ * addition to the {@link key/import Key Import Functions} you may use the
+ * {@link !SubtleCrypto.importKey} API to obtain a {@link !CryptoKey} from your existing key
+ * material.
+ */
+export type CryptoKey = Extract<
+ Awaited>,
+ { type: string }
+>
diff --git a/dist/deno/util/base64url.ts b/dist/deno/util/base64url.ts
new file mode 100644
index 0000000000..49a0d6d5de
--- /dev/null
+++ b/dist/deno/util/base64url.ts
@@ -0,0 +1,21 @@
+import * as base64url from '../lib/base64url.ts'
+
+/**
+ * Utility function to encode a string or {@link !Uint8Array} as a base64url string.
+ *
+ * @param input Value that will be base64url-encoded.
+ */
+interface Base64UrlEncode {
+ (input: Uint8Array | string): string
+}
+/**
+ * Utility function to decode a base64url encoded string.
+ *
+ * @param input Value that will be base64url-decoded.
+ */
+interface Base64UrlDecode {
+ (input: Uint8Array | string): Uint8Array
+}
+
+export const encode: Base64UrlEncode = base64url.encode
+export const decode: Base64UrlDecode = base64url.decode
diff --git a/dist/deno/util/decode_jwt.ts b/dist/deno/util/decode_jwt.ts
new file mode 100644
index 0000000000..2381a3a010
--- /dev/null
+++ b/dist/deno/util/decode_jwt.ts
@@ -0,0 +1,48 @@
+import { decode as base64url } from './base64url.ts'
+import { decoder } from '../lib/buffer_utils.ts'
+import isObject from '../lib/is_object.ts'
+import type * as types from '../types.d.ts'
+import { JWTInvalid } from './errors.ts'
+
+/**
+ * Decodes a signed JSON Web Token payload. This does not validate the JWT Claims Set types or
+ * values. This does not validate the JWS Signature. For a proper Signed JWT Claims Set validation
+ * and JWS signature verification use `jose.jwtVerify()`. For an encrypted JWT Claims Set validation
+ * and JWE decryption use `jose.jwtDecrypt()`.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwt/decode'`.
+ *
+ * @param jwt JWT token in compact JWS serialization.
+ */
+export function decodeJwt(
+ jwt: string,
+): PayloadType & types.JWTPayload {
+ if (typeof jwt !== 'string')
+ throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string')
+
+ const { 1: payload, length } = jwt.split('.')
+
+ if (length === 5) throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded')
+ if (length !== 3) throw new JWTInvalid('Invalid JWT')
+ if (!payload) throw new JWTInvalid('JWTs must contain a payload')
+
+ let decoded: Uint8Array
+ try {
+ decoded = base64url(payload)
+ } catch {
+ throw new JWTInvalid('Failed to base64url decode the payload')
+ }
+
+ let result: unknown
+ try {
+ result = JSON.parse(decoder.decode(decoded))
+ } catch {
+ throw new JWTInvalid('Failed to parse the decoded payload as JSON')
+ }
+
+ if (!isObject(result))
+ throw new JWTInvalid('Invalid JWT Claims Set')
+
+ return result
+}
diff --git a/dist/deno/util/decode_protected_header.ts b/dist/deno/util/decode_protected_header.ts
new file mode 100644
index 0000000000..728ca7fbfa
--- /dev/null
+++ b/dist/deno/util/decode_protected_header.ts
@@ -0,0 +1,44 @@
+import { decode as base64url } from './base64url.ts'
+import { decoder } from '../lib/buffer_utils.ts'
+import isObject from '../lib/is_object.ts'
+import type * as types from '../types.d.ts'
+
+export type ProtectedHeaderParameters = types.JWSHeaderParameters & types.JWEHeaderParameters
+
+/**
+ * Decodes the Protected Header of a JWE/JWS/JWT token utilizing any JOSE serialization.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/decode/protected_header'`.
+ *
+ * @param token JWE/JWS/JWT token in any JOSE serialization.
+ */
+export function decodeProtectedHeader(token: string | object): ProtectedHeaderParameters {
+ let protectedB64u!: unknown
+
+ if (typeof token === 'string') {
+ const parts = token.split('.')
+ if (parts.length === 3 || parts.length === 5) {
+ ;[protectedB64u] = parts
+ }
+ } else if (typeof token === 'object' && token) {
+ if ('protected' in token) {
+ protectedB64u = token.protected
+ } else {
+ throw new TypeError('Token does not contain a Protected Header')
+ }
+ }
+
+ try {
+ if (typeof protectedB64u !== 'string' || !protectedB64u) {
+ throw new Error()
+ }
+ const result = JSON.parse(decoder.decode(base64url(protectedB64u!)))
+ if (!isObject(result)) {
+ throw new Error()
+ }
+ return result as ProtectedHeaderParameters
+ } catch {
+ throw new TypeError('Invalid Token or Protected Header formatting')
+ }
+}
diff --git a/dist/deno/util/errors.ts b/dist/deno/util/errors.ts
new file mode 100644
index 0000000000..4cfaa24d36
--- /dev/null
+++ b/dist/deno/util/errors.ts
@@ -0,0 +1,268 @@
+import type * as types from '../types.d.ts'
+
+/**
+ * A generic Error that all other JOSE specific Error subclasses extend.
+ *
+ */
+export class JOSEError extends Error {
+ /**
+ * A unique error code for the particular error subclass.
+ *
+ * @ignore
+ */
+ static code = 'ERR_JOSE_GENERIC'
+
+ /** A unique error code for this particular error subclass. */
+ code = 'ERR_JOSE_GENERIC'
+
+ /** @ignore */
+ constructor(message?: string, options?: { cause?: unknown }) {
+ super(message, options)
+ this.name = this.constructor.name
+ // @ts-ignore
+ Error.captureStackTrace?.(this, this.constructor)
+ }
+}
+
+/**
+ * An error subclass thrown when a JWT Claim Set member validation fails.
+ *
+ */
+export class JWTClaimValidationFailed extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'
+
+ override code = 'ERR_JWT_CLAIM_VALIDATION_FAILED'
+
+ /** The Claim for which the validation failed. */
+ claim: string
+
+ /** Reason code for the validation failure. */
+ reason: string
+
+ /**
+ * The parsed JWT Claims Set (aka payload). Other JWT claims may or may not have been verified at
+ * this point. The JSON Web Signature (JWS) or a JSON Web Encryption (JWE) structures' integrity
+ * has however been verified. Claims Set verification happens after the JWS Signature or JWE
+ * Decryption processes.
+ */
+ payload: types.JWTPayload
+
+ /** @ignore */
+ constructor(
+ message: string,
+ payload: types.JWTPayload,
+ claim = 'unspecified',
+ reason = 'unspecified',
+ ) {
+ super(message, { cause: { claim, reason, payload } })
+ this.claim = claim
+ this.reason = reason
+ this.payload = payload
+ }
+}
+
+/**
+ * An error subclass thrown when a JWT is expired.
+ *
+ */
+export class JWTExpired extends JOSEError implements JWTClaimValidationFailed {
+ /** @ignore */
+ static override code = 'ERR_JWT_EXPIRED'
+
+ override code = 'ERR_JWT_EXPIRED'
+
+ /** The Claim for which the validation failed. */
+ claim: string
+
+ /** Reason code for the validation failure. */
+ reason: string
+
+ /**
+ * The parsed JWT Claims Set (aka payload). Other JWT claims may or may not have been verified at
+ * this point. The JSON Web Signature (JWS) or a JSON Web Encryption (JWE) structures' integrity
+ * has however been verified. Claims Set verification happens after the JWS Signature or JWE
+ * Decryption processes.
+ */
+ payload: types.JWTPayload
+
+ /** @ignore */
+ constructor(
+ message: string,
+ payload: types.JWTPayload,
+ claim = 'unspecified',
+ reason = 'unspecified',
+ ) {
+ super(message, { cause: { claim, reason, payload } })
+ this.claim = claim
+ this.reason = reason
+ this.payload = payload
+ }
+}
+
+/**
+ * An error subclass thrown when a JOSE Algorithm is not allowed per developer preference.
+ *
+ */
+export class JOSEAlgNotAllowed extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JOSE_ALG_NOT_ALLOWED'
+
+ override code = 'ERR_JOSE_ALG_NOT_ALLOWED'
+}
+
+/**
+ * An error subclass thrown when a particular feature or algorithm is not supported by this
+ * implementation or JOSE in general.
+ *
+ */
+export class JOSENotSupported extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JOSE_NOT_SUPPORTED'
+
+ override code = 'ERR_JOSE_NOT_SUPPORTED'
+}
+
+/**
+ * An error subclass thrown when a JWE ciphertext decryption fails.
+ *
+ */
+export class JWEDecryptionFailed extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JWE_DECRYPTION_FAILED'
+
+ override code = 'ERR_JWE_DECRYPTION_FAILED'
+
+ /** @ignore */
+ constructor(message = 'decryption operation failed', options?: { cause?: unknown }) {
+ super(message, options)
+ }
+}
+
+/**
+ * An error subclass thrown when a JWE is invalid.
+ *
+ */
+export class JWEInvalid extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JWE_INVALID'
+
+ override code = 'ERR_JWE_INVALID'
+}
+
+/**
+ * An error subclass thrown when a JWS is invalid.
+ *
+ */
+export class JWSInvalid extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JWS_INVALID'
+
+ override code = 'ERR_JWS_INVALID'
+}
+
+/**
+ * An error subclass thrown when a JWT is invalid.
+ *
+ */
+export class JWTInvalid extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JWT_INVALID'
+
+ override code = 'ERR_JWT_INVALID'
+}
+
+/**
+ * An error subclass thrown when a JWK is invalid.
+ *
+ */
+export class JWKInvalid extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JWK_INVALID'
+
+ override code = 'ERR_JWK_INVALID'
+}
+
+/**
+ * An error subclass thrown when a JWKS is invalid.
+ *
+ */
+export class JWKSInvalid extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JWKS_INVALID'
+
+ override code = 'ERR_JWKS_INVALID'
+}
+
+/**
+ * An error subclass thrown when no keys match from a JWKS.
+ *
+ */
+export class JWKSNoMatchingKey extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JWKS_NO_MATCHING_KEY'
+
+ override code = 'ERR_JWKS_NO_MATCHING_KEY'
+
+ /** @ignore */
+ constructor(
+ message = 'no applicable key found in the JSON Web Key Set',
+ options?: { cause?: unknown },
+ ) {
+ super(message, options)
+ }
+}
+
+/**
+ * An error subclass thrown when multiple keys match from a JWKS.
+ *
+ */
+export class JWKSMultipleMatchingKeys extends JOSEError {
+ /** @ignore */
+ [Symbol.asyncIterator]!: () => AsyncIterableIterator
+
+ /** @ignore */
+ static override code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'
+
+ override code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS'
+
+ /** @ignore */
+ constructor(
+ message = 'multiple matching keys found in the JSON Web Key Set',
+ options?: { cause?: unknown },
+ ) {
+ super(message, options)
+ }
+}
+
+/**
+ * Timeout was reached when retrieving the JWKS response.
+ *
+ */
+export class JWKSTimeout extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JWKS_TIMEOUT'
+
+ override code = 'ERR_JWKS_TIMEOUT'
+
+ /** @ignore */
+ constructor(message = 'request timed out', options?: { cause?: unknown }) {
+ super(message, options)
+ }
+}
+
+/**
+ * An error subclass thrown when JWS signature verification fails.
+ *
+ */
+export class JWSSignatureVerificationFailed extends JOSEError {
+ /** @ignore */
+ static override code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'
+
+ override code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'
+
+ /** @ignore */
+ constructor(message = 'signature verification failed', options?: { cause?: unknown }) {
+ super(message, options)
+ }
+}
diff --git a/dist/types/index.d.ts b/dist/types/index.d.ts
new file mode 100644
index 0000000000..edc50c1ba3
--- /dev/null
+++ b/dist/types/index.d.ts
@@ -0,0 +1,48 @@
+export { compactDecrypt } from './jwe/compact/decrypt.js';
+export type { CompactDecryptGetKey } from './jwe/compact/decrypt.js';
+export { flattenedDecrypt } from './jwe/flattened/decrypt.js';
+export type { FlattenedDecryptGetKey } from './jwe/flattened/decrypt.js';
+export { generalDecrypt } from './jwe/general/decrypt.js';
+export type { GeneralDecryptGetKey } from './jwe/general/decrypt.js';
+export { GeneralEncrypt } from './jwe/general/encrypt.js';
+export type { Recipient } from './jwe/general/encrypt.js';
+export { compactVerify } from './jws/compact/verify.js';
+export type { CompactVerifyGetKey } from './jws/compact/verify.js';
+export { flattenedVerify } from './jws/flattened/verify.js';
+export type { FlattenedVerifyGetKey } from './jws/flattened/verify.js';
+export { generalVerify } from './jws/general/verify.js';
+export type { GeneralVerifyGetKey } from './jws/general/verify.js';
+export { jwtVerify } from './jwt/verify.js';
+export type { JWTVerifyOptions, JWTVerifyGetKey } from './jwt/verify.js';
+export { jwtDecrypt } from './jwt/decrypt.js';
+export type { JWTDecryptOptions, JWTDecryptGetKey } from './jwt/decrypt.js';
+export type { ProduceJWT } from './jwt/produce.js';
+export { CompactEncrypt } from './jwe/compact/encrypt.js';
+export { FlattenedEncrypt } from './jwe/flattened/encrypt.js';
+export { CompactSign } from './jws/compact/sign.js';
+export { FlattenedSign } from './jws/flattened/sign.js';
+export { GeneralSign } from './jws/general/sign.js';
+export type { Signature } from './jws/general/sign.js';
+export { SignJWT } from './jwt/sign.js';
+export { EncryptJWT } from './jwt/encrypt.js';
+export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js';
+export { EmbeddedJWK } from './jwk/embedded.js';
+export { createLocalJWKSet } from './jwks/local.js';
+export { createRemoteJWKSet, jwksCache } from './jwks/remote.js';
+export type { RemoteJWKSetOptions, JWKSCacheInput, ExportedJWKSCache, customFetch, FetchImplementation, } from './jwks/remote.js';
+export { UnsecuredJWT } from './jwt/unsecured.js';
+export type { UnsecuredResult } from './jwt/unsecured.js';
+export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js';
+export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js';
+export type { KeyImportOptions } from './key/import.js';
+export { decodeProtectedHeader } from './util/decode_protected_header.js';
+export { decodeJwt } from './util/decode_jwt.js';
+export type { ProtectedHeaderParameters } from './util/decode_protected_header.js';
+export * as errors from './util/errors.js';
+export { generateKeyPair } from './key/generate_key_pair.js';
+export type { GenerateKeyPairResult, GenerateKeyPairOptions } from './key/generate_key_pair.js';
+export { generateSecret } from './key/generate_secret.js';
+export type { GenerateSecretOptions } from './key/generate_secret.js';
+export * as base64url from './util/base64url.js';
+export type { CompactDecryptResult, CompactJWEHeaderParameters, CompactJWSHeaderParameters, CompactVerifyResult, CritOption, CryptoKey, DecryptOptions, EncryptOptions, FlattenedDecryptResult, FlattenedJWE, FlattenedJWS, FlattenedJWSInput, FlattenedVerifyResult, GeneralDecryptResult, GeneralJWE, GeneralJWS, GeneralJWSInput, GeneralVerifyResult, GetKeyFunction, JoseHeaderParameters, JSONWebKeySet, JWEHeaderParameters, JWEKeyManagementHeaderParameters, JWK_EC_Private, JWK_EC_Public, JWK_oct, JWK_OKP_Private, JWK_OKP_Public, JWK_RSA_Private, JWK_RSA_Public, JWK, JWKParameters, JWSHeaderParameters, JWTClaimVerificationOptions, JWTDecryptResult, JWTHeaderParameters, JWTPayload, JWTVerifyResult, KeyObject, ResolvedKey, SignOptions, VerifyOptions, } from './types.d.ts';
+export declare const cryptoRuntime = "WebCryptoAPI";
diff --git a/dist/types/jwe/compact/decrypt.d.ts b/dist/types/jwe/compact/decrypt.d.ts
new file mode 100644
index 0000000000..d55686df70
--- /dev/null
+++ b/dist/types/jwe/compact/decrypt.d.ts
@@ -0,0 +1,26 @@
+import type * as types from '../../types.d.ts';
+/**
+ * Interface for Compact JWE Decryption dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ */
+export interface CompactDecryptGetKey extends types.GetKeyFunction {
+}
+/**
+ * Decrypts a Compact JWE.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwe/compact/decrypt'`.
+ *
+ * @param jwe Compact JWE.
+ * @param key Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export declare function compactDecrypt(jwe: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.DecryptOptions): Promise;
+/**
+ * @param jwe Compact JWE.
+ * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export declare function compactDecrypt(jwe: string | Uint8Array, getKey: CompactDecryptGetKey, options?: types.DecryptOptions): Promise;
diff --git a/dist/types/jwe/compact/encrypt.d.ts b/dist/types/jwe/compact/encrypt.d.ts
new file mode 100644
index 0000000000..5980f81b52
--- /dev/null
+++ b/dist/types/jwe/compact/encrypt.d.ts
@@ -0,0 +1,55 @@
+import type * as types from '../../types.d.ts';
+/**
+ * The CompactEncrypt class is used to build and encrypt Compact JWE strings.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwe/compact/encrypt'`.
+ *
+ */
+export declare class CompactEncrypt {
+ private _flattened;
+ /** @param plaintext Binary representation of the plaintext to encrypt. */
+ constructor(plaintext: Uint8Array);
+ /**
+ * Sets a content encryption key to use, by default a random suitable one is generated for the JWE
+ * enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param cek JWE Content Encryption Key.
+ */
+ setContentEncryptionKey(cek: Uint8Array): this;
+ /**
+ * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable
+ * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param iv JWE Initialization Vector.
+ */
+ setInitializationVector(iv: Uint8Array): this;
+ /**
+ * Sets the JWE Protected Header on the CompactEncrypt object.
+ *
+ * @param protectedHeader JWE Protected Header object.
+ */
+ setProtectedHeader(protectedHeader: types.CompactJWEHeaderParameters): this;
+ /**
+ * Sets the JWE Key Management parameters to be used when encrypting the Content Encryption Key.
+ * You do not need to invoke this method, it is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param parameters JWE Key Management parameters.
+ */
+ setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): this;
+ /**
+ * Encrypts and resolves the value of the Compact JWE string.
+ *
+ * @param key Public Key or Secret to encrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Encryption options.
+ */
+ encrypt(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.EncryptOptions): Promise;
+}
diff --git a/dist/types/jwe/flattened/decrypt.d.ts b/dist/types/jwe/flattened/decrypt.d.ts
new file mode 100644
index 0000000000..f8290467f6
--- /dev/null
+++ b/dist/types/jwe/flattened/decrypt.d.ts
@@ -0,0 +1,26 @@
+import type * as types from '../../types.d.ts';
+/**
+ * Interface for Flattened JWE Decryption dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ */
+export interface FlattenedDecryptGetKey extends types.GetKeyFunction {
+}
+/**
+ * Decrypts a Flattened JWE.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwe/flattened/decrypt'`.
+ *
+ * @param jwe Flattened JWE.
+ * @param key Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export declare function flattenedDecrypt(jwe: types.FlattenedJWE, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.DecryptOptions): Promise;
+/**
+ * @param jwe Flattened JWE.
+ * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export declare function flattenedDecrypt(jwe: types.FlattenedJWE, getKey: FlattenedDecryptGetKey, options?: types.DecryptOptions): Promise;
diff --git a/dist/types/jwe/flattened/encrypt.d.ts b/dist/types/jwe/flattened/encrypt.d.ts
new file mode 100644
index 0000000000..9af1a21528
--- /dev/null
+++ b/dist/types/jwe/flattened/encrypt.d.ts
@@ -0,0 +1,81 @@
+import type * as types from '../../types.d.ts';
+/**
+ * The FlattenedEncrypt class is used to build and encrypt Flattened JWE objects.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwe/flattened/encrypt'`.
+ *
+ */
+export declare class FlattenedEncrypt {
+ private _plaintext;
+ private _protectedHeader;
+ private _sharedUnprotectedHeader;
+ private _unprotectedHeader;
+ private _aad;
+ private _cek;
+ private _iv;
+ private _keyManagementParameters;
+ /** @param plaintext Binary representation of the plaintext to encrypt. */
+ constructor(plaintext: Uint8Array);
+ /**
+ * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is
+ * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or
+ * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed
+ * and missing.
+ *
+ * @param parameters JWE Key Management parameters.
+ */
+ setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): this;
+ /**
+ * Sets the JWE Protected Header on the FlattenedEncrypt object.
+ *
+ * @param protectedHeader JWE Protected Header.
+ */
+ setProtectedHeader(protectedHeader: types.JWEHeaderParameters): this;
+ /**
+ * Sets the JWE Shared Unprotected Header on the FlattenedEncrypt object.
+ *
+ * @param sharedUnprotectedHeader JWE Shared Unprotected Header.
+ */
+ setSharedUnprotectedHeader(sharedUnprotectedHeader: types.JWEHeaderParameters): this;
+ /**
+ * Sets the JWE Per-Recipient Unprotected Header on the FlattenedEncrypt object.
+ *
+ * @param unprotectedHeader JWE Per-Recipient Unprotected Header.
+ */
+ setUnprotectedHeader(unprotectedHeader: types.JWEHeaderParameters): this;
+ /**
+ * Sets the Additional Authenticated Data on the FlattenedEncrypt object.
+ *
+ * @param aad Additional Authenticated Data.
+ */
+ setAdditionalAuthenticatedData(aad: Uint8Array): this;
+ /**
+ * Sets a content encryption key to use, by default a random suitable one is generated for the JWE
+ * enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param cek JWE Content Encryption Key.
+ */
+ setContentEncryptionKey(cek: Uint8Array): this;
+ /**
+ * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable
+ * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param iv JWE Initialization Vector.
+ */
+ setInitializationVector(iv: Uint8Array): this;
+ /**
+ * Encrypts and resolves the value of the Flattened JWE object.
+ *
+ * @param key Public Key or Secret to encrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Encryption options.
+ */
+ encrypt(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.EncryptOptions): Promise;
+}
diff --git a/dist/types/jwe/general/decrypt.d.ts b/dist/types/jwe/general/decrypt.d.ts
new file mode 100644
index 0000000000..5b77daa5e1
--- /dev/null
+++ b/dist/types/jwe/general/decrypt.d.ts
@@ -0,0 +1,26 @@
+import type * as types from '../../types.d.ts';
+/**
+ * Interface for General JWE Decryption dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ */
+export interface GeneralDecryptGetKey extends types.GetKeyFunction {
+}
+/**
+ * Decrypts a General JWE.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwe/general/decrypt'`.
+ *
+ * @param jwe General JWE.
+ * @param key Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export declare function generalDecrypt(jwe: types.GeneralJWE, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.DecryptOptions): Promise;
+/**
+ * @param jwe General JWE.
+ * @param getKey Function resolving Private Key or Secret to decrypt the JWE with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Decryption options.
+ */
+export declare function generalDecrypt(jwe: types.GeneralJWE, getKey: GeneralDecryptGetKey, options?: types.DecryptOptions): Promise;
diff --git a/dist/types/jwe/general/encrypt.d.ts b/dist/types/jwe/general/encrypt.d.ts
new file mode 100644
index 0000000000..767aafa06b
--- /dev/null
+++ b/dist/types/jwe/general/encrypt.d.ts
@@ -0,0 +1,59 @@
+import type * as types from '../../types.d.ts';
+export interface Recipient {
+ /**
+ * Sets the JWE Per-Recipient Unprotected Header on the Recipient object.
+ *
+ * @param unprotectedHeader JWE Per-Recipient Unprotected Header.
+ */
+ setUnprotectedHeader(unprotectedHeader: types.JWEHeaderParameters): Recipient;
+ /** A shorthand for calling addRecipient() on the enclosing GeneralEncrypt instance */
+ addRecipient(...args: Parameters): Recipient;
+ /** A shorthand for calling encrypt() on the enclosing GeneralEncrypt instance */
+ encrypt(...args: Parameters): Promise;
+ /** Returns the enclosing GeneralEncrypt */
+ done(): GeneralEncrypt;
+}
+/**
+ * The GeneralEncrypt class is used to build and encrypt General JWE objects.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwe/general/encrypt'`.
+ *
+ */
+export declare class GeneralEncrypt {
+ private _plaintext;
+ private _recipients;
+ private _protectedHeader;
+ private _unprotectedHeader;
+ private _aad;
+ /** @param plaintext Binary representation of the plaintext to encrypt. */
+ constructor(plaintext: Uint8Array);
+ /**
+ * Adds an additional recipient for the General JWE object.
+ *
+ * @param key Public Key or Secret to encrypt the Content Encryption Key for the recipient with.
+ * See {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Encryption options.
+ */
+ addRecipient(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.CritOption): Recipient;
+ /**
+ * Sets the JWE Protected Header on the GeneralEncrypt object.
+ *
+ * @param protectedHeader JWE Protected Header object.
+ */
+ setProtectedHeader(protectedHeader: types.JWEHeaderParameters): this;
+ /**
+ * Sets the JWE Shared Unprotected Header on the GeneralEncrypt object.
+ *
+ * @param sharedUnprotectedHeader JWE Shared Unprotected Header object.
+ */
+ setSharedUnprotectedHeader(sharedUnprotectedHeader: types.JWEHeaderParameters): this;
+ /**
+ * Sets the Additional Authenticated Data on the GeneralEncrypt object.
+ *
+ * @param aad Additional Authenticated Data.
+ */
+ setAdditionalAuthenticatedData(aad: Uint8Array): this;
+ /** Encrypts and resolves the value of the General JWE object. */
+ encrypt(): Promise;
+}
diff --git a/dist/types/jwk/embedded.d.ts b/dist/types/jwk/embedded.d.ts
new file mode 100644
index 0000000000..78375b752a
--- /dev/null
+++ b/dist/types/jwk/embedded.d.ts
@@ -0,0 +1,12 @@
+import type * as types from '../types.d.ts';
+/**
+ * EmbeddedJWK is an implementation of a GetKeyFunction intended to be used with the JWS/JWT verify
+ * operations whenever you need to opt-in to verify signatures with a public key embedded in the
+ * token's "jwk" (JSON Web Key) Header Parameter. It is recommended to combine this with the verify
+ * function's `algorithms` option to define accepted JWS "alg" (Algorithm) Header Parameter values.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwk/embedded'`.
+ *
+ */
+export declare function EmbeddedJWK(protectedHeader?: types.JWSHeaderParameters, token?: types.FlattenedJWSInput): Promise;
diff --git a/dist/types/jwk/thumbprint.d.ts b/dist/types/jwk/thumbprint.d.ts
new file mode 100644
index 0000000000..0f88d9d22f
--- /dev/null
+++ b/dist/types/jwk/thumbprint.d.ts
@@ -0,0 +1,27 @@
+import type * as types from '../types.d.ts';
+/**
+ * Calculates a base64url-encoded JSON Web Key (JWK) Thumbprint
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwk/thumbprint'`.
+ *
+ * @param key Key to calculate the thumbprint for.
+ * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is
+ * "sha256".
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7638 RFC7638}
+ */
+export declare function calculateJwkThumbprint(key: types.JWK | types.CryptoKey | types.KeyObject, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512'): Promise;
+/**
+ * Calculates a JSON Web Key (JWK) Thumbprint URI
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwk/thumbprint'`.
+ *
+ * @param key Key to calculate the thumbprint for.
+ * @param digestAlgorithm Digest Algorithm to use for calculating the thumbprint. Default is
+ * "sha256".
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc9278 RFC9278}
+ */
+export declare function calculateJwkThumbprintUri(key: types.CryptoKey | types.KeyObject | types.JWK, digestAlgorithm?: 'sha256' | 'sha384' | 'sha512'): Promise;
diff --git a/dist/types/jwks/local.d.ts b/dist/types/jwks/local.d.ts
new file mode 100644
index 0000000000..2e5e7cba94
--- /dev/null
+++ b/dist/types/jwks/local.d.ts
@@ -0,0 +1,23 @@
+import type * as types from '../types.d.ts';
+/**
+ * Returns a function that resolves a JWS JOSE Header to a public key object from a locally stored,
+ * or otherwise available, JSON Web Key Set.
+ *
+ * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type),
+ * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if
+ * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key
+ * Operations) Parameters (if they are present on the JWK).
+ *
+ * Only a single public key must match the selection process. As shown in the example below when
+ * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt
+ * verification in an iterative manner.
+ *
+ * Note: The function's purpose is to resolve public keys used for verifying signatures and will not
+ * work for public encryption keys.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwks/local'`.
+ *
+ * @param jwks JSON Web Key Set formatted object.
+ */
+export declare function createLocalJWKSet(jwks: types.JSONWebKeySet): (protectedHeader?: types.JWSHeaderParameters, token?: types.FlattenedJWSInput) => Promise;
diff --git a/dist/types/jwks/remote.d.ts b/dist/types/jwks/remote.d.ts
new file mode 100644
index 0000000000..165154026a
--- /dev/null
+++ b/dist/types/jwks/remote.d.ts
@@ -0,0 +1,214 @@
+import type * as types from '../types.d.ts';
+/**
+ * When passed to {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} this allows the resolver
+ * to make use of advanced fetch configurations, HTTP Proxies, retry on network errors, etc.
+ *
+ * import ky from 'ky'
+ *
+ * let logRequest!: (request: Request) => void
+ * let logResponse!: (request: Request, response: Response) => void
+ * let logRetry!: (request: Request, error: Error, retryCount: number) => void
+ *
+ * const JWKS = jose.createRemoteJWKSet(url, {
+ * [jose.customFetch]: (...args) =>
+ * ky(args[0], {
+ * ...args[1],
+ * hooks: {
+ * beforeRequest: [
+ * (request) => {
+ * logRequest(request)
+ * },
+ * ],
+ * beforeRetry: [
+ * ({ request, error, retryCount }) => {
+ * logRetry(request, error, retryCount)
+ * },
+ * ],
+ * afterResponse: [
+ * (request, _, response) => {
+ * logResponse(request, response)
+ * },
+ * ],
+ * },
+ * }),
+ * })
+ * ```
+ *
+ * import * as undici from 'undici'
+ *
+ * // see https://undici.nodejs.org/#/docs/api/EnvHttpProxyAgent
+ * let envHttpProxyAgent = new undici.EnvHttpProxyAgent()
+ *
+ * // @ts-ignore
+ * const JWKS = jose.createRemoteJWKSet(url, {
+ * [jose.customFetch]: (...args) => {
+ * // @ts-ignore
+ * return undici.fetch(args[0], { ...args[1], dispatcher: envHttpProxyAgent }) // prettier-ignore
+ * },
+ * })
+ * ```
+ *
+ * import * as undici from 'undici'
+ *
+ * // see https://undici.nodejs.org/#/docs/api/RetryAgent
+ * let retryAgent = new undici.RetryAgent(new undici.Agent(), {
+ * statusCodes: [],
+ * errorCodes: [
+ * 'ECONNRESET',
+ * 'ECONNREFUSED',
+ * 'ENOTFOUND',
+ * 'ENETDOWN',
+ * 'ENETUNREACH',
+ * 'EHOSTDOWN',
+ * 'UND_ERR_SOCKET',
+ * ],
+ * })
+ *
+ * // @ts-ignore
+ * const JWKS = jose.createRemoteJWKSet(url, {
+ * [jose.customFetch]: (...args) => {
+ * // @ts-ignore
+ * return undici.fetch(args[0], { ...args[1], dispatcher: retryAgent }) // prettier-ignore
+ * },
+ * })
+ * ```
+ *
+ * import * as undici from 'undici'
+ *
+ * // see https://undici.nodejs.org/#/docs/api/MockAgent
+ * let mockAgent = new undici.MockAgent()
+ * mockAgent.disableNetConnect()
+ *
+ * // @ts-ignore
+ * const JWKS = jose.createRemoteJWKSet(url, {
+ * [jose.customFetch]: (...args) => {
+ * // @ts-ignore
+ * return undici.fetch(args[0], { ...args[1], dispatcher: mockAgent }) // prettier-ignore
+ * },
+ * })
+ * ```
+ */
+export declare const customFetch: unique symbol;
+export type FetchImplementation = (url: string, options: {
+ headers: Headers;
+ method: 'GET';
+ redirect: 'manual';
+ signal: AbortSignal;
+}) => Promise;
+/**
+ * DANGER ZONE - This option has security implications that must be understood, assessed for
+ * applicability, and accepted before use. It is critical that the JSON Web Key Set cache only be
+ * writable by your own code.
+ *
+ * This option is intended for cloud computing runtimes that cannot keep an in memory cache between
+ * their code's invocations. Use in runtimes where an in memory cache between requests is available
+ * is not desirable.
+ *
+ * When passed to {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} this allows the passed in
+ * object to:
+ *
+ * - Serve as an initial value for the JSON Web Key Set that the module would otherwise need to
+ * trigger an HTTP request for
+ * - Have the JSON Web Key Set the function optionally ended up triggering an HTTP request for
+ * assigned to it as properties
+ *
+ * The intended use pattern is:
+ *
+ * - Before verifying with {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} you pull the
+ * previously cached object from a low-latency key-value store offered by the cloud computing
+ * runtime it is executed on;
+ * - Default to an empty object `{}` instead when there's no previously cached value;
+ * - Pass it in as {@link RemoteJWKSetOptions[jwksCache]};
+ * - Afterwards, update the key-value storage if the {@link ExportedJWKSCache.uat `uat`} property of
+ * the object has changed.
+ *
+ * // Prerequisites
+ * let url!: URL
+ * let jwt!: string
+ * let getPreviouslyCachedJWKS!: () => Promise
+ * let storeNewJWKScache!: (cache: jose.ExportedJWKSCache) => Promise
+ *
+ * // Load JSON Web Key Set cache
+ * const jwksCache: jose.JWKSCacheInput = (await getPreviouslyCachedJWKS()) || {}
+ * const { uat } = jwksCache
+ *
+ * const JWKS = jose.createRemoteJWKSet(url, {
+ * [jose.jwksCache]: jwksCache,
+ * })
+ *
+ * // Use JSON Web Key Set cache
+ * await jose.jwtVerify(jwt, JWKS)
+ *
+ * if (uat !== jwksCache.uat) {
+ * // Update JSON Web Key Set cache
+ * await storeNewJWKScache(jwksCache)
+ * }
+ * ```
+ */
+export declare const jwksCache: unique symbol;
+/** Options for the remote JSON Web Key Set. */
+export interface RemoteJWKSetOptions {
+ /**
+ * Timeout (in milliseconds) for the HTTP request. When reached the request will be aborted and
+ * the verification will fail. Default is 5000 (5 seconds).
+ */
+ timeoutDuration?: number;
+ /**
+ * Duration (in milliseconds) for which no more HTTP requests will be triggered after a previous
+ * successful fetch. Default is 30000 (30 seconds).
+ */
+ cooldownDuration?: number;
+ /**
+ * Maximum time (in milliseconds) between successful HTTP requests. Default is 600000 (10
+ * minutes).
+ */
+ cacheMaxAge?: number | typeof Infinity;
+ /** Headers to be sent with the HTTP request. */
+ headers?: Record;
+ /** See {@link jwksCache}. */
+ [jwksCache]?: JWKSCacheInput;
+ /** See {@link customFetch}. */
+ [customFetch]?: FetchImplementation;
+}
+export interface ExportedJWKSCache {
+ jwks: types.JSONWebKeySet;
+ uat: number;
+}
+export type JWKSCacheInput = ExportedJWKSCache | Record;
+/**
+ * Returns a function that resolves a JWS JOSE Header to a public key object downloaded from a
+ * remote endpoint returning a JSON Web Key Set, that is, for example, an OAuth 2.0 or OIDC
+ * jwks_uri. The JSON Web Key Set is fetched when no key matches the selection process but only as
+ * frequently as the `cooldownDuration` option allows to prevent abuse.
+ *
+ * It uses the "alg" (JWS Algorithm) Header Parameter to determine the right JWK "kty" (Key Type),
+ * then proceeds to match the JWK "kid" (Key ID) with one found in the JWS Header Parameters (if
+ * there is one) while also respecting the JWK "use" (Public Key Use) and JWK "key_ops" (Key
+ * Operations) Parameters (if they are present on the JWK).
+ *
+ * Only a single public key must match the selection process. As shown in the example below when
+ * multiple keys get matched it is possible to opt-in to iterate over the matched keys and attempt
+ * verification in an iterative manner.
+ *
+ * Note: The function's purpose is to resolve public keys used for verifying signatures and will not
+ * work for public encryption keys.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwks/remote'`.
+ *
+ * @param url URL to fetch the JSON Web Key Set from.
+ * @param options Options for the remote JSON Web Key Set.
+ */
+export declare function createRemoteJWKSet(url: URL, options?: RemoteJWKSetOptions): {
+ (protectedHeader?: types.JWSHeaderParameters, token?: types.FlattenedJWSInput): Promise;
+ /** @ignore */
+ coolingDown: boolean;
+ /** @ignore */
+ fresh: boolean;
+ /** @ignore */
+ reloading: boolean;
+ /** @ignore */
+ reload: () => Promise;
+ /** @ignore */
+ jwks: () => types.JSONWebKeySet | undefined;
+};
diff --git a/dist/types/jws/compact/sign.d.ts b/dist/types/jws/compact/sign.d.ts
new file mode 100644
index 0000000000..0bcde8e9f9
--- /dev/null
+++ b/dist/types/jws/compact/sign.d.ts
@@ -0,0 +1,27 @@
+import type * as types from '../../types.d.ts';
+/**
+ * The CompactSign class is used to build and sign Compact JWS strings.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jws/compact/sign'`.
+ *
+ */
+export declare class CompactSign {
+ private _flattened;
+ /** @param payload Binary representation of the payload to sign. */
+ constructor(payload: Uint8Array);
+ /**
+ * Sets the JWS Protected Header on the CompactSign object.
+ *
+ * @param protectedHeader JWS Protected Header.
+ */
+ setProtectedHeader(protectedHeader: types.CompactJWSHeaderParameters): this;
+ /**
+ * Signs and resolves the value of the Compact JWS string.
+ *
+ * @param key Private Key or Secret to sign the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Sign options.
+ */
+ sign(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.SignOptions): Promise;
+}
diff --git a/dist/types/jws/compact/verify.d.ts b/dist/types/jws/compact/verify.d.ts
new file mode 100644
index 0000000000..e6a56e526b
--- /dev/null
+++ b/dist/types/jws/compact/verify.d.ts
@@ -0,0 +1,28 @@
+import type * as types from '../../types.d.ts';
+/**
+ * Interface for Compact JWS Verification dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ *
+ * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set.
+ */
+export interface CompactVerifyGetKey extends types.GenericGetKeyFunction {
+}
+/**
+ * Verifies the signature and format of and afterwards decodes the Compact JWS.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jws/compact/verify'`.
+ *
+ * @param jws Compact JWS.
+ * @param key Key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export declare function compactVerify(jws: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.VerifyOptions): Promise;
+/**
+ * @param jws Compact JWS.
+ * @param getKey Function resolving a key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export declare function compactVerify(jws: string | Uint8Array, getKey: CompactVerifyGetKey, options?: types.VerifyOptions): Promise;
diff --git a/dist/types/jws/flattened/sign.d.ts b/dist/types/jws/flattened/sign.d.ts
new file mode 100644
index 0000000000..2a0a509e77
--- /dev/null
+++ b/dist/types/jws/flattened/sign.d.ts
@@ -0,0 +1,35 @@
+import type * as types from '../../types.d.ts';
+/**
+ * The FlattenedSign class is used to build and sign Flattened JWS objects.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jws/flattened/sign'`.
+ *
+ */
+export declare class FlattenedSign {
+ private _payload;
+ private _protectedHeader;
+ private _unprotectedHeader;
+ /** @param payload Binary representation of the payload to sign. */
+ constructor(payload: Uint8Array);
+ /**
+ * Sets the JWS Protected Header on the FlattenedSign object.
+ *
+ * @param protectedHeader JWS Protected Header.
+ */
+ setProtectedHeader(protectedHeader: types.JWSHeaderParameters): this;
+ /**
+ * Sets the JWS Unprotected Header on the FlattenedSign object.
+ *
+ * @param unprotectedHeader JWS Unprotected Header.
+ */
+ setUnprotectedHeader(unprotectedHeader: types.JWSHeaderParameters): this;
+ /**
+ * Signs and resolves the value of the Flattened JWS object.
+ *
+ * @param key Private Key or Secret to sign the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Sign options.
+ */
+ sign(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.SignOptions): Promise;
+}
diff --git a/dist/types/jws/flattened/verify.d.ts b/dist/types/jws/flattened/verify.d.ts
new file mode 100644
index 0000000000..014790ac65
--- /dev/null
+++ b/dist/types/jws/flattened/verify.d.ts
@@ -0,0 +1,28 @@
+import type * as types from '../../types.d.ts';
+/**
+ * Interface for Flattened JWS Verification dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ *
+ * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set.
+ */
+export interface FlattenedVerifyGetKey extends types.GenericGetKeyFunction {
+}
+/**
+ * Verifies the signature and format of and afterwards decodes the Flattened JWS.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jws/flattened/verify'`.
+ *
+ * @param jws Flattened JWS.
+ * @param key Key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export declare function flattenedVerify(jws: types.FlattenedJWSInput, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.VerifyOptions): Promise;
+/**
+ * @param jws Flattened JWS.
+ * @param getKey Function resolving a key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export declare function flattenedVerify(jws: types.FlattenedJWSInput, getKey: FlattenedVerifyGetKey, options?: types.VerifyOptions): Promise;
diff --git a/dist/types/jws/general/sign.d.ts b/dist/types/jws/general/sign.d.ts
new file mode 100644
index 0000000000..b84cc32855
--- /dev/null
+++ b/dist/types/jws/general/sign.d.ts
@@ -0,0 +1,44 @@
+import type * as types from '../../types.d.ts';
+export interface Signature {
+ /**
+ * Sets the JWS Protected Header on the Signature object.
+ *
+ * @param protectedHeader JWS Protected Header.
+ */
+ setProtectedHeader(protectedHeader: types.JWSHeaderParameters): Signature;
+ /**
+ * Sets the JWS Unprotected Header on the Signature object.
+ *
+ * @param unprotectedHeader JWS Unprotected Header.
+ */
+ setUnprotectedHeader(unprotectedHeader: types.JWSHeaderParameters): Signature;
+ /** A shorthand for calling addSignature() on the enclosing GeneralSign instance */
+ addSignature(...args: Parameters): Signature;
+ /** A shorthand for calling encrypt() on the enclosing GeneralSign instance */
+ sign(...args: Parameters): Promise;
+ /** Returns the enclosing GeneralSign */
+ done(): GeneralSign;
+}
+/**
+ * The GeneralSign class is used to build and sign General JWS objects.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jws/general/sign'`.
+ *
+ */
+export declare class GeneralSign {
+ private _payload;
+ private _signatures;
+ /** @param payload Binary representation of the payload to sign. */
+ constructor(payload: Uint8Array);
+ /**
+ * Adds an additional signature for the General JWS object.
+ *
+ * @param key Private Key or Secret to sign the individual JWS signature with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Sign options.
+ */
+ addSignature(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.SignOptions): Signature;
+ /** Signs and resolves the value of the General JWS object. */
+ sign(): Promise;
+}
diff --git a/dist/types/jws/general/verify.d.ts b/dist/types/jws/general/verify.d.ts
new file mode 100644
index 0000000000..6b51d0e0b6
--- /dev/null
+++ b/dist/types/jws/general/verify.d.ts
@@ -0,0 +1,28 @@
+import type * as types from '../../types.d.ts';
+/**
+ * Interface for General JWS Verification dynamic key resolution. No token components have been
+ * verified at the time of this function call.
+ *
+ * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set.
+ */
+export interface GeneralVerifyGetKey extends types.GenericGetKeyFunction {
+}
+/**
+ * Verifies the signature and format of and afterwards decodes the General JWS.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jws/general/verify'`.
+ *
+ * @param jws General JWS.
+ * @param key Key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export declare function generalVerify(jws: types.GeneralJWSInput, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.VerifyOptions): Promise;
+/**
+ * @param jws General JWS.
+ * @param getKey Function resolving a key to verify the JWS with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWS Verify options.
+ */
+export declare function generalVerify(jws: types.GeneralJWSInput, getKey: GeneralVerifyGetKey, options?: types.VerifyOptions): Promise;
diff --git a/dist/types/jwt/decrypt.d.ts b/dist/types/jwt/decrypt.d.ts
new file mode 100644
index 0000000000..c0f51f09bc
--- /dev/null
+++ b/dist/types/jwt/decrypt.d.ts
@@ -0,0 +1,30 @@
+import type * as types from '../types.d.ts';
+/** Combination of JWE Decryption options and JWT Claims Set verification options. */
+export interface JWTDecryptOptions extends types.DecryptOptions, types.JWTClaimVerificationOptions {
+}
+/**
+ * Interface for JWT Decryption dynamic key resolution. No token components have been verified at
+ * the time of this function call.
+ */
+export interface JWTDecryptGetKey extends types.GetKeyFunction {
+}
+/**
+ * Verifies the JWT format (to be a JWE Compact format), decrypts the ciphertext, validates the JWT
+ * Claims Set.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwt/decrypt'`.
+ *
+ * @param jwt JSON Web Token value (encoded as JWE).
+ * @param key Private Key or Secret to decrypt and verify the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWT Decryption and JWT Claims Set validation options.
+ */
+export declare function jwtDecrypt(jwt: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: JWTDecryptOptions): Promise>;
+/**
+ * @param jwt JSON Web Token value (encoded as JWE).
+ * @param getKey Function resolving Private Key or Secret to decrypt and verify the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWT Decryption and JWT Claims Set validation options.
+ */
+export declare function jwtDecrypt(jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions): Promise & types.ResolvedKey>;
diff --git a/dist/types/jwt/encrypt.d.ts b/dist/types/jwt/encrypt.d.ts
new file mode 100644
index 0000000000..f459af19dc
--- /dev/null
+++ b/dist/types/jwt/encrypt.d.ts
@@ -0,0 +1,80 @@
+import type * as types from '../types.d.ts';
+import { ProduceJWT } from './produce.js';
+/**
+ * The EncryptJWT class is used to build and encrypt Compact JWE formatted JSON Web Tokens.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwt/encrypt'`.
+ *
+ */
+export declare class EncryptJWT extends ProduceJWT {
+ private _cek;
+ private _iv;
+ private _keyManagementParameters;
+ private _protectedHeader;
+ private _replicateIssuerAsHeader;
+ private _replicateSubjectAsHeader;
+ private _replicateAudienceAsHeader;
+ /**
+ * Sets the JWE Protected Header on the EncryptJWT object.
+ *
+ * @param protectedHeader JWE Protected Header. Must contain an "alg" (JWE Algorithm) and "enc"
+ * (JWE Encryption Algorithm) properties.
+ */
+ setProtectedHeader(protectedHeader: types.CompactJWEHeaderParameters): this;
+ /**
+ * Sets the JWE Key Management parameters to be used when encrypting. Use of this is method is
+ * really only needed for ECDH based algorithms when utilizing the Agreement PartyUInfo or
+ * Agreement PartyVInfo parameters. Other parameters will always be randomly generated when needed
+ * and missing.
+ *
+ * @param parameters JWE Key Management parameters.
+ */
+ setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): this;
+ /**
+ * Sets a content encryption key to use, by default a random suitable one is generated for the JWE
+ * enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param cek JWE Content Encryption Key.
+ */
+ setContentEncryptionKey(cek: Uint8Array): this;
+ /**
+ * Sets the JWE Initialization Vector to use for content encryption, by default a random suitable
+ * one is generated for the JWE enc" (Encryption Algorithm) Header Parameter.
+ *
+ * @deprecated You should not use this method. It is only really intended for test and vector
+ * validation purposes.
+ *
+ * @param iv JWE Initialization Vector.
+ */
+ setInitializationVector(iv: Uint8Array): this;
+ /**
+ * Replicates the "iss" (Issuer) Claim as a JWE Protected Header Parameter.
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3}
+ */
+ replicateIssuerAsHeader(): this;
+ /**
+ * Replicates the "sub" (Subject) Claim as a JWE Protected Header Parameter.
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3}
+ */
+ replicateSubjectAsHeader(): this;
+ /**
+ * Replicates the "aud" (Audience) Claim as a JWE Protected Header Parameter.
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-5.3 RFC7519#section-5.3}
+ */
+ replicateAudienceAsHeader(): this;
+ /**
+ * Encrypts and returns the JWT.
+ *
+ * @param key Public Key or Secret to encrypt the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}.
+ * @param options JWE Encryption options.
+ */
+ encrypt(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.EncryptOptions): Promise;
+}
diff --git a/dist/types/jwt/produce.d.ts b/dist/types/jwt/produce.d.ts
new file mode 100644
index 0000000000..da70951e5e
--- /dev/null
+++ b/dist/types/jwt/produce.d.ts
@@ -0,0 +1,104 @@
+import type * as types from '../types.d.ts';
+/** Generic class for JWT producing. */
+export declare class ProduceJWT {
+ protected _payload: types.JWTPayload;
+ /** @param payload The JWT Claims Set object. Defaults to an empty object. */
+ constructor(payload?: types.JWTPayload);
+ /**
+ * Set the "iss" (Issuer) Claim.
+ *
+ * @param issuer "Issuer" Claim value to set on the JWT Claims Set.
+ */
+ setIssuer(issuer: string): this;
+ /**
+ * Set the "sub" (Subject) Claim.
+ *
+ * @param subject "sub" (Subject) Claim value to set on the JWT Claims Set.
+ */
+ setSubject(subject: string): this;
+ /**
+ * Set the "aud" (Audience) Claim.
+ *
+ * @param audience "aud" (Audience) Claim value to set on the JWT Claims Set.
+ */
+ setAudience(audience: string | string[]): this;
+ /**
+ * Set the "jti" (JWT ID) Claim.
+ *
+ * @param jwtId "jti" (JWT ID) Claim value to set on the JWT Claims Set.
+ */
+ setJti(jwtId: string): this;
+ /**
+ * Set the "nbf" (Not Before) Claim.
+ *
+ * - If a `number` is passed as an argument it is used as the claim directly.
+ * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the
+ * claim.
+ * - If a `string` is passed as an argument it is resolved to a time span, and then added to the
+ * current unix timestamp and used as the claim.
+ *
+ * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1
+ * day".
+ *
+ * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins",
+ * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year",
+ * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an
+ * alias for a year.
+ *
+ * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets
+ * subtracted from the current unix timestamp. A "from now" suffix can also be used for
+ * readability when adding to the current unix timestamp.
+ *
+ * @param input "nbf" (Not Before) Claim value to set on the JWT Claims Set.
+ */
+ setNotBefore(input: number | string | Date): this;
+ /**
+ * Set the "exp" (Expiration Time) Claim.
+ *
+ * - If a `number` is passed as an argument it is used as the claim directly.
+ * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the
+ * claim.
+ * - If a `string` is passed as an argument it is resolved to a time span, and then added to the
+ * current unix timestamp and used as the claim.
+ *
+ * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1
+ * day".
+ *
+ * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins",
+ * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year",
+ * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an
+ * alias for a year.
+ *
+ * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets
+ * subtracted from the current unix timestamp. A "from now" suffix can also be used for
+ * readability when adding to the current unix timestamp.
+ *
+ * @param input "exp" (Expiration Time) Claim value to set on the JWT Claims Set.
+ */
+ setExpirationTime(input: number | string | Date): this;
+ /**
+ * Set the "iat" (Issued At) Claim.
+ *
+ * - If no argument is used the current unix timestamp is used as the claim.
+ * - If a `number` is passed as an argument it is used as the claim directly.
+ * - If a `Date` instance is passed as an argument it is converted to unix timestamp and used as the
+ * claim.
+ * - If a `string` is passed as an argument it is resolved to a time span, and then added to the
+ * current unix timestamp and used as the claim.
+ *
+ * Format used for time span should be a number followed by a unit, such as "5 minutes" or "1
+ * day".
+ *
+ * Valid units are: "sec", "secs", "second", "seconds", "s", "minute", "minutes", "min", "mins",
+ * "m", "hour", "hours", "hr", "hrs", "h", "day", "days", "d", "week", "weeks", "w", "year",
+ * "years", "yr", "yrs", and "y". It is not possible to specify months. 365.25 days is used as an
+ * alias for a year.
+ *
+ * If the string is suffixed with "ago", or prefixed with a "-", the resulting time span gets
+ * subtracted from the current unix timestamp. A "from now" suffix can also be used for
+ * readability when adding to the current unix timestamp.
+ *
+ * @param input "iat" (Expiration Time) Claim value to set on the JWT Claims Set.
+ */
+ setIssuedAt(input?: number | string | Date): this;
+}
diff --git a/dist/types/jwt/sign.d.ts b/dist/types/jwt/sign.d.ts
new file mode 100644
index 0000000000..80698744a6
--- /dev/null
+++ b/dist/types/jwt/sign.d.ts
@@ -0,0 +1,26 @@
+import type * as types from '../types.d.ts';
+import { ProduceJWT } from './produce.js';
+/**
+ * The SignJWT class is used to build and sign Compact JWS formatted JSON Web Tokens.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwt/sign'`.
+ *
+ */
+export declare class SignJWT extends ProduceJWT {
+ private _protectedHeader;
+ /**
+ * Sets the JWS Protected Header on the SignJWT object.
+ *
+ * @param protectedHeader JWS Protected Header. Must contain an "alg" (JWS Algorithm) property.
+ */
+ setProtectedHeader(protectedHeader: types.JWTHeaderParameters): this;
+ /**
+ * Signs and returns the JWT.
+ *
+ * @param key Private Key or Secret to sign the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWT Sign options.
+ */
+ sign(key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.SignOptions): Promise;
+}
diff --git a/dist/types/jwt/unsecured.d.ts b/dist/types/jwt/unsecured.d.ts
new file mode 100644
index 0000000000..ae33fc5beb
--- /dev/null
+++ b/dist/types/jwt/unsecured.d.ts
@@ -0,0 +1,24 @@
+import type * as types from '../types.d.ts';
+import { ProduceJWT } from './produce.js';
+export interface UnsecuredResult {
+ payload: PayloadType & types.JWTPayload;
+ header: types.JWSHeaderParameters;
+}
+/**
+ * The UnsecuredJWT class is a utility for dealing with `{ "alg": "none" }` Unsecured JWTs.
+ *
+ * This class is exported (as a named export) from the main `'jose'` module entry point as well as
+ * from its subpath export `'jose/jwt/unsecured'`.
+ *
+ */
+export declare class UnsecuredJWT extends ProduceJWT {
+ /** Encodes the Unsecured JWT. */
+ encode(): string;
+ /**
+ * Decodes an unsecured JWT.
+ *
+ * @param jwt Unsecured JWT to decode the payload of.
+ * @param options JWT Claims Set validation options.
+ */
+ static decode(jwt: string, options?: types.JWTClaimVerificationOptions): UnsecuredResult;
+}
diff --git a/dist/types/jwt/verify.d.ts b/dist/types/jwt/verify.d.ts
new file mode 100644
index 0000000000..0195ad20a7
--- /dev/null
+++ b/dist/types/jwt/verify.d.ts
@@ -0,0 +1,32 @@
+import type * as types from '../types.d.ts';
+/** Combination of JWS Verification options and JWT Claims Set verification options. */
+export interface JWTVerifyOptions extends types.VerifyOptions, types.JWTClaimVerificationOptions {
+}
+/**
+ * Interface for JWT Verification dynamic key resolution. No token components have been verified at
+ * the time of this function call.
+ *
+ * @see {@link jwks/remote.createRemoteJWKSet createRemoteJWKSet} to verify using a remote JSON Web Key Set.
+ */
+export interface JWTVerifyGetKey extends types.GenericGetKeyFunction {
+}
+/**
+ * Verifies the JWT format (to be a JWS Compact format), verifies the JWS signature, validates the
+ * JWT Claims Set.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwt/verify'`.
+ *
+ * @param jwt JSON Web Token value (encoded as JWS).
+ * @param key Key to verify the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWT Decryption and JWT Claims Set validation options.
+ */
+export declare function jwtVerify(jwt: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: JWTVerifyOptions): Promise>;
+/**
+ * @param jwt JSON Web Token value (encoded as JWS).
+ * @param getKey Function resolving a key to verify the JWT with. See
+ * {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}.
+ * @param options JWT Decryption and JWT Claims Set validation options.
+ */
+export declare function jwtVerify(jwt: string | Uint8Array, getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): Promise & types.ResolvedKey>;
diff --git a/dist/types/key/export.d.ts b/dist/types/key/export.d.ts
new file mode 100644
index 0000000000..01dd4020bf
--- /dev/null
+++ b/dist/types/key/export.d.ts
@@ -0,0 +1,28 @@
+import type * as types from '../types.d.ts';
+/**
+ * Exports a public {@link !CryptoKey} or {@link !KeyObject} to a PEM-encoded SPKI string format.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/export'`.
+ *
+ * @param key Key to export to a PEM-encoded SPKI string format.
+ */
+export declare function exportSPKI(key: types.CryptoKey | types.KeyObject): Promise;
+/**
+ * Exports a private {@link !CryptoKey} or {@link !KeyObject} to a PEM-encoded PKCS8 string format.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/export'`.
+ *
+ * @param key Key to export to a PEM-encoded PKCS8 string format.
+ */
+export declare function exportPKCS8(key: types.CryptoKey | types.KeyObject): Promise;
+/**
+ * Exports a {@link !CryptoKey}, {@link !KeyObject}, or {@link !Uint8Array} to a JWK.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/export'`.
+ *
+ * @param key Key to export as JWK.
+ */
+export declare function exportJWK(key: types.CryptoKey | types.KeyObject | Uint8Array): Promise;
diff --git a/dist/types/key/generate_key_pair.d.ts b/dist/types/key/generate_key_pair.d.ts
new file mode 100644
index 0000000000..da3ce2ed21
--- /dev/null
+++ b/dist/types/key/generate_key_pair.d.ts
@@ -0,0 +1,39 @@
+import type * as types from '../types.d.ts';
+export interface GenerateKeyPairResult {
+ /** The generated Private Key. */
+ privateKey: types.CryptoKey;
+ /** Public Key corresponding to the generated Private Key. */
+ publicKey: types.CryptoKey;
+}
+export interface GenerateKeyPairOptions {
+ /**
+ * The EC "crv" (Curve) or OKP "crv" (Subtype of Key Pair) value to generate. The curve must be
+ * both supported on the runtime as well as applicable for the given JWA algorithm identifier.
+ */
+ crv?: string;
+ /**
+ * A hint for RSA algorithms to generate an RSA key of a given `modulusLength` (Key size in bits).
+ * JOSE requires 2048 bits or larger. Default is 2048.
+ */
+ modulusLength?: number;
+ /**
+ * The value to use as {@link !SubtleCrypto.generateKey} `extractable` argument. Default is false.
+ *
+ */
+ extractable?: boolean;
+}
+/**
+ * Generates a private and a public key for a given JWA algorithm identifier. This can only generate
+ * asymmetric key pairs. For symmetric secrets use the `generateSecret` function.
+ *
+ * Note: The `privateKey` is generated with `extractable` set to `false` by default. See
+ * {@link GenerateKeyPairOptions.extractable} to generate an extractable `privateKey`.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/generate/keypair'`.
+ *
+ * @param alg JWA Algorithm Identifier to be used with the generated key pair. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ * @param options Additional options passed down to the key pair generation.
+ */
+export declare function generateKeyPair(alg: string, options?: GenerateKeyPairOptions): Promise;
diff --git a/dist/types/key/generate_secret.d.ts b/dist/types/key/generate_secret.d.ts
new file mode 100644
index 0000000000..84cde0b14d
--- /dev/null
+++ b/dist/types/key/generate_secret.d.ts
@@ -0,0 +1,18 @@
+import type * as types from '../types.d.ts';
+export interface GenerateSecretOptions {
+ /** The value to use as {@link !SubtleCrypto.generateKey} `extractable` argument. Default is false. */
+ extractable?: boolean;
+}
+/**
+ * Generates a symmetric secret key for a given JWA algorithm identifier.
+ *
+ * Note: The secret key is generated with `extractable` set to `false` by default.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/generate/secret'`.
+ *
+ * @param alg JWA Algorithm Identifier to be used with the generated secret. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ * @param options Additional options passed down to the secret generation.
+ */
+export declare function generateSecret(alg: string, options?: GenerateSecretOptions): Promise;
diff --git a/dist/types/key/import.d.ts b/dist/types/key/import.d.ts
new file mode 100644
index 0000000000..d7b2f8cb74
--- /dev/null
+++ b/dist/types/key/import.d.ts
@@ -0,0 +1,69 @@
+import type * as types from '../types.d.ts';
+export interface KeyImportOptions {
+ /**
+ * The value to use as {@link !SubtleCrypto.importKey} `extractable` argument. Default is false for
+ * private and secret keys, true otherwise.
+ */
+ extractable?: boolean;
+}
+/**
+ * Imports a PEM-encoded SPKI string as a {@link !CryptoKey}.
+ *
+ * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in
+ * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption
+ * (1.2.840.113549.1.1.1) instead for all RSA algorithms.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/import'`.
+ *
+ * @param spki PEM-encoded SPKI string
+ * @param alg JSON Web Algorithm identifier to be used with the imported key. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ */
+export declare function importSPKI(spki: string, alg: string, options?: KeyImportOptions): Promise;
+/**
+ * Imports the SPKI from an X.509 string certificate as a {@link !CryptoKey}.
+ *
+ * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in
+ * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption
+ * (1.2.840.113549.1.1.1) instead for all RSA algorithms.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/import'`.
+ *
+ * @param x509 X.509 certificate string
+ * @param alg JSON Web Algorithm identifier to be used with the imported key. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ */
+export declare function importX509(x509: string, alg: string, options?: KeyImportOptions): Promise;
+/**
+ * Imports a PEM-encoded PKCS#8 string as a {@link !CryptoKey}.
+ *
+ * Note: The OID id-RSASSA-PSS (1.2.840.113549.1.1.10) is not supported in
+ * {@link https://w3c.github.io/webcrypto/ Web Cryptography API}, use the OID rsaEncryption
+ * (1.2.840.113549.1.1.1) instead for all RSA algorithms.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/import'`.
+ *
+ * @param pkcs8 PEM-encoded PKCS#8 string
+ * @param alg JSON Web Algorithm identifier to be used with the imported key. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ */
+export declare function importPKCS8(pkcs8: string, alg: string, options?: KeyImportOptions): Promise;
+/**
+ * Imports a JWK to a {@link !CryptoKey}. Either the JWK "alg" (Algorithm) Parameter, or the optional
+ * "alg" argument, must be present.
+ *
+ * Note: The JSON Web Key parameters "use", "key_ops", and "ext" are also used in the
+ * {@link !CryptoKey} import process.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/key/import'`.
+ *
+ * @param jwk JSON Web Key.
+ * @param alg JSON Web Algorithm identifier to be used with the imported key. Default is the "alg"
+ * property on the JWK. See
+ * {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
+ */
+export declare function importJWK(jwk: types.JWK, alg?: string, options?: KeyImportOptions): Promise;
diff --git a/dist/types/types.d.ts b/dist/types/types.d.ts
new file mode 100644
index 0000000000..c3d0e39610
--- /dev/null
+++ b/dist/types/types.d.ts
@@ -0,0 +1,694 @@
+/** Generic JSON Web Key Parameters. */
+export interface JWKParameters {
+ /** JWK "kty" (Key Type) Parameter */
+ kty: string
+ /**
+ * JWK "alg" (Algorithm) Parameter
+ *
+ * @see {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}
+ */
+ alg?: string
+ /** JWK "key_ops" (Key Operations) Parameter */
+ key_ops?: string[]
+ /** JWK "ext" (Extractable) Parameter */
+ ext?: boolean
+ /** JWK "use" (Public Key Use) Parameter */
+ use?: string
+ /** JWK "x5c" (X.509 Certificate Chain) Parameter */
+ x5c?: string[]
+ /** JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter */
+ x5t?: string
+ /** JWK "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter */
+ 'x5t#S256'?: string
+ /** JWK "x5u" (X.509 URL) Parameter */
+ x5u?: string
+ /** JWK "kid" (Key ID) Parameter */
+ kid?: string
+}
+
+/** Convenience interface for Public OKP JSON Web Keys */
+export interface JWK_OKP_Public extends JWKParameters {
+ /** OKP JWK "crv" (The Subtype of Key Pair) Parameter */
+ crv: string
+ /** OKP JWK "x" (The public key) Parameter */
+ x: string
+}
+
+/** Convenience interface for Private OKP JSON Web Keys */
+export interface JWK_OKP_Private extends JWK_OKP_Public, JWKParameters {
+ /** OKP JWK "d" (The Private Key) Parameter */
+ d: string
+}
+
+/** Convenience interface for Public EC JSON Web Keys */
+export interface JWK_EC_Public extends JWKParameters {
+ /** EC JWK "crv" (Curve) Parameter */
+ crv: string
+ /** EC JWK "x" (X Coordinate) Parameter */
+ x: string
+ /** EC JWK "y" (Y Coordinate) Parameter */
+ y: string
+}
+
+/** Convenience interface for Private EC JSON Web Keys */
+export interface JWK_EC_Private extends JWK_EC_Public, JWKParameters {
+ /** EC JWK "d" (ECC Private Key) Parameter */
+ d: string
+}
+
+/** Convenience interface for Public RSA JSON Web Keys */
+export interface JWK_RSA_Public extends JWKParameters {
+ /** RSA JWK "e" (Exponent) Parameter */
+ e: string
+ /** RSA JWK "n" (Modulus) Parameter */
+ n: string
+}
+
+/** Convenience interface for Private RSA JSON Web Keys */
+export interface JWK_RSA_Private extends JWK_RSA_Public, JWKParameters {
+ /** RSA JWK "d" (Private Exponent) Parameter */
+ d: string
+ /** RSA JWK "dp" (First Factor CRT Exponent) Parameter */
+ dp: string
+ /** RSA JWK "dq" (Second Factor CRT Exponent) Parameter */
+ dq: string
+ /** RSA JWK "p" (First Prime Factor) Parameter */
+ p: string
+ /** RSA JWK "q" (Second Prime Factor) Parameter */
+ q: string
+ /** RSA JWK "qi" (First CRT Coefficient) Parameter */
+ qi: string
+}
+
+/** Convenience interface for oct JSON Web Keys */
+export interface JWK_oct extends JWKParameters {
+ /** Oct JWK "k" (Key Value) Parameter */
+ k: string
+}
+
+/**
+ * JSON Web Key ({@link https://www.rfc-editor.org/rfc/rfc7517 JWK}). "RSA", "EC", "OKP", and "oct"
+ * key types are supported.
+ *
+ * @see {@link JWK_OKP_Public}
+ * @see {@link JWK_OKP_Private}
+ * @see {@link JWK_EC_Public}
+ * @see {@link JWK_EC_Private}
+ * @see {@link JWK_RSA_Public}
+ * @see {@link JWK_RSA_Private}
+ * @see {@link JWK_oct}
+ */
+export interface JWK extends JWKParameters {
+ /**
+ * - EC JWK "crv" (Curve) Parameter
+ * - OKP JWK "crv" (The Subtype of Key Pair) Parameter
+ */
+ crv?: string
+ /**
+ * - Private RSA JWK "d" (Private Exponent) Parameter
+ * - Private EC JWK "d" (ECC Private Key) Parameter
+ * - Private OKP JWK "d" (The Private Key) Parameter
+ */
+ d?: string
+ /** Private RSA JWK "dp" (First Factor CRT Exponent) Parameter */
+ dp?: string
+ /** Private RSA JWK "dq" (Second Factor CRT Exponent) Parameter */
+ dq?: string
+ /** RSA JWK "e" (Exponent) Parameter */
+ e?: string
+ /** Oct JWK "k" (Key Value) Parameter */
+ k?: string
+ /** RSA JWK "n" (Modulus) Parameter */
+ n?: string
+ /** Private RSA JWK "p" (First Prime Factor) Parameter */
+ p?: string
+ /** Private RSA JWK "q" (Second Prime Factor) Parameter */
+ q?: string
+ /** Private RSA JWK "qi" (First CRT Coefficient) Parameter */
+ qi?: string
+ /**
+ * - EC JWK "x" (X Coordinate) Parameter
+ * - OKP JWK "x" (The public key) Parameter
+ */
+ x?: string
+ /** EC JWK "y" (Y Coordinate) Parameter */
+ y?: string
+}
+
+/**
+ * @private
+ *
+ * @internal
+ */
+export interface GenericGetKeyFunction {
+ /**
+ * Dynamic key resolution function. No token components have been verified at the time of this
+ * function call.
+ *
+ * If you cannot match a key suitable for the token, throw an error instead.
+ *
+ * @param protectedHeader JWE or JWS Protected Header.
+ * @param token The consumed JWE or JWS token.
+ */
+ (protectedHeader: IProtectedHeader, token: IToken): Promise | ReturnKeyTypes
+}
+
+/**
+ * Generic Interface for consuming operations dynamic key resolution.
+ *
+ * @param IProtectedHeader Type definition of the JWE or JWS Protected Header.
+ * @param IToken Type definition of the consumed JWE or JWS token.
+ */
+export interface GetKeyFunction
+ extends GenericGetKeyFunction<
+ IProtectedHeader,
+ IToken,
+ CryptoKey | KeyObject | JWK | Uint8Array
+ > {}
+
+/**
+ * Flattened JWS definition for verify function inputs, allows payload as {@link !Uint8Array} for
+ * detached signature validation.
+ */
+export interface FlattenedJWSInput {
+ /**
+ * The "header" member MUST be present and contain the value JWS Unprotected Header when the JWS
+ * Unprotected Header value is non- empty; otherwise, it MUST be absent. This value is represented
+ * as an unencoded JSON object, rather than as a string. These Header Parameter values are not
+ * integrity protected.
+ */
+ header?: JWSHeaderParameters
+
+ /**
+ * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When RFC7797
+ * "b64": false is used the value passed may also be a {@link !Uint8Array}.
+ */
+ payload: string | Uint8Array
+
+ /**
+ * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWS Protected
+ * Header)) when the JWS Protected Header value is non-empty; otherwise, it MUST be absent. These
+ * Header Parameter values are integrity protected.
+ */
+ protected?: string
+
+ /** The "signature" member MUST be present and contain the value BASE64URL(JWS Signature). */
+ signature: string
+}
+
+/**
+ * General JWS definition for verify function inputs, allows payload as {@link !Uint8Array} for
+ * detached signature validation.
+ */
+export interface GeneralJWSInput {
+ /**
+ * The "payload" member MUST be present and contain the value BASE64URL(JWS Payload). When when
+ * JWS Unencoded Payload ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) "b64": false is
+ * used the value passed may also be a {@link !Uint8Array}.
+ */
+ payload: string | Uint8Array
+
+ /**
+ * The "signatures" member value MUST be an array of JSON objects. Each object represents a
+ * signature or MAC over the JWS Payload and the JWS Protected Header.
+ */
+ signatures: Omit[]
+}
+
+/**
+ * Flattened JWS definition. Payload is returned as an empty string when JWS Unencoded Payload
+ * ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used.
+ */
+export interface FlattenedJWS extends Partial {
+ payload: string
+ signature: string
+}
+
+/**
+ * General JWS definition. Payload is returned as an empty string when JWS Unencoded Payload
+ * ({@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}) is used.
+ */
+export interface GeneralJWS {
+ payload: string
+ signatures: Omit[]
+}
+
+export interface JoseHeaderParameters {
+ /** "kid" (Key ID) Header Parameter */
+ kid?: string
+
+ /** "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter */
+ x5t?: string
+
+ /** "x5c" (X.509 Certificate Chain) Header Parameter */
+ x5c?: string[]
+
+ /** "x5u" (X.509 URL) Header Parameter */
+ x5u?: string
+
+ /** "jku" (JWK Set URL) Header Parameter */
+ jku?: string
+
+ /** "jwk" (JSON Web Key) Header Parameter */
+ jwk?: Pick
+
+ /** "typ" (Type) Header Parameter */
+ typ?: string
+
+ /** "cty" (Content Type) Header Parameter */
+ cty?: string
+}
+
+/** Recognized JWS Header Parameters, any other Header Members may also be present. */
+export interface JWSHeaderParameters extends JoseHeaderParameters {
+ /**
+ * JWS "alg" (Algorithm) Header Parameter
+ *
+ * @see {@link https://github.com/panva/jose/issues/210#jws-alg Algorithm Key Requirements}
+ */
+ alg?: string
+
+ /**
+ * This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing
+ * Input computation as per {@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}.
+ */
+ b64?: boolean
+
+ /** JWS "crit" (Critical) Header Parameter */
+ crit?: string[]
+
+ /** Any other JWS Header member. */
+ [propName: string]: unknown
+}
+
+/** Recognized JWE Key Management-related Header Parameters. */
+export interface JWEKeyManagementHeaderParameters {
+ apu?: Uint8Array
+ apv?: Uint8Array
+ /**
+ * @deprecated You should not use this parameter. It is only really intended for test and vector
+ * validation purposes.
+ */
+ p2c?: number
+ /**
+ * @deprecated You should not use this parameter. It is only really intended for test and vector
+ * validation purposes.
+ */
+ p2s?: Uint8Array
+ /**
+ * @deprecated You should not use this parameter. It is only really intended for test and vector
+ * validation purposes.
+ */
+ iv?: Uint8Array
+ /**
+ * @deprecated You should not use this parameter. It is only really intended for test and vector
+ * validation purposes.
+ */
+ epk?: CryptoKey | KeyObject
+}
+
+/** Flattened JWE definition. */
+export interface FlattenedJWE {
+ /**
+ * The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD
+ * value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a
+ * base64url-encoded value to be integrity protected but not encrypted.
+ */
+ aad?: string
+
+ /** The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). */
+ ciphertext: string
+
+ /**
+ * The "encrypted_key" member MUST be present and contain the value BASE64URL(JWE Encrypted Key)
+ * when the JWE Encrypted Key value is non-empty; otherwise, it MUST be absent.
+ */
+ encrypted_key?: string
+
+ /**
+ * The "header" member MUST be present and contain the value JWE Per- Recipient Unprotected Header
+ * when the JWE Per-Recipient Unprotected Header value is non-empty; otherwise, it MUST be absent.
+ * This value is represented as an unencoded JSON object, rather than as a string. These Header
+ * Parameter values are not integrity protected.
+ */
+ header?: JWEHeaderParameters
+
+ /**
+ * The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when
+ * the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent.
+ */
+ iv?: string
+
+ /**
+ * The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected
+ * Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These
+ * Header Parameter values are integrity protected.
+ */
+ protected?: string
+
+ /**
+ * The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when
+ * the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent.
+ */
+ tag?: string
+
+ /**
+ * The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header
+ * when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This
+ * value is represented as an unencoded JSON object, rather than as a string. These Header
+ * Parameter values are not integrity protected.
+ */
+ unprotected?: JWEHeaderParameters
+}
+
+export interface GeneralJWE extends Omit {
+ recipients: Pick[]
+}
+
+/** Recognized JWE Header Parameters, any other Header members may also be present. */
+export interface JWEHeaderParameters extends JoseHeaderParameters {
+ /**
+ * JWE "alg" (Algorithm) Header Parameter
+ *
+ * @see {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}
+ */
+ alg?: string
+
+ /**
+ * JWE "enc" (Encryption Algorithm) Header Parameter
+ *
+ * @see {@link https://github.com/panva/jose/issues/210#jwe-alg Algorithm Key Requirements}
+ */
+ enc?: string
+
+ /** JWE "crit" (Critical) Header Parameter */
+ crit?: string[]
+
+ /**
+ * JWE "zip" (Compression Algorithm) Header Parameter. This parameter is not supported anymore.
+ *
+ * @deprecated Compression of data SHOULD NOT be done before encryption, because such compressed
+ * data often reveals information about the plaintext.
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc8725#name-avoid-compression-of-encryp Avoid Compression of Encryption Inputs}
+ */
+ zip?: string
+
+ /** Any other JWE Header member. */
+ [propName: string]: unknown
+}
+
+/** Shared Interface with a "crit" property for all sign, verify, encrypt and decrypt operations. */
+export interface CritOption {
+ /**
+ * An object with keys representing recognized "crit" (Critical) Header Parameter names. The value
+ * for those is either `true` or `false`. `true` when the Header Parameter MUST be integrity
+ * protected, `false` when it's irrelevant.
+ *
+ * This makes the "Extension Header Parameter "..." is not recognized" error go away.
+ *
+ * Use this when a given JWS/JWT/JWE profile requires the use of proprietary non-registered "crit"
+ * (Critical) Header Parameters. This will only make sure the Header Parameter is syntactically
+ * correct when provided and that it is optionally integrity protected. It will not process the
+ * Header Parameter in any way or reject the operation if it is missing. You MUST still verify the
+ * Header Parameter was present and process it according to the profile's validation steps after
+ * the operation succeeds.
+ *
+ * The JWS extension Header Parameter `b64` is always recognized and processed properly. No other
+ * registered Header Parameters that need this kind of default built-in treatment are currently
+ * available.
+ */
+ crit?: {
+ [propName: string]: boolean
+ }
+}
+
+/** JWE Decryption options. */
+export interface DecryptOptions extends CritOption {
+ /**
+ * A list of accepted JWE "alg" (Algorithm) Header Parameter values. By default all "alg"
+ * (Algorithm) Header Parameter values applicable for the used key/secret are allowed except for
+ * all PBES2 Key Management Algorithms, these need to be explicitly allowed using this option.
+ */
+ keyManagementAlgorithms?: string[]
+
+ /**
+ * A list of accepted JWE "enc" (Encryption Algorithm) Header Parameter values. By default all
+ * "enc" (Encryption Algorithm) values applicable for the used key/secret are allowed.
+ */
+ contentEncryptionAlgorithms?: string[]
+
+ /**
+ * (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter
+ * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default
+ * this value is set to 10000.
+ */
+ maxPBES2Count?: number
+}
+
+/** JWE Encryption options. */
+export interface EncryptOptions extends CritOption {}
+
+/** JWT Claims Set verification options. */
+export interface JWTClaimVerificationOptions {
+ /**
+ * Expected JWT "aud" (Audience) Claim value(s).
+ *
+ * This option makes the JWT "aud" (Audience) Claim presence required.
+ */
+ audience?: string | string[]
+
+ /**
+ * Clock skew tolerance
+ *
+ * - In seconds when number (e.g. 5)
+ * - Resolved into a number of seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours").
+ *
+ * Used when validating the JWT "nbf" (Not Before) and "exp" (Expiration Time) claims, and when
+ * validating the "iat" (Issued At) claim if the {@link maxTokenAge `maxTokenAge` option} is set.
+ */
+ clockTolerance?: string | number
+
+ /**
+ * Expected JWT "iss" (Issuer) Claim value(s).
+ *
+ * This option makes the JWT "iss" (Issuer) Claim presence required.
+ */
+ issuer?: string | string[]
+
+ /**
+ * Maximum time elapsed (in seconds) from the JWT "iat" (Issued At) Claim value.
+ *
+ * - In seconds when number (e.g. 5)
+ * - Resolved into a number of seconds when a string (e.g. "5 seconds", "10 minutes", "2 hours").
+ *
+ * This option makes the JWT "iat" (Issued At) Claim presence required.
+ */
+ maxTokenAge?: string | number
+
+ /**
+ * Expected JWT "sub" (Subject) Claim value.
+ *
+ * This option makes the JWT "sub" (Subject) Claim presence required.
+ */
+ subject?: string
+
+ /**
+ * Expected JWT "typ" (Type) Header Parameter value.
+ *
+ * This option makes the JWT "typ" (Type) Header Parameter presence required.
+ */
+ typ?: string
+
+ /** Date to use when comparing NumericDate claims, defaults to `new Date()`. */
+ currentDate?: Date
+
+ /**
+ * Array of required Claim Names that must be present in the JWT Claims Set. Default is that: if
+ * the {@link issuer `issuer` option} is set, then JWT "iss" (Issuer) Claim must be present; if the
+ * {@link audience `audience` option} is set, then JWT "aud" (Audience) Claim must be present; if
+ * the {@link subject `subject` option} is set, then JWT "sub" (Subject) Claim must be present; if
+ * the {@link maxTokenAge `maxTokenAge` option} is set, then JWT "iat" (Issued At) Claim must be
+ * present.
+ */
+ requiredClaims?: string[]
+}
+
+/** JWS Verification options. */
+export interface VerifyOptions extends CritOption {
+ /**
+ * A list of accepted JWS "alg" (Algorithm) Header Parameter values. By default all "alg"
+ * (Algorithm) values applicable for the used key/secret are allowed.
+ *
+ * Note: Unsecured JWTs (`{ "alg": "none" }`) are never accepted by this API.
+ */
+ algorithms?: string[]
+}
+
+/** JWS Signing options. */
+export interface SignOptions extends CritOption {}
+
+/** Recognized JWT Claims Set members, any other members may also be present. */
+export interface JWTPayload {
+ /**
+ * JWT Issuer
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1 RFC7519#section-4.1.1}
+ */
+ iss?: string
+
+ /**
+ * JWT Subject
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2 RFC7519#section-4.1.2}
+ */
+ sub?: string
+
+ /**
+ * JWT Audience
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3 RFC7519#section-4.1.3}
+ */
+ aud?: string | string[]
+
+ /**
+ * JWT ID
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7 RFC7519#section-4.1.7}
+ */
+ jti?: string
+
+ /**
+ * JWT Not Before
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5 RFC7519#section-4.1.5}
+ */
+ nbf?: number
+
+ /**
+ * JWT Expiration Time
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4 RFC7519#section-4.1.4}
+ */
+ exp?: number
+
+ /**
+ * JWT Issued At
+ *
+ * @see {@link https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 RFC7519#section-4.1.6}
+ */
+ iat?: number
+
+ /** Any other JWT Claim Set member. */
+ [propName: string]: unknown
+}
+
+export interface FlattenedDecryptResult {
+ /** JWE AAD. */
+ additionalAuthenticatedData?: Uint8Array
+
+ /** Plaintext. */
+ plaintext: Uint8Array
+
+ /** JWE Protected Header. */
+ protectedHeader?: JWEHeaderParameters
+
+ /** JWE Shared Unprotected Header. */
+ sharedUnprotectedHeader?: JWEHeaderParameters
+
+ /** JWE Per-Recipient Unprotected Header. */
+ unprotectedHeader?: JWEHeaderParameters
+}
+
+export interface GeneralDecryptResult extends FlattenedDecryptResult {}
+
+export interface CompactDecryptResult {
+ /** Plaintext. */
+ plaintext: Uint8Array
+
+ /** JWE Protected Header. */
+ protectedHeader: CompactJWEHeaderParameters
+}
+
+export interface FlattenedVerifyResult {
+ /** JWS Payload. */
+ payload: Uint8Array
+
+ /** JWS Protected Header. */
+ protectedHeader?: JWSHeaderParameters
+
+ /** JWS Unprotected Header. */
+ unprotectedHeader?: JWSHeaderParameters
+}
+
+export interface GeneralVerifyResult extends FlattenedVerifyResult {}
+
+export interface CompactVerifyResult {
+ /** JWS Payload. */
+ payload: Uint8Array
+
+ /** JWS Protected Header. */
+ protectedHeader: CompactJWSHeaderParameters
+}
+
+export interface JWTVerifyResult {
+ /** JWT Claims Set. */
+ payload: PayloadType & JWTPayload
+
+ /** JWS Protected Header. */
+ protectedHeader: JWTHeaderParameters
+}
+
+export interface JWTDecryptResult {
+ /** JWT Claims Set. */
+ payload: PayloadType & JWTPayload
+
+ /** JWE Protected Header. */
+ protectedHeader: CompactJWEHeaderParameters
+}
+
+export interface ResolvedKey {
+ /** Key resolved from the key resolver function. */
+ key: CryptoKey | Uint8Array
+}
+
+/** Recognized Compact JWS Header Parameters, any other Header Members may also be present. */
+export interface CompactJWSHeaderParameters extends JWSHeaderParameters {
+ alg: string
+}
+
+/** Recognized Signed JWT Header Parameters, any other Header Members may also be present. */
+export interface JWTHeaderParameters extends CompactJWSHeaderParameters {
+ b64?: true
+}
+
+/** Recognized Compact JWE Header Parameters, any other Header Members may also be present. */
+export interface CompactJWEHeaderParameters extends JWEHeaderParameters {
+ alg: string
+ enc: string
+}
+
+/** JSON Web Key Set */
+export interface JSONWebKeySet {
+ keys: JWK[]
+}
+
+/**
+ * {@link !KeyObject} is a representation of a key/secret available in the Node.js runtime. You may
+ * use the Node.js runtime APIs {@link !createPublicKey}, {@link !createPrivateKey}, and
+ * {@link !createSecretKey} to obtain a {@link !KeyObject} from your existing key material.
+ */
+export interface KeyObject {
+ type: string
+}
+
+/**
+ * {@link !CryptoKey} is a representation of a key/secret available in all supported runtimes. In
+ * addition to the {@link key/import Key Import Functions} you may use the
+ * {@link !SubtleCrypto.importKey} API to obtain a {@link !CryptoKey} from your existing key
+ * material.
+ */
+export type CryptoKey = Extract<
+ Awaited>,
+ { type: string }
+>
diff --git a/dist/types/util/base64url.d.ts b/dist/types/util/base64url.d.ts
new file mode 100644
index 0000000000..1f86cc6609
--- /dev/null
+++ b/dist/types/util/base64url.d.ts
@@ -0,0 +1,19 @@
+/**
+ * Utility function to encode a string or {@link !Uint8Array} as a base64url string.
+ *
+ * @param input Value that will be base64url-encoded.
+ */
+interface Base64UrlEncode {
+ (input: Uint8Array | string): string;
+}
+/**
+ * Utility function to decode a base64url encoded string.
+ *
+ * @param input Value that will be base64url-decoded.
+ */
+interface Base64UrlDecode {
+ (input: Uint8Array | string): Uint8Array;
+}
+export declare const encode: Base64UrlEncode;
+export declare const decode: Base64UrlDecode;
+export {};
diff --git a/dist/types/util/decode_jwt.d.ts b/dist/types/util/decode_jwt.d.ts
new file mode 100644
index 0000000000..c9956a995e
--- /dev/null
+++ b/dist/types/util/decode_jwt.d.ts
@@ -0,0 +1,13 @@
+import type * as types from '../types.d.ts';
+/**
+ * Decodes a signed JSON Web Token payload. This does not validate the JWT Claims Set types or
+ * values. This does not validate the JWS Signature. For a proper Signed JWT Claims Set validation
+ * and JWS signature verification use `jose.jwtVerify()`. For an encrypted JWT Claims Set validation
+ * and JWE decryption use `jose.jwtDecrypt()`.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/jwt/decode'`.
+ *
+ * @param jwt JWT token in compact JWS serialization.
+ */
+export declare function decodeJwt(jwt: string): PayloadType & types.JWTPayload;
diff --git a/dist/types/util/decode_protected_header.d.ts b/dist/types/util/decode_protected_header.d.ts
new file mode 100644
index 0000000000..8bf8b1437b
--- /dev/null
+++ b/dist/types/util/decode_protected_header.d.ts
@@ -0,0 +1,11 @@
+import type * as types from '../types.d.ts';
+export type ProtectedHeaderParameters = types.JWSHeaderParameters & types.JWEHeaderParameters;
+/**
+ * Decodes the Protected Header of a JWE/JWS/JWT token utilizing any JOSE serialization.
+ *
+ * This function is exported (as a named export) from the main `'jose'` module entry point as well
+ * as from its subpath export `'jose/decode/protected_header'`.
+ *
+ * @param token JWE/JWS/JWT token in any JOSE serialization.
+ */
+export declare function decodeProtectedHeader(token: string | object): ProtectedHeaderParameters;
diff --git a/dist/types/util/errors.d.ts b/dist/types/util/errors.d.ts
new file mode 100644
index 0000000000..64f4c97f94
--- /dev/null
+++ b/dist/types/util/errors.d.ts
@@ -0,0 +1,194 @@
+import type * as types from '../types.d.ts';
+/**
+ * A generic Error that all other JOSE specific Error subclasses extend.
+ *
+ */
+export declare class JOSEError extends Error {
+ /**
+ * A unique error code for the particular error subclass.
+ *
+ * @ignore
+ */
+ static code: string;
+ /** A unique error code for this particular error subclass. */
+ code: string;
+ /** @ignore */
+ constructor(message?: string, options?: {
+ cause?: unknown;
+ });
+}
+/**
+ * An error subclass thrown when a JWT Claim Set member validation fails.
+ *
+ */
+export declare class JWTClaimValidationFailed extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+ /** The Claim for which the validation failed. */
+ claim: string;
+ /** Reason code for the validation failure. */
+ reason: string;
+ /**
+ * The parsed JWT Claims Set (aka payload). Other JWT claims may or may not have been verified at
+ * this point. The JSON Web Signature (JWS) or a JSON Web Encryption (JWE) structures' integrity
+ * has however been verified. Claims Set verification happens after the JWS Signature or JWE
+ * Decryption processes.
+ */
+ payload: types.JWTPayload;
+ /** @ignore */
+ constructor(message: string, payload: types.JWTPayload, claim?: string, reason?: string);
+}
+/**
+ * An error subclass thrown when a JWT is expired.
+ *
+ */
+export declare class JWTExpired extends JOSEError implements JWTClaimValidationFailed {
+ /** @ignore */
+ static code: string;
+ code: string;
+ /** The Claim for which the validation failed. */
+ claim: string;
+ /** Reason code for the validation failure. */
+ reason: string;
+ /**
+ * The parsed JWT Claims Set (aka payload). Other JWT claims may or may not have been verified at
+ * this point. The JSON Web Signature (JWS) or a JSON Web Encryption (JWE) structures' integrity
+ * has however been verified. Claims Set verification happens after the JWS Signature or JWE
+ * Decryption processes.
+ */
+ payload: types.JWTPayload;
+ /** @ignore */
+ constructor(message: string, payload: types.JWTPayload, claim?: string, reason?: string);
+}
+/**
+ * An error subclass thrown when a JOSE Algorithm is not allowed per developer preference.
+ *
+ */
+export declare class JOSEAlgNotAllowed extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+}
+/**
+ * An error subclass thrown when a particular feature or algorithm is not supported by this
+ * implementation or JOSE in general.
+ *
+ */
+export declare class JOSENotSupported extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+}
+/**
+ * An error subclass thrown when a JWE ciphertext decryption fails.
+ *
+ */
+export declare class JWEDecryptionFailed extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+ /** @ignore */
+ constructor(message?: string, options?: {
+ cause?: unknown;
+ });
+}
+/**
+ * An error subclass thrown when a JWE is invalid.
+ *
+ */
+export declare class JWEInvalid extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+}
+/**
+ * An error subclass thrown when a JWS is invalid.
+ *
+ */
+export declare class JWSInvalid extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+}
+/**
+ * An error subclass thrown when a JWT is invalid.
+ *
+ */
+export declare class JWTInvalid extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+}
+/**
+ * An error subclass thrown when a JWK is invalid.
+ *
+ */
+export declare class JWKInvalid extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+}
+/**
+ * An error subclass thrown when a JWKS is invalid.
+ *
+ */
+export declare class JWKSInvalid extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+}
+/**
+ * An error subclass thrown when no keys match from a JWKS.
+ *
+ */
+export declare class JWKSNoMatchingKey extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+ /** @ignore */
+ constructor(message?: string, options?: {
+ cause?: unknown;
+ });
+}
+/**
+ * An error subclass thrown when multiple keys match from a JWKS.
+ *
+ */
+export declare class JWKSMultipleMatchingKeys extends JOSEError {
+ /** @ignore */
+ [Symbol.asyncIterator]: () => AsyncIterableIterator;
+ /** @ignore */
+ static code: string;
+ code: string;
+ /** @ignore */
+ constructor(message?: string, options?: {
+ cause?: unknown;
+ });
+}
+/**
+ * Timeout was reached when retrieving the JWKS response.
+ *
+ */
+export declare class JWKSTimeout extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+ /** @ignore */
+ constructor(message?: string, options?: {
+ cause?: unknown;
+ });
+}
+/**
+ * An error subclass thrown when JWS signature verification fails.
+ *
+ */
+export declare class JWSSignatureVerificationFailed extends JOSEError {
+ /** @ignore */
+ static code: string;
+ code: string;
+ /** @ignore */
+ constructor(message?: string, options?: {
+ cause?: unknown;
+ });
+}
diff --git a/dist/webapi/index.bundle.js b/dist/webapi/index.bundle.js
new file mode 100644
index 0000000000..21f05f8203
--- /dev/null
+++ b/dist/webapi/index.bundle.js
@@ -0,0 +1,3603 @@
+var __defProp = Object.defineProperty;
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+};
+
+// dist/webapi/lib/buffer_utils.js
+var encoder = new TextEncoder();
+var decoder = new TextDecoder();
+var MAX_INT32 = 2 ** 32;
+var Buffer2 = globalThis.process?.getBuiltinModule?.("node:buffer")?.Buffer;
+function concat(...buffers) {
+ if (Buffer2)
+ return Buffer2.concat(buffers);
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
+ const buf = new Uint8Array(size);
+ let i = 0;
+ for (const buffer of buffers) {
+ buf.set(buffer, i);
+ i += buffer.length;
+ }
+ return buf;
+}
+function writeUInt32BE(buf, value, offset) {
+ if (value < 0 || value >= MAX_INT32) {
+ throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
+ }
+ buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);
+}
+function uint64be(value) {
+ const high = Math.floor(value / MAX_INT32);
+ const low = value % MAX_INT32;
+ const buf = new Uint8Array(8);
+ writeUInt32BE(buf, high, 0);
+ writeUInt32BE(buf, low, 4);
+ return buf;
+}
+function uint32be(value) {
+ const buf = new Uint8Array(4);
+ writeUInt32BE(buf, value);
+ return buf;
+}
+
+// dist/webapi/lib/base64url.js
+function encodeBase64(input) {
+ if (Buffer2)
+ return Buffer2.from(input).toString("base64");
+ let unencoded = input;
+ if (typeof unencoded === "string") {
+ unencoded = encoder.encode(unencoded);
+ }
+ const CHUNK_SIZE = 32768;
+ const arr = [];
+ for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {
+ arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));
+ }
+ return btoa(arr.join(""));
+}
+function encode(input) {
+ if (Buffer2)
+ return Buffer2.from(input).toString("base64url");
+ return encodeBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
+}
+function decodeBase64(encoded) {
+ if (Buffer2)
+ return Buffer2.from(encoded, "base64");
+ const binary = atob(encoded);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i++) {
+ bytes[i] = binary.charCodeAt(i);
+ }
+ return bytes;
+}
+function decode(input) {
+ let encoded = input;
+ if (encoded instanceof Uint8Array) {
+ encoded = decoder.decode(encoded);
+ }
+ if (Buffer2)
+ return Buffer2.from(encoded, "base64url");
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
+ try {
+ return decodeBase64(encoded);
+ } catch {
+ throw new TypeError("The input to be decoded is not correctly encoded.");
+ }
+}
+
+// dist/webapi/util/errors.js
+var errors_exports = {};
+__export(errors_exports, {
+ JOSEAlgNotAllowed: () => JOSEAlgNotAllowed,
+ JOSEError: () => JOSEError,
+ JOSENotSupported: () => JOSENotSupported,
+ JWEDecryptionFailed: () => JWEDecryptionFailed,
+ JWEInvalid: () => JWEInvalid,
+ JWKInvalid: () => JWKInvalid,
+ JWKSInvalid: () => JWKSInvalid,
+ JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys,
+ JWKSNoMatchingKey: () => JWKSNoMatchingKey,
+ JWKSTimeout: () => JWKSTimeout,
+ JWSInvalid: () => JWSInvalid,
+ JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed,
+ JWTClaimValidationFailed: () => JWTClaimValidationFailed,
+ JWTExpired: () => JWTExpired,
+ JWTInvalid: () => JWTInvalid
+});
+var JOSEError = class extends Error {
+ static code = "ERR_JOSE_GENERIC";
+ code = "ERR_JOSE_GENERIC";
+ constructor(message2, options) {
+ super(message2, options);
+ this.name = this.constructor.name;
+ Error.captureStackTrace?.(this, this.constructor);
+ }
+};
+var JWTClaimValidationFailed = class extends JOSEError {
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
+ claim;
+ reason;
+ payload;
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
+ super(message2, { cause: { claim, reason, payload } });
+ this.claim = claim;
+ this.reason = reason;
+ this.payload = payload;
+ }
+};
+var JWTExpired = class extends JOSEError {
+ static code = "ERR_JWT_EXPIRED";
+ code = "ERR_JWT_EXPIRED";
+ claim;
+ reason;
+ payload;
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
+ super(message2, { cause: { claim, reason, payload } });
+ this.claim = claim;
+ this.reason = reason;
+ this.payload = payload;
+ }
+};
+var JOSEAlgNotAllowed = class extends JOSEError {
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
+};
+var JOSENotSupported = class extends JOSEError {
+ static code = "ERR_JOSE_NOT_SUPPORTED";
+ code = "ERR_JOSE_NOT_SUPPORTED";
+};
+var JWEDecryptionFailed = class extends JOSEError {
+ static code = "ERR_JWE_DECRYPTION_FAILED";
+ code = "ERR_JWE_DECRYPTION_FAILED";
+ constructor(message2 = "decryption operation failed", options) {
+ super(message2, options);
+ }
+};
+var JWEInvalid = class extends JOSEError {
+ static code = "ERR_JWE_INVALID";
+ code = "ERR_JWE_INVALID";
+};
+var JWSInvalid = class extends JOSEError {
+ static code = "ERR_JWS_INVALID";
+ code = "ERR_JWS_INVALID";
+};
+var JWTInvalid = class extends JOSEError {
+ static code = "ERR_JWT_INVALID";
+ code = "ERR_JWT_INVALID";
+};
+var JWKInvalid = class extends JOSEError {
+ static code = "ERR_JWK_INVALID";
+ code = "ERR_JWK_INVALID";
+};
+var JWKSInvalid = class extends JOSEError {
+ static code = "ERR_JWKS_INVALID";
+ code = "ERR_JWKS_INVALID";
+};
+var JWKSNoMatchingKey = class extends JOSEError {
+ static code = "ERR_JWKS_NO_MATCHING_KEY";
+ code = "ERR_JWKS_NO_MATCHING_KEY";
+ constructor(message2 = "no applicable key found in the JSON Web Key Set", options) {
+ super(message2, options);
+ }
+};
+var JWKSMultipleMatchingKeys = class extends JOSEError {
+ [Symbol.asyncIterator];
+ static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
+ code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
+ constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) {
+ super(message2, options);
+ }
+};
+var JWKSTimeout = class extends JOSEError {
+ static code = "ERR_JWKS_TIMEOUT";
+ code = "ERR_JWKS_TIMEOUT";
+ constructor(message2 = "request timed out", options) {
+ super(message2, options);
+ }
+};
+var JWSSignatureVerificationFailed = class extends JOSEError {
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
+ constructor(message2 = "signature verification failed", options) {
+ super(message2, options);
+ }
+};
+
+// dist/webapi/lib/iv.js
+function bitLength(alg) {
+ switch (alg) {
+ case "A128GCM":
+ case "A128GCMKW":
+ case "A192GCM":
+ case "A192GCMKW":
+ case "A256GCM":
+ case "A256GCMKW":
+ return 96;
+ case "A128CBC-HS256":
+ case "A192CBC-HS384":
+ case "A256CBC-HS512":
+ return 128;
+ default:
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
+ }
+}
+var iv_default = (alg) => crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3));
+
+// dist/webapi/lib/check_iv_length.js
+var check_iv_length_default = (enc, iv) => {
+ if (iv.length << 3 !== bitLength(enc)) {
+ throw new JWEInvalid("Invalid Initialization Vector length");
+ }
+};
+
+// dist/webapi/lib/check_cek_length.js
+var check_cek_length_default = (cek, expected) => {
+ const actual = cek.byteLength << 3;
+ if (actual !== expected) {
+ throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
+ }
+};
+
+// dist/webapi/lib/crypto_key.js
+function unusable(name, prop = "algorithm.name") {
+ return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
+}
+function isAlgorithm(algorithm, name) {
+ return algorithm.name === name;
+}
+function getHashLength(hash) {
+ return parseInt(hash.name.slice(4), 10);
+}
+function getNamedCurve(alg) {
+ switch (alg) {
+ case "ES256":
+ return "P-256";
+ case "ES384":
+ return "P-384";
+ case "ES512":
+ return "P-521";
+ default:
+ throw new Error("unreachable");
+ }
+}
+function checkUsage(key, usage) {
+ if (usage && !key.usages.includes(usage)) {
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
+ }
+}
+function checkSigCryptoKey(key, alg, usage) {
+ switch (alg) {
+ case "HS256":
+ case "HS384":
+ case "HS512": {
+ if (!isAlgorithm(key.algorithm, "HMAC"))
+ throw unusable("HMAC");
+ const expected = parseInt(alg.slice(2), 10);
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
+ break;
+ }
+ case "RS256":
+ case "RS384":
+ case "RS512": {
+ if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
+ throw unusable("RSASSA-PKCS1-v1_5");
+ const expected = parseInt(alg.slice(2), 10);
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
+ break;
+ }
+ case "PS256":
+ case "PS384":
+ case "PS512": {
+ if (!isAlgorithm(key.algorithm, "RSA-PSS"))
+ throw unusable("RSA-PSS");
+ const expected = parseInt(alg.slice(2), 10);
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
+ break;
+ }
+ case "Ed25519":
+ case "EdDSA": {
+ if (!isAlgorithm(key.algorithm, "Ed25519"))
+ throw unusable("Ed25519");
+ break;
+ }
+ case "ES256":
+ case "ES384":
+ case "ES512": {
+ if (!isAlgorithm(key.algorithm, "ECDSA"))
+ throw unusable("ECDSA");
+ const expected = getNamedCurve(alg);
+ const actual = key.algorithm.namedCurve;
+ if (actual !== expected)
+ throw unusable(expected, "algorithm.namedCurve");
+ break;
+ }
+ default:
+ throw new TypeError("CryptoKey does not support this operation");
+ }
+ checkUsage(key, usage);
+}
+function checkEncCryptoKey(key, alg, usage) {
+ switch (alg) {
+ case "A128GCM":
+ case "A192GCM":
+ case "A256GCM": {
+ if (!isAlgorithm(key.algorithm, "AES-GCM"))
+ throw unusable("AES-GCM");
+ const expected = parseInt(alg.slice(1, 4), 10);
+ const actual = key.algorithm.length;
+ if (actual !== expected)
+ throw unusable(expected, "algorithm.length");
+ break;
+ }
+ case "A128KW":
+ case "A192KW":
+ case "A256KW": {
+ if (!isAlgorithm(key.algorithm, "AES-KW"))
+ throw unusable("AES-KW");
+ const expected = parseInt(alg.slice(1, 4), 10);
+ const actual = key.algorithm.length;
+ if (actual !== expected)
+ throw unusable(expected, "algorithm.length");
+ break;
+ }
+ case "ECDH": {
+ switch (key.algorithm.name) {
+ case "ECDH":
+ case "X25519":
+ break;
+ default:
+ throw unusable("ECDH or X25519");
+ }
+ break;
+ }
+ case "PBES2-HS256+A128KW":
+ case "PBES2-HS384+A192KW":
+ case "PBES2-HS512+A256KW":
+ if (!isAlgorithm(key.algorithm, "PBKDF2"))
+ throw unusable("PBKDF2");
+ break;
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512": {
+ if (!isAlgorithm(key.algorithm, "RSA-OAEP"))
+ throw unusable("RSA-OAEP");
+ const expected = parseInt(alg.slice(9), 10) || 1;
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
+ break;
+ }
+ default:
+ throw new TypeError("CryptoKey does not support this operation");
+ }
+ checkUsage(key, usage);
+}
+
+// dist/webapi/lib/invalid_key_input.js
+function message(msg, actual, ...types) {
+ types = types.filter(Boolean);
+ if (types.length > 2) {
+ const last = types.pop();
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
+ } else if (types.length === 2) {
+ msg += `one of type ${types[0]} or ${types[1]}.`;
+ } else {
+ msg += `of type ${types[0]}.`;
+ }
+ if (actual == null) {
+ msg += ` Received ${actual}`;
+ } else if (typeof actual === "function" && actual.name) {
+ msg += ` Received function ${actual.name}`;
+ } else if (typeof actual === "object" && actual != null) {
+ if (actual.constructor?.name) {
+ msg += ` Received an instance of ${actual.constructor.name}`;
+ }
+ }
+ return msg;
+}
+var invalid_key_input_default = (actual, ...types) => {
+ return message("Key must be ", actual, ...types);
+};
+function withAlg(alg, actual, ...types) {
+ return message(`Key for the ${alg} algorithm must be `, actual, ...types);
+}
+
+// dist/webapi/lib/is_key_like.js
+function assertCryptoKey(key) {
+ if (!isCryptoKey(key)) {
+ throw new Error("CryptoKey instance expected");
+ }
+}
+function isCryptoKey(key) {
+ return key?.[Symbol.toStringTag] === "CryptoKey";
+}
+function isKeyObject(key) {
+ return key?.[Symbol.toStringTag] === "KeyObject";
+}
+var is_key_like_default = (key) => {
+ return isCryptoKey(key) || isKeyObject(key);
+};
+
+// dist/webapi/lib/decrypt.js
+var timingSafeEqual = globalThis.process?.getBuiltinModule?.("node:crypto")?.timingSafeEqual;
+timingSafeEqual ||= (a, b) => {
+ if (!(a instanceof Uint8Array)) {
+ throw new TypeError("First argument must be a buffer");
+ }
+ if (!(b instanceof Uint8Array)) {
+ throw new TypeError("Second argument must be a buffer");
+ }
+ if (a.length !== b.length) {
+ throw new TypeError("Input buffers must have the same length");
+ }
+ const len = a.length;
+ let out = 0;
+ let i = -1;
+ while (++i < len) {
+ out |= a[i] ^ b[i];
+ }
+ return out === 0;
+};
+async function cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
+ if (!(cek instanceof Uint8Array)) {
+ throw new TypeError(invalid_key_input_default(cek, "Uint8Array"));
+ }
+ const keySize = parseInt(enc.slice(1, 4), 10);
+ const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"]);
+ const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
+ hash: `SHA-${keySize << 1}`,
+ name: "HMAC"
+ }, false, ["sign"]);
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
+ const expectedTag = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
+ let macCheckPassed;
+ try {
+ macCheckPassed = timingSafeEqual(tag2, expectedTag);
+ } catch {
+ }
+ if (!macCheckPassed) {
+ throw new JWEDecryptionFailed();
+ }
+ let plaintext;
+ try {
+ plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext));
+ } catch {
+ }
+ if (!plaintext) {
+ throw new JWEDecryptionFailed();
+ }
+ return plaintext;
+}
+async function gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
+ let encKey;
+ if (cek instanceof Uint8Array) {
+ encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]);
+ } else {
+ checkEncCryptoKey(cek, enc, "decrypt");
+ encKey = cek;
+ }
+ try {
+ return new Uint8Array(await crypto.subtle.decrypt({
+ additionalData: aad,
+ iv,
+ name: "AES-GCM",
+ tagLength: 128
+ }, encKey, concat(ciphertext, tag2)));
+ } catch {
+ throw new JWEDecryptionFailed();
+ }
+}
+var decrypt_default = async (enc, cek, ciphertext, iv, tag2, aad) => {
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
+ throw new TypeError(invalid_key_input_default(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
+ }
+ if (!iv) {
+ throw new JWEInvalid("JWE Initialization Vector missing");
+ }
+ if (!tag2) {
+ throw new JWEInvalid("JWE Authentication Tag missing");
+ }
+ check_iv_length_default(enc, iv);
+ switch (enc) {
+ case "A128CBC-HS256":
+ case "A192CBC-HS384":
+ case "A256CBC-HS512":
+ if (cek instanceof Uint8Array)
+ check_cek_length_default(cek, parseInt(enc.slice(-3), 10));
+ return cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad);
+ case "A128GCM":
+ case "A192GCM":
+ case "A256GCM":
+ if (cek instanceof Uint8Array)
+ check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10));
+ return gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad);
+ default:
+ throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
+ }
+};
+
+// dist/webapi/lib/is_disjoint.js
+var is_disjoint_default = (...headers) => {
+ const sources = headers.filter(Boolean);
+ if (sources.length === 0 || sources.length === 1) {
+ return true;
+ }
+ let acc;
+ for (const header of sources) {
+ const parameters = Object.keys(header);
+ if (!acc || acc.size === 0) {
+ acc = new Set(parameters);
+ continue;
+ }
+ for (const parameter of parameters) {
+ if (acc.has(parameter)) {
+ return false;
+ }
+ acc.add(parameter);
+ }
+ }
+ return true;
+};
+
+// dist/webapi/lib/is_object.js
+function isObjectLike(value) {
+ return typeof value === "object" && value !== null;
+}
+var is_object_default = (input) => {
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
+ return false;
+ }
+ if (Object.getPrototypeOf(input) === null) {
+ return true;
+ }
+ let proto = input;
+ while (Object.getPrototypeOf(proto) !== null) {
+ proto = Object.getPrototypeOf(proto);
+ }
+ return Object.getPrototypeOf(input) === proto;
+};
+
+// dist/webapi/lib/aeskw.js
+function checkKeySize(key, alg) {
+ if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {
+ throw new TypeError(`Invalid key size for alg: ${alg}`);
+ }
+}
+function getCryptoKey(key, alg, usage) {
+ if (key instanceof Uint8Array) {
+ return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]);
+ }
+ checkEncCryptoKey(key, alg, usage);
+ return key;
+}
+async function wrap(alg, key, cek) {
+ const cryptoKey = await getCryptoKey(key, alg, "wrapKey");
+ checkKeySize(cryptoKey, alg);
+ const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
+ return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW"));
+}
+async function unwrap(alg, key, encryptedKey) {
+ const cryptoKey = await getCryptoKey(key, alg, "unwrapKey");
+ checkKeySize(cryptoKey, alg);
+ const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
+ return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek));
+}
+
+// dist/webapi/lib/digest.js
+var digest_default = async (algorithm, data) => {
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
+};
+
+// dist/webapi/lib/ecdhes.js
+function lengthAndInput(input) {
+ return concat(uint32be(input.length), input);
+}
+async function concatKdf(secret, bits, value) {
+ const iterations = Math.ceil((bits >> 3) / 32);
+ const res = new Uint8Array(iterations * 32);
+ for (let iter = 0; iter < iterations; iter++) {
+ const buf = new Uint8Array(4 + secret.length + value.length);
+ buf.set(uint32be(iter + 1));
+ buf.set(secret, 4);
+ buf.set(value, 4 + secret.length);
+ res.set(await digest_default("sha256", buf), iter * 32);
+ }
+ return res.slice(0, bits >> 3);
+}
+async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
+ checkEncCryptoKey(publicKey, "ECDH");
+ checkEncCryptoKey(privateKey, "ECDH", "deriveBits");
+ const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength));
+ let length;
+ if (publicKey.algorithm.name === "X25519") {
+ length = 256;
+ } else {
+ length = Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3;
+ }
+ const sharedSecret = new Uint8Array(await crypto.subtle.deriveBits({
+ name: publicKey.algorithm.name,
+ public: publicKey
+ }, privateKey, length));
+ return concatKdf(sharedSecret, keyLength, value);
+}
+function allowed(key) {
+ switch (key.algorithm.namedCurve) {
+ case "P-256":
+ case "P-384":
+ case "P-521":
+ return true;
+ default:
+ return key.algorithm.name === "X25519";
+ }
+}
+
+// dist/webapi/lib/pbes2kw.js
+function getCryptoKey2(key, alg) {
+ if (key instanceof Uint8Array) {
+ return crypto.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]);
+ }
+ checkEncCryptoKey(key, alg, "deriveBits");
+ return key;
+}
+var concatSalt = (alg, p2sInput) => concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);
+async function deriveKey2(p2s, alg, p2c, key) {
+ if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
+ throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets");
+ }
+ const salt = concatSalt(alg, p2s);
+ const keylen = parseInt(alg.slice(13, 16), 10);
+ const subtleAlg = {
+ hash: `SHA-${alg.slice(8, 11)}`,
+ iterations: p2c,
+ name: "PBKDF2",
+ salt
+ };
+ const cryptoKey = await getCryptoKey2(key, alg);
+ return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
+}
+async function wrap2(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {
+ const derived = await deriveKey2(p2s, alg, p2c, key);
+ const encryptedKey = await wrap(alg.slice(-6), derived, cek);
+ return { encryptedKey, p2c, p2s: encode(p2s) };
+}
+async function unwrap2(alg, key, encryptedKey, p2c, p2s) {
+ const derived = await deriveKey2(p2s, alg, p2c, key);
+ return unwrap(alg.slice(-6), derived, encryptedKey);
+}
+
+// dist/webapi/lib/check_key_length.js
+var check_key_length_default = (alg, key) => {
+ if (alg.startsWith("RS") || alg.startsWith("PS")) {
+ const { modulusLength } = key.algorithm;
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
+ }
+ }
+};
+
+// dist/webapi/lib/rsaes.js
+var subtleAlgorithm = (alg) => {
+ switch (alg) {
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512":
+ return "RSA-OAEP";
+ default:
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+ }
+};
+async function encrypt(alg, key, cek) {
+ checkEncCryptoKey(key, alg, "encrypt");
+ check_key_length_default(alg, key);
+ return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));
+}
+async function decrypt(alg, key, encryptedKey) {
+ checkEncCryptoKey(key, alg, "decrypt");
+ check_key_length_default(alg, key);
+ return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));
+}
+
+// dist/webapi/lib/cek.js
+function bitLength2(alg) {
+ switch (alg) {
+ case "A128GCM":
+ return 128;
+ case "A192GCM":
+ return 192;
+ case "A256GCM":
+ case "A128CBC-HS256":
+ return 256;
+ case "A192CBC-HS384":
+ return 384;
+ case "A256CBC-HS512":
+ return 512;
+ default:
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
+ }
+}
+var cek_default = (alg) => crypto.getRandomValues(new Uint8Array(bitLength2(alg) >> 3));
+
+// dist/webapi/lib/asn1.js
+var formatPEM = (b64, descriptor) => {
+ const newlined = (b64.match(/.{1,64}/g) || []).join("\n");
+ return `-----BEGIN ${descriptor}-----
+${newlined}
+-----END ${descriptor}-----`;
+};
+var genericExport = async (keyType, keyFormat, key) => {
+ if (isKeyObject(key)) {
+ if (key.type !== keyType) {
+ throw new TypeError(`key is not a ${keyType} key`);
+ }
+ return key.export({ format: "pem", type: keyFormat });
+ }
+ if (!isCryptoKey(key)) {
+ throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject"));
+ }
+ if (!key.extractable) {
+ throw new TypeError("CryptoKey is not extractable");
+ }
+ if (key.type !== keyType) {
+ throw new TypeError(`key is not a ${keyType} key`);
+ }
+ return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
+};
+var toSPKI = (key) => {
+ return genericExport("public", "spki", key);
+};
+var toPKCS8 = (key) => {
+ return genericExport("private", "pkcs8", key);
+};
+var findOid = (keyData, oid, from = 0) => {
+ if (from === 0) {
+ oid.unshift(oid.length);
+ oid.unshift(6);
+ }
+ const i = keyData.indexOf(oid[0], from);
+ if (i === -1)
+ return false;
+ const sub = keyData.subarray(i, i + oid.length);
+ if (sub.length !== oid.length)
+ return false;
+ return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1);
+};
+var getNamedCurve2 = (keyData) => {
+ switch (true) {
+ case findOid(keyData, [42, 134, 72, 206, 61, 3, 1, 7]):
+ return "P-256";
+ case findOid(keyData, [43, 129, 4, 0, 34]):
+ return "P-384";
+ case findOid(keyData, [43, 129, 4, 0, 35]):
+ return "P-521";
+ default:
+ return void 0;
+ }
+};
+var genericImport = async (replace, keyFormat, pem, alg, options) => {
+ let algorithm;
+ let keyUsages;
+ const keyData = new Uint8Array(atob(pem.replace(replace, "")).split("").map((c) => c.charCodeAt(0)));
+ const isPublic = keyFormat === "spki";
+ switch (alg) {
+ case "PS256":
+ case "PS384":
+ case "PS512":
+ algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ case "RS256":
+ case "RS384":
+ case "RS512":
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512":
+ algorithm = {
+ name: "RSA-OAEP",
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`
+ };
+ keyUsages = isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"];
+ break;
+ case "ES256":
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ case "ES384":
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ case "ES512":
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW": {
+ const namedCurve = getNamedCurve2(keyData);
+ algorithm = namedCurve?.startsWith("P-") ? { name: "ECDH", namedCurve } : { name: "X25519" };
+ keyUsages = isPublic ? [] : ["deriveBits"];
+ break;
+ }
+ case "Ed25519":
+ case "EdDSA":
+ algorithm = { name: "Ed25519" };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
+ }
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);
+};
+var fromPKCS8 = (pem, alg, options) => {
+ return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "pkcs8", pem, alg, options);
+};
+var fromSPKI = (pem, alg, options) => {
+ return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", pem, alg, options);
+};
+function getElement(seq) {
+ const result = [];
+ let next = 0;
+ while (next < seq.length) {
+ const nextPart = parseElement(seq.subarray(next));
+ result.push(nextPart);
+ next += nextPart.byteLength;
+ }
+ return result;
+}
+function parseElement(bytes) {
+ let position = 0;
+ let tag2 = bytes[0] & 31;
+ position++;
+ if (tag2 === 31) {
+ tag2 = 0;
+ while (bytes[position] >= 128) {
+ tag2 = tag2 * 128 + bytes[position] - 128;
+ position++;
+ }
+ tag2 = tag2 * 128 + bytes[position] - 128;
+ position++;
+ }
+ let length = 0;
+ if (bytes[position] < 128) {
+ length = bytes[position];
+ position++;
+ } else if (length === 128) {
+ length = 0;
+ while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) {
+ if (length > bytes.byteLength) {
+ throw new TypeError("invalid indefinite form length");
+ }
+ length++;
+ }
+ const byteLength2 = position + length + 2;
+ return {
+ byteLength: byteLength2,
+ contents: bytes.subarray(position, position + length),
+ raw: bytes.subarray(0, byteLength2)
+ };
+ } else {
+ const numberOfDigits = bytes[position] & 127;
+ position++;
+ length = 0;
+ for (let i = 0; i < numberOfDigits; i++) {
+ length = length * 256 + bytes[position];
+ position++;
+ }
+ }
+ const byteLength = position + length;
+ return {
+ byteLength,
+ contents: bytes.subarray(position, byteLength),
+ raw: bytes.subarray(0, byteLength)
+ };
+}
+function spkiFromX509(buf) {
+ const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents);
+ return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 160 ? 6 : 5].raw);
+}
+var X509Certificate;
+function getSPKI(x509) {
+ if (X509Certificate ||= globalThis.process?.getBuiltinModule?.("node:crypto")?.X509Certificate) {
+ try {
+ return new X509Certificate(x509).publicKey.export({ format: "pem", type: "spki" });
+ } catch {
+ }
+ }
+ const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, "");
+ const raw = decodeBase64(pem);
+ return formatPEM(spkiFromX509(raw), "PUBLIC KEY");
+}
+var fromX509 = (pem, alg, options) => {
+ let spki;
+ try {
+ spki = getSPKI(pem);
+ } catch (cause) {
+ throw new TypeError("Failed to parse the X.509 certificate", { cause });
+ }
+ return fromSPKI(spki, alg, options);
+};
+
+// dist/webapi/lib/jwk_to_key.js
+function subtleMapping(jwk) {
+ let algorithm;
+ let keyUsages;
+ switch (jwk.kty) {
+ case "RSA": {
+ switch (jwk.alg) {
+ case "PS256":
+ case "PS384":
+ case "PS512":
+ algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "RS256":
+ case "RS384":
+ case "RS512":
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512":
+ algorithm = {
+ name: "RSA-OAEP",
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
+ };
+ keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ break;
+ }
+ case "EC": {
+ switch (jwk.alg) {
+ case "ES256":
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "ES384":
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "ES512":
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW":
+ algorithm = { name: "ECDH", namedCurve: jwk.crv };
+ keyUsages = jwk.d ? ["deriveBits"] : [];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ break;
+ }
+ case "OKP": {
+ switch (jwk.alg) {
+ case "Ed25519":
+ case "EdDSA":
+ algorithm = { name: "Ed25519" };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW":
+ algorithm = { name: jwk.crv };
+ keyUsages = jwk.d ? ["deriveBits"] : [];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ break;
+ }
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
+ }
+ return { algorithm, keyUsages };
+}
+var jwk_to_key_default = async (jwk) => {
+ if (!jwk.alg) {
+ throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
+ }
+ const { algorithm, keyUsages } = subtleMapping(jwk);
+ const keyData = { ...jwk };
+ delete keyData.alg;
+ delete keyData.use;
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d ? false : true), jwk.key_ops ?? keyUsages);
+};
+
+// dist/webapi/key/import.js
+async function importSPKI(spki, alg, options) {
+ if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) {
+ throw new TypeError('"spki" must be SPKI formatted string');
+ }
+ return fromSPKI(spki, alg, options);
+}
+async function importX509(x509, alg, options) {
+ if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) {
+ throw new TypeError('"x509" must be X.509 formatted string');
+ }
+ return fromX509(x509, alg, options);
+}
+async function importPKCS8(pkcs8, alg, options) {
+ if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
+ throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
+ }
+ return fromPKCS8(pkcs8, alg, options);
+}
+async function importJWK(jwk, alg, options) {
+ if (!is_object_default(jwk)) {
+ throw new TypeError("JWK must be an object");
+ }
+ let ext;
+ alg ??= jwk.alg;
+ ext ??= options?.extractable ?? jwk.ext;
+ switch (jwk.kty) {
+ case "oct":
+ if (typeof jwk.k !== "string" || !jwk.k) {
+ throw new TypeError('missing "k" (Key Value) Parameter value');
+ }
+ return decode(jwk.k);
+ case "RSA":
+ if ("oth" in jwk && jwk.oth !== void 0) {
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
+ }
+ case "EC":
+ case "OKP":
+ return jwk_to_key_default({ ...jwk, alg, ext });
+ default:
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
+ }
+}
+
+// dist/webapi/lib/encrypt.js
+async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
+ if (!(cek instanceof Uint8Array)) {
+ throw new TypeError(invalid_key_input_default(cek, "Uint8Array"));
+ }
+ const keySize = parseInt(enc.slice(1, 4), 10);
+ const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["encrypt"]);
+ const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
+ hash: `SHA-${keySize << 1}`,
+ name: "HMAC"
+ }, false, ["sign"]);
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
+ iv,
+ name: "AES-CBC"
+ }, encKey, plaintext));
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
+ const tag2 = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
+ return { ciphertext, tag: tag2, iv };
+}
+async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
+ let encKey;
+ if (cek instanceof Uint8Array) {
+ encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
+ } else {
+ checkEncCryptoKey(cek, enc, "encrypt");
+ encKey = cek;
+ }
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({
+ additionalData: aad,
+ iv,
+ name: "AES-GCM",
+ tagLength: 128
+ }, encKey, plaintext));
+ const tag2 = encrypted.slice(-16);
+ const ciphertext = encrypted.slice(0, -16);
+ return { ciphertext, tag: tag2, iv };
+}
+var encrypt_default = async (enc, plaintext, cek, iv, aad) => {
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
+ throw new TypeError(invalid_key_input_default(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
+ }
+ if (iv) {
+ check_iv_length_default(enc, iv);
+ } else {
+ iv = iv_default(enc);
+ }
+ switch (enc) {
+ case "A128CBC-HS256":
+ case "A192CBC-HS384":
+ case "A256CBC-HS512":
+ if (cek instanceof Uint8Array) {
+ check_cek_length_default(cek, parseInt(enc.slice(-3), 10));
+ }
+ return cbcEncrypt(enc, plaintext, cek, iv, aad);
+ case "A128GCM":
+ case "A192GCM":
+ case "A256GCM":
+ if (cek instanceof Uint8Array) {
+ check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10));
+ }
+ return gcmEncrypt(enc, plaintext, cek, iv, aad);
+ default:
+ throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
+ }
+};
+
+// dist/webapi/lib/aesgcmkw.js
+async function wrap3(alg, key, cek, iv) {
+ const jweAlgorithm = alg.slice(0, 7);
+ const wrapped = await encrypt_default(jweAlgorithm, cek, key, iv, new Uint8Array(0));
+ return {
+ encryptedKey: wrapped.ciphertext,
+ iv: encode(wrapped.iv),
+ tag: encode(wrapped.tag)
+ };
+}
+async function unwrap3(alg, key, encryptedKey, iv, tag2) {
+ const jweAlgorithm = alg.slice(0, 7);
+ return decrypt_default(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array(0));
+}
+
+// dist/webapi/lib/decrypt_key_management.js
+var decrypt_key_management_default = async (alg, key, encryptedKey, joseHeader, options) => {
+ switch (alg) {
+ case "dir": {
+ if (encryptedKey !== void 0)
+ throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
+ return key;
+ }
+ case "ECDH-ES":
+ if (encryptedKey !== void 0)
+ throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW": {
+ if (!is_object_default(joseHeader.epk))
+ throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
+ assertCryptoKey(key);
+ if (!allowed(key))
+ throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
+ const epk = await importJWK(joseHeader.epk, alg);
+ assertCryptoKey(epk);
+ let partyUInfo;
+ let partyVInfo;
+ if (joseHeader.apu !== void 0) {
+ if (typeof joseHeader.apu !== "string")
+ throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
+ try {
+ partyUInfo = decode(joseHeader.apu);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the apu");
+ }
+ }
+ if (joseHeader.apv !== void 0) {
+ if (typeof joseHeader.apv !== "string")
+ throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
+ try {
+ partyVInfo = decode(joseHeader.apv);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the apv");
+ }
+ }
+ const sharedSecret = await deriveKey(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? bitLength2(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
+ if (alg === "ECDH-ES")
+ return sharedSecret;
+ if (encryptedKey === void 0)
+ throw new JWEInvalid("JWE Encrypted Key missing");
+ return unwrap(alg.slice(-6), sharedSecret, encryptedKey);
+ }
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512": {
+ if (encryptedKey === void 0)
+ throw new JWEInvalid("JWE Encrypted Key missing");
+ assertCryptoKey(key);
+ return decrypt(alg, key, encryptedKey);
+ }
+ case "PBES2-HS256+A128KW":
+ case "PBES2-HS384+A192KW":
+ case "PBES2-HS512+A256KW": {
+ if (encryptedKey === void 0)
+ throw new JWEInvalid("JWE Encrypted Key missing");
+ if (typeof joseHeader.p2c !== "number")
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
+ const p2cLimit = options?.maxPBES2Count || 1e4;
+ if (joseHeader.p2c > p2cLimit)
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
+ if (typeof joseHeader.p2s !== "string")
+ throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
+ let p2s;
+ try {
+ p2s = decode(joseHeader.p2s);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the p2s");
+ }
+ return unwrap2(alg, key, encryptedKey, joseHeader.p2c, p2s);
+ }
+ case "A128KW":
+ case "A192KW":
+ case "A256KW": {
+ if (encryptedKey === void 0)
+ throw new JWEInvalid("JWE Encrypted Key missing");
+ return unwrap(alg, key, encryptedKey);
+ }
+ case "A128GCMKW":
+ case "A192GCMKW":
+ case "A256GCMKW": {
+ if (encryptedKey === void 0)
+ throw new JWEInvalid("JWE Encrypted Key missing");
+ if (typeof joseHeader.iv !== "string")
+ throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
+ if (typeof joseHeader.tag !== "string")
+ throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
+ let iv;
+ try {
+ iv = decode(joseHeader.iv);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the iv");
+ }
+ let tag2;
+ try {
+ tag2 = decode(joseHeader.tag);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the tag");
+ }
+ return unwrap3(alg, key, encryptedKey, iv, tag2);
+ }
+ default: {
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
+ }
+ }
+};
+
+// dist/webapi/lib/validate_crit.js
+var validate_crit_default = (Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) => {
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
+ }
+ if (!protectedHeader || protectedHeader.crit === void 0) {
+ return /* @__PURE__ */ new Set();
+ }
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
+ }
+ let recognized;
+ if (recognizedOption !== void 0) {
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
+ } else {
+ recognized = recognizedDefault;
+ }
+ for (const parameter of protectedHeader.crit) {
+ if (!recognized.has(parameter)) {
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
+ }
+ if (joseHeader[parameter] === void 0) {
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
+ }
+ if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
+ }
+ }
+ return new Set(protectedHeader.crit);
+};
+
+// dist/webapi/lib/validate_algorithms.js
+var validate_algorithms_default = (option, algorithms) => {
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
+ throw new TypeError(`"${option}" option must be an array of strings`);
+ }
+ if (!algorithms) {
+ return void 0;
+ }
+ return new Set(algorithms);
+};
+
+// dist/webapi/lib/is_jwk.js
+function isJWK(key) {
+ return is_object_default(key) && typeof key.kty === "string";
+}
+function isPrivateJWK(key) {
+ return key.kty !== "oct" && typeof key.d === "string";
+}
+function isPublicJWK(key) {
+ return key.kty !== "oct" && typeof key.d === "undefined";
+}
+function isSecretJWK(key) {
+ return key.kty === "oct" && typeof key.k === "string";
+}
+
+// dist/webapi/lib/normalize_key.js
+var cache;
+var handleJWK = async (key, jwk, alg, freeze = false) => {
+ cache ||= /* @__PURE__ */ new WeakMap();
+ let cached = cache.get(key);
+ if (cached?.[alg]) {
+ return cached[alg];
+ }
+ const cryptoKey = await jwk_to_key_default({ ...jwk, alg });
+ if (freeze)
+ Object.freeze(key);
+ if (!cached) {
+ cache.set(key, { [alg]: cryptoKey });
+ } else {
+ cached[alg] = cryptoKey;
+ }
+ return cryptoKey;
+};
+var handleKeyObject = (keyObject, alg) => {
+ cache ||= /* @__PURE__ */ new WeakMap();
+ let cached = cache.get(keyObject);
+ if (cached?.[alg]) {
+ return cached[alg];
+ }
+ const isPublic = keyObject.type === "public";
+ const extractable = isPublic ? true : false;
+ let cryptoKey;
+ if (keyObject.asymmetricKeyType === "x25519") {
+ switch (alg) {
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW":
+ break;
+ default:
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
+ }
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
+ }
+ if (keyObject.asymmetricKeyType === "ed25519") {
+ if (alg !== "EdDSA" && alg !== "Ed25519") {
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
+ }
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
+ isPublic ? "verify" : "sign"
+ ]);
+ }
+ if (keyObject.asymmetricKeyType === "rsa") {
+ let hash;
+ switch (alg) {
+ case "RSA-OAEP":
+ hash = "SHA-1";
+ break;
+ case "RS256":
+ case "PS256":
+ case "RSA-OAEP-256":
+ hash = "SHA-256";
+ break;
+ case "RS384":
+ case "PS384":
+ case "RSA-OAEP-384":
+ hash = "SHA-384";
+ break;
+ case "RS512":
+ case "PS512":
+ case "RSA-OAEP-512":
+ hash = "SHA-512";
+ break;
+ default:
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
+ }
+ if (alg.startsWith("RSA-OAEP")) {
+ return keyObject.toCryptoKey({
+ name: "RSA-OAEP",
+ hash
+ }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
+ }
+ cryptoKey = keyObject.toCryptoKey({
+ name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
+ hash
+ }, extractable, [isPublic ? "verify" : "sign"]);
+ }
+ if (keyObject.asymmetricKeyType === "ec") {
+ const nist = /* @__PURE__ */ new Map([
+ ["prime256v1", "P-256"],
+ ["secp384r1", "P-384"],
+ ["secp521r1", "P-521"]
+ ]);
+ const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
+ if (!namedCurve) {
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
+ }
+ if (alg === "ES256" && namedCurve === "P-256") {
+ cryptoKey = keyObject.toCryptoKey({
+ name: "ECDSA",
+ namedCurve
+ }, extractable, [isPublic ? "verify" : "sign"]);
+ }
+ if (alg === "ES384" && namedCurve === "P-384") {
+ cryptoKey = keyObject.toCryptoKey({
+ name: "ECDSA",
+ namedCurve
+ }, extractable, [isPublic ? "verify" : "sign"]);
+ }
+ if (alg === "ES512" && namedCurve === "P-521") {
+ cryptoKey = keyObject.toCryptoKey({
+ name: "ECDSA",
+ namedCurve
+ }, extractable, [isPublic ? "verify" : "sign"]);
+ }
+ if (alg.startsWith("ECDH-ES")) {
+ cryptoKey = keyObject.toCryptoKey({
+ name: "ECDH",
+ namedCurve
+ }, extractable, isPublic ? [] : ["deriveBits"]);
+ }
+ }
+ if (!cryptoKey) {
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
+ }
+ if (!cached) {
+ cache.set(keyObject, { [alg]: cryptoKey });
+ } else {
+ cached[alg] = cryptoKey;
+ }
+ return cryptoKey;
+};
+var normalize_key_default = async (key, alg) => {
+ if (key instanceof Uint8Array) {
+ return key;
+ }
+ if (isCryptoKey(key)) {
+ return key;
+ }
+ if (isKeyObject(key)) {
+ if (key.type === "secret") {
+ return key.export();
+ }
+ if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
+ try {
+ return handleKeyObject(key, alg);
+ } catch (err) {
+ if (err instanceof TypeError) {
+ throw err;
+ }
+ }
+ }
+ let jwk = key.export({ format: "jwk" });
+ return handleJWK(key, jwk, alg);
+ }
+ if (isJWK(key)) {
+ if (key.k) {
+ return decode(key.k);
+ }
+ return handleJWK(key, key, alg, true);
+ }
+ throw new Error("unreachable");
+};
+
+// dist/webapi/lib/check_key_type.js
+var tag = (key) => key?.[Symbol.toStringTag];
+var jwkMatchesOp = (alg, key, usage) => {
+ if (key.use !== void 0) {
+ let expected;
+ switch (usage) {
+ case "sign":
+ case "verify":
+ expected = "sig";
+ break;
+ case "encrypt":
+ case "decrypt":
+ expected = "enc";
+ break;
+ }
+ if (key.use !== expected) {
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
+ }
+ }
+ if (key.alg !== void 0 && key.alg !== alg) {
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
+ }
+ if (Array.isArray(key.key_ops)) {
+ let expectedKeyOp;
+ switch (true) {
+ case (usage === "sign" || usage === "verify"):
+ case alg === "dir":
+ case alg.includes("CBC-HS"):
+ expectedKeyOp = usage;
+ break;
+ case alg.startsWith("PBES2"):
+ expectedKeyOp = "deriveBits";
+ break;
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
+ if (!alg.includes("GCM") && alg.endsWith("KW")) {
+ expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
+ } else {
+ expectedKeyOp = usage;
+ }
+ break;
+ case (usage === "encrypt" && alg.startsWith("RSA")):
+ expectedKeyOp = "wrapKey";
+ break;
+ case usage === "decrypt":
+ expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
+ break;
+ }
+ if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
+ }
+ }
+ return true;
+};
+var symmetricTypeCheck = (alg, key, usage) => {
+ if (key instanceof Uint8Array)
+ return;
+ if (isJWK(key)) {
+ if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
+ return;
+ throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
+ }
+ if (!is_key_like_default(key)) {
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
+ }
+ if (key.type !== "secret") {
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
+ }
+};
+var asymmetricTypeCheck = (alg, key, usage) => {
+ if (isJWK(key)) {
+ switch (usage) {
+ case "decrypt":
+ case "sign":
+ if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
+ return;
+ throw new TypeError(`JSON Web Key for this operation be a private JWK`);
+ case "encrypt":
+ case "verify":
+ if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
+ return;
+ throw new TypeError(`JSON Web Key for this operation be a public JWK`);
+ }
+ }
+ if (!is_key_like_default(key)) {
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
+ }
+ if (key.type === "secret") {
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
+ }
+ if (key.type === "public") {
+ switch (usage) {
+ case "sign":
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
+ case "decrypt":
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
+ default:
+ break;
+ }
+ }
+ if (key.type === "private") {
+ switch (usage) {
+ case "verify":
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
+ case "encrypt":
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
+ default:
+ break;
+ }
+ }
+};
+var check_key_type_default = (alg, key, usage) => {
+ const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(alg) || /^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(alg);
+ if (symmetric) {
+ symmetricTypeCheck(alg, key, usage);
+ } else {
+ asymmetricTypeCheck(alg, key, usage);
+ }
+};
+
+// dist/webapi/jwe/flattened/decrypt.js
+async function flattenedDecrypt(jwe, key, options) {
+ if (!is_object_default(jwe)) {
+ throw new JWEInvalid("Flattened JWE must be an object");
+ }
+ if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) {
+ throw new JWEInvalid("JOSE Header missing");
+ }
+ if (jwe.iv !== void 0 && typeof jwe.iv !== "string") {
+ throw new JWEInvalid("JWE Initialization Vector incorrect type");
+ }
+ if (typeof jwe.ciphertext !== "string") {
+ throw new JWEInvalid("JWE Ciphertext missing or incorrect type");
+ }
+ if (jwe.tag !== void 0 && typeof jwe.tag !== "string") {
+ throw new JWEInvalid("JWE Authentication Tag incorrect type");
+ }
+ if (jwe.protected !== void 0 && typeof jwe.protected !== "string") {
+ throw new JWEInvalid("JWE Protected Header incorrect type");
+ }
+ if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") {
+ throw new JWEInvalid("JWE Encrypted Key incorrect type");
+ }
+ if (jwe.aad !== void 0 && typeof jwe.aad !== "string") {
+ throw new JWEInvalid("JWE AAD incorrect type");
+ }
+ if (jwe.header !== void 0 && !is_object_default(jwe.header)) {
+ throw new JWEInvalid("JWE Shared Unprotected Header incorrect type");
+ }
+ if (jwe.unprotected !== void 0 && !is_object_default(jwe.unprotected)) {
+ throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");
+ }
+ let parsedProt;
+ if (jwe.protected) {
+ try {
+ const protectedHeader2 = decode(jwe.protected);
+ parsedProt = JSON.parse(decoder.decode(protectedHeader2));
+ } catch {
+ throw new JWEInvalid("JWE Protected Header is invalid");
+ }
+ }
+ if (!is_disjoint_default(parsedProt, jwe.header, jwe.unprotected)) {
+ throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");
+ }
+ const joseHeader = {
+ ...parsedProt,
+ ...jwe.header,
+ ...jwe.unprotected
+ };
+ validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader);
+ if (joseHeader.zip !== void 0) {
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+ }
+ const { alg, enc } = joseHeader;
+ if (typeof alg !== "string" || !alg) {
+ throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header");
+ }
+ if (typeof enc !== "string" || !enc) {
+ throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");
+ }
+ const keyManagementAlgorithms = options && validate_algorithms_default("keyManagementAlgorithms", options.keyManagementAlgorithms);
+ const contentEncryptionAlgorithms = options && validate_algorithms_default("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms);
+ if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) {
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
+ }
+ if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
+ throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
+ }
+ let encryptedKey;
+ if (jwe.encrypted_key !== void 0) {
+ try {
+ encryptedKey = decode(jwe.encrypted_key);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the encrypted_key");
+ }
+ }
+ let resolvedKey = false;
+ if (typeof key === "function") {
+ key = await key(parsedProt, jwe);
+ resolvedKey = true;
+ }
+ check_key_type_default(alg === "dir" ? enc : alg, key, "decrypt");
+ const k = await normalize_key_default(key, alg);
+ let cek;
+ try {
+ cek = await decrypt_key_management_default(alg, k, encryptedKey, joseHeader, options);
+ } catch (err) {
+ if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
+ throw err;
+ }
+ cek = cek_default(enc);
+ }
+ let iv;
+ let tag2;
+ if (jwe.iv !== void 0) {
+ try {
+ iv = decode(jwe.iv);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the iv");
+ }
+ }
+ if (jwe.tag !== void 0) {
+ try {
+ tag2 = decode(jwe.tag);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the tag");
+ }
+ }
+ const protectedHeader = encoder.encode(jwe.protected ?? "");
+ let additionalData;
+ if (jwe.aad !== void 0) {
+ additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(jwe.aad));
+ } else {
+ additionalData = protectedHeader;
+ }
+ let ciphertext;
+ try {
+ ciphertext = decode(jwe.ciphertext);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the ciphertext");
+ }
+ const plaintext = await decrypt_default(enc, cek, ciphertext, iv, tag2, additionalData);
+ const result = { plaintext };
+ if (jwe.protected !== void 0) {
+ result.protectedHeader = parsedProt;
+ }
+ if (jwe.aad !== void 0) {
+ try {
+ result.additionalAuthenticatedData = decode(jwe.aad);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the aad");
+ }
+ }
+ if (jwe.unprotected !== void 0) {
+ result.sharedUnprotectedHeader = jwe.unprotected;
+ }
+ if (jwe.header !== void 0) {
+ result.unprotectedHeader = jwe.header;
+ }
+ if (resolvedKey) {
+ return { ...result, key: k };
+ }
+ return result;
+}
+
+// dist/webapi/jwe/compact/decrypt.js
+async function compactDecrypt(jwe, key, options) {
+ if (jwe instanceof Uint8Array) {
+ jwe = decoder.decode(jwe);
+ }
+ if (typeof jwe !== "string") {
+ throw new JWEInvalid("Compact JWE must be a string or Uint8Array");
+ }
+ const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag2, length } = jwe.split(".");
+ if (length !== 5) {
+ throw new JWEInvalid("Invalid Compact JWE");
+ }
+ const decrypted = await flattenedDecrypt({
+ ciphertext,
+ iv: iv || void 0,
+ protected: protectedHeader,
+ tag: tag2 || void 0,
+ encrypted_key: encryptedKey || void 0
+ }, key, options);
+ const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };
+ if (typeof key === "function") {
+ return { ...result, key: decrypted.key };
+ }
+ return result;
+}
+
+// dist/webapi/jwe/general/decrypt.js
+async function generalDecrypt(jwe, key, options) {
+ if (!is_object_default(jwe)) {
+ throw new JWEInvalid("General JWE must be an object");
+ }
+ if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(is_object_default)) {
+ throw new JWEInvalid("JWE Recipients missing or incorrect type");
+ }
+ if (!jwe.recipients.length) {
+ throw new JWEInvalid("JWE Recipients has no members");
+ }
+ for (const recipient of jwe.recipients) {
+ try {
+ return await flattenedDecrypt({
+ aad: jwe.aad,
+ ciphertext: jwe.ciphertext,
+ encrypted_key: recipient.encrypted_key,
+ header: recipient.header,
+ iv: jwe.iv,
+ protected: jwe.protected,
+ tag: jwe.tag,
+ unprotected: jwe.unprotected
+ }, key, options);
+ } catch {
+ }
+ }
+ throw new JWEDecryptionFailed();
+}
+
+// dist/webapi/lib/private_symbols.js
+var unprotected = Symbol();
+
+// dist/webapi/lib/key_to_jwk.js
+async function keyToJWK(key) {
+ if (isKeyObject(key)) {
+ if (key.type === "secret") {
+ key = key.export();
+ } else {
+ return key.export({ format: "jwk" });
+ }
+ }
+ if (key instanceof Uint8Array) {
+ return {
+ kty: "oct",
+ k: encode(key)
+ };
+ }
+ if (!isCryptoKey(key)) {
+ throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject", "Uint8Array"));
+ }
+ if (!key.extractable) {
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
+ }
+ const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key);
+ return jwk;
+}
+
+// dist/webapi/key/export.js
+async function exportSPKI(key) {
+ return toSPKI(key);
+}
+async function exportPKCS8(key) {
+ return toPKCS8(key);
+}
+async function exportJWK(key) {
+ return keyToJWK(key);
+}
+
+// dist/webapi/lib/encrypt_key_management.js
+var encrypt_key_management_default = async (alg, enc, key, providedCek, providedParameters = {}) => {
+ let encryptedKey;
+ let parameters;
+ let cek;
+ switch (alg) {
+ case "dir": {
+ cek = key;
+ break;
+ }
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW": {
+ assertCryptoKey(key);
+ if (!allowed(key)) {
+ throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
+ }
+ const { apu, apv } = providedParameters;
+ let ephemeralKey;
+ if (providedParameters.epk) {
+ ephemeralKey = await normalize_key_default(providedParameters.epk, alg);
+ } else {
+ ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey;
+ }
+ const { x, y, crv, kty } = await exportJWK(ephemeralKey);
+ const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? bitLength2(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
+ parameters = { epk: { x, crv, kty } };
+ if (kty === "EC")
+ parameters.epk.y = y;
+ if (apu)
+ parameters.apu = encode(apu);
+ if (apv)
+ parameters.apv = encode(apv);
+ if (alg === "ECDH-ES") {
+ cek = sharedSecret;
+ break;
+ }
+ cek = providedCek || cek_default(enc);
+ const kwAlg = alg.slice(-6);
+ encryptedKey = await wrap(kwAlg, sharedSecret, cek);
+ break;
+ }
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512": {
+ cek = providedCek || cek_default(enc);
+ assertCryptoKey(key);
+ encryptedKey = await encrypt(alg, key, cek);
+ break;
+ }
+ case "PBES2-HS256+A128KW":
+ case "PBES2-HS384+A192KW":
+ case "PBES2-HS512+A256KW": {
+ cek = providedCek || cek_default(enc);
+ const { p2c, p2s } = providedParameters;
+ ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, p2c, p2s));
+ break;
+ }
+ case "A128KW":
+ case "A192KW":
+ case "A256KW": {
+ cek = providedCek || cek_default(enc);
+ encryptedKey = await wrap(alg, key, cek);
+ break;
+ }
+ case "A128GCMKW":
+ case "A192GCMKW":
+ case "A256GCMKW": {
+ cek = providedCek || cek_default(enc);
+ const { iv } = providedParameters;
+ ({ encryptedKey, ...parameters } = await wrap3(alg, key, cek, iv));
+ break;
+ }
+ default: {
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
+ }
+ }
+ return { cek, encryptedKey, parameters };
+};
+
+// dist/webapi/jwe/flattened/encrypt.js
+var FlattenedEncrypt = class {
+ _plaintext;
+ _protectedHeader;
+ _sharedUnprotectedHeader;
+ _unprotectedHeader;
+ _aad;
+ _cek;
+ _iv;
+ _keyManagementParameters;
+ constructor(plaintext) {
+ if (!(plaintext instanceof Uint8Array)) {
+ throw new TypeError("plaintext must be an instance of Uint8Array");
+ }
+ this._plaintext = plaintext;
+ }
+ setKeyManagementParameters(parameters) {
+ if (this._keyManagementParameters) {
+ throw new TypeError("setKeyManagementParameters can only be called once");
+ }
+ this._keyManagementParameters = parameters;
+ return this;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError("setProtectedHeader can only be called once");
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setSharedUnprotectedHeader(sharedUnprotectedHeader) {
+ if (this._sharedUnprotectedHeader) {
+ throw new TypeError("setSharedUnprotectedHeader can only be called once");
+ }
+ this._sharedUnprotectedHeader = sharedUnprotectedHeader;
+ return this;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this._unprotectedHeader) {
+ throw new TypeError("setUnprotectedHeader can only be called once");
+ }
+ this._unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ setAdditionalAuthenticatedData(aad) {
+ this._aad = aad;
+ return this;
+ }
+ setContentEncryptionKey(cek) {
+ if (this._cek) {
+ throw new TypeError("setContentEncryptionKey can only be called once");
+ }
+ this._cek = cek;
+ return this;
+ }
+ setInitializationVector(iv) {
+ if (this._iv) {
+ throw new TypeError("setInitializationVector can only be called once");
+ }
+ this._iv = iv;
+ return this;
+ }
+ async encrypt(key, options) {
+ if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {
+ throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");
+ }
+ if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) {
+ throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
+ }
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...this._sharedUnprotectedHeader
+ };
+ validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this._protectedHeader, joseHeader);
+ if (joseHeader.zip !== void 0) {
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+ }
+ const { alg, enc } = joseHeader;
+ if (typeof alg !== "string" || !alg) {
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ if (typeof enc !== "string" || !enc) {
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
+ }
+ let encryptedKey;
+ if (this._cek && (alg === "dir" || alg === "ECDH-ES")) {
+ throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
+ }
+ check_key_type_default(alg === "dir" ? enc : alg, key, "encrypt");
+ let cek;
+ {
+ let parameters;
+ const k = await normalize_key_default(key, alg);
+ ({ cek, encryptedKey, parameters } = await encrypt_key_management_default(alg, enc, k, this._cek, this._keyManagementParameters));
+ if (parameters) {
+ if (options && unprotected in options) {
+ if (!this._unprotectedHeader) {
+ this.setUnprotectedHeader(parameters);
+ } else {
+ this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters };
+ }
+ } else if (!this._protectedHeader) {
+ this.setProtectedHeader(parameters);
+ } else {
+ this._protectedHeader = { ...this._protectedHeader, ...parameters };
+ }
+ }
+ }
+ let additionalData;
+ let protectedHeader;
+ let aadMember;
+ if (this._protectedHeader) {
+ protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader)));
+ } else {
+ protectedHeader = encoder.encode("");
+ }
+ if (this._aad) {
+ aadMember = encode(this._aad);
+ additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(aadMember));
+ } else {
+ additionalData = protectedHeader;
+ }
+ const { ciphertext, tag: tag2, iv } = await encrypt_default(enc, this._plaintext, cek, this._iv, additionalData);
+ const jwe = {
+ ciphertext: encode(ciphertext)
+ };
+ if (iv) {
+ jwe.iv = encode(iv);
+ }
+ if (tag2) {
+ jwe.tag = encode(tag2);
+ }
+ if (encryptedKey) {
+ jwe.encrypted_key = encode(encryptedKey);
+ }
+ if (aadMember) {
+ jwe.aad = aadMember;
+ }
+ if (this._protectedHeader) {
+ jwe.protected = decoder.decode(protectedHeader);
+ }
+ if (this._sharedUnprotectedHeader) {
+ jwe.unprotected = this._sharedUnprotectedHeader;
+ }
+ if (this._unprotectedHeader) {
+ jwe.header = this._unprotectedHeader;
+ }
+ return jwe;
+ }
+};
+
+// dist/webapi/jwe/general/encrypt.js
+var IndividualRecipient = class {
+ parent;
+ unprotectedHeader;
+ key;
+ options;
+ constructor(enc, key, options) {
+ this.parent = enc;
+ this.key = key;
+ this.options = options;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this.unprotectedHeader) {
+ throw new TypeError("setUnprotectedHeader can only be called once");
+ }
+ this.unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ addRecipient(...args) {
+ return this.parent.addRecipient(...args);
+ }
+ encrypt(...args) {
+ return this.parent.encrypt(...args);
+ }
+ done() {
+ return this.parent;
+ }
+};
+var GeneralEncrypt = class {
+ _plaintext;
+ _recipients = [];
+ _protectedHeader;
+ _unprotectedHeader;
+ _aad;
+ constructor(plaintext) {
+ this._plaintext = plaintext;
+ }
+ addRecipient(key, options) {
+ const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
+ this._recipients.push(recipient);
+ return recipient;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError("setProtectedHeader can only be called once");
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setSharedUnprotectedHeader(sharedUnprotectedHeader) {
+ if (this._unprotectedHeader) {
+ throw new TypeError("setSharedUnprotectedHeader can only be called once");
+ }
+ this._unprotectedHeader = sharedUnprotectedHeader;
+ return this;
+ }
+ setAdditionalAuthenticatedData(aad) {
+ this._aad = aad;
+ return this;
+ }
+ async encrypt() {
+ if (!this._recipients.length) {
+ throw new JWEInvalid("at least one recipient must be added");
+ }
+ if (this._recipients.length === 1) {
+ const [recipient] = this._recipients;
+ const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options });
+ const jwe2 = {
+ ciphertext: flattened.ciphertext,
+ iv: flattened.iv,
+ recipients: [{}],
+ tag: flattened.tag
+ };
+ if (flattened.aad)
+ jwe2.aad = flattened.aad;
+ if (flattened.protected)
+ jwe2.protected = flattened.protected;
+ if (flattened.unprotected)
+ jwe2.unprotected = flattened.unprotected;
+ if (flattened.encrypted_key)
+ jwe2.recipients[0].encrypted_key = flattened.encrypted_key;
+ if (flattened.header)
+ jwe2.recipients[0].header = flattened.header;
+ return jwe2;
+ }
+ let enc;
+ for (let i = 0; i < this._recipients.length; i++) {
+ const recipient = this._recipients[i];
+ if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) {
+ throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
+ }
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...recipient.unprotectedHeader
+ };
+ const { alg } = joseHeader;
+ if (typeof alg !== "string" || !alg) {
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ if (alg === "dir" || alg === "ECDH-ES") {
+ throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');
+ }
+ if (typeof joseHeader.enc !== "string" || !joseHeader.enc) {
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
+ }
+ if (!enc) {
+ enc = joseHeader.enc;
+ } else if (enc !== joseHeader.enc) {
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');
+ }
+ validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this._protectedHeader, joseHeader);
+ if (joseHeader.zip !== void 0) {
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+ }
+ }
+ const cek = cek_default(enc);
+ const jwe = {
+ ciphertext: "",
+ iv: "",
+ recipients: [],
+ tag: ""
+ };
+ for (let i = 0; i < this._recipients.length; i++) {
+ const recipient = this._recipients[i];
+ const target = {};
+ jwe.recipients.push(target);
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...recipient.unprotectedHeader
+ };
+ const p2c = joseHeader.alg.startsWith("PBES2") ? 2048 + i : void 0;
+ if (i === 0) {
+ const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(cek).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).setKeyManagementParameters({ p2c }).encrypt(recipient.key, {
+ ...recipient.options,
+ [unprotected]: true
+ });
+ jwe.ciphertext = flattened.ciphertext;
+ jwe.iv = flattened.iv;
+ jwe.tag = flattened.tag;
+ if (flattened.aad)
+ jwe.aad = flattened.aad;
+ if (flattened.protected)
+ jwe.protected = flattened.protected;
+ if (flattened.unprotected)
+ jwe.unprotected = flattened.unprotected;
+ target.encrypted_key = flattened.encrypted_key;
+ if (flattened.header)
+ target.header = flattened.header;
+ continue;
+ }
+ const alg = recipient.unprotectedHeader?.alg || this._protectedHeader?.alg || this._unprotectedHeader?.alg;
+ check_key_type_default(alg === "dir" ? enc : alg, recipient.key, "encrypt");
+ const k = await normalize_key_default(recipient.key, alg);
+ const { encryptedKey, parameters } = await encrypt_key_management_default(alg, enc, k, cek, { p2c });
+ target.encrypted_key = encode(encryptedKey);
+ if (recipient.unprotectedHeader || parameters)
+ target.header = { ...recipient.unprotectedHeader, ...parameters };
+ }
+ return jwe;
+ }
+};
+
+// dist/webapi/lib/subtle_dsa.js
+var subtle_dsa_default = (alg, algorithm) => {
+ const hash = `SHA-${alg.slice(-3)}`;
+ switch (alg) {
+ case "HS256":
+ case "HS384":
+ case "HS512":
+ return { hash, name: "HMAC" };
+ case "PS256":
+ case "PS384":
+ case "PS512":
+ return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
+ case "RS256":
+ case "RS384":
+ case "RS512":
+ return { hash, name: "RSASSA-PKCS1-v1_5" };
+ case "ES256":
+ case "ES384":
+ case "ES512":
+ return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
+ case "Ed25519":
+ case "EdDSA":
+ return { name: "Ed25519" };
+ default:
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+ }
+};
+
+// dist/webapi/lib/get_sign_verify_key.js
+var get_sign_verify_key_default = async (alg, key, usage) => {
+ if (key instanceof Uint8Array) {
+ if (!alg.startsWith("HS")) {
+ throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject", "JSON Web Key"));
+ }
+ return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
+ }
+ checkSigCryptoKey(key, alg, usage);
+ return key;
+};
+
+// dist/webapi/lib/verify.js
+var verify_default = async (alg, key, signature, data) => {
+ const cryptoKey = await get_sign_verify_key_default(alg, key, "verify");
+ check_key_length_default(alg, cryptoKey);
+ const algorithm = subtle_dsa_default(alg, cryptoKey.algorithm);
+ try {
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
+ } catch {
+ return false;
+ }
+};
+
+// dist/webapi/jws/flattened/verify.js
+async function flattenedVerify(jws, key, options) {
+ if (!is_object_default(jws)) {
+ throw new JWSInvalid("Flattened JWS must be an object");
+ }
+ if (jws.protected === void 0 && jws.header === void 0) {
+ throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
+ }
+ if (jws.protected !== void 0 && typeof jws.protected !== "string") {
+ throw new JWSInvalid("JWS Protected Header incorrect type");
+ }
+ if (jws.payload === void 0) {
+ throw new JWSInvalid("JWS Payload missing");
+ }
+ if (typeof jws.signature !== "string") {
+ throw new JWSInvalid("JWS Signature missing or incorrect type");
+ }
+ if (jws.header !== void 0 && !is_object_default(jws.header)) {
+ throw new JWSInvalid("JWS Unprotected Header incorrect type");
+ }
+ let parsedProt = {};
+ if (jws.protected) {
+ try {
+ const protectedHeader = decode(jws.protected);
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
+ } catch {
+ throw new JWSInvalid("JWS Protected Header is invalid");
+ }
+ }
+ if (!is_disjoint_default(parsedProt, jws.header)) {
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
+ }
+ const joseHeader = {
+ ...parsedProt,
+ ...jws.header
+ };
+ const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
+ let b64 = true;
+ if (extensions.has("b64")) {
+ b64 = parsedProt.b64;
+ if (typeof b64 !== "boolean") {
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
+ }
+ }
+ const { alg } = joseHeader;
+ if (typeof alg !== "string" || !alg) {
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ const algorithms = options && validate_algorithms_default("algorithms", options.algorithms);
+ if (algorithms && !algorithms.has(alg)) {
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
+ }
+ if (b64) {
+ if (typeof jws.payload !== "string") {
+ throw new JWSInvalid("JWS Payload must be a string");
+ }
+ } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
+ throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
+ }
+ let resolvedKey = false;
+ if (typeof key === "function") {
+ key = await key(parsedProt, jws);
+ resolvedKey = true;
+ }
+ check_key_type_default(alg, key, "verify");
+ const data = concat(encoder.encode(jws.protected ?? ""), encoder.encode("."), typeof jws.payload === "string" ? encoder.encode(jws.payload) : jws.payload);
+ let signature;
+ try {
+ signature = decode(jws.signature);
+ } catch {
+ throw new JWSInvalid("Failed to base64url decode the signature");
+ }
+ const k = await normalize_key_default(key, alg);
+ const verified = await verify_default(alg, k, signature, data);
+ if (!verified) {
+ throw new JWSSignatureVerificationFailed();
+ }
+ let payload;
+ if (b64) {
+ try {
+ payload = decode(jws.payload);
+ } catch {
+ throw new JWSInvalid("Failed to base64url decode the payload");
+ }
+ } else if (typeof jws.payload === "string") {
+ payload = encoder.encode(jws.payload);
+ } else {
+ payload = jws.payload;
+ }
+ const result = { payload };
+ if (jws.protected !== void 0) {
+ result.protectedHeader = parsedProt;
+ }
+ if (jws.header !== void 0) {
+ result.unprotectedHeader = jws.header;
+ }
+ if (resolvedKey) {
+ return { ...result, key: k };
+ }
+ return result;
+}
+
+// dist/webapi/jws/compact/verify.js
+async function compactVerify(jws, key, options) {
+ if (jws instanceof Uint8Array) {
+ jws = decoder.decode(jws);
+ }
+ if (typeof jws !== "string") {
+ throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
+ }
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
+ if (length !== 3) {
+ throw new JWSInvalid("Invalid Compact JWS");
+ }
+ const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
+ const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
+ if (typeof key === "function") {
+ return { ...result, key: verified.key };
+ }
+ return result;
+}
+
+// dist/webapi/jws/general/verify.js
+async function generalVerify(jws, key, options) {
+ if (!is_object_default(jws)) {
+ throw new JWSInvalid("General JWS must be an object");
+ }
+ if (!Array.isArray(jws.signatures) || !jws.signatures.every(is_object_default)) {
+ throw new JWSInvalid("JWS Signatures missing or incorrect type");
+ }
+ for (const signature of jws.signatures) {
+ try {
+ return await flattenedVerify({
+ header: signature.header,
+ payload: jws.payload,
+ protected: signature.protected,
+ signature: signature.signature
+ }, key, options);
+ } catch {
+ }
+ }
+ throw new JWSSignatureVerificationFailed();
+}
+
+// dist/webapi/lib/epoch.js
+var epoch_default = (date) => Math.floor(date.getTime() / 1e3);
+
+// dist/webapi/lib/secs.js
+var minute = 60;
+var hour = minute * 60;
+var day = hour * 24;
+var week = day * 7;
+var year = day * 365.25;
+var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
+var secs_default = (str) => {
+ const matched = REGEX.exec(str);
+ if (!matched || matched[4] && matched[1]) {
+ throw new TypeError("Invalid time period format");
+ }
+ const value = parseFloat(matched[2]);
+ const unit = matched[3].toLowerCase();
+ let numericDate;
+ switch (unit) {
+ case "sec":
+ case "secs":
+ case "second":
+ case "seconds":
+ case "s":
+ numericDate = Math.round(value);
+ break;
+ case "minute":
+ case "minutes":
+ case "min":
+ case "mins":
+ case "m":
+ numericDate = Math.round(value * minute);
+ break;
+ case "hour":
+ case "hours":
+ case "hr":
+ case "hrs":
+ case "h":
+ numericDate = Math.round(value * hour);
+ break;
+ case "day":
+ case "days":
+ case "d":
+ numericDate = Math.round(value * day);
+ break;
+ case "week":
+ case "weeks":
+ case "w":
+ numericDate = Math.round(value * week);
+ break;
+ default:
+ numericDate = Math.round(value * year);
+ break;
+ }
+ if (matched[1] === "-" || matched[4] === "ago") {
+ return -numericDate;
+ }
+ return numericDate;
+};
+
+// dist/webapi/lib/jwt_claims_set.js
+var normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, "");
+var checkAudiencePresence = (audPayload, audOption) => {
+ if (typeof audPayload === "string") {
+ return audOption.includes(audPayload);
+ }
+ if (Array.isArray(audPayload)) {
+ return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
+ }
+ return false;
+};
+var jwt_claims_set_default = (protectedHeader, encodedPayload, options = {}) => {
+ let payload;
+ try {
+ payload = JSON.parse(decoder.decode(encodedPayload));
+ } catch {
+ }
+ if (!is_object_default(payload)) {
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
+ }
+ const { typ } = options;
+ if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
+ throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
+ }
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
+ const presenceCheck = [...requiredClaims];
+ if (maxTokenAge !== void 0)
+ presenceCheck.push("iat");
+ if (audience !== void 0)
+ presenceCheck.push("aud");
+ if (subject !== void 0)
+ presenceCheck.push("sub");
+ if (issuer !== void 0)
+ presenceCheck.push("iss");
+ for (const claim of new Set(presenceCheck.reverse())) {
+ if (!(claim in payload)) {
+ throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
+ }
+ }
+ if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
+ throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
+ }
+ if (subject && payload.sub !== subject) {
+ throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
+ }
+ if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
+ throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
+ }
+ let tolerance;
+ switch (typeof options.clockTolerance) {
+ case "string":
+ tolerance = secs_default(options.clockTolerance);
+ break;
+ case "number":
+ tolerance = options.clockTolerance;
+ break;
+ case "undefined":
+ tolerance = 0;
+ break;
+ default:
+ throw new TypeError("Invalid clockTolerance option type");
+ }
+ const { currentDate } = options;
+ const now = epoch_default(currentDate || /* @__PURE__ */ new Date());
+ if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
+ throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
+ }
+ if (payload.nbf !== void 0) {
+ if (typeof payload.nbf !== "number") {
+ throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
+ }
+ if (payload.nbf > now + tolerance) {
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
+ }
+ }
+ if (payload.exp !== void 0) {
+ if (typeof payload.exp !== "number") {
+ throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
+ }
+ if (payload.exp <= now - tolerance) {
+ throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
+ }
+ }
+ if (maxTokenAge) {
+ const age = now - payload.iat;
+ const max = typeof maxTokenAge === "number" ? maxTokenAge : secs_default(maxTokenAge);
+ if (age - tolerance > max) {
+ throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
+ }
+ if (age < 0 - tolerance) {
+ throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
+ }
+ }
+ return payload;
+};
+
+// dist/webapi/jwt/verify.js
+async function jwtVerify(jwt, key, options) {
+ const verified = await compactVerify(jwt, key, options);
+ if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
+ }
+ const payload = jwt_claims_set_default(verified.protectedHeader, verified.payload, options);
+ const result = { payload, protectedHeader: verified.protectedHeader };
+ if (typeof key === "function") {
+ return { ...result, key: verified.key };
+ }
+ return result;
+}
+
+// dist/webapi/jwt/decrypt.js
+async function jwtDecrypt(jwt, key, options) {
+ const decrypted = await compactDecrypt(jwt, key, options);
+ const payload = jwt_claims_set_default(decrypted.protectedHeader, decrypted.plaintext, options);
+ const { protectedHeader } = decrypted;
+ if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) {
+ throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch");
+ }
+ if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) {
+ throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch");
+ }
+ if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
+ throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch");
+ }
+ const result = { payload, protectedHeader };
+ if (typeof key === "function") {
+ return { ...result, key: decrypted.key };
+ }
+ return result;
+}
+
+// dist/webapi/jwe/compact/encrypt.js
+var CompactEncrypt = class {
+ _flattened;
+ constructor(plaintext) {
+ this._flattened = new FlattenedEncrypt(plaintext);
+ }
+ setContentEncryptionKey(cek) {
+ this._flattened.setContentEncryptionKey(cek);
+ return this;
+ }
+ setInitializationVector(iv) {
+ this._flattened.setInitializationVector(iv);
+ return this;
+ }
+ setProtectedHeader(protectedHeader) {
+ this._flattened.setProtectedHeader(protectedHeader);
+ return this;
+ }
+ setKeyManagementParameters(parameters) {
+ this._flattened.setKeyManagementParameters(parameters);
+ return this;
+ }
+ async encrypt(key, options) {
+ const jwe = await this._flattened.encrypt(key, options);
+ return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join(".");
+ }
+};
+
+// dist/webapi/lib/sign.js
+var sign_default = async (alg, key, data) => {
+ const cryptoKey = await get_sign_verify_key_default(alg, key, "sign");
+ check_key_length_default(alg, cryptoKey);
+ const signature = await crypto.subtle.sign(subtle_dsa_default(alg, cryptoKey.algorithm), cryptoKey, data);
+ return new Uint8Array(signature);
+};
+
+// dist/webapi/jws/flattened/sign.js
+var FlattenedSign = class {
+ _payload;
+ _protectedHeader;
+ _unprotectedHeader;
+ constructor(payload) {
+ if (!(payload instanceof Uint8Array)) {
+ throw new TypeError("payload must be an instance of Uint8Array");
+ }
+ this._payload = payload;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError("setProtectedHeader can only be called once");
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this._unprotectedHeader) {
+ throw new TypeError("setUnprotectedHeader can only be called once");
+ }
+ this._unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ async sign(key, options) {
+ if (!this._protectedHeader && !this._unprotectedHeader) {
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
+ }
+ if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader)) {
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
+ }
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader
+ };
+ const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this._protectedHeader, joseHeader);
+ let b64 = true;
+ if (extensions.has("b64")) {
+ b64 = this._protectedHeader.b64;
+ if (typeof b64 !== "boolean") {
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
+ }
+ }
+ const { alg } = joseHeader;
+ if (typeof alg !== "string" || !alg) {
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ check_key_type_default(alg, key, "sign");
+ let payload = this._payload;
+ if (b64) {
+ payload = encoder.encode(encode(payload));
+ }
+ let protectedHeader;
+ if (this._protectedHeader) {
+ protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader)));
+ } else {
+ protectedHeader = encoder.encode("");
+ }
+ const data = concat(protectedHeader, encoder.encode("."), payload);
+ const k = await normalize_key_default(key, alg);
+ const signature = await sign_default(alg, k, data);
+ const jws = {
+ signature: encode(signature),
+ payload: ""
+ };
+ if (b64) {
+ jws.payload = decoder.decode(payload);
+ }
+ if (this._unprotectedHeader) {
+ jws.header = this._unprotectedHeader;
+ }
+ if (this._protectedHeader) {
+ jws.protected = decoder.decode(protectedHeader);
+ }
+ return jws;
+ }
+};
+
+// dist/webapi/jws/compact/sign.js
+var CompactSign = class {
+ _flattened;
+ constructor(payload) {
+ this._flattened = new FlattenedSign(payload);
+ }
+ setProtectedHeader(protectedHeader) {
+ this._flattened.setProtectedHeader(protectedHeader);
+ return this;
+ }
+ async sign(key, options) {
+ const jws = await this._flattened.sign(key, options);
+ if (jws.payload === void 0) {
+ throw new TypeError("use the flattened module for creating JWS with b64: false");
+ }
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
+ }
+};
+
+// dist/webapi/jws/general/sign.js
+var IndividualSignature = class {
+ parent;
+ protectedHeader;
+ unprotectedHeader;
+ options;
+ key;
+ constructor(sig, key, options) {
+ this.parent = sig;
+ this.key = key;
+ this.options = options;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this.protectedHeader) {
+ throw new TypeError("setProtectedHeader can only be called once");
+ }
+ this.protectedHeader = protectedHeader;
+ return this;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this.unprotectedHeader) {
+ throw new TypeError("setUnprotectedHeader can only be called once");
+ }
+ this.unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ addSignature(...args) {
+ return this.parent.addSignature(...args);
+ }
+ sign(...args) {
+ return this.parent.sign(...args);
+ }
+ done() {
+ return this.parent;
+ }
+};
+var GeneralSign = class {
+ _payload;
+ _signatures = [];
+ constructor(payload) {
+ this._payload = payload;
+ }
+ addSignature(key, options) {
+ const signature = new IndividualSignature(this, key, options);
+ this._signatures.push(signature);
+ return signature;
+ }
+ async sign() {
+ if (!this._signatures.length) {
+ throw new JWSInvalid("at least one signature must be added");
+ }
+ const jws = {
+ signatures: [],
+ payload: ""
+ };
+ for (let i = 0; i < this._signatures.length; i++) {
+ const signature = this._signatures[i];
+ const flattened = new FlattenedSign(this._payload);
+ flattened.setProtectedHeader(signature.protectedHeader);
+ flattened.setUnprotectedHeader(signature.unprotectedHeader);
+ const { payload, ...rest } = await flattened.sign(signature.key, signature.options);
+ if (i === 0) {
+ jws.payload = payload;
+ } else if (jws.payload !== payload) {
+ throw new JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");
+ }
+ jws.signatures.push(rest);
+ }
+ return jws;
+ }
+};
+
+// dist/webapi/jwt/produce.js
+function validateInput(label, input) {
+ if (!Number.isFinite(input)) {
+ throw new TypeError(`Invalid ${label} input`);
+ }
+ return input;
+}
+var ProduceJWT = class {
+ _payload;
+ constructor(payload = {}) {
+ if (!is_object_default(payload)) {
+ throw new TypeError("JWT Claims Set MUST be an object");
+ }
+ this._payload = payload;
+ }
+ setIssuer(issuer) {
+ this._payload = { ...this._payload, iss: issuer };
+ return this;
+ }
+ setSubject(subject) {
+ this._payload = { ...this._payload, sub: subject };
+ return this;
+ }
+ setAudience(audience) {
+ this._payload = { ...this._payload, aud: audience };
+ return this;
+ }
+ setJti(jwtId) {
+ this._payload = { ...this._payload, jti: jwtId };
+ return this;
+ }
+ setNotBefore(input) {
+ if (typeof input === "number") {
+ this._payload = { ...this._payload, nbf: validateInput("setNotBefore", input) };
+ } else if (input instanceof Date) {
+ this._payload = { ...this._payload, nbf: validateInput("setNotBefore", epoch_default(input)) };
+ } else {
+ this._payload = { ...this._payload, nbf: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) };
+ }
+ return this;
+ }
+ setExpirationTime(input) {
+ if (typeof input === "number") {
+ this._payload = { ...this._payload, exp: validateInput("setExpirationTime", input) };
+ } else if (input instanceof Date) {
+ this._payload = { ...this._payload, exp: validateInput("setExpirationTime", epoch_default(input)) };
+ } else {
+ this._payload = { ...this._payload, exp: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) };
+ }
+ return this;
+ }
+ setIssuedAt(input) {
+ if (typeof input === "undefined") {
+ this._payload = { ...this._payload, iat: epoch_default(/* @__PURE__ */ new Date()) };
+ } else if (input instanceof Date) {
+ this._payload = { ...this._payload, iat: validateInput("setIssuedAt", epoch_default(input)) };
+ } else if (typeof input === "string") {
+ this._payload = {
+ ...this._payload,
+ iat: validateInput("setIssuedAt", epoch_default(/* @__PURE__ */ new Date()) + secs_default(input))
+ };
+ } else {
+ this._payload = { ...this._payload, iat: validateInput("setIssuedAt", input) };
+ }
+ return this;
+ }
+};
+
+// dist/webapi/jwt/sign.js
+var SignJWT = class extends ProduceJWT {
+ _protectedHeader;
+ setProtectedHeader(protectedHeader) {
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ async sign(key, options) {
+ const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)));
+ sig.setProtectedHeader(this._protectedHeader);
+ if (Array.isArray(this._protectedHeader?.crit) && this._protectedHeader.crit.includes("b64") && this._protectedHeader.b64 === false) {
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
+ }
+ return sig.sign(key, options);
+ }
+};
+
+// dist/webapi/jwt/encrypt.js
+var EncryptJWT = class extends ProduceJWT {
+ _cek;
+ _iv;
+ _keyManagementParameters;
+ _protectedHeader;
+ _replicateIssuerAsHeader;
+ _replicateSubjectAsHeader;
+ _replicateAudienceAsHeader;
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError("setProtectedHeader can only be called once");
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setKeyManagementParameters(parameters) {
+ if (this._keyManagementParameters) {
+ throw new TypeError("setKeyManagementParameters can only be called once");
+ }
+ this._keyManagementParameters = parameters;
+ return this;
+ }
+ setContentEncryptionKey(cek) {
+ if (this._cek) {
+ throw new TypeError("setContentEncryptionKey can only be called once");
+ }
+ this._cek = cek;
+ return this;
+ }
+ setInitializationVector(iv) {
+ if (this._iv) {
+ throw new TypeError("setInitializationVector can only be called once");
+ }
+ this._iv = iv;
+ return this;
+ }
+ replicateIssuerAsHeader() {
+ this._replicateIssuerAsHeader = true;
+ return this;
+ }
+ replicateSubjectAsHeader() {
+ this._replicateSubjectAsHeader = true;
+ return this;
+ }
+ replicateAudienceAsHeader() {
+ this._replicateAudienceAsHeader = true;
+ return this;
+ }
+ async encrypt(key, options) {
+ const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload)));
+ if (this._replicateIssuerAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss };
+ }
+ if (this._replicateSubjectAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub };
+ }
+ if (this._replicateAudienceAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud };
+ }
+ enc.setProtectedHeader(this._protectedHeader);
+ if (this._iv) {
+ enc.setInitializationVector(this._iv);
+ }
+ if (this._cek) {
+ enc.setContentEncryptionKey(this._cek);
+ }
+ if (this._keyManagementParameters) {
+ enc.setKeyManagementParameters(this._keyManagementParameters);
+ }
+ return enc.encrypt(key, options);
+ }
+};
+
+// dist/webapi/jwk/thumbprint.js
+var check = (value, description) => {
+ if (typeof value !== "string" || !value) {
+ throw new JWKInvalid(`${description} missing or invalid`);
+ }
+};
+async function calculateJwkThumbprint(key, digestAlgorithm) {
+ let jwk;
+ if (isJWK(key)) {
+ jwk = key;
+ } else if (is_key_like_default(key)) {
+ jwk = await exportJWK(key);
+ } else {
+ throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject", "JSON Web Key"));
+ }
+ digestAlgorithm ??= "sha256";
+ if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") {
+ throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
+ }
+ let components;
+ switch (jwk.kty) {
+ case "EC":
+ check(jwk.crv, '"crv" (Curve) Parameter');
+ check(jwk.x, '"x" (X Coordinate) Parameter');
+ check(jwk.y, '"y" (Y Coordinate) Parameter');
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
+ break;
+ case "OKP":
+ check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
+ check(jwk.x, '"x" (Public Key) Parameter');
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
+ break;
+ case "RSA":
+ check(jwk.e, '"e" (Exponent) Parameter');
+ check(jwk.n, '"n" (Modulus) Parameter');
+ components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
+ break;
+ case "oct":
+ check(jwk.k, '"k" (Key Value) Parameter');
+ components = { k: jwk.k, kty: jwk.kty };
+ break;
+ default:
+ throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
+ }
+ const data = encoder.encode(JSON.stringify(components));
+ return encode(await digest_default(digestAlgorithm, data));
+}
+async function calculateJwkThumbprintUri(key, digestAlgorithm) {
+ digestAlgorithm ??= "sha256";
+ const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm);
+ return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
+}
+
+// dist/webapi/jwk/embedded.js
+async function EmbeddedJWK(protectedHeader, token) {
+ const joseHeader = {
+ ...protectedHeader,
+ ...token?.header
+ };
+ if (!is_object_default(joseHeader.jwk)) {
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');
+ }
+ const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
+ if (key instanceof Uint8Array || key.type !== "public") {
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');
+ }
+ return key;
+}
+
+// dist/webapi/jwks/local.js
+function getKtyFromAlg(alg) {
+ switch (typeof alg === "string" && alg.slice(0, 2)) {
+ case "RS":
+ case "PS":
+ return "RSA";
+ case "ES":
+ return "EC";
+ case "Ed":
+ return "OKP";
+ default:
+ throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
+ }
+}
+function isJWKSLike(jwks) {
+ return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
+}
+function isJWKLike(key) {
+ return is_object_default(key);
+}
+function clone(obj) {
+ if (typeof structuredClone === "function") {
+ return structuredClone(obj);
+ }
+ return JSON.parse(JSON.stringify(obj));
+}
+var LocalJWKSet = class {
+ _jwks;
+ _cached = /* @__PURE__ */ new WeakMap();
+ constructor(jwks) {
+ if (!isJWKSLike(jwks)) {
+ throw new JWKSInvalid("JSON Web Key Set malformed");
+ }
+ this._jwks = clone(jwks);
+ }
+ async getKey(protectedHeader, token) {
+ const { alg, kid } = { ...protectedHeader, ...token?.header };
+ const kty = getKtyFromAlg(alg);
+ const candidates = this._jwks.keys.filter((jwk2) => {
+ let candidate = kty === jwk2.kty;
+ if (candidate && typeof kid === "string") {
+ candidate = kid === jwk2.kid;
+ }
+ if (candidate && typeof jwk2.alg === "string") {
+ candidate = alg === jwk2.alg;
+ }
+ if (candidate && typeof jwk2.use === "string") {
+ candidate = jwk2.use === "sig";
+ }
+ if (candidate && Array.isArray(jwk2.key_ops)) {
+ candidate = jwk2.key_ops.includes("verify");
+ }
+ if (candidate) {
+ switch (alg) {
+ case "ES256":
+ candidate = jwk2.crv === "P-256";
+ break;
+ case "ES384":
+ candidate = jwk2.crv === "P-384";
+ break;
+ case "ES512":
+ candidate = jwk2.crv === "P-521";
+ break;
+ case "Ed25519":
+ case "EdDSA":
+ candidate = jwk2.crv === "Ed25519";
+ break;
+ }
+ }
+ return candidate;
+ });
+ const { 0: jwk, length } = candidates;
+ if (length === 0) {
+ throw new JWKSNoMatchingKey();
+ }
+ if (length !== 1) {
+ const error = new JWKSMultipleMatchingKeys();
+ const { _cached } = this;
+ error[Symbol.asyncIterator] = async function* () {
+ for (const jwk2 of candidates) {
+ try {
+ yield await importWithAlgCache(_cached, jwk2, alg);
+ } catch {
+ }
+ }
+ };
+ throw error;
+ }
+ return importWithAlgCache(this._cached, jwk, alg);
+ }
+};
+async function importWithAlgCache(cache2, jwk, alg) {
+ const cached = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk);
+ if (cached[alg] === void 0) {
+ const key = await importJWK({ ...jwk, ext: true }, alg);
+ if (key instanceof Uint8Array || key.type !== "public") {
+ throw new JWKSInvalid("JSON Web Key Set members must be public keys");
+ }
+ cached[alg] = key;
+ }
+ return cached[alg];
+}
+function createLocalJWKSet(jwks) {
+ const set = new LocalJWKSet(jwks);
+ const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
+ Object.defineProperties(localJWKSet, {
+ jwks: {
+ value: () => clone(set._jwks),
+ enumerable: true,
+ configurable: false,
+ writable: false
+ }
+ });
+ return localJWKSet;
+}
+
+// dist/webapi/jwks/remote.js
+function isCloudflareWorkers() {
+ return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
+}
+var USER_AGENT;
+if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
+ const NAME = "jose";
+ const VERSION = "v6.0.1";
+ USER_AGENT = `${NAME}/${VERSION}`;
+}
+var customFetch = Symbol();
+async function fetchJwks(url, options) {
+ const response = await (options?.[customFetch] || fetch)(url, {
+ method: "GET",
+ signal: options.signal,
+ redirect: "manual",
+ headers: options.headers
+ }).catch((err) => {
+ if (err.name === "TimeoutError") {
+ throw new JWKSTimeout();
+ }
+ throw err;
+ });
+ if (response.status !== 200) {
+ throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
+ }
+ try {
+ return await response.json();
+ } catch {
+ throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
+ }
+}
+var jwksCache = Symbol();
+function isFreshJwksCache(input, cacheMaxAge) {
+ if (typeof input !== "object" || input === null) {
+ return false;
+ }
+ if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) {
+ return false;
+ }
+ if (!("jwks" in input) || !is_object_default(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, is_object_default)) {
+ return false;
+ }
+ return true;
+}
+var RemoteJWKSet = class {
+ _url;
+ _timeoutDuration;
+ _cooldownDuration;
+ _cacheMaxAge;
+ _jwksTimestamp;
+ _pendingFetch;
+ _options;
+ _local;
+ _cache;
+ constructor(url, options) {
+ if (!(url instanceof URL)) {
+ throw new TypeError("url must be an instance of URL");
+ }
+ this._url = new URL(url.href);
+ this._options = { headers: options?.headers };
+ this._timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3;
+ this._cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4;
+ this._cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5;
+ if (options?.[jwksCache] !== void 0) {
+ this._cache = options?.[jwksCache];
+ if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) {
+ this._jwksTimestamp = this._cache.uat;
+ this._local = createLocalJWKSet(this._cache.jwks);
+ }
+ }
+ }
+ coolingDown() {
+ return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false;
+ }
+ fresh() {
+ return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false;
+ }
+ async getKey(protectedHeader, token) {
+ if (!this._local || !this.fresh()) {
+ await this.reload();
+ }
+ try {
+ return await this._local(protectedHeader, token);
+ } catch (err) {
+ if (err instanceof JWKSNoMatchingKey) {
+ if (this.coolingDown() === false) {
+ await this.reload();
+ return this._local(protectedHeader, token);
+ }
+ }
+ throw err;
+ }
+ }
+ async reload() {
+ if (this._pendingFetch && isCloudflareWorkers()) {
+ this._pendingFetch = void 0;
+ }
+ const headers = new Headers(this._options.headers);
+ if (USER_AGENT && !headers.has("User-Agent")) {
+ headers.set("User-Agent", USER_AGENT);
+ this._options.headers = Object.fromEntries(headers.entries());
+ }
+ if (!headers.has("accept")) {
+ headers.set("accept", "application/json");
+ headers.append("accept", "application/jwk-set+json");
+ }
+ this._pendingFetch ||= fetchJwks(this._url.href, {
+ headers,
+ signal: AbortSignal.timeout(this._timeoutDuration)
+ }).then((json) => {
+ this._local = createLocalJWKSet(json);
+ if (this._cache) {
+ this._cache.uat = Date.now();
+ this._cache.jwks = json;
+ }
+ this._jwksTimestamp = Date.now();
+ this._pendingFetch = void 0;
+ }).catch((err) => {
+ this._pendingFetch = void 0;
+ throw err;
+ });
+ await this._pendingFetch;
+ }
+};
+function createRemoteJWKSet(url, options) {
+ const set = new RemoteJWKSet(url, options);
+ const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
+ Object.defineProperties(remoteJWKSet, {
+ coolingDown: {
+ get: () => set.coolingDown(),
+ enumerable: true,
+ configurable: false
+ },
+ fresh: {
+ get: () => set.fresh(),
+ enumerable: true,
+ configurable: false
+ },
+ reload: {
+ value: () => set.reload(),
+ enumerable: true,
+ configurable: false,
+ writable: false
+ },
+ reloading: {
+ get: () => !!set._pendingFetch,
+ enumerable: true,
+ configurable: false
+ },
+ jwks: {
+ value: () => set._local?.jwks(),
+ enumerable: true,
+ configurable: false,
+ writable: false
+ }
+ });
+ return remoteJWKSet;
+}
+
+// dist/webapi/jwt/unsecured.js
+var UnsecuredJWT = class extends ProduceJWT {
+ encode() {
+ const header = encode(JSON.stringify({ alg: "none" }));
+ const payload = encode(JSON.stringify(this._payload));
+ return `${header}.${payload}.`;
+ }
+ static decode(jwt, options) {
+ if (typeof jwt !== "string") {
+ throw new JWTInvalid("Unsecured JWT must be a string");
+ }
+ const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split(".");
+ if (length !== 3 || signature !== "") {
+ throw new JWTInvalid("Invalid Unsecured JWT");
+ }
+ let header;
+ try {
+ header = JSON.parse(decoder.decode(decode(encodedHeader)));
+ if (header.alg !== "none")
+ throw new Error();
+ } catch {
+ throw new JWTInvalid("Invalid Unsecured JWT");
+ }
+ const payload = jwt_claims_set_default(header, decode(encodedPayload), options);
+ return { payload, header };
+ }
+};
+
+// dist/webapi/util/base64url.js
+var base64url_exports2 = {};
+__export(base64url_exports2, {
+ decode: () => decode2,
+ encode: () => encode2
+});
+var encode2 = encode;
+var decode2 = decode;
+
+// dist/webapi/util/decode_protected_header.js
+function decodeProtectedHeader(token) {
+ let protectedB64u;
+ if (typeof token === "string") {
+ const parts = token.split(".");
+ if (parts.length === 3 || parts.length === 5) {
+ ;
+ [protectedB64u] = parts;
+ }
+ } else if (typeof token === "object" && token) {
+ if ("protected" in token) {
+ protectedB64u = token.protected;
+ } else {
+ throw new TypeError("Token does not contain a Protected Header");
+ }
+ }
+ try {
+ if (typeof protectedB64u !== "string" || !protectedB64u) {
+ throw new Error();
+ }
+ const result = JSON.parse(decoder.decode(decode2(protectedB64u)));
+ if (!is_object_default(result)) {
+ throw new Error();
+ }
+ return result;
+ } catch {
+ throw new TypeError("Invalid Token or Protected Header formatting");
+ }
+}
+
+// dist/webapi/util/decode_jwt.js
+function decodeJwt(jwt) {
+ if (typeof jwt !== "string")
+ throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
+ const { 1: payload, length } = jwt.split(".");
+ if (length === 5)
+ throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
+ if (length !== 3)
+ throw new JWTInvalid("Invalid JWT");
+ if (!payload)
+ throw new JWTInvalid("JWTs must contain a payload");
+ let decoded;
+ try {
+ decoded = decode2(payload);
+ } catch {
+ throw new JWTInvalid("Failed to base64url decode the payload");
+ }
+ let result;
+ try {
+ result = JSON.parse(decoder.decode(decoded));
+ } catch {
+ throw new JWTInvalid("Failed to parse the decoded payload as JSON");
+ }
+ if (!is_object_default(result))
+ throw new JWTInvalid("Invalid JWT Claims Set");
+ return result;
+}
+
+// dist/webapi/key/generate_key_pair.js
+function getModulusLengthOption(options) {
+ const modulusLength = options?.modulusLength ?? 2048;
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
+ throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
+ }
+ return modulusLength;
+}
+async function generateKeyPair(alg, options) {
+ let algorithm;
+ let keyUsages;
+ switch (alg) {
+ case "PS256":
+ case "PS384":
+ case "PS512":
+ algorithm = {
+ name: "RSA-PSS",
+ hash: `SHA-${alg.slice(-3)}`,
+ publicExponent: new Uint8Array([1, 0, 1]),
+ modulusLength: getModulusLengthOption(options)
+ };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "RS256":
+ case "RS384":
+ case "RS512":
+ algorithm = {
+ name: "RSASSA-PKCS1-v1_5",
+ hash: `SHA-${alg.slice(-3)}`,
+ publicExponent: new Uint8Array([1, 0, 1]),
+ modulusLength: getModulusLengthOption(options)
+ };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512":
+ algorithm = {
+ name: "RSA-OAEP",
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
+ publicExponent: new Uint8Array([1, 0, 1]),
+ modulusLength: getModulusLengthOption(options)
+ };
+ keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"];
+ break;
+ case "ES256":
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "ES384":
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "ES512":
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "Ed25519":
+ case "EdDSA": {
+ keyUsages = ["sign", "verify"];
+ algorithm = { name: "Ed25519" };
+ break;
+ }
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW": {
+ keyUsages = ["deriveBits"];
+ const crv = options?.crv ?? "P-256";
+ switch (crv) {
+ case "P-256":
+ case "P-384":
+ case "P-521": {
+ algorithm = { name: "ECDH", namedCurve: crv };
+ break;
+ }
+ case "X25519":
+ algorithm = { name: "X25519" };
+ break;
+ default:
+ throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
+ }
+ break;
+ }
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
+}
+
+// dist/webapi/key/generate_secret.js
+async function generateSecret(alg, options) {
+ let length;
+ let algorithm;
+ let keyUsages;
+ switch (alg) {
+ case "HS256":
+ case "HS384":
+ case "HS512":
+ length = parseInt(alg.slice(-3), 10);
+ algorithm = { name: "HMAC", hash: `SHA-${length}`, length };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "A128CBC-HS256":
+ case "A192CBC-HS384":
+ case "A256CBC-HS512":
+ length = parseInt(alg.slice(-3), 10);
+ return crypto.getRandomValues(new Uint8Array(length >> 3));
+ case "A128KW":
+ case "A192KW":
+ case "A256KW":
+ length = parseInt(alg.slice(1, 4), 10);
+ algorithm = { name: "AES-KW", length };
+ keyUsages = ["wrapKey", "unwrapKey"];
+ break;
+ case "A128GCMKW":
+ case "A192GCMKW":
+ case "A256GCMKW":
+ case "A128GCM":
+ case "A192GCM":
+ case "A256GCM":
+ length = parseInt(alg.slice(1, 4), 10);
+ algorithm = { name: "AES-GCM", length };
+ keyUsages = ["encrypt", "decrypt"];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
+}
+
+// dist/webapi/index.js
+var cryptoRuntime = "WebCryptoAPI";
+export {
+ CompactEncrypt,
+ CompactSign,
+ EmbeddedJWK,
+ EncryptJWT,
+ FlattenedEncrypt,
+ FlattenedSign,
+ GeneralEncrypt,
+ GeneralSign,
+ SignJWT,
+ UnsecuredJWT,
+ base64url_exports2 as base64url,
+ calculateJwkThumbprint,
+ calculateJwkThumbprintUri,
+ compactDecrypt,
+ compactVerify,
+ createLocalJWKSet,
+ createRemoteJWKSet,
+ cryptoRuntime,
+ decodeJwt,
+ decodeProtectedHeader,
+ errors_exports as errors,
+ exportJWK,
+ exportPKCS8,
+ exportSPKI,
+ flattenedDecrypt,
+ flattenedVerify,
+ generalDecrypt,
+ generalVerify,
+ generateKeyPair,
+ generateSecret,
+ importJWK,
+ importPKCS8,
+ importSPKI,
+ importX509,
+ jwksCache,
+ jwtDecrypt,
+ jwtVerify
+};
diff --git a/dist/webapi/index.bundle.min.js b/dist/webapi/index.bundle.min.js
new file mode 100644
index 0000000000..5811f1e8fc
--- /dev/null
+++ b/dist/webapi/index.bundle.min.js
@@ -0,0 +1,4 @@
+var tr=Object.defineProperty;var ht=(e,t)=>{for(var r in t)tr(e,r,{get:t[r],enumerable:!0})};var m=new TextEncoder,b=new TextDecoder,_e=2**32,I=globalThis.process?.getBuiltinModule?.("node:buffer")?.Buffer;function x(...e){if(I)return I.concat(e);let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Ge(e,t,r){if(t<0||t>=_e)throw new RangeError(`value must be >= 0 and <= ${_e-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function He(e){let t=Math.floor(e/_e),r=e%_e,n=new Uint8Array(8);return Ge(n,t,0),Ge(n,r,4),n}function xe(e){let t=new Uint8Array(4);return Ge(t,e),t}function Ce(e){if(I)return I.from(e).toString("base64");let t=e;typeof t=="string"&&(t=m.encode(t));let r=32768,n=[];for(let o=0;oL,JOSEError:()=>_,JOSENotSupported:()=>f,JWEDecryptionFailed:()=>N,JWEInvalid:()=>c,JWKInvalid:()=>pe,JWKSInvalid:()=>ae,JWKSMultipleMatchingKeys:()=>fe,JWKSNoMatchingKey:()=>V,JWKSTimeout:()=>ue,JWSInvalid:()=>h,JWSSignatureVerificationFailed:()=>z,JWTClaimValidationFailed:()=>C,JWTExpired:()=>oe,JWTInvalid:()=>K});var _=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},C=class extends _{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},oe=class extends _{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r}},L=class extends _{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},f=class extends _{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},N=class extends _{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(t="decryption operation failed",r){super(t,r)}},c=class extends _{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},h=class extends _{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},K=class extends _{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},pe=class extends _{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},ae=class extends _{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},V=class extends _{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r)}},fe=class extends _{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r)}},ue=class extends _{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(t="request timed out",r){super(t,r)}},z=class extends _{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r)}};function Ve(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new f(`Unsupported JWE Algorithm: ${e}`)}}var mt=e=>crypto.getRandomValues(new Uint8Array(Ve(e)>>3));var We=(e,t)=>{if(t.length<<3!==Ve(e))throw new c("Invalid Initialization Vector length")};var ie=(e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new c(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)};function P(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function B(e,t){return e.name===t}function ve(e){return parseInt(e.name.slice(4),10)}function rr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function yt(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function wt(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!B(e.algorithm,"HMAC"))throw P("HMAC");let n=parseInt(t.slice(2),10);if(ve(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!B(e.algorithm,"RSASSA-PKCS1-v1_5"))throw P("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(ve(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!B(e.algorithm,"RSA-PSS"))throw P("RSA-PSS");let n=parseInt(t.slice(2),10);if(ve(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":{if(!B(e.algorithm,"Ed25519"))throw P("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!B(e.algorithm,"ECDSA"))throw P("ECDSA");let n=rr(t);if(e.algorithm.namedCurve!==n)throw P(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}yt(e,r)}function W(e,t,r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!B(e.algorithm,"AES-GCM"))throw P("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw P(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!B(e.algorithm,"AES-KW"))throw P("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw P(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":break;default:throw P("ECDH or X25519")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!B(e.algorithm,"PBKDF2"))throw P("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!B(e.algorithm,"RSA-OAEP"))throw P("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(ve(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}yt(e,r)}function Et(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var v=(e,...t)=>Et("Key must be ",e,...t);function ze(e,t,...r){return Et(`Key for the ${e} algorithm must be `,t,...r)}function X(e){if(!J(e))throw new Error("CryptoKey instance expected")}function J(e){return e?.[Symbol.toStringTag]==="CryptoKey"}function Y(e){return e?.[Symbol.toStringTag]==="KeyObject"}var he=e=>J(e)||Y(e);var St=globalThis.process?.getBuiltinModule?.("node:crypto")?.timingSafeEqual;St||=(e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");let r=e.length,n=0,o=-1;for(;++o>3),"AES-CBC",!1,["decrypt"]),d=await crypto.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},!1,["sign"]),p=x(a,n,r,He(a.length<<3)),u=new Uint8Array((await crypto.subtle.sign("HMAC",d,p)).slice(0,i>>3)),w;try{w=St(o,u)}catch{}if(!w)throw new N;let g;try{g=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},s,r))}catch{}if(!g)throw new N;return g}async function or(e,t,r,n,o,a){let i;t instanceof Uint8Array?i=await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(W(t,e,"decrypt"),i=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},i,x(r,o)))}catch{throw new N}}var Je=async(e,t,r,n,o,a)=>{if(!J(t)&&!(t instanceof Uint8Array))throw new TypeError(v(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new c("JWE Initialization Vector missing");if(!o)throw new c("JWE Authentication Tag missing");switch(We(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&ie(t,parseInt(e.slice(-3),10)),nr(e,t,r,n,o,a);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&ie(t,parseInt(e.slice(1,4),10)),or(e,t,r,n,o,a);default:throw new f("Unsupported JWE Content Encryption Algorithm")}};var R=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return!1;r.add(a)}}return!0};function ar(e){return typeof e=="object"&&e!==null}var l=e=>{if(!ar(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t};function gt(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function At(e,t,r){return e instanceof Uint8Array?crypto.subtle.importKey("raw",e,"AES-KW",!0,[r]):(W(e,t,r),e)}async function le(e,t,r){let n=await At(t,e,"wrapKey");gt(n,e);let o=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",o,n,"AES-KW"))}async function me(e,t,r){let n=await At(t,e,"unwrapKey");gt(n,e);let o=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},!0,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",o))}var Te=async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))};function Ye(e){return x(xe(e.length),e)}async function ir(e,t,r){let n=Math.ceil((t>>3)/32),o=new Uint8Array(n*32);for(let a=0;a>3)}async function Ie(e,t,r,n,o=new Uint8Array(0),a=new Uint8Array(0)){W(e,"ECDH"),W(t,"ECDH","deriveBits");let i=x(Ye(m.encode(r)),Ye(o),Ye(a),xe(n)),s;e.algorithm.name==="X25519"?s=256:s=Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3;let d=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,s));return ir(d,n,i)}function Re(e){switch(e.algorithm.namedCurve){case"P-256":case"P-384":case"P-521":return!0;default:return e.algorithm.name==="X25519"}}function sr(e,t){return e instanceof Uint8Array?crypto.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]):(W(e,t,"deriveBits"),e)}var cr=(e,t)=>x(m.encode(e),new Uint8Array([0]),t);async function Kt(e,t,r,n){if(!(e instanceof Uint8Array)||e.length<8)throw new c("PBES2 Salt Input must be 8 or more octets");let o=cr(t,e),a=parseInt(t.slice(13,16),10),i={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s=await sr(n,t);return new Uint8Array(await crypto.subtle.deriveBits(i,s,a))}async function _t(e,t,r,n=2048,o=crypto.getRandomValues(new Uint8Array(16))){let a=await Kt(o,e,n,t);return{encryptedKey:await le(e.slice(-6),a,r),p2c:n,p2s:y(o)}}async function Ht(e,t,r,n,o){let a=await Kt(o,e,n,t);return me(e.slice(-6),a,r)}var q=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var Ct=e=>{switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new f(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};async function Pt(e,t,r){return W(t,e,"encrypt"),q(e,t),new Uint8Array(await crypto.subtle.encrypt(Ct(e),t,r))}async function Wt(e,t,r){return W(t,e,"decrypt"),q(e,t),new Uint8Array(await crypto.subtle.decrypt(Ct(e),t,r))}function ye(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new f(`Unsupported JWE Algorithm: ${e}`)}}var O=e=>crypto.getRandomValues(new Uint8Array(ye(e)>>3));var It=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(`
+`);return`-----BEGIN ${t}-----
+${r}
+-----END ${t}-----`},Rt=async(e,t,r)=>{if(Y(r)){if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return r.export({format:"pem",type:t})}if(!J(r))throw new TypeError(v(r,"CryptoKey","KeyObject"));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return It(Ce(new Uint8Array(await crypto.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Ot=e=>Rt("public","spki",e),Dt=e=>Rt("private","pkcs8",e),Oe=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let o=e.subarray(n,n+t.length);return o.length!==t.length?!1:o.every((a,i)=>a===t[i])||Oe(e,t,n+1)},dr=e=>{switch(!0){case Oe(e,[42,134,72,206,61,3,1,7]):return"P-256";case Oe(e,[43,129,4,0,34]):return"P-384";case Oe(e,[43,129,4,0,35]):return"P-521";default:return}},Ut=async(e,t,r,n,o)=>{let a,i,s=new Uint8Array(atob(r.replace(e,"")).split("").map(p=>p.charCodeAt(0))),d=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},i=d?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},i=d?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},i=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},i=d?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},i=d?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},i=d?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let p=dr(s);a=p?.startsWith("P-")?{name:"ECDH",namedCurve:p}:{name:"X25519"},i=d?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":a={name:"Ed25519"},i=d?["verify"]:["sign"];break;default:throw new f('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(t,s,a,o?.extractable??!!d,i)},kt=(e,t,r)=>Ut(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),qe=(e,t,r)=>Ut(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function Jt(e){let t=[],r=0;for(;r=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}let a=t+n+2;return{byteLength:a,contents:e.subarray(t,t+n),raw:e.subarray(0,a)}}else{let a=e[t]&127;t++,n=0;for(let i=0;i{let n;try{n=fr(e)}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return qe(n,t,r)};function ur(e){let t,r;switch(e.kty){case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new f('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var De=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=ur(e),n={...e};return delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!e.d,e.key_ops??r)};async function hr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return qe(e,t,r)}async function lr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Nt(e,t,r)}async function mr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return kt(e,t,r)}async function Z(e,t,r){if(!l(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return S(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new f('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return De({...e,alg:t,ext:n});default:throw new f('Unsupported "kty" (Key Type) Parameter value')}}async function yr(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(v(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await crypto.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",!1,["encrypt"]),s=await crypto.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),d=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),p=x(o,n,d,He(o.length<<3)),u=new Uint8Array((await crypto.subtle.sign("HMAC",s,p)).slice(0,a>>3));return{ciphertext:d,tag:u,iv:n}}async function wr(e,t,r,n,o){let a;r instanceof Uint8Array?a=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(W(r,e,"encrypt"),a=r);let i=new Uint8Array(await crypto.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=i.slice(-16);return{ciphertext:i.slice(0,-16),tag:s,iv:n}}var Ue=async(e,t,r,n,o)=>{if(!J(r)&&!(r instanceof Uint8Array))throw new TypeError(v(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(n?We(e,n):n=mt(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&ie(r,parseInt(e.slice(-3),10)),yr(e,t,r,n,o);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&ie(r,parseInt(e.slice(1,4),10)),wr(e,t,r,n,o);default:throw new f("Unsupported JWE Content Encryption Algorithm")}};async function Bt(e,t,r,n){let o=e.slice(0,7),a=await Ue(o,r,t,n,new Uint8Array(0));return{encryptedKey:a.ciphertext,iv:y(a.iv),tag:y(a.tag)}}async function Lt(e,t,r,n,o){let a=e.slice(0,7);return Je(a,t,r,n,o,new Uint8Array(0))}var $t=async(e,t,r,n,o)=>{switch(e){case"dir":{if(r!==void 0)throw new c("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new c("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!l(n.epk))throw new c('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(X(t),!Re(t))throw new f("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await Z(n.epk,e);X(a);let i,s;if(n.apu!==void 0){if(typeof n.apu!="string")throw new c('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{i=S(n.apu)}catch{throw new c("Failed to base64url decode the apu")}}if(n.apv!==void 0){if(typeof n.apv!="string")throw new c('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{s=S(n.apv)}catch{throw new c("Failed to base64url decode the apv")}}let d=await Ie(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?ye(n.enc):parseInt(e.slice(-5,-2),10),i,s);if(e==="ECDH-ES")return d;if(r===void 0)throw new c("JWE Encrypted Key missing");return me(e.slice(-6),d,r)}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new c("JWE Encrypted Key missing");return X(t),Wt(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new c('JOSE Header "p2c" (PBES2 Count) missing or invalid');let a=o?.maxPBES2Count||1e4;if(n.p2c>a)throw new c('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new c('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let i;try{i=S(n.p2s)}catch{throw new c("Failed to base64url decode the p2s")}return Ht(e,t,r,n.p2c,i)}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");return me(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new c("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new c('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new c('JOSE Header "tag" (Authentication Tag) missing or invalid');let a;try{a=S(n.iv)}catch{throw new c("Failed to base64url decode the iv")}let i;try{i=S(n.tag)}catch{throw new c("Failed to base64url decode the tag")}return Lt(e,t,r,a,i)}default:throw new f('Invalid or unsupported "alg" (JWE Algorithm) header value')}};var D=(e,t,r,n,o)=>{if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let i of n.crit){if(!a.has(i))throw new f(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)};var we=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};function Q(e){return l(e)&&typeof e.kty=="string"}function Gt(e){return e.kty!=="oct"&&typeof e.d=="string"}function Ft(e){return e.kty!=="oct"&&typeof e.d>"u"}function Vt(e){return e.kty==="oct"&&typeof e.k=="string"}var se,zt=async(e,t,r,n=!1)=>{se||=new WeakMap;let o=se.get(e);if(o?.[r])return o[r];let a=await De({...t,alg:r});return n&&Object.freeze(e),o?o[r]=a:se.set(e,{[r]:a}),a},Sr=(e,t)=>{se||=new WeakMap;let r=se.get(e);if(r?.[t])return r[t];let n=e.type==="public",o=!!n,a;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}a=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");a=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="rsa"){let i;switch(t){case"RSA-OAEP":i="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":i="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":i="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":i="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:i},o,n?["encrypt"]:["decrypt"]);a=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},o,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){let s=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!s)throw new TypeError("given KeyObject instance cannot be used for this algorithm");t==="ES256"&&s==="P-256"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:s},o,[n?"verify":"sign"])),t==="ES384"&&s==="P-384"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:s},o,[n?"verify":"sign"])),t==="ES512"&&s==="P-521"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:s},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(a=e.toCryptoKey({name:"ECDH",namedCurve:s},o,n?[]:["deriveBits"]))}if(!a)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return r?r[t]=a:se.set(e,{[t]:a}),a},T=async(e,t)=>{if(e instanceof Uint8Array||J(e))return e;if(Y(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return Sr(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return zt(e,r,t)}if(Q(e))return e.k?S(e.k):zt(e,e,t,!0);throw new Error("unreachable")};var ce=e=>e?.[Symbol.toStringTag],Ze=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},gr=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(Q(t)){if(Vt(t)&&Ze(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!he(t))throw new TypeError(ze(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${ce(t)} instances for symmetric algorithms must be of type "secret"`)}},Ar=(e,t,r)=>{if(Q(t))switch(r){case"decrypt":case"sign":if(Gt(t)&&Ze(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"encrypt":case"verify":if(Ft(t)&&Ze(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!he(t))throw new TypeError(ze(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${ce(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${ce(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${ce(t)} instances for asymmetric algorithm decryption must be of type "private"`);default:break}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${ce(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${ce(t)} instances for asymmetric algorithm encryption must be of type "public"`);default:break}},U=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(e)||/^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(e)?gr(e,t,r):Ar(e,t,r)};async function Ee(e,t,r){if(!l(e))throw new c("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new c("JOSE Header missing");if(e.iv!==void 0&&typeof e.iv!="string")throw new c("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new c("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new c("JWE Authentication Tag incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new c("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new c("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new c("JWE AAD incorrect type");if(e.header!==void 0&&!l(e.header))throw new c("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!l(e.unprotected))throw new c("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let ne=S(e.protected);n=JSON.parse(b.decode(ne))}catch{throw new c("JWE Protected Header is invalid")}if(!R(n,e.header,e.unprotected))throw new c("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...n,...e.header,...e.unprotected};if(D(c,new Map,r?.crit,n,o),o.zip!==void 0)throw new f('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:a,enc:i}=o;if(typeof a!="string"||!a)throw new c("missing JWE Algorithm (alg) in JWE Header");if(typeof i!="string"||!i)throw new c("missing JWE Encryption Algorithm (enc) in JWE Header");let s=r&&we("keyManagementAlgorithms",r.keyManagementAlgorithms),d=r&&we("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(s&&!s.has(a)||!s&&a.startsWith("PBES2"))throw new L('"alg" (Algorithm) Header Parameter value not allowed');if(d&&!d.has(i))throw new L('"enc" (Encryption Algorithm) Header Parameter value not allowed');let p;if(e.encrypted_key!==void 0)try{p=S(e.encrypted_key)}catch{throw new c("Failed to base64url decode the encrypted_key")}let u=!1;typeof t=="function"&&(t=await t(n,e),u=!0),U(a==="dir"?i:a,t,"decrypt");let w=await T(t,a),g;try{g=await $t(a,w,p,o,r)}catch(ne){if(ne instanceof TypeError||ne instanceof c||ne instanceof f)throw ne;g=O(i)}let A,E;if(e.iv!==void 0)try{A=S(e.iv)}catch{throw new c("Failed to base64url decode the iv")}if(e.tag!==void 0)try{E=S(e.tag)}catch{throw new c("Failed to base64url decode the tag")}let H=m.encode(e.protected??""),M;e.aad!==void 0?M=x(H,m.encode("."),m.encode(e.aad)):M=H;let ut;try{ut=S(e.ciphertext)}catch{throw new c("Failed to base64url decode the ciphertext")}let re={plaintext:await Je(i,g,ut,A,E,M)};if(e.protected!==void 0&&(re.protectedHeader=n),e.aad!==void 0)try{re.additionalAuthenticatedData=S(e.aad)}catch{throw new c("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(re.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(re.unprotectedHeader=e.header),u?{...re,key:w}:re}async function Qe(e,t,r){if(e instanceof Uint8Array&&(e=b.decode(e)),typeof e!="string")throw new c("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:a,3:i,4:s,length:d}=e.split(".");if(d!==5)throw new c("Invalid Compact JWE");let p=await Ee({ciphertext:i,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},t,r),u={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return typeof t=="function"?{...u,key:p.key}:u}async function br(e,t,r){if(!l(e))throw new c("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(l))throw new c("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new c("JWE Recipients has no members");for(let n of e.recipients)try{return await Ee({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new N}var ke=Symbol();async function je(e){if(Y(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:y(e)};if(!J(e))throw new TypeError(v(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...a}=await crypto.subtle.exportKey("jwk",e);return a}async function Kr(e){return Ot(e)}async function _r(e){return Dt(e)}async function Se(e){return je(e)}var Me=async(e,t,r,n,o={})=>{let a,i,s;switch(e){case"dir":{s=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(X(r),!Re(r))throw new f("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:d,apv:p}=o,u;o.epk?u=await T(o.epk,e):u=(await crypto.subtle.generateKey(r.algorithm,!0,["deriveBits"])).privateKey;let{x:w,y:g,crv:A,kty:E}=await Se(u),H=await Ie(r,u,e==="ECDH-ES"?t:e,e==="ECDH-ES"?ye(t):parseInt(e.slice(-5,-2),10),d,p);if(i={epk:{x:w,crv:A,kty:E}},E==="EC"&&(i.epk.y=g),d&&(i.apu=y(d)),p&&(i.apv=y(p)),e==="ECDH-ES"){s=H;break}s=n||O(t);let M=e.slice(-6);a=await le(M,H,s);break}case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=n||O(t),X(r),a=await Pt(e,r,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=n||O(t);let{p2c:d,p2s:p}=o;({encryptedKey:a,...i}=await _t(e,r,s,d,p));break}case"A128KW":case"A192KW":case"A256KW":{s=n||O(t),a=await le(e,r,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=n||O(t);let{iv:d}=o;({encryptedKey:a,...i}=await Bt(e,r,s,d));break}default:throw new f('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:s,encryptedKey:a,parameters:i}};var $=class{_plaintext;_protectedHeader;_sharedUnprotectedHeader;_unprotectedHeader;_aad;_cek;_iv;_keyManagementParameters;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new c("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!R(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new c("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(D(c,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0)throw new f('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:o,enc:a}=n;if(typeof o!="string"||!o)throw new c('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof a!="string"||!a)throw new c('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let i;if(this._cek&&(o==="dir"||o==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);U(o==="dir"?a:o,t,"encrypt");let s;{let H,M=await T(t,o);({cek:s,encryptedKey:i,parameters:H}=await Me(o,a,M,this._cek,this._keyManagementParameters)),H&&(r&&ke in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...H}:this.setUnprotectedHeader(H):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...H}:this.setProtectedHeader(H))}let d,p,u;this._protectedHeader?p=m.encode(y(JSON.stringify(this._protectedHeader))):p=m.encode(""),this._aad?(u=y(this._aad),d=x(p,m.encode("."),m.encode(u))):d=p;let{ciphertext:w,tag:g,iv:A}=await Ue(a,this._plaintext,s,this._iv,d),E={ciphertext:y(w)};return A&&(E.iv=y(A)),g&&(E.tag=y(g)),i&&(E.encrypted_key=y(i)),u&&(E.aad=u),this._protectedHeader&&(E.protected=b.decode(p)),this._sharedUnprotectedHeader&&(E.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(E.header=this._unprotectedHeader),E}};var et=class{parent;unprotectedHeader;key;options;constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},tt=class{_plaintext;_recipients=[];_protectedHeader;_unprotectedHeader;_aad;constructor(t){this._plaintext=t}addRecipient(t,r){let n=new et(this,t,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(){if(!this._recipients.length)throw new c("at least one recipient must be added");if(this._recipients.length===1){let[o]=this._recipients,a=await new $(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(o.unprotectedHeader).encrypt(o.key,{...o.options}),i={ciphertext:a.ciphertext,iv:a.iv,recipients:[{}],tag:a.tag};return a.aad&&(i.aad=a.aad),a.protected&&(i.protected=a.protected),a.unprotected&&(i.unprotected=a.unprotected),a.encrypted_key&&(i.recipients[0].encrypted_key=a.encrypted_key),a.header&&(i.recipients[0].header=a.header),i}let t;for(let o=0;o{let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};default:throw new f(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};var Be=async(e,t,r)=>{if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(v(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return wt(t,e,r),t};var Xt=async(e,t,r,n)=>{let o=await Be(e,t,"verify");q(e,o);let a=Ne(e,o.algorithm);try{return await crypto.subtle.verify(a,o,r,n)}catch{return!1}};async function ge(e,t,r){if(!l(e))throw new h("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new h('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new h("JWS Protected Header incorrect type");if(e.payload===void 0)throw new h("JWS Payload missing");if(typeof e.signature!="string")throw new h("JWS Signature missing or incorrect type");if(e.header!==void 0&&!l(e.header))throw new h("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let M=S(e.protected);n=JSON.parse(b.decode(M))}catch{throw new h("JWS Protected Header is invalid")}if(!R(n,e.header))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},a=D(h,new Map([["b64",!0]]),r?.crit,n,o),i=!0;if(a.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=r&&we("algorithms",r.algorithms);if(d&&!d.has(s))throw new L('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof e.payload!="string")throw new h("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new h("JWS Payload must be a string or an Uint8Array instance");let p=!1;typeof t=="function"&&(t=await t(n,e),p=!0),U(s,t,"verify");let u=x(m.encode(e.protected??""),m.encode("."),typeof e.payload=="string"?m.encode(e.payload):e.payload),w;try{w=S(e.signature)}catch{throw new h("Failed to base64url decode the signature")}let g=await T(t,s);if(!await Xt(s,g,w,u))throw new z;let E;if(i)try{E=S(e.payload)}catch{throw new h("Failed to base64url decode the payload")}else typeof e.payload=="string"?E=m.encode(e.payload):E=e.payload;let H={payload:E};return e.protected!==void 0&&(H.protectedHeader=n),e.header!==void 0&&(H.unprotectedHeader=e.header),p?{...H,key:g}:H}async function rt(e,t,r){if(e instanceof Uint8Array&&(e=b.decode(e)),typeof e!="string")throw new h("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:a,length:i}=e.split(".");if(i!==3)throw new h("Invalid Compact JWS");let s=await ge({payload:o,protected:n,signature:a},t,r),d={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t=="function"?{...d,key:s.key}:d}async function Hr(e,t,r){if(!l(e))throw new h("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(l))throw new h("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await ge({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new z}var k=e=>Math.floor(e.getTime()/1e3);var xr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,j=e=>{let t=xr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":o=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":o=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":o=Math.round(r*3600);break;case"day":case"days":case"d":o=Math.round(r*86400);break;case"week":case"weeks":case"w":o=Math.round(r*604800);break;default:o=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-o:o};var Yt=e=>e.toLowerCase().replace(/^application\//,""),Cr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,de=(e,t,r={})=>{let n;try{n=JSON.parse(b.decode(t))}catch{}if(!l(n))throw new K("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||Yt(e.typ)!==Yt(o)))throw new C('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:a=[],issuer:i,subject:s,audience:d,maxTokenAge:p}=r,u=[...a];p!==void 0&&u.push("iat"),d!==void 0&&u.push("aud"),s!==void 0&&u.push("sub"),i!==void 0&&u.push("iss");for(let E of new Set(u.reverse()))if(!(E in n))throw new C(`missing required "${E}" claim`,n,E,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new C('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new C('unexpected "sub" claim value',n,"sub","check_failed");if(d&&!Cr(n.aud,typeof d=="string"?[d]:d))throw new C('unexpected "aud" claim value',n,"aud","check_failed");let w;switch(typeof r.clockTolerance){case"string":w=j(r.clockTolerance);break;case"number":w=r.clockTolerance;break;case"undefined":w=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:g}=r,A=k(g||new Date);if((n.iat!==void 0||p)&&typeof n.iat!="number")throw new C('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new C('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>A+w)throw new C('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new C('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=A-w)throw new oe('"exp" claim timestamp check failed',n,"exp","check_failed")}if(p){let E=A-n.iat,H=typeof p=="number"?p:j(p);if(E-w>H)throw new oe('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(E<0-w)throw new C('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Pr(e,t,r){let n=await rt(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new K("JWTs MUST NOT use unencoded payload");let a={payload:de(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...a,key:n.key}:a}async function Wr(e,t,r){let n=await Qe(e,t,r),o=de(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new C('replicated "iss" claim header parameter mismatch',o,"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new C('replicated "sub" claim header parameter mismatch',o,"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new C('replicated "aud" claim header parameter mismatch',o,"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var Ae=class{_flattened;constructor(t){this._flattened=new $(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}};var qt=async(e,t,r)=>{let n=await Be(e,t,"sign");q(e,n);let o=await crypto.subtle.sign(Ne(e,n.algorithm),n,r);return new Uint8Array(o)};var ee=class{_payload;_protectedHeader;_unprotectedHeader;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new h("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!R(this._protectedHeader,this._unprotectedHeader))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=D(h,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),a=!0;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');U(i,t,"sign");let s=this._payload;a&&(s=m.encode(y(s)));let d;this._protectedHeader?d=m.encode(y(JSON.stringify(this._protectedHeader))):d=m.encode("");let p=x(d,m.encode("."),s),u=await T(t,i),w=await qt(i,u,p),g={signature:y(w),payload:""};return a&&(g.payload=b.decode(s)),this._unprotectedHeader&&(g.header=this._unprotectedHeader),this._protectedHeader&&(g.protected=b.decode(d)),g}};var be=class{_flattened;constructor(t){this._flattened=new ee(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};var nt=class{parent;protectedHeader;unprotectedHeader;options;key;constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},ot=class{_payload;_signatures=[];constructor(t){this._payload=t}addSignature(t,r){let n=new nt(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new h("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r"u"?this._payload={...this._payload,iat:k(new Date)}:t instanceof Date?this._payload={...this._payload,iat:te("setIssuedAt",k(t))}:typeof t=="string"?this._payload={...this._payload,iat:te("setIssuedAt",k(new Date)+j(t))}:this._payload={...this._payload,iat:te("setIssuedAt",t)},this}};var at=class extends G{_protectedHeader;setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new be(m.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new K("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var it=class extends G{_cek;_iv;_keyManagementParameters;_protectedHeader;_replicateIssuerAsHeader;_replicateSubjectAsHeader;_replicateAudienceAsHeader;setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,r){let n=new Ae(m.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}};var F=(e,t)=>{if(typeof e!="string"||!e)throw new pe(`${t} missing or invalid`)};async function Zt(e,t){let r;if(Q(e))r=e;else if(he(e))r=await Se(e);else throw new TypeError(v(e,"CryptoKey","KeyObject","JSON Web Key"));if(t??="sha256",t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let n;switch(r.kty){case"EC":F(r.crv,'"crv" (Curve) Parameter'),F(r.x,'"x" (X Coordinate) Parameter'),F(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case"OKP":F(r.crv,'"crv" (Subtype of Key Pair) Parameter'),F(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case"RSA":F(r.e,'"e" (Exponent) Parameter'),F(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case"oct":F(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new f('"kty" (Key Type) Parameter missing or unsupported')}let o=m.encode(JSON.stringify(n));return y(await Te(t,o))}async function vr(e,t){t??="sha256";let r=await Zt(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function Jr(e,t){let r={...e,...t?.header};if(!l(r.jwk))throw new h('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await Z({...r.jwk,ext:!0},r.alg);if(n instanceof Uint8Array||n.type!=="public")throw new h('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}function Tr(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new f('Unsupported "alg" value for a JSON Web Key Set')}}function Ir(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(Rr)}function Rr(e){return l(e)}function jt(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var st=class{_jwks;_cached=new WeakMap;constructor(t){if(!Ir(t))throw new ae("JSON Web Key Set malformed");this._jwks=jt(t)}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},a=Tr(n),i=this._jwks.keys.filter(p=>{let u=a===p.kty;if(u&&typeof o=="string"&&(u=o===p.kid),u&&typeof p.alg=="string"&&(u=n===p.alg),u&&typeof p.use=="string"&&(u=p.use==="sig"),u&&Array.isArray(p.key_ops)&&(u=p.key_ops.includes("verify")),u)switch(n){case"ES256":u=p.crv==="P-256";break;case"ES384":u=p.crv==="P-384";break;case"ES512":u=p.crv==="P-521";break;case"Ed25519":case"EdDSA":u=p.crv==="Ed25519";break}return u}),{0:s,length:d}=i;if(d===0)throw new V;if(d!==1){let p=new fe,{_cached:u}=this;throw p[Symbol.asyncIterator]=async function*(){for(let w of i)try{yield await Qt(u,w,n)}catch{}},p}return Qt(this._cached,s,n)}};async function Qt(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await Z({...t,ext:!0},r);if(o instanceof Uint8Array||o.type!=="public")throw new ae("JSON Web Key Set members must be public keys");n[r]=o}return n[r]}function Le(e){let t=new st(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>jt(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}function Or(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var ct;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ct="jose/v6.0.1");var Dr=Symbol();async function Ur(e,t){let r=await(t?.[Dr]||fetch)(e,{method:"GET",signal:t.signal,redirect:"manual",headers:t.headers}).catch(n=>{throw n.name==="TimeoutError"?new ue:n});if(r.status!==200)throw new _("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await r.json()}catch{throw new _("Failed to parse the JSON Web Key Set HTTP response as JSON")}}var $e=Symbol();function kr(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!l(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,l))}var dt=class{_url;_timeoutDuration;_cooldownDuration;_cacheMaxAge;_jwksTimestamp;_pendingFetch;_options;_local;_cache;constructor(t,r){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={headers:r?.headers},this._timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this._cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this._cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,r?.[$e]!==void 0&&(this._cache=r?.[$e],kr(r?.[$e],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Le(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now(){this._local=Le(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r}),await this._pendingFetch}};function Mr(e,t){let r=new dt(e,t),n=async(o,a)=>r.getKey(o,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),n}var pt=class extends G{encode(){let t=y(JSON.stringify({alg:"none"})),r=y(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new K("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new K("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(b.decode(S(n))),s.alg!=="none")throw new Error}catch{throw new K("Invalid Unsecured JWT")}return{payload:de(s,S(o),r),header:s}}};var er={};ht(er,{decode:()=>Ke,encode:()=>Nr});var Nr=y,Ke=S;function Br(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(b.decode(Ke(t)));if(!l(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function Lr(e){if(typeof e!="string")throw new K("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new K("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new K("Invalid JWT");if(!t)throw new K("JWTs must contain a payload");let n;try{n=Ke(t)}catch{throw new K("Failed to base64url decode the payload")}let o;try{o=JSON.parse(b.decode(n))}catch{throw new K("Failed to parse the decoded payload as JSON")}if(!l(o))throw new K("Invalid JWT Claims Set");return o}function ft(e){let t=e?.modulusLength??2048;if(typeof t!="number"||t<2048)throw new f("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function $r(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:ft(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:ft(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:ft(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":case"EdDSA":{n=["sign","verify"],r={name:"Ed25519"};break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveBits"];let o=t?.crv??"P-256";switch(o){case"P-256":case"P-384":case"P-521":{r={name:"ECDH",namedCurve:o};break}case"X25519":r={name:"X25519"};break;default:throw new f("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}break}default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(r,t?.extractable??!1,n)}async function Gr(e,t){let r,n,o;switch(e){case"HS256":case"HS384":case"HS512":r=parseInt(e.slice(-3),10),n={name:"HMAC",hash:`SHA-${r}`,length:r},o=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r=parseInt(e.slice(-3),10),crypto.getRandomValues(new Uint8Array(r>>3));case"A128KW":case"A192KW":case"A256KW":r=parseInt(e.slice(1,4),10),n={name:"AES-KW",length:r},o=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":r=parseInt(e.slice(1,4),10),n={name:"AES-GCM",length:r},o=["encrypt","decrypt"];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(n,t?.extractable??!1,o)}var Us="WebCryptoAPI";export{Ae as CompactEncrypt,be as CompactSign,Jr as EmbeddedJWK,it as EncryptJWT,$ as FlattenedEncrypt,ee as FlattenedSign,tt as GeneralEncrypt,ot as GeneralSign,at as SignJWT,pt as UnsecuredJWT,er as base64url,Zt as calculateJwkThumbprint,vr as calculateJwkThumbprintUri,Qe as compactDecrypt,rt as compactVerify,Le as createLocalJWKSet,Mr as createRemoteJWKSet,Us as cryptoRuntime,Lr as decodeJwt,Br as decodeProtectedHeader,lt as errors,Se as exportJWK,_r as exportPKCS8,Kr as exportSPKI,Ee as flattenedDecrypt,ge as flattenedVerify,br as generalDecrypt,Hr as generalVerify,$r as generateKeyPair,Gr as generateSecret,Z as importJWK,mr as importPKCS8,hr as importSPKI,lr as importX509,$e as jwksCache,Wr as jwtDecrypt,Pr as jwtVerify};
diff --git a/dist/webapi/index.js b/dist/webapi/index.js
new file mode 100644
index 0000000000..99b1ac993e
--- /dev/null
+++ b/dist/webapi/index.js
@@ -0,0 +1,30 @@
+export { compactDecrypt } from './jwe/compact/decrypt.js';
+export { flattenedDecrypt } from './jwe/flattened/decrypt.js';
+export { generalDecrypt } from './jwe/general/decrypt.js';
+export { GeneralEncrypt } from './jwe/general/encrypt.js';
+export { compactVerify } from './jws/compact/verify.js';
+export { flattenedVerify } from './jws/flattened/verify.js';
+export { generalVerify } from './jws/general/verify.js';
+export { jwtVerify } from './jwt/verify.js';
+export { jwtDecrypt } from './jwt/decrypt.js';
+export { CompactEncrypt } from './jwe/compact/encrypt.js';
+export { FlattenedEncrypt } from './jwe/flattened/encrypt.js';
+export { CompactSign } from './jws/compact/sign.js';
+export { FlattenedSign } from './jws/flattened/sign.js';
+export { GeneralSign } from './jws/general/sign.js';
+export { SignJWT } from './jwt/sign.js';
+export { EncryptJWT } from './jwt/encrypt.js';
+export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js';
+export { EmbeddedJWK } from './jwk/embedded.js';
+export { createLocalJWKSet } from './jwks/local.js';
+export { createRemoteJWKSet, jwksCache } from './jwks/remote.js';
+export { UnsecuredJWT } from './jwt/unsecured.js';
+export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js';
+export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js';
+export { decodeProtectedHeader } from './util/decode_protected_header.js';
+export { decodeJwt } from './util/decode_jwt.js';
+export * as errors from './util/errors.js';
+export { generateKeyPair } from './key/generate_key_pair.js';
+export { generateSecret } from './key/generate_secret.js';
+export * as base64url from './util/base64url.js';
+export const cryptoRuntime = 'WebCryptoAPI';
diff --git a/dist/webapi/index.umd.js b/dist/webapi/index.umd.js
new file mode 100644
index 0000000000..924a81248f
--- /dev/null
+++ b/dist/webapi/index.umd.js
@@ -0,0 +1,3605 @@
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jose = {}));
+})(this, (function (exports) { 'use strict';
+
+ var __defProp = Object.defineProperty;
+ var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+ };
+
+ // dist/webapi/lib/buffer_utils.js
+ var encoder = new TextEncoder();
+ var decoder = new TextDecoder();
+ var MAX_INT32 = 2 ** 32;
+ var Buffer2 = globalThis.process?.getBuiltinModule?.("node:buffer")?.Buffer;
+ function concat(...buffers) {
+ if (Buffer2)
+ return Buffer2.concat(buffers);
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
+ const buf = new Uint8Array(size);
+ let i = 0;
+ for (const buffer of buffers) {
+ buf.set(buffer, i);
+ i += buffer.length;
+ }
+ return buf;
+ }
+ function writeUInt32BE(buf, value, offset) {
+ if (value < 0 || value >= MAX_INT32) {
+ throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
+ }
+ buf.set([value >>> 24, value >>> 16, value >>> 8, value & 255], offset);
+ }
+ function uint64be(value) {
+ const high = Math.floor(value / MAX_INT32);
+ const low = value % MAX_INT32;
+ const buf = new Uint8Array(8);
+ writeUInt32BE(buf, high, 0);
+ writeUInt32BE(buf, low, 4);
+ return buf;
+ }
+ function uint32be(value) {
+ const buf = new Uint8Array(4);
+ writeUInt32BE(buf, value);
+ return buf;
+ }
+
+ // dist/webapi/lib/base64url.js
+ function encodeBase64(input) {
+ if (Buffer2)
+ return Buffer2.from(input).toString("base64");
+ let unencoded = input;
+ if (typeof unencoded === "string") {
+ unencoded = encoder.encode(unencoded);
+ }
+ const CHUNK_SIZE = 32768;
+ const arr = [];
+ for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {
+ arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));
+ }
+ return btoa(arr.join(""));
+ }
+ function encode(input) {
+ if (Buffer2)
+ return Buffer2.from(input).toString("base64url");
+ return encodeBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
+ }
+ function decodeBase64(encoded) {
+ if (Buffer2)
+ return Buffer2.from(encoded, "base64");
+ const binary = atob(encoded);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i++) {
+ bytes[i] = binary.charCodeAt(i);
+ }
+ return bytes;
+ }
+ function decode(input) {
+ let encoded = input;
+ if (encoded instanceof Uint8Array) {
+ encoded = decoder.decode(encoded);
+ }
+ if (Buffer2)
+ return Buffer2.from(encoded, "base64url");
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
+ try {
+ return decodeBase64(encoded);
+ } catch {
+ throw new TypeError("The input to be decoded is not correctly encoded.");
+ }
+ }
+
+ // dist/webapi/util/errors.js
+ var errors_exports = {};
+ __export(errors_exports, {
+ JOSEAlgNotAllowed: () => JOSEAlgNotAllowed,
+ JOSEError: () => JOSEError,
+ JOSENotSupported: () => JOSENotSupported,
+ JWEDecryptionFailed: () => JWEDecryptionFailed,
+ JWEInvalid: () => JWEInvalid,
+ JWKInvalid: () => JWKInvalid,
+ JWKSInvalid: () => JWKSInvalid,
+ JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys,
+ JWKSNoMatchingKey: () => JWKSNoMatchingKey,
+ JWKSTimeout: () => JWKSTimeout,
+ JWSInvalid: () => JWSInvalid,
+ JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed,
+ JWTClaimValidationFailed: () => JWTClaimValidationFailed,
+ JWTExpired: () => JWTExpired,
+ JWTInvalid: () => JWTInvalid
+ });
+ var JOSEError = class extends Error {
+ static code = "ERR_JOSE_GENERIC";
+ code = "ERR_JOSE_GENERIC";
+ constructor(message2, options) {
+ super(message2, options);
+ this.name = this.constructor.name;
+ Error.captureStackTrace?.(this, this.constructor);
+ }
+ };
+ var JWTClaimValidationFailed = class extends JOSEError {
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
+ claim;
+ reason;
+ payload;
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
+ super(message2, { cause: { claim, reason, payload } });
+ this.claim = claim;
+ this.reason = reason;
+ this.payload = payload;
+ }
+ };
+ var JWTExpired = class extends JOSEError {
+ static code = "ERR_JWT_EXPIRED";
+ code = "ERR_JWT_EXPIRED";
+ claim;
+ reason;
+ payload;
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
+ super(message2, { cause: { claim, reason, payload } });
+ this.claim = claim;
+ this.reason = reason;
+ this.payload = payload;
+ }
+ };
+ var JOSEAlgNotAllowed = class extends JOSEError {
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
+ };
+ var JOSENotSupported = class extends JOSEError {
+ static code = "ERR_JOSE_NOT_SUPPORTED";
+ code = "ERR_JOSE_NOT_SUPPORTED";
+ };
+ var JWEDecryptionFailed = class extends JOSEError {
+ static code = "ERR_JWE_DECRYPTION_FAILED";
+ code = "ERR_JWE_DECRYPTION_FAILED";
+ constructor(message2 = "decryption operation failed", options) {
+ super(message2, options);
+ }
+ };
+ var JWEInvalid = class extends JOSEError {
+ static code = "ERR_JWE_INVALID";
+ code = "ERR_JWE_INVALID";
+ };
+ var JWSInvalid = class extends JOSEError {
+ static code = "ERR_JWS_INVALID";
+ code = "ERR_JWS_INVALID";
+ };
+ var JWTInvalid = class extends JOSEError {
+ static code = "ERR_JWT_INVALID";
+ code = "ERR_JWT_INVALID";
+ };
+ var JWKInvalid = class extends JOSEError {
+ static code = "ERR_JWK_INVALID";
+ code = "ERR_JWK_INVALID";
+ };
+ var JWKSInvalid = class extends JOSEError {
+ static code = "ERR_JWKS_INVALID";
+ code = "ERR_JWKS_INVALID";
+ };
+ var JWKSNoMatchingKey = class extends JOSEError {
+ static code = "ERR_JWKS_NO_MATCHING_KEY";
+ code = "ERR_JWKS_NO_MATCHING_KEY";
+ constructor(message2 = "no applicable key found in the JSON Web Key Set", options) {
+ super(message2, options);
+ }
+ };
+ var JWKSMultipleMatchingKeys = class extends JOSEError {
+ [Symbol.asyncIterator];
+ static code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
+ code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
+ constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) {
+ super(message2, options);
+ }
+ };
+ var JWKSTimeout = class extends JOSEError {
+ static code = "ERR_JWKS_TIMEOUT";
+ code = "ERR_JWKS_TIMEOUT";
+ constructor(message2 = "request timed out", options) {
+ super(message2, options);
+ }
+ };
+ var JWSSignatureVerificationFailed = class extends JOSEError {
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
+ constructor(message2 = "signature verification failed", options) {
+ super(message2, options);
+ }
+ };
+
+ // dist/webapi/lib/iv.js
+ function bitLength(alg) {
+ switch (alg) {
+ case "A128GCM":
+ case "A128GCMKW":
+ case "A192GCM":
+ case "A192GCMKW":
+ case "A256GCM":
+ case "A256GCMKW":
+ return 96;
+ case "A128CBC-HS256":
+ case "A192CBC-HS384":
+ case "A256CBC-HS512":
+ return 128;
+ default:
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
+ }
+ }
+ var iv_default = (alg) => crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3));
+
+ // dist/webapi/lib/check_iv_length.js
+ var check_iv_length_default = (enc, iv) => {
+ if (iv.length << 3 !== bitLength(enc)) {
+ throw new JWEInvalid("Invalid Initialization Vector length");
+ }
+ };
+
+ // dist/webapi/lib/check_cek_length.js
+ var check_cek_length_default = (cek, expected) => {
+ const actual = cek.byteLength << 3;
+ if (actual !== expected) {
+ throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
+ }
+ };
+
+ // dist/webapi/lib/crypto_key.js
+ function unusable(name, prop = "algorithm.name") {
+ return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
+ }
+ function isAlgorithm(algorithm, name) {
+ return algorithm.name === name;
+ }
+ function getHashLength(hash) {
+ return parseInt(hash.name.slice(4), 10);
+ }
+ function getNamedCurve(alg) {
+ switch (alg) {
+ case "ES256":
+ return "P-256";
+ case "ES384":
+ return "P-384";
+ case "ES512":
+ return "P-521";
+ default:
+ throw new Error("unreachable");
+ }
+ }
+ function checkUsage(key, usage) {
+ if (usage && !key.usages.includes(usage)) {
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
+ }
+ }
+ function checkSigCryptoKey(key, alg, usage) {
+ switch (alg) {
+ case "HS256":
+ case "HS384":
+ case "HS512": {
+ if (!isAlgorithm(key.algorithm, "HMAC"))
+ throw unusable("HMAC");
+ const expected = parseInt(alg.slice(2), 10);
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
+ break;
+ }
+ case "RS256":
+ case "RS384":
+ case "RS512": {
+ if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
+ throw unusable("RSASSA-PKCS1-v1_5");
+ const expected = parseInt(alg.slice(2), 10);
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
+ break;
+ }
+ case "PS256":
+ case "PS384":
+ case "PS512": {
+ if (!isAlgorithm(key.algorithm, "RSA-PSS"))
+ throw unusable("RSA-PSS");
+ const expected = parseInt(alg.slice(2), 10);
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
+ break;
+ }
+ case "Ed25519":
+ case "EdDSA": {
+ if (!isAlgorithm(key.algorithm, "Ed25519"))
+ throw unusable("Ed25519");
+ break;
+ }
+ case "ES256":
+ case "ES384":
+ case "ES512": {
+ if (!isAlgorithm(key.algorithm, "ECDSA"))
+ throw unusable("ECDSA");
+ const expected = getNamedCurve(alg);
+ const actual = key.algorithm.namedCurve;
+ if (actual !== expected)
+ throw unusable(expected, "algorithm.namedCurve");
+ break;
+ }
+ default:
+ throw new TypeError("CryptoKey does not support this operation");
+ }
+ checkUsage(key, usage);
+ }
+ function checkEncCryptoKey(key, alg, usage) {
+ switch (alg) {
+ case "A128GCM":
+ case "A192GCM":
+ case "A256GCM": {
+ if (!isAlgorithm(key.algorithm, "AES-GCM"))
+ throw unusable("AES-GCM");
+ const expected = parseInt(alg.slice(1, 4), 10);
+ const actual = key.algorithm.length;
+ if (actual !== expected)
+ throw unusable(expected, "algorithm.length");
+ break;
+ }
+ case "A128KW":
+ case "A192KW":
+ case "A256KW": {
+ if (!isAlgorithm(key.algorithm, "AES-KW"))
+ throw unusable("AES-KW");
+ const expected = parseInt(alg.slice(1, 4), 10);
+ const actual = key.algorithm.length;
+ if (actual !== expected)
+ throw unusable(expected, "algorithm.length");
+ break;
+ }
+ case "ECDH": {
+ switch (key.algorithm.name) {
+ case "ECDH":
+ case "X25519":
+ break;
+ default:
+ throw unusable("ECDH or X25519");
+ }
+ break;
+ }
+ case "PBES2-HS256+A128KW":
+ case "PBES2-HS384+A192KW":
+ case "PBES2-HS512+A256KW":
+ if (!isAlgorithm(key.algorithm, "PBKDF2"))
+ throw unusable("PBKDF2");
+ break;
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512": {
+ if (!isAlgorithm(key.algorithm, "RSA-OAEP"))
+ throw unusable("RSA-OAEP");
+ const expected = parseInt(alg.slice(9), 10) || 1;
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
+ break;
+ }
+ default:
+ throw new TypeError("CryptoKey does not support this operation");
+ }
+ checkUsage(key, usage);
+ }
+
+ // dist/webapi/lib/invalid_key_input.js
+ function message(msg, actual, ...types) {
+ types = types.filter(Boolean);
+ if (types.length > 2) {
+ const last = types.pop();
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
+ } else if (types.length === 2) {
+ msg += `one of type ${types[0]} or ${types[1]}.`;
+ } else {
+ msg += `of type ${types[0]}.`;
+ }
+ if (actual == null) {
+ msg += ` Received ${actual}`;
+ } else if (typeof actual === "function" && actual.name) {
+ msg += ` Received function ${actual.name}`;
+ } else if (typeof actual === "object" && actual != null) {
+ if (actual.constructor?.name) {
+ msg += ` Received an instance of ${actual.constructor.name}`;
+ }
+ }
+ return msg;
+ }
+ var invalid_key_input_default = (actual, ...types) => {
+ return message("Key must be ", actual, ...types);
+ };
+ function withAlg(alg, actual, ...types) {
+ return message(`Key for the ${alg} algorithm must be `, actual, ...types);
+ }
+
+ // dist/webapi/lib/is_key_like.js
+ function assertCryptoKey(key) {
+ if (!isCryptoKey(key)) {
+ throw new Error("CryptoKey instance expected");
+ }
+ }
+ function isCryptoKey(key) {
+ return key?.[Symbol.toStringTag] === "CryptoKey";
+ }
+ function isKeyObject(key) {
+ return key?.[Symbol.toStringTag] === "KeyObject";
+ }
+ var is_key_like_default = (key) => {
+ return isCryptoKey(key) || isKeyObject(key);
+ };
+
+ // dist/webapi/lib/decrypt.js
+ var timingSafeEqual = globalThis.process?.getBuiltinModule?.("node:crypto")?.timingSafeEqual;
+ timingSafeEqual ||= (a, b) => {
+ if (!(a instanceof Uint8Array)) {
+ throw new TypeError("First argument must be a buffer");
+ }
+ if (!(b instanceof Uint8Array)) {
+ throw new TypeError("Second argument must be a buffer");
+ }
+ if (a.length !== b.length) {
+ throw new TypeError("Input buffers must have the same length");
+ }
+ const len = a.length;
+ let out = 0;
+ let i = -1;
+ while (++i < len) {
+ out |= a[i] ^ b[i];
+ }
+ return out === 0;
+ };
+ async function cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
+ if (!(cek instanceof Uint8Array)) {
+ throw new TypeError(invalid_key_input_default(cek, "Uint8Array"));
+ }
+ const keySize = parseInt(enc.slice(1, 4), 10);
+ const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"]);
+ const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
+ hash: `SHA-${keySize << 1}`,
+ name: "HMAC"
+ }, false, ["sign"]);
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
+ const expectedTag = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
+ let macCheckPassed;
+ try {
+ macCheckPassed = timingSafeEqual(tag2, expectedTag);
+ } catch {
+ }
+ if (!macCheckPassed) {
+ throw new JWEDecryptionFailed();
+ }
+ let plaintext;
+ try {
+ plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: "AES-CBC" }, encKey, ciphertext));
+ } catch {
+ }
+ if (!plaintext) {
+ throw new JWEDecryptionFailed();
+ }
+ return plaintext;
+ }
+ async function gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad) {
+ let encKey;
+ if (cek instanceof Uint8Array) {
+ encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]);
+ } else {
+ checkEncCryptoKey(cek, enc, "decrypt");
+ encKey = cek;
+ }
+ try {
+ return new Uint8Array(await crypto.subtle.decrypt({
+ additionalData: aad,
+ iv,
+ name: "AES-GCM",
+ tagLength: 128
+ }, encKey, concat(ciphertext, tag2)));
+ } catch {
+ throw new JWEDecryptionFailed();
+ }
+ }
+ var decrypt_default = async (enc, cek, ciphertext, iv, tag2, aad) => {
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
+ throw new TypeError(invalid_key_input_default(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
+ }
+ if (!iv) {
+ throw new JWEInvalid("JWE Initialization Vector missing");
+ }
+ if (!tag2) {
+ throw new JWEInvalid("JWE Authentication Tag missing");
+ }
+ check_iv_length_default(enc, iv);
+ switch (enc) {
+ case "A128CBC-HS256":
+ case "A192CBC-HS384":
+ case "A256CBC-HS512":
+ if (cek instanceof Uint8Array)
+ check_cek_length_default(cek, parseInt(enc.slice(-3), 10));
+ return cbcDecrypt(enc, cek, ciphertext, iv, tag2, aad);
+ case "A128GCM":
+ case "A192GCM":
+ case "A256GCM":
+ if (cek instanceof Uint8Array)
+ check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10));
+ return gcmDecrypt(enc, cek, ciphertext, iv, tag2, aad);
+ default:
+ throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
+ }
+ };
+
+ // dist/webapi/lib/is_disjoint.js
+ var is_disjoint_default = (...headers) => {
+ const sources = headers.filter(Boolean);
+ if (sources.length === 0 || sources.length === 1) {
+ return true;
+ }
+ let acc;
+ for (const header of sources) {
+ const parameters = Object.keys(header);
+ if (!acc || acc.size === 0) {
+ acc = new Set(parameters);
+ continue;
+ }
+ for (const parameter of parameters) {
+ if (acc.has(parameter)) {
+ return false;
+ }
+ acc.add(parameter);
+ }
+ }
+ return true;
+ };
+
+ // dist/webapi/lib/is_object.js
+ function isObjectLike(value) {
+ return typeof value === "object" && value !== null;
+ }
+ var is_object_default = (input) => {
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
+ return false;
+ }
+ if (Object.getPrototypeOf(input) === null) {
+ return true;
+ }
+ let proto = input;
+ while (Object.getPrototypeOf(proto) !== null) {
+ proto = Object.getPrototypeOf(proto);
+ }
+ return Object.getPrototypeOf(input) === proto;
+ };
+
+ // dist/webapi/lib/aeskw.js
+ function checkKeySize(key, alg) {
+ if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {
+ throw new TypeError(`Invalid key size for alg: ${alg}`);
+ }
+ }
+ function getCryptoKey(key, alg, usage) {
+ if (key instanceof Uint8Array) {
+ return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]);
+ }
+ checkEncCryptoKey(key, alg, usage);
+ return key;
+ }
+ async function wrap(alg, key, cek) {
+ const cryptoKey = await getCryptoKey(key, alg, "wrapKey");
+ checkKeySize(cryptoKey, alg);
+ const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
+ return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW"));
+ }
+ async function unwrap(alg, key, encryptedKey) {
+ const cryptoKey = await getCryptoKey(key, alg, "unwrapKey");
+ checkKeySize(cryptoKey, alg);
+ const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", { hash: "SHA-256", name: "HMAC" }, true, ["sign"]);
+ return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek));
+ }
+
+ // dist/webapi/lib/digest.js
+ var digest_default = async (algorithm, data) => {
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
+ };
+
+ // dist/webapi/lib/ecdhes.js
+ function lengthAndInput(input) {
+ return concat(uint32be(input.length), input);
+ }
+ async function concatKdf(secret, bits, value) {
+ const iterations = Math.ceil((bits >> 3) / 32);
+ const res = new Uint8Array(iterations * 32);
+ for (let iter = 0; iter < iterations; iter++) {
+ const buf = new Uint8Array(4 + secret.length + value.length);
+ buf.set(uint32be(iter + 1));
+ buf.set(secret, 4);
+ buf.set(value, 4 + secret.length);
+ res.set(await digest_default("sha256", buf), iter * 32);
+ }
+ return res.slice(0, bits >> 3);
+ }
+ async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
+ checkEncCryptoKey(publicKey, "ECDH");
+ checkEncCryptoKey(privateKey, "ECDH", "deriveBits");
+ const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength));
+ let length;
+ if (publicKey.algorithm.name === "X25519") {
+ length = 256;
+ } else {
+ length = Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3;
+ }
+ const sharedSecret = new Uint8Array(await crypto.subtle.deriveBits({
+ name: publicKey.algorithm.name,
+ public: publicKey
+ }, privateKey, length));
+ return concatKdf(sharedSecret, keyLength, value);
+ }
+ function allowed(key) {
+ switch (key.algorithm.namedCurve) {
+ case "P-256":
+ case "P-384":
+ case "P-521":
+ return true;
+ default:
+ return key.algorithm.name === "X25519";
+ }
+ }
+
+ // dist/webapi/lib/pbes2kw.js
+ function getCryptoKey2(key, alg) {
+ if (key instanceof Uint8Array) {
+ return crypto.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]);
+ }
+ checkEncCryptoKey(key, alg, "deriveBits");
+ return key;
+ }
+ var concatSalt = (alg, p2sInput) => concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);
+ async function deriveKey2(p2s, alg, p2c, key) {
+ if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
+ throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets");
+ }
+ const salt = concatSalt(alg, p2s);
+ const keylen = parseInt(alg.slice(13, 16), 10);
+ const subtleAlg = {
+ hash: `SHA-${alg.slice(8, 11)}`,
+ iterations: p2c,
+ name: "PBKDF2",
+ salt
+ };
+ const cryptoKey = await getCryptoKey2(key, alg);
+ return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
+ }
+ async function wrap2(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {
+ const derived = await deriveKey2(p2s, alg, p2c, key);
+ const encryptedKey = await wrap(alg.slice(-6), derived, cek);
+ return { encryptedKey, p2c, p2s: encode(p2s) };
+ }
+ async function unwrap2(alg, key, encryptedKey, p2c, p2s) {
+ const derived = await deriveKey2(p2s, alg, p2c, key);
+ return unwrap(alg.slice(-6), derived, encryptedKey);
+ }
+
+ // dist/webapi/lib/check_key_length.js
+ var check_key_length_default = (alg, key) => {
+ if (alg.startsWith("RS") || alg.startsWith("PS")) {
+ const { modulusLength } = key.algorithm;
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
+ }
+ }
+ };
+
+ // dist/webapi/lib/rsaes.js
+ var subtleAlgorithm = (alg) => {
+ switch (alg) {
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512":
+ return "RSA-OAEP";
+ default:
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+ }
+ };
+ async function encrypt(alg, key, cek) {
+ checkEncCryptoKey(key, alg, "encrypt");
+ check_key_length_default(alg, key);
+ return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));
+ }
+ async function decrypt(alg, key, encryptedKey) {
+ checkEncCryptoKey(key, alg, "decrypt");
+ check_key_length_default(alg, key);
+ return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));
+ }
+
+ // dist/webapi/lib/cek.js
+ function bitLength2(alg) {
+ switch (alg) {
+ case "A128GCM":
+ return 128;
+ case "A192GCM":
+ return 192;
+ case "A256GCM":
+ case "A128CBC-HS256":
+ return 256;
+ case "A192CBC-HS384":
+ return 384;
+ case "A256CBC-HS512":
+ return 512;
+ default:
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
+ }
+ }
+ var cek_default = (alg) => crypto.getRandomValues(new Uint8Array(bitLength2(alg) >> 3));
+
+ // dist/webapi/lib/asn1.js
+ var formatPEM = (b64, descriptor) => {
+ const newlined = (b64.match(/.{1,64}/g) || []).join("\n");
+ return `-----BEGIN ${descriptor}-----
+${newlined}
+-----END ${descriptor}-----`;
+ };
+ var genericExport = async (keyType, keyFormat, key) => {
+ if (isKeyObject(key)) {
+ if (key.type !== keyType) {
+ throw new TypeError(`key is not a ${keyType} key`);
+ }
+ return key.export({ format: "pem", type: keyFormat });
+ }
+ if (!isCryptoKey(key)) {
+ throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject"));
+ }
+ if (!key.extractable) {
+ throw new TypeError("CryptoKey is not extractable");
+ }
+ if (key.type !== keyType) {
+ throw new TypeError(`key is not a ${keyType} key`);
+ }
+ return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
+ };
+ var toSPKI = (key) => {
+ return genericExport("public", "spki", key);
+ };
+ var toPKCS8 = (key) => {
+ return genericExport("private", "pkcs8", key);
+ };
+ var findOid = (keyData, oid, from = 0) => {
+ if (from === 0) {
+ oid.unshift(oid.length);
+ oid.unshift(6);
+ }
+ const i = keyData.indexOf(oid[0], from);
+ if (i === -1)
+ return false;
+ const sub = keyData.subarray(i, i + oid.length);
+ if (sub.length !== oid.length)
+ return false;
+ return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1);
+ };
+ var getNamedCurve2 = (keyData) => {
+ switch (true) {
+ case findOid(keyData, [42, 134, 72, 206, 61, 3, 1, 7]):
+ return "P-256";
+ case findOid(keyData, [43, 129, 4, 0, 34]):
+ return "P-384";
+ case findOid(keyData, [43, 129, 4, 0, 35]):
+ return "P-521";
+ default:
+ return void 0;
+ }
+ };
+ var genericImport = async (replace, keyFormat, pem, alg, options) => {
+ let algorithm;
+ let keyUsages;
+ const keyData = new Uint8Array(atob(pem.replace(replace, "")).split("").map((c) => c.charCodeAt(0)));
+ const isPublic = keyFormat === "spki";
+ switch (alg) {
+ case "PS256":
+ case "PS384":
+ case "PS512":
+ algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ case "RS256":
+ case "RS384":
+ case "RS512":
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512":
+ algorithm = {
+ name: "RSA-OAEP",
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`
+ };
+ keyUsages = isPublic ? ["encrypt", "wrapKey"] : ["decrypt", "unwrapKey"];
+ break;
+ case "ES256":
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ case "ES384":
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ case "ES512":
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW": {
+ const namedCurve = getNamedCurve2(keyData);
+ algorithm = namedCurve?.startsWith("P-") ? { name: "ECDH", namedCurve } : { name: "X25519" };
+ keyUsages = isPublic ? [] : ["deriveBits"];
+ break;
+ }
+ case "Ed25519":
+ case "EdDSA":
+ algorithm = { name: "Ed25519" };
+ keyUsages = isPublic ? ["verify"] : ["sign"];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
+ }
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);
+ };
+ var fromPKCS8 = (pem, alg, options) => {
+ return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "pkcs8", pem, alg, options);
+ };
+ var fromSPKI = (pem, alg, options) => {
+ return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, "spki", pem, alg, options);
+ };
+ function getElement(seq) {
+ const result = [];
+ let next = 0;
+ while (next < seq.length) {
+ const nextPart = parseElement(seq.subarray(next));
+ result.push(nextPart);
+ next += nextPart.byteLength;
+ }
+ return result;
+ }
+ function parseElement(bytes) {
+ let position = 0;
+ let tag2 = bytes[0] & 31;
+ position++;
+ if (tag2 === 31) {
+ tag2 = 0;
+ while (bytes[position] >= 128) {
+ tag2 = tag2 * 128 + bytes[position] - 128;
+ position++;
+ }
+ tag2 = tag2 * 128 + bytes[position] - 128;
+ position++;
+ }
+ let length = 0;
+ if (bytes[position] < 128) {
+ length = bytes[position];
+ position++;
+ } else if (length === 128) {
+ length = 0;
+ while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) {
+ if (length > bytes.byteLength) {
+ throw new TypeError("invalid indefinite form length");
+ }
+ length++;
+ }
+ const byteLength2 = position + length + 2;
+ return {
+ byteLength: byteLength2,
+ contents: bytes.subarray(position, position + length),
+ raw: bytes.subarray(0, byteLength2)
+ };
+ } else {
+ const numberOfDigits = bytes[position] & 127;
+ position++;
+ length = 0;
+ for (let i = 0; i < numberOfDigits; i++) {
+ length = length * 256 + bytes[position];
+ position++;
+ }
+ }
+ const byteLength = position + length;
+ return {
+ byteLength,
+ contents: bytes.subarray(position, byteLength),
+ raw: bytes.subarray(0, byteLength)
+ };
+ }
+ function spkiFromX509(buf) {
+ const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents);
+ return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 160 ? 6 : 5].raw);
+ }
+ var X509Certificate;
+ function getSPKI(x509) {
+ if (X509Certificate ||= globalThis.process?.getBuiltinModule?.("node:crypto")?.X509Certificate) {
+ try {
+ return new X509Certificate(x509).publicKey.export({ format: "pem", type: "spki" });
+ } catch {
+ }
+ }
+ const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, "");
+ const raw = decodeBase64(pem);
+ return formatPEM(spkiFromX509(raw), "PUBLIC KEY");
+ }
+ var fromX509 = (pem, alg, options) => {
+ let spki;
+ try {
+ spki = getSPKI(pem);
+ } catch (cause) {
+ throw new TypeError("Failed to parse the X.509 certificate", { cause });
+ }
+ return fromSPKI(spki, alg, options);
+ };
+
+ // dist/webapi/lib/jwk_to_key.js
+ function subtleMapping(jwk) {
+ let algorithm;
+ let keyUsages;
+ switch (jwk.kty) {
+ case "RSA": {
+ switch (jwk.alg) {
+ case "PS256":
+ case "PS384":
+ case "PS512":
+ algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "RS256":
+ case "RS384":
+ case "RS512":
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512":
+ algorithm = {
+ name: "RSA-OAEP",
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
+ };
+ keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ break;
+ }
+ case "EC": {
+ switch (jwk.alg) {
+ case "ES256":
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "ES384":
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "ES512":
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW":
+ algorithm = { name: "ECDH", namedCurve: jwk.crv };
+ keyUsages = jwk.d ? ["deriveBits"] : [];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ break;
+ }
+ case "OKP": {
+ switch (jwk.alg) {
+ case "Ed25519":
+ case "EdDSA":
+ algorithm = { name: "Ed25519" };
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
+ break;
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW":
+ algorithm = { name: jwk.crv };
+ keyUsages = jwk.d ? ["deriveBits"] : [];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ break;
+ }
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
+ }
+ return { algorithm, keyUsages };
+ }
+ var jwk_to_key_default = async (jwk) => {
+ if (!jwk.alg) {
+ throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
+ }
+ const { algorithm, keyUsages } = subtleMapping(jwk);
+ const keyData = { ...jwk };
+ delete keyData.alg;
+ delete keyData.use;
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d ? false : true), jwk.key_ops ?? keyUsages);
+ };
+
+ // dist/webapi/key/import.js
+ async function importSPKI(spki, alg, options) {
+ if (typeof spki !== "string" || spki.indexOf("-----BEGIN PUBLIC KEY-----") !== 0) {
+ throw new TypeError('"spki" must be SPKI formatted string');
+ }
+ return fromSPKI(spki, alg, options);
+ }
+ async function importX509(x509, alg, options) {
+ if (typeof x509 !== "string" || x509.indexOf("-----BEGIN CERTIFICATE-----") !== 0) {
+ throw new TypeError('"x509" must be X.509 formatted string');
+ }
+ return fromX509(x509, alg, options);
+ }
+ async function importPKCS8(pkcs8, alg, options) {
+ if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
+ throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
+ }
+ return fromPKCS8(pkcs8, alg, options);
+ }
+ async function importJWK(jwk, alg, options) {
+ if (!is_object_default(jwk)) {
+ throw new TypeError("JWK must be an object");
+ }
+ let ext;
+ alg ??= jwk.alg;
+ ext ??= options?.extractable ?? jwk.ext;
+ switch (jwk.kty) {
+ case "oct":
+ if (typeof jwk.k !== "string" || !jwk.k) {
+ throw new TypeError('missing "k" (Key Value) Parameter value');
+ }
+ return decode(jwk.k);
+ case "RSA":
+ if ("oth" in jwk && jwk.oth !== void 0) {
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
+ }
+ case "EC":
+ case "OKP":
+ return jwk_to_key_default({ ...jwk, alg, ext });
+ default:
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
+ }
+ }
+
+ // dist/webapi/lib/encrypt.js
+ async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
+ if (!(cek instanceof Uint8Array)) {
+ throw new TypeError(invalid_key_input_default(cek, "Uint8Array"));
+ }
+ const keySize = parseInt(enc.slice(1, 4), 10);
+ const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["encrypt"]);
+ const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
+ hash: `SHA-${keySize << 1}`,
+ name: "HMAC"
+ }, false, ["sign"]);
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
+ iv,
+ name: "AES-CBC"
+ }, encKey, plaintext));
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
+ const tag2 = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
+ return { ciphertext, tag: tag2, iv };
+ }
+ async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
+ let encKey;
+ if (cek instanceof Uint8Array) {
+ encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
+ } else {
+ checkEncCryptoKey(cek, enc, "encrypt");
+ encKey = cek;
+ }
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({
+ additionalData: aad,
+ iv,
+ name: "AES-GCM",
+ tagLength: 128
+ }, encKey, plaintext));
+ const tag2 = encrypted.slice(-16);
+ const ciphertext = encrypted.slice(0, -16);
+ return { ciphertext, tag: tag2, iv };
+ }
+ var encrypt_default = async (enc, plaintext, cek, iv, aad) => {
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
+ throw new TypeError(invalid_key_input_default(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
+ }
+ if (iv) {
+ check_iv_length_default(enc, iv);
+ } else {
+ iv = iv_default(enc);
+ }
+ switch (enc) {
+ case "A128CBC-HS256":
+ case "A192CBC-HS384":
+ case "A256CBC-HS512":
+ if (cek instanceof Uint8Array) {
+ check_cek_length_default(cek, parseInt(enc.slice(-3), 10));
+ }
+ return cbcEncrypt(enc, plaintext, cek, iv, aad);
+ case "A128GCM":
+ case "A192GCM":
+ case "A256GCM":
+ if (cek instanceof Uint8Array) {
+ check_cek_length_default(cek, parseInt(enc.slice(1, 4), 10));
+ }
+ return gcmEncrypt(enc, plaintext, cek, iv, aad);
+ default:
+ throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
+ }
+ };
+
+ // dist/webapi/lib/aesgcmkw.js
+ async function wrap3(alg, key, cek, iv) {
+ const jweAlgorithm = alg.slice(0, 7);
+ const wrapped = await encrypt_default(jweAlgorithm, cek, key, iv, new Uint8Array(0));
+ return {
+ encryptedKey: wrapped.ciphertext,
+ iv: encode(wrapped.iv),
+ tag: encode(wrapped.tag)
+ };
+ }
+ async function unwrap3(alg, key, encryptedKey, iv, tag2) {
+ const jweAlgorithm = alg.slice(0, 7);
+ return decrypt_default(jweAlgorithm, key, encryptedKey, iv, tag2, new Uint8Array(0));
+ }
+
+ // dist/webapi/lib/decrypt_key_management.js
+ var decrypt_key_management_default = async (alg, key, encryptedKey, joseHeader, options) => {
+ switch (alg) {
+ case "dir": {
+ if (encryptedKey !== void 0)
+ throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
+ return key;
+ }
+ case "ECDH-ES":
+ if (encryptedKey !== void 0)
+ throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW": {
+ if (!is_object_default(joseHeader.epk))
+ throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
+ assertCryptoKey(key);
+ if (!allowed(key))
+ throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
+ const epk = await importJWK(joseHeader.epk, alg);
+ assertCryptoKey(epk);
+ let partyUInfo;
+ let partyVInfo;
+ if (joseHeader.apu !== void 0) {
+ if (typeof joseHeader.apu !== "string")
+ throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
+ try {
+ partyUInfo = decode(joseHeader.apu);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the apu");
+ }
+ }
+ if (joseHeader.apv !== void 0) {
+ if (typeof joseHeader.apv !== "string")
+ throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
+ try {
+ partyVInfo = decode(joseHeader.apv);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the apv");
+ }
+ }
+ const sharedSecret = await deriveKey(epk, key, alg === "ECDH-ES" ? joseHeader.enc : alg, alg === "ECDH-ES" ? bitLength2(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
+ if (alg === "ECDH-ES")
+ return sharedSecret;
+ if (encryptedKey === void 0)
+ throw new JWEInvalid("JWE Encrypted Key missing");
+ return unwrap(alg.slice(-6), sharedSecret, encryptedKey);
+ }
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512": {
+ if (encryptedKey === void 0)
+ throw new JWEInvalid("JWE Encrypted Key missing");
+ assertCryptoKey(key);
+ return decrypt(alg, key, encryptedKey);
+ }
+ case "PBES2-HS256+A128KW":
+ case "PBES2-HS384+A192KW":
+ case "PBES2-HS512+A256KW": {
+ if (encryptedKey === void 0)
+ throw new JWEInvalid("JWE Encrypted Key missing");
+ if (typeof joseHeader.p2c !== "number")
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
+ const p2cLimit = options?.maxPBES2Count || 1e4;
+ if (joseHeader.p2c > p2cLimit)
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
+ if (typeof joseHeader.p2s !== "string")
+ throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
+ let p2s;
+ try {
+ p2s = decode(joseHeader.p2s);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the p2s");
+ }
+ return unwrap2(alg, key, encryptedKey, joseHeader.p2c, p2s);
+ }
+ case "A128KW":
+ case "A192KW":
+ case "A256KW": {
+ if (encryptedKey === void 0)
+ throw new JWEInvalid("JWE Encrypted Key missing");
+ return unwrap(alg, key, encryptedKey);
+ }
+ case "A128GCMKW":
+ case "A192GCMKW":
+ case "A256GCMKW": {
+ if (encryptedKey === void 0)
+ throw new JWEInvalid("JWE Encrypted Key missing");
+ if (typeof joseHeader.iv !== "string")
+ throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
+ if (typeof joseHeader.tag !== "string")
+ throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
+ let iv;
+ try {
+ iv = decode(joseHeader.iv);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the iv");
+ }
+ let tag2;
+ try {
+ tag2 = decode(joseHeader.tag);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the tag");
+ }
+ return unwrap3(alg, key, encryptedKey, iv, tag2);
+ }
+ default: {
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
+ }
+ }
+ };
+
+ // dist/webapi/lib/validate_crit.js
+ var validate_crit_default = (Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) => {
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
+ }
+ if (!protectedHeader || protectedHeader.crit === void 0) {
+ return /* @__PURE__ */ new Set();
+ }
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
+ }
+ let recognized;
+ if (recognizedOption !== void 0) {
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
+ } else {
+ recognized = recognizedDefault;
+ }
+ for (const parameter of protectedHeader.crit) {
+ if (!recognized.has(parameter)) {
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
+ }
+ if (joseHeader[parameter] === void 0) {
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
+ }
+ if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
+ }
+ }
+ return new Set(protectedHeader.crit);
+ };
+
+ // dist/webapi/lib/validate_algorithms.js
+ var validate_algorithms_default = (option, algorithms) => {
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
+ throw new TypeError(`"${option}" option must be an array of strings`);
+ }
+ if (!algorithms) {
+ return void 0;
+ }
+ return new Set(algorithms);
+ };
+
+ // dist/webapi/lib/is_jwk.js
+ function isJWK(key) {
+ return is_object_default(key) && typeof key.kty === "string";
+ }
+ function isPrivateJWK(key) {
+ return key.kty !== "oct" && typeof key.d === "string";
+ }
+ function isPublicJWK(key) {
+ return key.kty !== "oct" && typeof key.d === "undefined";
+ }
+ function isSecretJWK(key) {
+ return key.kty === "oct" && typeof key.k === "string";
+ }
+
+ // dist/webapi/lib/normalize_key.js
+ var cache;
+ var handleJWK = async (key, jwk, alg, freeze = false) => {
+ cache ||= /* @__PURE__ */ new WeakMap();
+ let cached = cache.get(key);
+ if (cached?.[alg]) {
+ return cached[alg];
+ }
+ const cryptoKey = await jwk_to_key_default({ ...jwk, alg });
+ if (freeze)
+ Object.freeze(key);
+ if (!cached) {
+ cache.set(key, { [alg]: cryptoKey });
+ } else {
+ cached[alg] = cryptoKey;
+ }
+ return cryptoKey;
+ };
+ var handleKeyObject = (keyObject, alg) => {
+ cache ||= /* @__PURE__ */ new WeakMap();
+ let cached = cache.get(keyObject);
+ if (cached?.[alg]) {
+ return cached[alg];
+ }
+ const isPublic = keyObject.type === "public";
+ const extractable = isPublic ? true : false;
+ let cryptoKey;
+ if (keyObject.asymmetricKeyType === "x25519") {
+ switch (alg) {
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW":
+ break;
+ default:
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
+ }
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
+ }
+ if (keyObject.asymmetricKeyType === "ed25519") {
+ if (alg !== "EdDSA" && alg !== "Ed25519") {
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
+ }
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
+ isPublic ? "verify" : "sign"
+ ]);
+ }
+ if (keyObject.asymmetricKeyType === "rsa") {
+ let hash;
+ switch (alg) {
+ case "RSA-OAEP":
+ hash = "SHA-1";
+ break;
+ case "RS256":
+ case "PS256":
+ case "RSA-OAEP-256":
+ hash = "SHA-256";
+ break;
+ case "RS384":
+ case "PS384":
+ case "RSA-OAEP-384":
+ hash = "SHA-384";
+ break;
+ case "RS512":
+ case "PS512":
+ case "RSA-OAEP-512":
+ hash = "SHA-512";
+ break;
+ default:
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
+ }
+ if (alg.startsWith("RSA-OAEP")) {
+ return keyObject.toCryptoKey({
+ name: "RSA-OAEP",
+ hash
+ }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
+ }
+ cryptoKey = keyObject.toCryptoKey({
+ name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
+ hash
+ }, extractable, [isPublic ? "verify" : "sign"]);
+ }
+ if (keyObject.asymmetricKeyType === "ec") {
+ const nist = /* @__PURE__ */ new Map([
+ ["prime256v1", "P-256"],
+ ["secp384r1", "P-384"],
+ ["secp521r1", "P-521"]
+ ]);
+ const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
+ if (!namedCurve) {
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
+ }
+ if (alg === "ES256" && namedCurve === "P-256") {
+ cryptoKey = keyObject.toCryptoKey({
+ name: "ECDSA",
+ namedCurve
+ }, extractable, [isPublic ? "verify" : "sign"]);
+ }
+ if (alg === "ES384" && namedCurve === "P-384") {
+ cryptoKey = keyObject.toCryptoKey({
+ name: "ECDSA",
+ namedCurve
+ }, extractable, [isPublic ? "verify" : "sign"]);
+ }
+ if (alg === "ES512" && namedCurve === "P-521") {
+ cryptoKey = keyObject.toCryptoKey({
+ name: "ECDSA",
+ namedCurve
+ }, extractable, [isPublic ? "verify" : "sign"]);
+ }
+ if (alg.startsWith("ECDH-ES")) {
+ cryptoKey = keyObject.toCryptoKey({
+ name: "ECDH",
+ namedCurve
+ }, extractable, isPublic ? [] : ["deriveBits"]);
+ }
+ }
+ if (!cryptoKey) {
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
+ }
+ if (!cached) {
+ cache.set(keyObject, { [alg]: cryptoKey });
+ } else {
+ cached[alg] = cryptoKey;
+ }
+ return cryptoKey;
+ };
+ var normalize_key_default = async (key, alg) => {
+ if (key instanceof Uint8Array) {
+ return key;
+ }
+ if (isCryptoKey(key)) {
+ return key;
+ }
+ if (isKeyObject(key)) {
+ if (key.type === "secret") {
+ return key.export();
+ }
+ if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
+ try {
+ return handleKeyObject(key, alg);
+ } catch (err) {
+ if (err instanceof TypeError) {
+ throw err;
+ }
+ }
+ }
+ let jwk = key.export({ format: "jwk" });
+ return handleJWK(key, jwk, alg);
+ }
+ if (isJWK(key)) {
+ if (key.k) {
+ return decode(key.k);
+ }
+ return handleJWK(key, key, alg, true);
+ }
+ throw new Error("unreachable");
+ };
+
+ // dist/webapi/lib/check_key_type.js
+ var tag = (key) => key?.[Symbol.toStringTag];
+ var jwkMatchesOp = (alg, key, usage) => {
+ if (key.use !== void 0) {
+ let expected;
+ switch (usage) {
+ case "sign":
+ case "verify":
+ expected = "sig";
+ break;
+ case "encrypt":
+ case "decrypt":
+ expected = "enc";
+ break;
+ }
+ if (key.use !== expected) {
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
+ }
+ }
+ if (key.alg !== void 0 && key.alg !== alg) {
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
+ }
+ if (Array.isArray(key.key_ops)) {
+ let expectedKeyOp;
+ switch (true) {
+ case (usage === "sign" || usage === "verify"):
+ case alg === "dir":
+ case alg.includes("CBC-HS"):
+ expectedKeyOp = usage;
+ break;
+ case alg.startsWith("PBES2"):
+ expectedKeyOp = "deriveBits";
+ break;
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
+ if (!alg.includes("GCM") && alg.endsWith("KW")) {
+ expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
+ } else {
+ expectedKeyOp = usage;
+ }
+ break;
+ case (usage === "encrypt" && alg.startsWith("RSA")):
+ expectedKeyOp = "wrapKey";
+ break;
+ case usage === "decrypt":
+ expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
+ break;
+ }
+ if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
+ }
+ }
+ return true;
+ };
+ var symmetricTypeCheck = (alg, key, usage) => {
+ if (key instanceof Uint8Array)
+ return;
+ if (isJWK(key)) {
+ if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
+ return;
+ throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
+ }
+ if (!is_key_like_default(key)) {
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
+ }
+ if (key.type !== "secret") {
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
+ }
+ };
+ var asymmetricTypeCheck = (alg, key, usage) => {
+ if (isJWK(key)) {
+ switch (usage) {
+ case "decrypt":
+ case "sign":
+ if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
+ return;
+ throw new TypeError(`JSON Web Key for this operation be a private JWK`);
+ case "encrypt":
+ case "verify":
+ if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
+ return;
+ throw new TypeError(`JSON Web Key for this operation be a public JWK`);
+ }
+ }
+ if (!is_key_like_default(key)) {
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
+ }
+ if (key.type === "secret") {
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
+ }
+ if (key.type === "public") {
+ switch (usage) {
+ case "sign":
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
+ case "decrypt":
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
+ }
+ }
+ if (key.type === "private") {
+ switch (usage) {
+ case "verify":
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
+ case "encrypt":
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
+ }
+ }
+ };
+ var check_key_type_default = (alg, key, usage) => {
+ const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(alg) || /^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(alg);
+ if (symmetric) {
+ symmetricTypeCheck(alg, key, usage);
+ } else {
+ asymmetricTypeCheck(alg, key, usage);
+ }
+ };
+
+ // dist/webapi/jwe/flattened/decrypt.js
+ async function flattenedDecrypt(jwe, key, options) {
+ if (!is_object_default(jwe)) {
+ throw new JWEInvalid("Flattened JWE must be an object");
+ }
+ if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) {
+ throw new JWEInvalid("JOSE Header missing");
+ }
+ if (jwe.iv !== void 0 && typeof jwe.iv !== "string") {
+ throw new JWEInvalid("JWE Initialization Vector incorrect type");
+ }
+ if (typeof jwe.ciphertext !== "string") {
+ throw new JWEInvalid("JWE Ciphertext missing or incorrect type");
+ }
+ if (jwe.tag !== void 0 && typeof jwe.tag !== "string") {
+ throw new JWEInvalid("JWE Authentication Tag incorrect type");
+ }
+ if (jwe.protected !== void 0 && typeof jwe.protected !== "string") {
+ throw new JWEInvalid("JWE Protected Header incorrect type");
+ }
+ if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") {
+ throw new JWEInvalid("JWE Encrypted Key incorrect type");
+ }
+ if (jwe.aad !== void 0 && typeof jwe.aad !== "string") {
+ throw new JWEInvalid("JWE AAD incorrect type");
+ }
+ if (jwe.header !== void 0 && !is_object_default(jwe.header)) {
+ throw new JWEInvalid("JWE Shared Unprotected Header incorrect type");
+ }
+ if (jwe.unprotected !== void 0 && !is_object_default(jwe.unprotected)) {
+ throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");
+ }
+ let parsedProt;
+ if (jwe.protected) {
+ try {
+ const protectedHeader2 = decode(jwe.protected);
+ parsedProt = JSON.parse(decoder.decode(protectedHeader2));
+ } catch {
+ throw new JWEInvalid("JWE Protected Header is invalid");
+ }
+ }
+ if (!is_disjoint_default(parsedProt, jwe.header, jwe.unprotected)) {
+ throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");
+ }
+ const joseHeader = {
+ ...parsedProt,
+ ...jwe.header,
+ ...jwe.unprotected
+ };
+ validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader);
+ if (joseHeader.zip !== void 0) {
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+ }
+ const { alg, enc } = joseHeader;
+ if (typeof alg !== "string" || !alg) {
+ throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header");
+ }
+ if (typeof enc !== "string" || !enc) {
+ throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");
+ }
+ const keyManagementAlgorithms = options && validate_algorithms_default("keyManagementAlgorithms", options.keyManagementAlgorithms);
+ const contentEncryptionAlgorithms = options && validate_algorithms_default("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms);
+ if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg) || !keyManagementAlgorithms && alg.startsWith("PBES2")) {
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
+ }
+ if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
+ throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
+ }
+ let encryptedKey;
+ if (jwe.encrypted_key !== void 0) {
+ try {
+ encryptedKey = decode(jwe.encrypted_key);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the encrypted_key");
+ }
+ }
+ let resolvedKey = false;
+ if (typeof key === "function") {
+ key = await key(parsedProt, jwe);
+ resolvedKey = true;
+ }
+ check_key_type_default(alg === "dir" ? enc : alg, key, "decrypt");
+ const k = await normalize_key_default(key, alg);
+ let cek;
+ try {
+ cek = await decrypt_key_management_default(alg, k, encryptedKey, joseHeader, options);
+ } catch (err) {
+ if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
+ throw err;
+ }
+ cek = cek_default(enc);
+ }
+ let iv;
+ let tag2;
+ if (jwe.iv !== void 0) {
+ try {
+ iv = decode(jwe.iv);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the iv");
+ }
+ }
+ if (jwe.tag !== void 0) {
+ try {
+ tag2 = decode(jwe.tag);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the tag");
+ }
+ }
+ const protectedHeader = encoder.encode(jwe.protected ?? "");
+ let additionalData;
+ if (jwe.aad !== void 0) {
+ additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(jwe.aad));
+ } else {
+ additionalData = protectedHeader;
+ }
+ let ciphertext;
+ try {
+ ciphertext = decode(jwe.ciphertext);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the ciphertext");
+ }
+ const plaintext = await decrypt_default(enc, cek, ciphertext, iv, tag2, additionalData);
+ const result = { plaintext };
+ if (jwe.protected !== void 0) {
+ result.protectedHeader = parsedProt;
+ }
+ if (jwe.aad !== void 0) {
+ try {
+ result.additionalAuthenticatedData = decode(jwe.aad);
+ } catch {
+ throw new JWEInvalid("Failed to base64url decode the aad");
+ }
+ }
+ if (jwe.unprotected !== void 0) {
+ result.sharedUnprotectedHeader = jwe.unprotected;
+ }
+ if (jwe.header !== void 0) {
+ result.unprotectedHeader = jwe.header;
+ }
+ if (resolvedKey) {
+ return { ...result, key: k };
+ }
+ return result;
+ }
+
+ // dist/webapi/jwe/compact/decrypt.js
+ async function compactDecrypt(jwe, key, options) {
+ if (jwe instanceof Uint8Array) {
+ jwe = decoder.decode(jwe);
+ }
+ if (typeof jwe !== "string") {
+ throw new JWEInvalid("Compact JWE must be a string or Uint8Array");
+ }
+ const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag2, length } = jwe.split(".");
+ if (length !== 5) {
+ throw new JWEInvalid("Invalid Compact JWE");
+ }
+ const decrypted = await flattenedDecrypt({
+ ciphertext,
+ iv: iv || void 0,
+ protected: protectedHeader,
+ tag: tag2 || void 0,
+ encrypted_key: encryptedKey || void 0
+ }, key, options);
+ const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };
+ if (typeof key === "function") {
+ return { ...result, key: decrypted.key };
+ }
+ return result;
+ }
+
+ // dist/webapi/jwe/general/decrypt.js
+ async function generalDecrypt(jwe, key, options) {
+ if (!is_object_default(jwe)) {
+ throw new JWEInvalid("General JWE must be an object");
+ }
+ if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(is_object_default)) {
+ throw new JWEInvalid("JWE Recipients missing or incorrect type");
+ }
+ if (!jwe.recipients.length) {
+ throw new JWEInvalid("JWE Recipients has no members");
+ }
+ for (const recipient of jwe.recipients) {
+ try {
+ return await flattenedDecrypt({
+ aad: jwe.aad,
+ ciphertext: jwe.ciphertext,
+ encrypted_key: recipient.encrypted_key,
+ header: recipient.header,
+ iv: jwe.iv,
+ protected: jwe.protected,
+ tag: jwe.tag,
+ unprotected: jwe.unprotected
+ }, key, options);
+ } catch {
+ }
+ }
+ throw new JWEDecryptionFailed();
+ }
+
+ // dist/webapi/lib/private_symbols.js
+ var unprotected = Symbol();
+
+ // dist/webapi/lib/key_to_jwk.js
+ async function keyToJWK(key) {
+ if (isKeyObject(key)) {
+ if (key.type === "secret") {
+ key = key.export();
+ } else {
+ return key.export({ format: "jwk" });
+ }
+ }
+ if (key instanceof Uint8Array) {
+ return {
+ kty: "oct",
+ k: encode(key)
+ };
+ }
+ if (!isCryptoKey(key)) {
+ throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject", "Uint8Array"));
+ }
+ if (!key.extractable) {
+ throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
+ }
+ const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey("jwk", key);
+ return jwk;
+ }
+
+ // dist/webapi/key/export.js
+ async function exportSPKI(key) {
+ return toSPKI(key);
+ }
+ async function exportPKCS8(key) {
+ return toPKCS8(key);
+ }
+ async function exportJWK(key) {
+ return keyToJWK(key);
+ }
+
+ // dist/webapi/lib/encrypt_key_management.js
+ var encrypt_key_management_default = async (alg, enc, key, providedCek, providedParameters = {}) => {
+ let encryptedKey;
+ let parameters;
+ let cek;
+ switch (alg) {
+ case "dir": {
+ cek = key;
+ break;
+ }
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW": {
+ assertCryptoKey(key);
+ if (!allowed(key)) {
+ throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
+ }
+ const { apu, apv } = providedParameters;
+ let ephemeralKey;
+ if (providedParameters.epk) {
+ ephemeralKey = await normalize_key_default(providedParameters.epk, alg);
+ } else {
+ ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey;
+ }
+ const { x, y, crv, kty } = await exportJWK(ephemeralKey);
+ const sharedSecret = await deriveKey(key, ephemeralKey, alg === "ECDH-ES" ? enc : alg, alg === "ECDH-ES" ? bitLength2(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
+ parameters = { epk: { x, crv, kty } };
+ if (kty === "EC")
+ parameters.epk.y = y;
+ if (apu)
+ parameters.apu = encode(apu);
+ if (apv)
+ parameters.apv = encode(apv);
+ if (alg === "ECDH-ES") {
+ cek = sharedSecret;
+ break;
+ }
+ cek = providedCek || cek_default(enc);
+ const kwAlg = alg.slice(-6);
+ encryptedKey = await wrap(kwAlg, sharedSecret, cek);
+ break;
+ }
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512": {
+ cek = providedCek || cek_default(enc);
+ assertCryptoKey(key);
+ encryptedKey = await encrypt(alg, key, cek);
+ break;
+ }
+ case "PBES2-HS256+A128KW":
+ case "PBES2-HS384+A192KW":
+ case "PBES2-HS512+A256KW": {
+ cek = providedCek || cek_default(enc);
+ const { p2c, p2s } = providedParameters;
+ ({ encryptedKey, ...parameters } = await wrap2(alg, key, cek, p2c, p2s));
+ break;
+ }
+ case "A128KW":
+ case "A192KW":
+ case "A256KW": {
+ cek = providedCek || cek_default(enc);
+ encryptedKey = await wrap(alg, key, cek);
+ break;
+ }
+ case "A128GCMKW":
+ case "A192GCMKW":
+ case "A256GCMKW": {
+ cek = providedCek || cek_default(enc);
+ const { iv } = providedParameters;
+ ({ encryptedKey, ...parameters } = await wrap3(alg, key, cek, iv));
+ break;
+ }
+ default: {
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
+ }
+ }
+ return { cek, encryptedKey, parameters };
+ };
+
+ // dist/webapi/jwe/flattened/encrypt.js
+ var FlattenedEncrypt = class {
+ _plaintext;
+ _protectedHeader;
+ _sharedUnprotectedHeader;
+ _unprotectedHeader;
+ _aad;
+ _cek;
+ _iv;
+ _keyManagementParameters;
+ constructor(plaintext) {
+ if (!(plaintext instanceof Uint8Array)) {
+ throw new TypeError("plaintext must be an instance of Uint8Array");
+ }
+ this._plaintext = plaintext;
+ }
+ setKeyManagementParameters(parameters) {
+ if (this._keyManagementParameters) {
+ throw new TypeError("setKeyManagementParameters can only be called once");
+ }
+ this._keyManagementParameters = parameters;
+ return this;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError("setProtectedHeader can only be called once");
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setSharedUnprotectedHeader(sharedUnprotectedHeader) {
+ if (this._sharedUnprotectedHeader) {
+ throw new TypeError("setSharedUnprotectedHeader can only be called once");
+ }
+ this._sharedUnprotectedHeader = sharedUnprotectedHeader;
+ return this;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this._unprotectedHeader) {
+ throw new TypeError("setUnprotectedHeader can only be called once");
+ }
+ this._unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ setAdditionalAuthenticatedData(aad) {
+ this._aad = aad;
+ return this;
+ }
+ setContentEncryptionKey(cek) {
+ if (this._cek) {
+ throw new TypeError("setContentEncryptionKey can only be called once");
+ }
+ this._cek = cek;
+ return this;
+ }
+ setInitializationVector(iv) {
+ if (this._iv) {
+ throw new TypeError("setInitializationVector can only be called once");
+ }
+ this._iv = iv;
+ return this;
+ }
+ async encrypt(key, options) {
+ if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {
+ throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");
+ }
+ if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) {
+ throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
+ }
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...this._sharedUnprotectedHeader
+ };
+ validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this._protectedHeader, joseHeader);
+ if (joseHeader.zip !== void 0) {
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+ }
+ const { alg, enc } = joseHeader;
+ if (typeof alg !== "string" || !alg) {
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ if (typeof enc !== "string" || !enc) {
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
+ }
+ let encryptedKey;
+ if (this._cek && (alg === "dir" || alg === "ECDH-ES")) {
+ throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
+ }
+ check_key_type_default(alg === "dir" ? enc : alg, key, "encrypt");
+ let cek;
+ {
+ let parameters;
+ const k = await normalize_key_default(key, alg);
+ ({ cek, encryptedKey, parameters } = await encrypt_key_management_default(alg, enc, k, this._cek, this._keyManagementParameters));
+ if (parameters) {
+ if (options && unprotected in options) {
+ if (!this._unprotectedHeader) {
+ this.setUnprotectedHeader(parameters);
+ } else {
+ this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters };
+ }
+ } else if (!this._protectedHeader) {
+ this.setProtectedHeader(parameters);
+ } else {
+ this._protectedHeader = { ...this._protectedHeader, ...parameters };
+ }
+ }
+ }
+ let additionalData;
+ let protectedHeader;
+ let aadMember;
+ if (this._protectedHeader) {
+ protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader)));
+ } else {
+ protectedHeader = encoder.encode("");
+ }
+ if (this._aad) {
+ aadMember = encode(this._aad);
+ additionalData = concat(protectedHeader, encoder.encode("."), encoder.encode(aadMember));
+ } else {
+ additionalData = protectedHeader;
+ }
+ const { ciphertext, tag: tag2, iv } = await encrypt_default(enc, this._plaintext, cek, this._iv, additionalData);
+ const jwe = {
+ ciphertext: encode(ciphertext)
+ };
+ if (iv) {
+ jwe.iv = encode(iv);
+ }
+ if (tag2) {
+ jwe.tag = encode(tag2);
+ }
+ if (encryptedKey) {
+ jwe.encrypted_key = encode(encryptedKey);
+ }
+ if (aadMember) {
+ jwe.aad = aadMember;
+ }
+ if (this._protectedHeader) {
+ jwe.protected = decoder.decode(protectedHeader);
+ }
+ if (this._sharedUnprotectedHeader) {
+ jwe.unprotected = this._sharedUnprotectedHeader;
+ }
+ if (this._unprotectedHeader) {
+ jwe.header = this._unprotectedHeader;
+ }
+ return jwe;
+ }
+ };
+
+ // dist/webapi/jwe/general/encrypt.js
+ var IndividualRecipient = class {
+ parent;
+ unprotectedHeader;
+ key;
+ options;
+ constructor(enc, key, options) {
+ this.parent = enc;
+ this.key = key;
+ this.options = options;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this.unprotectedHeader) {
+ throw new TypeError("setUnprotectedHeader can only be called once");
+ }
+ this.unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ addRecipient(...args) {
+ return this.parent.addRecipient(...args);
+ }
+ encrypt(...args) {
+ return this.parent.encrypt(...args);
+ }
+ done() {
+ return this.parent;
+ }
+ };
+ var GeneralEncrypt = class {
+ _plaintext;
+ _recipients = [];
+ _protectedHeader;
+ _unprotectedHeader;
+ _aad;
+ constructor(plaintext) {
+ this._plaintext = plaintext;
+ }
+ addRecipient(key, options) {
+ const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
+ this._recipients.push(recipient);
+ return recipient;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError("setProtectedHeader can only be called once");
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setSharedUnprotectedHeader(sharedUnprotectedHeader) {
+ if (this._unprotectedHeader) {
+ throw new TypeError("setSharedUnprotectedHeader can only be called once");
+ }
+ this._unprotectedHeader = sharedUnprotectedHeader;
+ return this;
+ }
+ setAdditionalAuthenticatedData(aad) {
+ this._aad = aad;
+ return this;
+ }
+ async encrypt() {
+ if (!this._recipients.length) {
+ throw new JWEInvalid("at least one recipient must be added");
+ }
+ if (this._recipients.length === 1) {
+ const [recipient] = this._recipients;
+ const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).encrypt(recipient.key, { ...recipient.options });
+ const jwe2 = {
+ ciphertext: flattened.ciphertext,
+ iv: flattened.iv,
+ recipients: [{}],
+ tag: flattened.tag
+ };
+ if (flattened.aad)
+ jwe2.aad = flattened.aad;
+ if (flattened.protected)
+ jwe2.protected = flattened.protected;
+ if (flattened.unprotected)
+ jwe2.unprotected = flattened.unprotected;
+ if (flattened.encrypted_key)
+ jwe2.recipients[0].encrypted_key = flattened.encrypted_key;
+ if (flattened.header)
+ jwe2.recipients[0].header = flattened.header;
+ return jwe2;
+ }
+ let enc;
+ for (let i = 0; i < this._recipients.length; i++) {
+ const recipient = this._recipients[i];
+ if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) {
+ throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
+ }
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...recipient.unprotectedHeader
+ };
+ const { alg } = joseHeader;
+ if (typeof alg !== "string" || !alg) {
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ if (alg === "dir" || alg === "ECDH-ES") {
+ throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');
+ }
+ if (typeof joseHeader.enc !== "string" || !joseHeader.enc) {
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
+ }
+ if (!enc) {
+ enc = joseHeader.enc;
+ } else if (enc !== joseHeader.enc) {
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');
+ }
+ validate_crit_default(JWEInvalid, /* @__PURE__ */ new Map(), recipient.options.crit, this._protectedHeader, joseHeader);
+ if (joseHeader.zip !== void 0) {
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+ }
+ }
+ const cek = cek_default(enc);
+ const jwe = {
+ ciphertext: "",
+ iv: "",
+ recipients: [],
+ tag: ""
+ };
+ for (let i = 0; i < this._recipients.length; i++) {
+ const recipient = this._recipients[i];
+ const target = {};
+ jwe.recipients.push(target);
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...recipient.unprotectedHeader
+ };
+ const p2c = joseHeader.alg.startsWith("PBES2") ? 2048 + i : void 0;
+ if (i === 0) {
+ const flattened = await new FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(cek).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(recipient.unprotectedHeader).setKeyManagementParameters({ p2c }).encrypt(recipient.key, {
+ ...recipient.options,
+ [unprotected]: true
+ });
+ jwe.ciphertext = flattened.ciphertext;
+ jwe.iv = flattened.iv;
+ jwe.tag = flattened.tag;
+ if (flattened.aad)
+ jwe.aad = flattened.aad;
+ if (flattened.protected)
+ jwe.protected = flattened.protected;
+ if (flattened.unprotected)
+ jwe.unprotected = flattened.unprotected;
+ target.encrypted_key = flattened.encrypted_key;
+ if (flattened.header)
+ target.header = flattened.header;
+ continue;
+ }
+ const alg = recipient.unprotectedHeader?.alg || this._protectedHeader?.alg || this._unprotectedHeader?.alg;
+ check_key_type_default(alg === "dir" ? enc : alg, recipient.key, "encrypt");
+ const k = await normalize_key_default(recipient.key, alg);
+ const { encryptedKey, parameters } = await encrypt_key_management_default(alg, enc, k, cek, { p2c });
+ target.encrypted_key = encode(encryptedKey);
+ if (recipient.unprotectedHeader || parameters)
+ target.header = { ...recipient.unprotectedHeader, ...parameters };
+ }
+ return jwe;
+ }
+ };
+
+ // dist/webapi/lib/subtle_dsa.js
+ var subtle_dsa_default = (alg, algorithm) => {
+ const hash = `SHA-${alg.slice(-3)}`;
+ switch (alg) {
+ case "HS256":
+ case "HS384":
+ case "HS512":
+ return { hash, name: "HMAC" };
+ case "PS256":
+ case "PS384":
+ case "PS512":
+ return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
+ case "RS256":
+ case "RS384":
+ case "RS512":
+ return { hash, name: "RSASSA-PKCS1-v1_5" };
+ case "ES256":
+ case "ES384":
+ case "ES512":
+ return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
+ case "Ed25519":
+ case "EdDSA":
+ return { name: "Ed25519" };
+ default:
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+ }
+ };
+
+ // dist/webapi/lib/get_sign_verify_key.js
+ var get_sign_verify_key_default = async (alg, key, usage) => {
+ if (key instanceof Uint8Array) {
+ if (!alg.startsWith("HS")) {
+ throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject", "JSON Web Key"));
+ }
+ return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
+ }
+ checkSigCryptoKey(key, alg, usage);
+ return key;
+ };
+
+ // dist/webapi/lib/verify.js
+ var verify_default = async (alg, key, signature, data) => {
+ const cryptoKey = await get_sign_verify_key_default(alg, key, "verify");
+ check_key_length_default(alg, cryptoKey);
+ const algorithm = subtle_dsa_default(alg, cryptoKey.algorithm);
+ try {
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
+ } catch {
+ return false;
+ }
+ };
+
+ // dist/webapi/jws/flattened/verify.js
+ async function flattenedVerify(jws, key, options) {
+ if (!is_object_default(jws)) {
+ throw new JWSInvalid("Flattened JWS must be an object");
+ }
+ if (jws.protected === void 0 && jws.header === void 0) {
+ throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
+ }
+ if (jws.protected !== void 0 && typeof jws.protected !== "string") {
+ throw new JWSInvalid("JWS Protected Header incorrect type");
+ }
+ if (jws.payload === void 0) {
+ throw new JWSInvalid("JWS Payload missing");
+ }
+ if (typeof jws.signature !== "string") {
+ throw new JWSInvalid("JWS Signature missing or incorrect type");
+ }
+ if (jws.header !== void 0 && !is_object_default(jws.header)) {
+ throw new JWSInvalid("JWS Unprotected Header incorrect type");
+ }
+ let parsedProt = {};
+ if (jws.protected) {
+ try {
+ const protectedHeader = decode(jws.protected);
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
+ } catch {
+ throw new JWSInvalid("JWS Protected Header is invalid");
+ }
+ }
+ if (!is_disjoint_default(parsedProt, jws.header)) {
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
+ }
+ const joseHeader = {
+ ...parsedProt,
+ ...jws.header
+ };
+ const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
+ let b64 = true;
+ if (extensions.has("b64")) {
+ b64 = parsedProt.b64;
+ if (typeof b64 !== "boolean") {
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
+ }
+ }
+ const { alg } = joseHeader;
+ if (typeof alg !== "string" || !alg) {
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ const algorithms = options && validate_algorithms_default("algorithms", options.algorithms);
+ if (algorithms && !algorithms.has(alg)) {
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
+ }
+ if (b64) {
+ if (typeof jws.payload !== "string") {
+ throw new JWSInvalid("JWS Payload must be a string");
+ }
+ } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
+ throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
+ }
+ let resolvedKey = false;
+ if (typeof key === "function") {
+ key = await key(parsedProt, jws);
+ resolvedKey = true;
+ }
+ check_key_type_default(alg, key, "verify");
+ const data = concat(encoder.encode(jws.protected ?? ""), encoder.encode("."), typeof jws.payload === "string" ? encoder.encode(jws.payload) : jws.payload);
+ let signature;
+ try {
+ signature = decode(jws.signature);
+ } catch {
+ throw new JWSInvalid("Failed to base64url decode the signature");
+ }
+ const k = await normalize_key_default(key, alg);
+ const verified = await verify_default(alg, k, signature, data);
+ if (!verified) {
+ throw new JWSSignatureVerificationFailed();
+ }
+ let payload;
+ if (b64) {
+ try {
+ payload = decode(jws.payload);
+ } catch {
+ throw new JWSInvalid("Failed to base64url decode the payload");
+ }
+ } else if (typeof jws.payload === "string") {
+ payload = encoder.encode(jws.payload);
+ } else {
+ payload = jws.payload;
+ }
+ const result = { payload };
+ if (jws.protected !== void 0) {
+ result.protectedHeader = parsedProt;
+ }
+ if (jws.header !== void 0) {
+ result.unprotectedHeader = jws.header;
+ }
+ if (resolvedKey) {
+ return { ...result, key: k };
+ }
+ return result;
+ }
+
+ // dist/webapi/jws/compact/verify.js
+ async function compactVerify(jws, key, options) {
+ if (jws instanceof Uint8Array) {
+ jws = decoder.decode(jws);
+ }
+ if (typeof jws !== "string") {
+ throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
+ }
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
+ if (length !== 3) {
+ throw new JWSInvalid("Invalid Compact JWS");
+ }
+ const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
+ const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
+ if (typeof key === "function") {
+ return { ...result, key: verified.key };
+ }
+ return result;
+ }
+
+ // dist/webapi/jws/general/verify.js
+ async function generalVerify(jws, key, options) {
+ if (!is_object_default(jws)) {
+ throw new JWSInvalid("General JWS must be an object");
+ }
+ if (!Array.isArray(jws.signatures) || !jws.signatures.every(is_object_default)) {
+ throw new JWSInvalid("JWS Signatures missing or incorrect type");
+ }
+ for (const signature of jws.signatures) {
+ try {
+ return await flattenedVerify({
+ header: signature.header,
+ payload: jws.payload,
+ protected: signature.protected,
+ signature: signature.signature
+ }, key, options);
+ } catch {
+ }
+ }
+ throw new JWSSignatureVerificationFailed();
+ }
+
+ // dist/webapi/lib/epoch.js
+ var epoch_default = (date) => Math.floor(date.getTime() / 1e3);
+
+ // dist/webapi/lib/secs.js
+ var minute = 60;
+ var hour = minute * 60;
+ var day = hour * 24;
+ var week = day * 7;
+ var year = day * 365.25;
+ var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
+ var secs_default = (str) => {
+ const matched = REGEX.exec(str);
+ if (!matched || matched[4] && matched[1]) {
+ throw new TypeError("Invalid time period format");
+ }
+ const value = parseFloat(matched[2]);
+ const unit = matched[3].toLowerCase();
+ let numericDate;
+ switch (unit) {
+ case "sec":
+ case "secs":
+ case "second":
+ case "seconds":
+ case "s":
+ numericDate = Math.round(value);
+ break;
+ case "minute":
+ case "minutes":
+ case "min":
+ case "mins":
+ case "m":
+ numericDate = Math.round(value * minute);
+ break;
+ case "hour":
+ case "hours":
+ case "hr":
+ case "hrs":
+ case "h":
+ numericDate = Math.round(value * hour);
+ break;
+ case "day":
+ case "days":
+ case "d":
+ numericDate = Math.round(value * day);
+ break;
+ case "week":
+ case "weeks":
+ case "w":
+ numericDate = Math.round(value * week);
+ break;
+ default:
+ numericDate = Math.round(value * year);
+ break;
+ }
+ if (matched[1] === "-" || matched[4] === "ago") {
+ return -numericDate;
+ }
+ return numericDate;
+ };
+
+ // dist/webapi/lib/jwt_claims_set.js
+ var normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, "");
+ var checkAudiencePresence = (audPayload, audOption) => {
+ if (typeof audPayload === "string") {
+ return audOption.includes(audPayload);
+ }
+ if (Array.isArray(audPayload)) {
+ return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
+ }
+ return false;
+ };
+ var jwt_claims_set_default = (protectedHeader, encodedPayload, options = {}) => {
+ let payload;
+ try {
+ payload = JSON.parse(decoder.decode(encodedPayload));
+ } catch {
+ }
+ if (!is_object_default(payload)) {
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
+ }
+ const { typ } = options;
+ if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
+ throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
+ }
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
+ const presenceCheck = [...requiredClaims];
+ if (maxTokenAge !== void 0)
+ presenceCheck.push("iat");
+ if (audience !== void 0)
+ presenceCheck.push("aud");
+ if (subject !== void 0)
+ presenceCheck.push("sub");
+ if (issuer !== void 0)
+ presenceCheck.push("iss");
+ for (const claim of new Set(presenceCheck.reverse())) {
+ if (!(claim in payload)) {
+ throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
+ }
+ }
+ if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
+ throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
+ }
+ if (subject && payload.sub !== subject) {
+ throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
+ }
+ if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
+ throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
+ }
+ let tolerance;
+ switch (typeof options.clockTolerance) {
+ case "string":
+ tolerance = secs_default(options.clockTolerance);
+ break;
+ case "number":
+ tolerance = options.clockTolerance;
+ break;
+ case "undefined":
+ tolerance = 0;
+ break;
+ default:
+ throw new TypeError("Invalid clockTolerance option type");
+ }
+ const { currentDate } = options;
+ const now = epoch_default(currentDate || /* @__PURE__ */ new Date());
+ if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
+ throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
+ }
+ if (payload.nbf !== void 0) {
+ if (typeof payload.nbf !== "number") {
+ throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
+ }
+ if (payload.nbf > now + tolerance) {
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
+ }
+ }
+ if (payload.exp !== void 0) {
+ if (typeof payload.exp !== "number") {
+ throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
+ }
+ if (payload.exp <= now - tolerance) {
+ throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
+ }
+ }
+ if (maxTokenAge) {
+ const age = now - payload.iat;
+ const max = typeof maxTokenAge === "number" ? maxTokenAge : secs_default(maxTokenAge);
+ if (age - tolerance > max) {
+ throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
+ }
+ if (age < 0 - tolerance) {
+ throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
+ }
+ }
+ return payload;
+ };
+
+ // dist/webapi/jwt/verify.js
+ async function jwtVerify(jwt, key, options) {
+ const verified = await compactVerify(jwt, key, options);
+ if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
+ }
+ const payload = jwt_claims_set_default(verified.protectedHeader, verified.payload, options);
+ const result = { payload, protectedHeader: verified.protectedHeader };
+ if (typeof key === "function") {
+ return { ...result, key: verified.key };
+ }
+ return result;
+ }
+
+ // dist/webapi/jwt/decrypt.js
+ async function jwtDecrypt(jwt, key, options) {
+ const decrypted = await compactDecrypt(jwt, key, options);
+ const payload = jwt_claims_set_default(decrypted.protectedHeader, decrypted.plaintext, options);
+ const { protectedHeader } = decrypted;
+ if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) {
+ throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, "iss", "mismatch");
+ }
+ if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) {
+ throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, "sub", "mismatch");
+ }
+ if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
+ throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, "aud", "mismatch");
+ }
+ const result = { payload, protectedHeader };
+ if (typeof key === "function") {
+ return { ...result, key: decrypted.key };
+ }
+ return result;
+ }
+
+ // dist/webapi/jwe/compact/encrypt.js
+ var CompactEncrypt = class {
+ _flattened;
+ constructor(plaintext) {
+ this._flattened = new FlattenedEncrypt(plaintext);
+ }
+ setContentEncryptionKey(cek) {
+ this._flattened.setContentEncryptionKey(cek);
+ return this;
+ }
+ setInitializationVector(iv) {
+ this._flattened.setInitializationVector(iv);
+ return this;
+ }
+ setProtectedHeader(protectedHeader) {
+ this._flattened.setProtectedHeader(protectedHeader);
+ return this;
+ }
+ setKeyManagementParameters(parameters) {
+ this._flattened.setKeyManagementParameters(parameters);
+ return this;
+ }
+ async encrypt(key, options) {
+ const jwe = await this._flattened.encrypt(key, options);
+ return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join(".");
+ }
+ };
+
+ // dist/webapi/lib/sign.js
+ var sign_default = async (alg, key, data) => {
+ const cryptoKey = await get_sign_verify_key_default(alg, key, "sign");
+ check_key_length_default(alg, cryptoKey);
+ const signature = await crypto.subtle.sign(subtle_dsa_default(alg, cryptoKey.algorithm), cryptoKey, data);
+ return new Uint8Array(signature);
+ };
+
+ // dist/webapi/jws/flattened/sign.js
+ var FlattenedSign = class {
+ _payload;
+ _protectedHeader;
+ _unprotectedHeader;
+ constructor(payload) {
+ if (!(payload instanceof Uint8Array)) {
+ throw new TypeError("payload must be an instance of Uint8Array");
+ }
+ this._payload = payload;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError("setProtectedHeader can only be called once");
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this._unprotectedHeader) {
+ throw new TypeError("setUnprotectedHeader can only be called once");
+ }
+ this._unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ async sign(key, options) {
+ if (!this._protectedHeader && !this._unprotectedHeader) {
+ throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
+ }
+ if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader)) {
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
+ }
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader
+ };
+ const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this._protectedHeader, joseHeader);
+ let b64 = true;
+ if (extensions.has("b64")) {
+ b64 = this._protectedHeader.b64;
+ if (typeof b64 !== "boolean") {
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
+ }
+ }
+ const { alg } = joseHeader;
+ if (typeof alg !== "string" || !alg) {
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ check_key_type_default(alg, key, "sign");
+ let payload = this._payload;
+ if (b64) {
+ payload = encoder.encode(encode(payload));
+ }
+ let protectedHeader;
+ if (this._protectedHeader) {
+ protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader)));
+ } else {
+ protectedHeader = encoder.encode("");
+ }
+ const data = concat(protectedHeader, encoder.encode("."), payload);
+ const k = await normalize_key_default(key, alg);
+ const signature = await sign_default(alg, k, data);
+ const jws = {
+ signature: encode(signature),
+ payload: ""
+ };
+ if (b64) {
+ jws.payload = decoder.decode(payload);
+ }
+ if (this._unprotectedHeader) {
+ jws.header = this._unprotectedHeader;
+ }
+ if (this._protectedHeader) {
+ jws.protected = decoder.decode(protectedHeader);
+ }
+ return jws;
+ }
+ };
+
+ // dist/webapi/jws/compact/sign.js
+ var CompactSign = class {
+ _flattened;
+ constructor(payload) {
+ this._flattened = new FlattenedSign(payload);
+ }
+ setProtectedHeader(protectedHeader) {
+ this._flattened.setProtectedHeader(protectedHeader);
+ return this;
+ }
+ async sign(key, options) {
+ const jws = await this._flattened.sign(key, options);
+ if (jws.payload === void 0) {
+ throw new TypeError("use the flattened module for creating JWS with b64: false");
+ }
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
+ }
+ };
+
+ // dist/webapi/jws/general/sign.js
+ var IndividualSignature = class {
+ parent;
+ protectedHeader;
+ unprotectedHeader;
+ options;
+ key;
+ constructor(sig, key, options) {
+ this.parent = sig;
+ this.key = key;
+ this.options = options;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this.protectedHeader) {
+ throw new TypeError("setProtectedHeader can only be called once");
+ }
+ this.protectedHeader = protectedHeader;
+ return this;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this.unprotectedHeader) {
+ throw new TypeError("setUnprotectedHeader can only be called once");
+ }
+ this.unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ addSignature(...args) {
+ return this.parent.addSignature(...args);
+ }
+ sign(...args) {
+ return this.parent.sign(...args);
+ }
+ done() {
+ return this.parent;
+ }
+ };
+ var GeneralSign = class {
+ _payload;
+ _signatures = [];
+ constructor(payload) {
+ this._payload = payload;
+ }
+ addSignature(key, options) {
+ const signature = new IndividualSignature(this, key, options);
+ this._signatures.push(signature);
+ return signature;
+ }
+ async sign() {
+ if (!this._signatures.length) {
+ throw new JWSInvalid("at least one signature must be added");
+ }
+ const jws = {
+ signatures: [],
+ payload: ""
+ };
+ for (let i = 0; i < this._signatures.length; i++) {
+ const signature = this._signatures[i];
+ const flattened = new FlattenedSign(this._payload);
+ flattened.setProtectedHeader(signature.protectedHeader);
+ flattened.setUnprotectedHeader(signature.unprotectedHeader);
+ const { payload, ...rest } = await flattened.sign(signature.key, signature.options);
+ if (i === 0) {
+ jws.payload = payload;
+ } else if (jws.payload !== payload) {
+ throw new JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");
+ }
+ jws.signatures.push(rest);
+ }
+ return jws;
+ }
+ };
+
+ // dist/webapi/jwt/produce.js
+ function validateInput(label, input) {
+ if (!Number.isFinite(input)) {
+ throw new TypeError(`Invalid ${label} input`);
+ }
+ return input;
+ }
+ var ProduceJWT = class {
+ _payload;
+ constructor(payload = {}) {
+ if (!is_object_default(payload)) {
+ throw new TypeError("JWT Claims Set MUST be an object");
+ }
+ this._payload = payload;
+ }
+ setIssuer(issuer) {
+ this._payload = { ...this._payload, iss: issuer };
+ return this;
+ }
+ setSubject(subject) {
+ this._payload = { ...this._payload, sub: subject };
+ return this;
+ }
+ setAudience(audience) {
+ this._payload = { ...this._payload, aud: audience };
+ return this;
+ }
+ setJti(jwtId) {
+ this._payload = { ...this._payload, jti: jwtId };
+ return this;
+ }
+ setNotBefore(input) {
+ if (typeof input === "number") {
+ this._payload = { ...this._payload, nbf: validateInput("setNotBefore", input) };
+ } else if (input instanceof Date) {
+ this._payload = { ...this._payload, nbf: validateInput("setNotBefore", epoch_default(input)) };
+ } else {
+ this._payload = { ...this._payload, nbf: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) };
+ }
+ return this;
+ }
+ setExpirationTime(input) {
+ if (typeof input === "number") {
+ this._payload = { ...this._payload, exp: validateInput("setExpirationTime", input) };
+ } else if (input instanceof Date) {
+ this._payload = { ...this._payload, exp: validateInput("setExpirationTime", epoch_default(input)) };
+ } else {
+ this._payload = { ...this._payload, exp: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) };
+ }
+ return this;
+ }
+ setIssuedAt(input) {
+ if (typeof input === "undefined") {
+ this._payload = { ...this._payload, iat: epoch_default(/* @__PURE__ */ new Date()) };
+ } else if (input instanceof Date) {
+ this._payload = { ...this._payload, iat: validateInput("setIssuedAt", epoch_default(input)) };
+ } else if (typeof input === "string") {
+ this._payload = {
+ ...this._payload,
+ iat: validateInput("setIssuedAt", epoch_default(/* @__PURE__ */ new Date()) + secs_default(input))
+ };
+ } else {
+ this._payload = { ...this._payload, iat: validateInput("setIssuedAt", input) };
+ }
+ return this;
+ }
+ };
+
+ // dist/webapi/jwt/sign.js
+ var SignJWT = class extends ProduceJWT {
+ _protectedHeader;
+ setProtectedHeader(protectedHeader) {
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ async sign(key, options) {
+ const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)));
+ sig.setProtectedHeader(this._protectedHeader);
+ if (Array.isArray(this._protectedHeader?.crit) && this._protectedHeader.crit.includes("b64") && this._protectedHeader.b64 === false) {
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
+ }
+ return sig.sign(key, options);
+ }
+ };
+
+ // dist/webapi/jwt/encrypt.js
+ var EncryptJWT = class extends ProduceJWT {
+ _cek;
+ _iv;
+ _keyManagementParameters;
+ _protectedHeader;
+ _replicateIssuerAsHeader;
+ _replicateSubjectAsHeader;
+ _replicateAudienceAsHeader;
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError("setProtectedHeader can only be called once");
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setKeyManagementParameters(parameters) {
+ if (this._keyManagementParameters) {
+ throw new TypeError("setKeyManagementParameters can only be called once");
+ }
+ this._keyManagementParameters = parameters;
+ return this;
+ }
+ setContentEncryptionKey(cek) {
+ if (this._cek) {
+ throw new TypeError("setContentEncryptionKey can only be called once");
+ }
+ this._cek = cek;
+ return this;
+ }
+ setInitializationVector(iv) {
+ if (this._iv) {
+ throw new TypeError("setInitializationVector can only be called once");
+ }
+ this._iv = iv;
+ return this;
+ }
+ replicateIssuerAsHeader() {
+ this._replicateIssuerAsHeader = true;
+ return this;
+ }
+ replicateSubjectAsHeader() {
+ this._replicateSubjectAsHeader = true;
+ return this;
+ }
+ replicateAudienceAsHeader() {
+ this._replicateAudienceAsHeader = true;
+ return this;
+ }
+ async encrypt(key, options) {
+ const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload)));
+ if (this._replicateIssuerAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss };
+ }
+ if (this._replicateSubjectAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub };
+ }
+ if (this._replicateAudienceAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud };
+ }
+ enc.setProtectedHeader(this._protectedHeader);
+ if (this._iv) {
+ enc.setInitializationVector(this._iv);
+ }
+ if (this._cek) {
+ enc.setContentEncryptionKey(this._cek);
+ }
+ if (this._keyManagementParameters) {
+ enc.setKeyManagementParameters(this._keyManagementParameters);
+ }
+ return enc.encrypt(key, options);
+ }
+ };
+
+ // dist/webapi/jwk/thumbprint.js
+ var check = (value, description) => {
+ if (typeof value !== "string" || !value) {
+ throw new JWKInvalid(`${description} missing or invalid`);
+ }
+ };
+ async function calculateJwkThumbprint(key, digestAlgorithm) {
+ let jwk;
+ if (isJWK(key)) {
+ jwk = key;
+ } else if (is_key_like_default(key)) {
+ jwk = await exportJWK(key);
+ } else {
+ throw new TypeError(invalid_key_input_default(key, "CryptoKey", "KeyObject", "JSON Web Key"));
+ }
+ digestAlgorithm ??= "sha256";
+ if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") {
+ throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
+ }
+ let components;
+ switch (jwk.kty) {
+ case "EC":
+ check(jwk.crv, '"crv" (Curve) Parameter');
+ check(jwk.x, '"x" (X Coordinate) Parameter');
+ check(jwk.y, '"y" (Y Coordinate) Parameter');
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
+ break;
+ case "OKP":
+ check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
+ check(jwk.x, '"x" (Public Key) Parameter');
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
+ break;
+ case "RSA":
+ check(jwk.e, '"e" (Exponent) Parameter');
+ check(jwk.n, '"n" (Modulus) Parameter');
+ components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
+ break;
+ case "oct":
+ check(jwk.k, '"k" (Key Value) Parameter');
+ components = { k: jwk.k, kty: jwk.kty };
+ break;
+ default:
+ throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
+ }
+ const data = encoder.encode(JSON.stringify(components));
+ return encode(await digest_default(digestAlgorithm, data));
+ }
+ async function calculateJwkThumbprintUri(key, digestAlgorithm) {
+ digestAlgorithm ??= "sha256";
+ const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm);
+ return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
+ }
+
+ // dist/webapi/jwk/embedded.js
+ async function EmbeddedJWK(protectedHeader, token) {
+ const joseHeader = {
+ ...protectedHeader,
+ ...token?.header
+ };
+ if (!is_object_default(joseHeader.jwk)) {
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');
+ }
+ const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
+ if (key instanceof Uint8Array || key.type !== "public") {
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');
+ }
+ return key;
+ }
+
+ // dist/webapi/jwks/local.js
+ function getKtyFromAlg(alg) {
+ switch (typeof alg === "string" && alg.slice(0, 2)) {
+ case "RS":
+ case "PS":
+ return "RSA";
+ case "ES":
+ return "EC";
+ case "Ed":
+ return "OKP";
+ default:
+ throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
+ }
+ }
+ function isJWKSLike(jwks) {
+ return jwks && typeof jwks === "object" && Array.isArray(jwks.keys) && jwks.keys.every(isJWKLike);
+ }
+ function isJWKLike(key) {
+ return is_object_default(key);
+ }
+ function clone(obj) {
+ if (typeof structuredClone === "function") {
+ return structuredClone(obj);
+ }
+ return JSON.parse(JSON.stringify(obj));
+ }
+ var LocalJWKSet = class {
+ _jwks;
+ _cached = /* @__PURE__ */ new WeakMap();
+ constructor(jwks) {
+ if (!isJWKSLike(jwks)) {
+ throw new JWKSInvalid("JSON Web Key Set malformed");
+ }
+ this._jwks = clone(jwks);
+ }
+ async getKey(protectedHeader, token) {
+ const { alg, kid } = { ...protectedHeader, ...token?.header };
+ const kty = getKtyFromAlg(alg);
+ const candidates = this._jwks.keys.filter((jwk2) => {
+ let candidate = kty === jwk2.kty;
+ if (candidate && typeof kid === "string") {
+ candidate = kid === jwk2.kid;
+ }
+ if (candidate && typeof jwk2.alg === "string") {
+ candidate = alg === jwk2.alg;
+ }
+ if (candidate && typeof jwk2.use === "string") {
+ candidate = jwk2.use === "sig";
+ }
+ if (candidate && Array.isArray(jwk2.key_ops)) {
+ candidate = jwk2.key_ops.includes("verify");
+ }
+ if (candidate) {
+ switch (alg) {
+ case "ES256":
+ candidate = jwk2.crv === "P-256";
+ break;
+ case "ES384":
+ candidate = jwk2.crv === "P-384";
+ break;
+ case "ES512":
+ candidate = jwk2.crv === "P-521";
+ break;
+ case "Ed25519":
+ case "EdDSA":
+ candidate = jwk2.crv === "Ed25519";
+ break;
+ }
+ }
+ return candidate;
+ });
+ const { 0: jwk, length } = candidates;
+ if (length === 0) {
+ throw new JWKSNoMatchingKey();
+ }
+ if (length !== 1) {
+ const error = new JWKSMultipleMatchingKeys();
+ const { _cached } = this;
+ error[Symbol.asyncIterator] = async function* () {
+ for (const jwk2 of candidates) {
+ try {
+ yield await importWithAlgCache(_cached, jwk2, alg);
+ } catch {
+ }
+ }
+ };
+ throw error;
+ }
+ return importWithAlgCache(this._cached, jwk, alg);
+ }
+ };
+ async function importWithAlgCache(cache2, jwk, alg) {
+ const cached = cache2.get(jwk) || cache2.set(jwk, {}).get(jwk);
+ if (cached[alg] === void 0) {
+ const key = await importJWK({ ...jwk, ext: true }, alg);
+ if (key instanceof Uint8Array || key.type !== "public") {
+ throw new JWKSInvalid("JSON Web Key Set members must be public keys");
+ }
+ cached[alg] = key;
+ }
+ return cached[alg];
+ }
+ function createLocalJWKSet(jwks) {
+ const set = new LocalJWKSet(jwks);
+ const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
+ Object.defineProperties(localJWKSet, {
+ jwks: {
+ value: () => clone(set._jwks),
+ enumerable: true,
+ configurable: false,
+ writable: false
+ }
+ });
+ return localJWKSet;
+ }
+
+ // dist/webapi/jwks/remote.js
+ function isCloudflareWorkers() {
+ return typeof WebSocketPair !== "undefined" || typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" || typeof EdgeRuntime !== "undefined" && EdgeRuntime === "vercel";
+ }
+ var USER_AGENT;
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
+ const NAME = "jose";
+ const VERSION = "v6.0.1";
+ USER_AGENT = `${NAME}/${VERSION}`;
+ }
+ var customFetch = Symbol();
+ async function fetchJwks(url, options) {
+ const response = await (options?.[customFetch] || fetch)(url, {
+ method: "GET",
+ signal: options.signal,
+ redirect: "manual",
+ headers: options.headers
+ }).catch((err) => {
+ if (err.name === "TimeoutError") {
+ throw new JWKSTimeout();
+ }
+ throw err;
+ });
+ if (response.status !== 200) {
+ throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");
+ }
+ try {
+ return await response.json();
+ } catch {
+ throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON");
+ }
+ }
+ var jwksCache = Symbol();
+ function isFreshJwksCache(input, cacheMaxAge) {
+ if (typeof input !== "object" || input === null) {
+ return false;
+ }
+ if (!("uat" in input) || typeof input.uat !== "number" || Date.now() - input.uat >= cacheMaxAge) {
+ return false;
+ }
+ if (!("jwks" in input) || !is_object_default(input.jwks) || !Array.isArray(input.jwks.keys) || !Array.prototype.every.call(input.jwks.keys, is_object_default)) {
+ return false;
+ }
+ return true;
+ }
+ var RemoteJWKSet = class {
+ _url;
+ _timeoutDuration;
+ _cooldownDuration;
+ _cacheMaxAge;
+ _jwksTimestamp;
+ _pendingFetch;
+ _options;
+ _local;
+ _cache;
+ constructor(url, options) {
+ if (!(url instanceof URL)) {
+ throw new TypeError("url must be an instance of URL");
+ }
+ this._url = new URL(url.href);
+ this._options = { headers: options?.headers };
+ this._timeoutDuration = typeof options?.timeoutDuration === "number" ? options?.timeoutDuration : 5e3;
+ this._cooldownDuration = typeof options?.cooldownDuration === "number" ? options?.cooldownDuration : 3e4;
+ this._cacheMaxAge = typeof options?.cacheMaxAge === "number" ? options?.cacheMaxAge : 6e5;
+ if (options?.[jwksCache] !== void 0) {
+ this._cache = options?.[jwksCache];
+ if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) {
+ this._jwksTimestamp = this._cache.uat;
+ this._local = createLocalJWKSet(this._cache.jwks);
+ }
+ }
+ }
+ coolingDown() {
+ return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cooldownDuration : false;
+ }
+ fresh() {
+ return typeof this._jwksTimestamp === "number" ? Date.now() < this._jwksTimestamp + this._cacheMaxAge : false;
+ }
+ async getKey(protectedHeader, token) {
+ if (!this._local || !this.fresh()) {
+ await this.reload();
+ }
+ try {
+ return await this._local(protectedHeader, token);
+ } catch (err) {
+ if (err instanceof JWKSNoMatchingKey) {
+ if (this.coolingDown() === false) {
+ await this.reload();
+ return this._local(protectedHeader, token);
+ }
+ }
+ throw err;
+ }
+ }
+ async reload() {
+ if (this._pendingFetch && isCloudflareWorkers()) {
+ this._pendingFetch = void 0;
+ }
+ const headers = new Headers(this._options.headers);
+ if (USER_AGENT && !headers.has("User-Agent")) {
+ headers.set("User-Agent", USER_AGENT);
+ this._options.headers = Object.fromEntries(headers.entries());
+ }
+ if (!headers.has("accept")) {
+ headers.set("accept", "application/json");
+ headers.append("accept", "application/jwk-set+json");
+ }
+ this._pendingFetch ||= fetchJwks(this._url.href, {
+ headers,
+ signal: AbortSignal.timeout(this._timeoutDuration)
+ }).then((json) => {
+ this._local = createLocalJWKSet(json);
+ if (this._cache) {
+ this._cache.uat = Date.now();
+ this._cache.jwks = json;
+ }
+ this._jwksTimestamp = Date.now();
+ this._pendingFetch = void 0;
+ }).catch((err) => {
+ this._pendingFetch = void 0;
+ throw err;
+ });
+ await this._pendingFetch;
+ }
+ };
+ function createRemoteJWKSet(url, options) {
+ const set = new RemoteJWKSet(url, options);
+ const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
+ Object.defineProperties(remoteJWKSet, {
+ coolingDown: {
+ get: () => set.coolingDown(),
+ enumerable: true,
+ configurable: false
+ },
+ fresh: {
+ get: () => set.fresh(),
+ enumerable: true,
+ configurable: false
+ },
+ reload: {
+ value: () => set.reload(),
+ enumerable: true,
+ configurable: false,
+ writable: false
+ },
+ reloading: {
+ get: () => !!set._pendingFetch,
+ enumerable: true,
+ configurable: false
+ },
+ jwks: {
+ value: () => set._local?.jwks(),
+ enumerable: true,
+ configurable: false,
+ writable: false
+ }
+ });
+ return remoteJWKSet;
+ }
+
+ // dist/webapi/jwt/unsecured.js
+ var UnsecuredJWT = class extends ProduceJWT {
+ encode() {
+ const header = encode(JSON.stringify({ alg: "none" }));
+ const payload = encode(JSON.stringify(this._payload));
+ return `${header}.${payload}.`;
+ }
+ static decode(jwt, options) {
+ if (typeof jwt !== "string") {
+ throw new JWTInvalid("Unsecured JWT must be a string");
+ }
+ const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split(".");
+ if (length !== 3 || signature !== "") {
+ throw new JWTInvalid("Invalid Unsecured JWT");
+ }
+ let header;
+ try {
+ header = JSON.parse(decoder.decode(decode(encodedHeader)));
+ if (header.alg !== "none")
+ throw new Error();
+ } catch {
+ throw new JWTInvalid("Invalid Unsecured JWT");
+ }
+ const payload = jwt_claims_set_default(header, decode(encodedPayload), options);
+ return { payload, header };
+ }
+ };
+
+ // dist/webapi/util/base64url.js
+ var base64url_exports2 = {};
+ __export(base64url_exports2, {
+ decode: () => decode2,
+ encode: () => encode2
+ });
+ var encode2 = encode;
+ var decode2 = decode;
+
+ // dist/webapi/util/decode_protected_header.js
+ function decodeProtectedHeader(token) {
+ let protectedB64u;
+ if (typeof token === "string") {
+ const parts = token.split(".");
+ if (parts.length === 3 || parts.length === 5) {
+ [protectedB64u] = parts;
+ }
+ } else if (typeof token === "object" && token) {
+ if ("protected" in token) {
+ protectedB64u = token.protected;
+ } else {
+ throw new TypeError("Token does not contain a Protected Header");
+ }
+ }
+ try {
+ if (typeof protectedB64u !== "string" || !protectedB64u) {
+ throw new Error();
+ }
+ const result = JSON.parse(decoder.decode(decode2(protectedB64u)));
+ if (!is_object_default(result)) {
+ throw new Error();
+ }
+ return result;
+ } catch {
+ throw new TypeError("Invalid Token or Protected Header formatting");
+ }
+ }
+
+ // dist/webapi/util/decode_jwt.js
+ function decodeJwt(jwt) {
+ if (typeof jwt !== "string")
+ throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");
+ const { 1: payload, length } = jwt.split(".");
+ if (length === 5)
+ throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");
+ if (length !== 3)
+ throw new JWTInvalid("Invalid JWT");
+ if (!payload)
+ throw new JWTInvalid("JWTs must contain a payload");
+ let decoded;
+ try {
+ decoded = decode2(payload);
+ } catch {
+ throw new JWTInvalid("Failed to base64url decode the payload");
+ }
+ let result;
+ try {
+ result = JSON.parse(decoder.decode(decoded));
+ } catch {
+ throw new JWTInvalid("Failed to parse the decoded payload as JSON");
+ }
+ if (!is_object_default(result))
+ throw new JWTInvalid("Invalid JWT Claims Set");
+ return result;
+ }
+
+ // dist/webapi/key/generate_key_pair.js
+ function getModulusLengthOption(options) {
+ const modulusLength = options?.modulusLength ?? 2048;
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
+ throw new JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");
+ }
+ return modulusLength;
+ }
+ async function generateKeyPair(alg, options) {
+ let algorithm;
+ let keyUsages;
+ switch (alg) {
+ case "PS256":
+ case "PS384":
+ case "PS512":
+ algorithm = {
+ name: "RSA-PSS",
+ hash: `SHA-${alg.slice(-3)}`,
+ publicExponent: new Uint8Array([1, 0, 1]),
+ modulusLength: getModulusLengthOption(options)
+ };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "RS256":
+ case "RS384":
+ case "RS512":
+ algorithm = {
+ name: "RSASSA-PKCS1-v1_5",
+ hash: `SHA-${alg.slice(-3)}`,
+ publicExponent: new Uint8Array([1, 0, 1]),
+ modulusLength: getModulusLengthOption(options)
+ };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "RSA-OAEP":
+ case "RSA-OAEP-256":
+ case "RSA-OAEP-384":
+ case "RSA-OAEP-512":
+ algorithm = {
+ name: "RSA-OAEP",
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
+ publicExponent: new Uint8Array([1, 0, 1]),
+ modulusLength: getModulusLengthOption(options)
+ };
+ keyUsages = ["decrypt", "unwrapKey", "encrypt", "wrapKey"];
+ break;
+ case "ES256":
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "ES384":
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "ES512":
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "Ed25519":
+ case "EdDSA": {
+ keyUsages = ["sign", "verify"];
+ algorithm = { name: "Ed25519" };
+ break;
+ }
+ case "ECDH-ES":
+ case "ECDH-ES+A128KW":
+ case "ECDH-ES+A192KW":
+ case "ECDH-ES+A256KW": {
+ keyUsages = ["deriveBits"];
+ const crv = options?.crv ?? "P-256";
+ switch (crv) {
+ case "P-256":
+ case "P-384":
+ case "P-521": {
+ algorithm = { name: "ECDH", namedCurve: crv };
+ break;
+ }
+ case "X25519":
+ algorithm = { name: "X25519" };
+ break;
+ default:
+ throw new JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519");
+ }
+ break;
+ }
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
+ }
+
+ // dist/webapi/key/generate_secret.js
+ async function generateSecret(alg, options) {
+ let length;
+ let algorithm;
+ let keyUsages;
+ switch (alg) {
+ case "HS256":
+ case "HS384":
+ case "HS512":
+ length = parseInt(alg.slice(-3), 10);
+ algorithm = { name: "HMAC", hash: `SHA-${length}`, length };
+ keyUsages = ["sign", "verify"];
+ break;
+ case "A128CBC-HS256":
+ case "A192CBC-HS384":
+ case "A256CBC-HS512":
+ length = parseInt(alg.slice(-3), 10);
+ return crypto.getRandomValues(new Uint8Array(length >> 3));
+ case "A128KW":
+ case "A192KW":
+ case "A256KW":
+ length = parseInt(alg.slice(1, 4), 10);
+ algorithm = { name: "AES-KW", length };
+ keyUsages = ["wrapKey", "unwrapKey"];
+ break;
+ case "A128GCMKW":
+ case "A192GCMKW":
+ case "A256GCMKW":
+ case "A128GCM":
+ case "A192GCM":
+ case "A256GCM":
+ length = parseInt(alg.slice(1, 4), 10);
+ algorithm = { name: "AES-GCM", length };
+ keyUsages = ["encrypt", "decrypt"];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
+ }
+
+ // dist/webapi/index.js
+ var cryptoRuntime = "WebCryptoAPI";
+
+ exports.CompactEncrypt = CompactEncrypt;
+ exports.CompactSign = CompactSign;
+ exports.EmbeddedJWK = EmbeddedJWK;
+ exports.EncryptJWT = EncryptJWT;
+ exports.FlattenedEncrypt = FlattenedEncrypt;
+ exports.FlattenedSign = FlattenedSign;
+ exports.GeneralEncrypt = GeneralEncrypt;
+ exports.GeneralSign = GeneralSign;
+ exports.SignJWT = SignJWT;
+ exports.UnsecuredJWT = UnsecuredJWT;
+ exports.base64url = base64url_exports2;
+ exports.calculateJwkThumbprint = calculateJwkThumbprint;
+ exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri;
+ exports.compactDecrypt = compactDecrypt;
+ exports.compactVerify = compactVerify;
+ exports.createLocalJWKSet = createLocalJWKSet;
+ exports.createRemoteJWKSet = createRemoteJWKSet;
+ exports.cryptoRuntime = cryptoRuntime;
+ exports.decodeJwt = decodeJwt;
+ exports.decodeProtectedHeader = decodeProtectedHeader;
+ exports.errors = errors_exports;
+ exports.exportJWK = exportJWK;
+ exports.exportPKCS8 = exportPKCS8;
+ exports.exportSPKI = exportSPKI;
+ exports.flattenedDecrypt = flattenedDecrypt;
+ exports.flattenedVerify = flattenedVerify;
+ exports.generalDecrypt = generalDecrypt;
+ exports.generalVerify = generalVerify;
+ exports.generateKeyPair = generateKeyPair;
+ exports.generateSecret = generateSecret;
+ exports.importJWK = importJWK;
+ exports.importPKCS8 = importPKCS8;
+ exports.importSPKI = importSPKI;
+ exports.importX509 = importX509;
+ exports.jwksCache = jwksCache;
+ exports.jwtDecrypt = jwtDecrypt;
+ exports.jwtVerify = jwtVerify;
+
+}));
diff --git a/dist/webapi/index.umd.min.js b/dist/webapi/index.umd.min.js
new file mode 100644
index 0000000000..a12d14e987
--- /dev/null
+++ b/dist/webapi/index.umd.min.js
@@ -0,0 +1,5 @@
+(function(g,f){typeof exports==='object'&&typeof module!=='undefined'?f(exports):typeof define==='function'&&define.amd?define(['exports'],f):(g=typeof globalThis!=='undefined'?globalThis:g||self,f(g.jose={}));})(this,(function(exports){'use strict';var tr=Object.defineProperty;var ht=(e,t)=>{for(var r in t)tr(e,r,{get:t[r],enumerable:true});};var m=new TextEncoder,b=new TextDecoder,_e=2**32,I=globalThis.process?.getBuiltinModule?.("node:buffer")?.Buffer;function x(...e){if(I)return I.concat(e);let t=e.reduce((o,{length:a})=>o+a,0),r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.length;return r}function Ge(e,t,r){if(t<0||t>=_e)throw new RangeError(`value must be >= 0 and <= ${_e-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r);}function He(e){let t=Math.floor(e/_e),r=e%_e,n=new Uint8Array(8);return Ge(n,t,0),Ge(n,r,4),n}function xe(e){let t=new Uint8Array(4);return Ge(t,e),t}function Ce(e){if(I)return I.from(e).toString("base64");let t=e;typeof t=="string"&&(t=m.encode(t));let r=32768,n=[];for(let o=0;oL,JOSEError:()=>_,JOSENotSupported:()=>f,JWEDecryptionFailed:()=>N,JWEInvalid:()=>c,JWKInvalid:()=>pe,JWKSInvalid:()=>ae,JWKSMultipleMatchingKeys:()=>fe,JWKSNoMatchingKey:()=>V,JWKSTimeout:()=>ue,JWSInvalid:()=>h,JWSSignatureVerificationFailed:()=>z,JWTClaimValidationFailed:()=>C,JWTExpired:()=>oe,JWTInvalid:()=>K});var _=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor);}},C=class extends _{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r;}},oe=class extends _{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,r,n="unspecified",o="unspecified"){super(t,{cause:{claim:n,reason:o,payload:r}}),this.claim=n,this.reason=o,this.payload=r;}},L=class extends _{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"},f=class extends _{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"},N=class extends _{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(t="decryption operation failed",r){super(t,r);}},c=class extends _{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"},h=class extends _{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},K=class extends _{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"},pe=class extends _{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"},ae=class extends _{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"},V=class extends _{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",r){super(t,r);}},fe=class extends _{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",r){super(t,r);}},ue=class extends _{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(t="request timed out",r){super(t,r);}},z=class extends _{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",r){super(t,r);}};function Ve(e){switch(e){case "A128GCM":case "A128GCMKW":case "A192GCM":case "A192GCMKW":case "A256GCM":case "A256GCMKW":return 96;case "A128CBC-HS256":case "A192CBC-HS384":case "A256CBC-HS512":return 128;default:throw new f(`Unsupported JWE Algorithm: ${e}`)}}var mt=e=>crypto.getRandomValues(new Uint8Array(Ve(e)>>3));var We=(e,t)=>{if(t.length<<3!==Ve(e))throw new c("Invalid Initialization Vector length")};var ie=(e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new c(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)};function P(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function B(e,t){return e.name===t}function ve(e){return parseInt(e.name.slice(4),10)}function rr(e){switch(e){case "ES256":return "P-256";case "ES384":return "P-384";case "ES512":return "P-521";default:throw new Error("unreachable")}}function yt(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function wt(e,t,r){switch(t){case "HS256":case "HS384":case "HS512":{if(!B(e.algorithm,"HMAC"))throw P("HMAC");let n=parseInt(t.slice(2),10);if(ve(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case "RS256":case "RS384":case "RS512":{if(!B(e.algorithm,"RSASSA-PKCS1-v1_5"))throw P("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(ve(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case "PS256":case "PS384":case "PS512":{if(!B(e.algorithm,"RSA-PSS"))throw P("RSA-PSS");let n=parseInt(t.slice(2),10);if(ve(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}case "Ed25519":case "EdDSA":{if(!B(e.algorithm,"Ed25519"))throw P("Ed25519");break}case "ES256":case "ES384":case "ES512":{if(!B(e.algorithm,"ECDSA"))throw P("ECDSA");let n=rr(t);if(e.algorithm.namedCurve!==n)throw P(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}yt(e,r);}function W(e,t,r){switch(t){case "A128GCM":case "A192GCM":case "A256GCM":{if(!B(e.algorithm,"AES-GCM"))throw P("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw P(n,"algorithm.length");break}case "A128KW":case "A192KW":case "A256KW":{if(!B(e.algorithm,"AES-KW"))throw P("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw P(n,"algorithm.length");break}case "ECDH":{switch(e.algorithm.name){case "ECDH":case "X25519":break;default:throw P("ECDH or X25519")}break}case "PBES2-HS256+A128KW":case "PBES2-HS384+A192KW":case "PBES2-HS512+A256KW":if(!B(e.algorithm,"PBKDF2"))throw P("PBKDF2");break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":{if(!B(e.algorithm,"RSA-OAEP"))throw P("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(ve(e.algorithm.hash)!==n)throw P(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}yt(e,r);}function Et(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`;}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var v=(e,...t)=>Et("Key must be ",e,...t);function ze(e,t,...r){return Et(`Key for the ${e} algorithm must be `,t,...r)}function X(e){if(!J(e))throw new Error("CryptoKey instance expected")}function J(e){return e?.[Symbol.toStringTag]==="CryptoKey"}function Y(e){return e?.[Symbol.toStringTag]==="KeyObject"}var he=e=>J(e)||Y(e);var St=globalThis.process?.getBuiltinModule?.("node:crypto")?.timingSafeEqual;St||=(e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");let r=e.length,n=0,o=-1;for(;++o>3),"AES-CBC",false,["decrypt"]),d=await crypto.subtle.importKey("raw",t.subarray(0,i>>3),{hash:`SHA-${i<<1}`,name:"HMAC"},false,["sign"]),p=x(a,n,r,He(a.length<<3)),u=new Uint8Array((await crypto.subtle.sign("HMAC",d,p)).slice(0,i>>3)),w;try{w=St(o,u);}catch{}if(!w)throw new N;let g;try{g=new Uint8Array(await crypto.subtle.decrypt({iv:n,name:"AES-CBC"},s,r));}catch{}if(!g)throw new N;return g}async function or(e,t,r,n,o,a){let i;t instanceof Uint8Array?i=await crypto.subtle.importKey("raw",t,"AES-GCM",false,["decrypt"]):(W(t,e,"decrypt"),i=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:a,iv:n,name:"AES-GCM",tagLength:128},i,x(r,o)))}catch{throw new N}}var Je=async(e,t,r,n,o,a)=>{if(!J(t)&&!(t instanceof Uint8Array))throw new TypeError(v(t,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));if(!n)throw new c("JWE Initialization Vector missing");if(!o)throw new c("JWE Authentication Tag missing");switch(We(e,n),e){case "A128CBC-HS256":case "A192CBC-HS384":case "A256CBC-HS512":return t instanceof Uint8Array&&ie(t,parseInt(e.slice(-3),10)),nr(e,t,r,n,o,a);case "A128GCM":case "A192GCM":case "A256GCM":return t instanceof Uint8Array&&ie(t,parseInt(e.slice(1,4),10)),or(e,t,r,n,o,a);default:throw new f("Unsupported JWE Content Encryption Algorithm")}};var R=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return true;let r;for(let n of t){let o=Object.keys(n);if(!r||r.size===0){r=new Set(o);continue}for(let a of o){if(r.has(a))return false;r.add(a);}}return true};function ar(e){return typeof e=="object"&&e!==null}var l=e=>{if(!ar(e)||Object.prototype.toString.call(e)!=="[object Object]")return false;if(Object.getPrototypeOf(e)===null)return true;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t};function gt(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function At(e,t,r){return e instanceof Uint8Array?crypto.subtle.importKey("raw",e,"AES-KW",true,[r]):(W(e,t,r),e)}async function le(e,t,r){let n=await At(t,e,"wrapKey");gt(n,e);let o=await crypto.subtle.importKey("raw",r,{hash:"SHA-256",name:"HMAC"},true,["sign"]);return new Uint8Array(await crypto.subtle.wrapKey("raw",o,n,"AES-KW"))}async function me(e,t,r){let n=await At(t,e,"unwrapKey");gt(n,e);let o=await crypto.subtle.unwrapKey("raw",r,n,"AES-KW",{hash:"SHA-256",name:"HMAC"},true,["sign"]);return new Uint8Array(await crypto.subtle.exportKey("raw",o))}var Te=async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(r,t))};function Ye(e){return x(xe(e.length),e)}async function ir(e,t,r){let n=Math.ceil((t>>3)/32),o=new Uint8Array(n*32);for(let a=0;a>3)}async function Ie(e,t,r,n,o=new Uint8Array(0),a=new Uint8Array(0)){W(e,"ECDH"),W(t,"ECDH","deriveBits");let i=x(Ye(m.encode(r)),Ye(o),Ye(a),xe(n)),s;e.algorithm.name==="X25519"?s=256:s=Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3;let d=new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,s));return ir(d,n,i)}function Re(e){switch(e.algorithm.namedCurve){case "P-256":case "P-384":case "P-521":return true;default:return e.algorithm.name==="X25519"}}function sr(e,t){return e instanceof Uint8Array?crypto.subtle.importKey("raw",e,"PBKDF2",false,["deriveBits"]):(W(e,t,"deriveBits"),e)}var cr=(e,t)=>x(m.encode(e),new Uint8Array([0]),t);async function Kt(e,t,r,n){if(!(e instanceof Uint8Array)||e.length<8)throw new c("PBES2 Salt Input must be 8 or more octets");let o=cr(t,e),a=parseInt(t.slice(13,16),10),i={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:o},s=await sr(n,t);return new Uint8Array(await crypto.subtle.deriveBits(i,s,a))}async function _t(e,t,r,n=2048,o=crypto.getRandomValues(new Uint8Array(16))){let a=await Kt(o,e,n,t);return {encryptedKey:await le(e.slice(-6),a,r),p2c:n,p2s:y(o)}}async function Ht(e,t,r,n,o){let a=await Kt(o,e,n,t);return me(e.slice(-6),a,r)}var q=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};var Ct=e=>{switch(e){case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":return "RSA-OAEP";default:throw new f(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};async function Pt(e,t,r){return W(t,e,"encrypt"),q(e,t),new Uint8Array(await crypto.subtle.encrypt(Ct(e),t,r))}async function Wt(e,t,r){return W(t,e,"decrypt"),q(e,t),new Uint8Array(await crypto.subtle.decrypt(Ct(e),t,r))}function ye(e){switch(e){case "A128GCM":return 128;case "A192GCM":return 192;case "A256GCM":case "A128CBC-HS256":return 256;case "A192CBC-HS384":return 384;case "A256CBC-HS512":return 512;default:throw new f(`Unsupported JWE Algorithm: ${e}`)}}var O=e=>crypto.getRandomValues(new Uint8Array(ye(e)>>3));var It=(e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(`
+`);return `-----BEGIN ${t}-----
+${r}
+-----END ${t}-----`},Rt=async(e,t,r)=>{if(Y(r)){if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return r.export({format:"pem",type:t})}if(!J(r))throw new TypeError(v(r,"CryptoKey","KeyObject"));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return It(Ce(new Uint8Array(await crypto.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},Ot=e=>Rt("public","spki",e),Dt=e=>Rt("private","pkcs8",e),Oe=(e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return false;let o=e.subarray(n,n+t.length);return o.length!==t.length?false:o.every((a,i)=>a===t[i])||Oe(e,t,n+1)},dr=e=>{switch(true){case Oe(e,[42,134,72,206,61,3,1,7]):return "P-256";case Oe(e,[43,129,4,0,34]):return "P-384";case Oe(e,[43,129,4,0,35]):return "P-521";default:return}},Ut=async(e,t,r,n,o)=>{let a,i,s=new Uint8Array(atob(r.replace(e,"")).split("").map(p=>p.charCodeAt(0))),d=t==="spki";switch(n){case "PS256":case "PS384":case "PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},i=d?["verify"]:["sign"];break;case "RS256":case "RS384":case "RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},i=d?["verify"]:["sign"];break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},i=d?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case "ES256":a={name:"ECDSA",namedCurve:"P-256"},i=d?["verify"]:["sign"];break;case "ES384":a={name:"ECDSA",namedCurve:"P-384"},i=d?["verify"]:["sign"];break;case "ES512":a={name:"ECDSA",namedCurve:"P-521"},i=d?["verify"]:["sign"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":{let p=dr(s);a=p?.startsWith("P-")?{name:"ECDH",namedCurve:p}:{name:"X25519"},i=d?[]:["deriveBits"];break}case "Ed25519":case "EdDSA":a={name:"Ed25519"},i=d?["verify"]:["sign"];break;default:throw new f('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(t,s,a,o?.extractable??!!d,i)},kt=(e,t,r)=>Ut(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),qe=(e,t,r)=>Ut(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r);function Jt(e){let t=[],r=0;for(;r=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++;}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++;}let a=t+n+2;return {byteLength:a,contents:e.subarray(t,t+n),raw:e.subarray(0,a)}}else {let a=e[t]&127;t++,n=0;for(let i=0;i{let n;try{n=fr(e);}catch(o){throw new TypeError("Failed to parse the X.509 certificate",{cause:o})}return qe(n,t,r)};function ur(e){let t,r;switch(e.kty){case "RSA":{switch(e.alg){case "PS256":case "PS384":case "PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case "RS256":case "RS384":case "RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case "EC":{switch(e.alg){case "ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case "ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case "ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case "OKP":{switch(e.alg){case "Ed25519":case "EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new f('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return {algorithm:t,keyUsages:r}}var De=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=ur(e),n={...e};return delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!e.d,e.key_ops??r)};async function hr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return qe(e,t,r)}async function lr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Nt(e,t,r)}async function mr(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return kt(e,t,r)}async function Z(e,t,r){if(!l(e))throw new TypeError("JWK must be an object");let n;switch(t??=e.alg,n??=r?.extractable??e.ext,e.kty){case "oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return S(e.k);case "RSA":if("oth"in e&&e.oth!==void 0)throw new f('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case "EC":case "OKP":return De({...e,alg:t,ext:n});default:throw new f('Unsupported "kty" (Key Type) Parameter value')}}async function yr(e,t,r,n,o){if(!(r instanceof Uint8Array))throw new TypeError(v(r,"Uint8Array"));let a=parseInt(e.slice(1,4),10),i=await crypto.subtle.importKey("raw",r.subarray(a>>3),"AES-CBC",false,["encrypt"]),s=await crypto.subtle.importKey("raw",r.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},false,["sign"]),d=new Uint8Array(await crypto.subtle.encrypt({iv:n,name:"AES-CBC"},i,t)),p=x(o,n,d,He(o.length<<3)),u=new Uint8Array((await crypto.subtle.sign("HMAC",s,p)).slice(0,a>>3));return {ciphertext:d,tag:u,iv:n}}async function wr(e,t,r,n,o){let a;r instanceof Uint8Array?a=await crypto.subtle.importKey("raw",r,"AES-GCM",false,["encrypt"]):(W(r,e,"encrypt"),a=r);let i=new Uint8Array(await crypto.subtle.encrypt({additionalData:o,iv:n,name:"AES-GCM",tagLength:128},a,t)),s=i.slice(-16);return {ciphertext:i.slice(0,-16),tag:s,iv:n}}var Ue=async(e,t,r,n,o)=>{if(!J(r)&&!(r instanceof Uint8Array))throw new TypeError(v(r,"CryptoKey","KeyObject","Uint8Array","JSON Web Key"));switch(n?We(e,n):n=mt(e),e){case "A128CBC-HS256":case "A192CBC-HS384":case "A256CBC-HS512":return r instanceof Uint8Array&&ie(r,parseInt(e.slice(-3),10)),yr(e,t,r,n,o);case "A128GCM":case "A192GCM":case "A256GCM":return r instanceof Uint8Array&&ie(r,parseInt(e.slice(1,4),10)),wr(e,t,r,n,o);default:throw new f("Unsupported JWE Content Encryption Algorithm")}};async function Bt(e,t,r,n){let o=e.slice(0,7),a=await Ue(o,r,t,n,new Uint8Array(0));return {encryptedKey:a.ciphertext,iv:y(a.iv),tag:y(a.tag)}}async function Lt(e,t,r,n,o){let a=e.slice(0,7);return Je(a,t,r,n,o,new Uint8Array(0))}var $t=async(e,t,r,n,o)=>{switch(e){case "dir":{if(r!==void 0)throw new c("Encountered unexpected JWE Encrypted Key");return t}case "ECDH-ES":if(r!==void 0)throw new c("Encountered unexpected JWE Encrypted Key");case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":{if(!l(n.epk))throw new c('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(X(t),!Re(t))throw new f("ECDH with the provided key is not allowed or not supported by your javascript runtime");let a=await Z(n.epk,e);X(a);let i,s;if(n.apu!==void 0){if(typeof n.apu!="string")throw new c('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{i=S(n.apu);}catch{throw new c("Failed to base64url decode the apu")}}if(n.apv!==void 0){if(typeof n.apv!="string")throw new c('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{s=S(n.apv);}catch{throw new c("Failed to base64url decode the apv")}}let d=await Ie(a,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?ye(n.enc):parseInt(e.slice(-5,-2),10),i,s);if(e==="ECDH-ES")return d;if(r===void 0)throw new c("JWE Encrypted Key missing");return me(e.slice(-6),d,r)}case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":{if(r===void 0)throw new c("JWE Encrypted Key missing");return X(t),Wt(e,t,r)}case "PBES2-HS256+A128KW":case "PBES2-HS384+A192KW":case "PBES2-HS512+A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new c('JOSE Header "p2c" (PBES2 Count) missing or invalid');let a=o?.maxPBES2Count||1e4;if(n.p2c>a)throw new c('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new c('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let i;try{i=S(n.p2s);}catch{throw new c("Failed to base64url decode the p2s")}return Ht(e,t,r,n.p2c,i)}case "A128KW":case "A192KW":case "A256KW":{if(r===void 0)throw new c("JWE Encrypted Key missing");return me(e,t,r)}case "A128GCMKW":case "A192GCMKW":case "A256GCMKW":{if(r===void 0)throw new c("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new c('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new c('JOSE Header "tag" (Authentication Tag) missing or invalid');let a;try{a=S(n.iv);}catch{throw new c("Failed to base64url decode the iv")}let i;try{i=S(n.tag);}catch{throw new c("Failed to base64url decode the tag")}return Lt(e,t,r,a,i)}default:throw new f('Invalid or unsupported "alg" (JWE Algorithm) header value')}};var D=(e,t,r,n,o)=>{if(o.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let i of n.crit){if(!a.has(i))throw new f(`Extension Header Parameter "${i}" is not recognized`);if(o[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(a.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)};var we=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};function Q(e){return l(e)&&typeof e.kty=="string"}function Gt(e){return e.kty!=="oct"&&typeof e.d=="string"}function Ft(e){return e.kty!=="oct"&&typeof e.d>"u"}function Vt(e){return e.kty==="oct"&&typeof e.k=="string"}var se,zt=async(e,t,r,n=false)=>{se||=new WeakMap;let o=se.get(e);if(o?.[r])return o[r];let a=await De({...t,alg:r});return n&&Object.freeze(e),o?o[r]=a:se.set(e,{[r]:a}),a},Sr=(e,t)=>{se||=new WeakMap;let r=se.get(e);if(r?.[t])return r[t];let n=e.type==="public",o=!!n,a;if(e.asymmetricKeyType==="x25519"){switch(t){case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}a=e.toCryptoKey(e.asymmetricKeyType,o,n?[]:["deriveBits"]);}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");a=e.toCryptoKey(e.asymmetricKeyType,o,[n?"verify":"sign"]);}if(e.asymmetricKeyType==="rsa"){let i;switch(t){case "RSA-OAEP":i="SHA-1";break;case "RS256":case "PS256":case "RSA-OAEP-256":i="SHA-256";break;case "RS384":case "PS384":case "RSA-OAEP-384":i="SHA-384";break;case "RS512":case "PS512":case "RSA-OAEP-512":i="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:i},o,n?["encrypt"]:["decrypt"]);a=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},o,[n?"verify":"sign"]);}if(e.asymmetricKeyType==="ec"){let s=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!s)throw new TypeError("given KeyObject instance cannot be used for this algorithm");t==="ES256"&&s==="P-256"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:s},o,[n?"verify":"sign"])),t==="ES384"&&s==="P-384"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:s},o,[n?"verify":"sign"])),t==="ES512"&&s==="P-521"&&(a=e.toCryptoKey({name:"ECDSA",namedCurve:s},o,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(a=e.toCryptoKey({name:"ECDH",namedCurve:s},o,n?[]:["deriveBits"]));}if(!a)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return r?r[t]=a:se.set(e,{[t]:a}),a},T=async(e,t)=>{if(e instanceof Uint8Array||J(e))return e;if(Y(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return Sr(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return zt(e,r,t)}if(Q(e))return e.k?S(e.k):zt(e,e,t,true);throw new Error("unreachable")};var ce=e=>e?.[Symbol.toStringTag],Ze=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case "sign":case "verify":n="sig";break;case "encrypt":case "decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(true){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case /^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===false)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return true},gr=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(Q(t)){if(Vt(t)&&Ze(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!he(t))throw new TypeError(ze(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${ce(t)} instances for symmetric algorithms must be of type "secret"`)}},Ar=(e,t,r)=>{if(Q(t))switch(r){case "decrypt":case "sign":if(Gt(t)&&Ze(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case "encrypt":case "verify":if(Ft(t)&&Ze(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!he(t))throw new TypeError(ze(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${ce(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case "sign":throw new TypeError(`${ce(t)} instances for asymmetric algorithm signing must be of type "private"`);case "decrypt":throw new TypeError(`${ce(t)} instances for asymmetric algorithm decryption must be of type "private"`);}if(t.type==="private")switch(r){case "verify":throw new TypeError(`${ce(t)} instances for asymmetric algorithm verifying must be of type "public"`);case "encrypt":throw new TypeError(`${ce(t)} instances for asymmetric algorithm encryption must be of type "public"`);}},U=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(e)||/^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(e)?gr(e,t,r):Ar(e,t,r);};async function Ee(e,t,r){if(!l(e))throw new c("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new c("JOSE Header missing");if(e.iv!==void 0&&typeof e.iv!="string")throw new c("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new c("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new c("JWE Authentication Tag incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new c("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new c("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new c("JWE AAD incorrect type");if(e.header!==void 0&&!l(e.header))throw new c("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!l(e.unprotected))throw new c("JWE Per-Recipient Unprotected Header incorrect type");let n;if(e.protected)try{let ne=S(e.protected);n=JSON.parse(b.decode(ne));}catch{throw new c("JWE Protected Header is invalid")}if(!R(n,e.header,e.unprotected))throw new c("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let o={...n,...e.header,...e.unprotected};if(D(c,new Map,r?.crit,n,o),o.zip!==void 0)throw new f('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:a,enc:i}=o;if(typeof a!="string"||!a)throw new c("missing JWE Algorithm (alg) in JWE Header");if(typeof i!="string"||!i)throw new c("missing JWE Encryption Algorithm (enc) in JWE Header");let s=r&&we("keyManagementAlgorithms",r.keyManagementAlgorithms),d=r&&we("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(s&&!s.has(a)||!s&&a.startsWith("PBES2"))throw new L('"alg" (Algorithm) Header Parameter value not allowed');if(d&&!d.has(i))throw new L('"enc" (Encryption Algorithm) Header Parameter value not allowed');let p;if(e.encrypted_key!==void 0)try{p=S(e.encrypted_key);}catch{throw new c("Failed to base64url decode the encrypted_key")}let u=false;typeof t=="function"&&(t=await t(n,e),u=true),U(a==="dir"?i:a,t,"decrypt");let w=await T(t,a),g;try{g=await $t(a,w,p,o,r);}catch(ne){if(ne instanceof TypeError||ne instanceof c||ne instanceof f)throw ne;g=O(i);}let A,E;if(e.iv!==void 0)try{A=S(e.iv);}catch{throw new c("Failed to base64url decode the iv")}if(e.tag!==void 0)try{E=S(e.tag);}catch{throw new c("Failed to base64url decode the tag")}let H=m.encode(e.protected??""),M;e.aad!==void 0?M=x(H,m.encode("."),m.encode(e.aad)):M=H;let ut;try{ut=S(e.ciphertext);}catch{throw new c("Failed to base64url decode the ciphertext")}let re={plaintext:await Je(i,g,ut,A,E,M)};if(e.protected!==void 0&&(re.protectedHeader=n),e.aad!==void 0)try{re.additionalAuthenticatedData=S(e.aad);}catch{throw new c("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(re.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(re.unprotectedHeader=e.header),u?{...re,key:w}:re}async function Qe(e,t,r){if(e instanceof Uint8Array&&(e=b.decode(e)),typeof e!="string")throw new c("Compact JWE must be a string or Uint8Array");let{0:n,1:o,2:a,3:i,4:s,length:d}=e.split(".");if(d!==5)throw new c("Invalid Compact JWE");let p=await Ee({ciphertext:i,iv:a||void 0,protected:n,tag:s||void 0,encrypted_key:o||void 0},t,r),u={plaintext:p.plaintext,protectedHeader:p.protectedHeader};return typeof t=="function"?{...u,key:p.key}:u}async function br(e,t,r){if(!l(e))throw new c("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(l))throw new c("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new c("JWE Recipients has no members");for(let n of e.recipients)try{return await Ee({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new N}var ke=Symbol();async function je(e){if(Y(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return {kty:"oct",k:y(e)};if(!J(e))throw new TypeError(v(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:o,...a}=await crypto.subtle.exportKey("jwk",e);return a}async function Kr(e){return Ot(e)}async function _r(e){return Dt(e)}async function Se(e){return je(e)}var Me=async(e,t,r,n,o={})=>{let a,i,s;switch(e){case "dir":{s=r;break}case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":{if(X(r),!Re(r))throw new f("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:d,apv:p}=o,u;o.epk?u=await T(o.epk,e):u=(await crypto.subtle.generateKey(r.algorithm,true,["deriveBits"])).privateKey;let{x:w,y:g,crv:A,kty:E}=await Se(u),H=await Ie(r,u,e==="ECDH-ES"?t:e,e==="ECDH-ES"?ye(t):parseInt(e.slice(-5,-2),10),d,p);if(i={epk:{x:w,crv:A,kty:E}},E==="EC"&&(i.epk.y=g),d&&(i.apu=y(d)),p&&(i.apv=y(p)),e==="ECDH-ES"){s=H;break}s=n||O(t);let M=e.slice(-6);a=await le(M,H,s);break}case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":{s=n||O(t),X(r),a=await Pt(e,r,s);break}case "PBES2-HS256+A128KW":case "PBES2-HS384+A192KW":case "PBES2-HS512+A256KW":{s=n||O(t);let{p2c:d,p2s:p}=o;({encryptedKey:a,...i}=await _t(e,r,s,d,p));break}case "A128KW":case "A192KW":case "A256KW":{s=n||O(t),a=await le(e,r,s);break}case "A128GCMKW":case "A192GCMKW":case "A256GCMKW":{s=n||O(t);let{iv:d}=o;({encryptedKey:a,...i}=await Bt(e,r,s,d));break}default:throw new f('Invalid or unsupported "alg" (JWE Algorithm) header value')}return {cek:s,encryptedKey:a,parameters:i}};var $=class{_plaintext;_protectedHeader;_sharedUnprotectedHeader;_unprotectedHeader;_aad;_cek;_iv;_keyManagementParameters;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t;}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new c("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!R(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new c("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(D(c,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0)throw new f('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:o,enc:a}=n;if(typeof o!="string"||!o)throw new c('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof a!="string"||!a)throw new c('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let i;if(this._cek&&(o==="dir"||o==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${o}`);U(o==="dir"?a:o,t,"encrypt");let s;{let H,M=await T(t,o);(({cek:s,encryptedKey:i,parameters:H}=await Me(o,a,M,this._cek,this._keyManagementParameters))),H&&(r&&ke in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...H}:this.setUnprotectedHeader(H):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...H}:this.setProtectedHeader(H));}let d,p,u;this._protectedHeader?p=m.encode(y(JSON.stringify(this._protectedHeader))):p=m.encode(""),this._aad?(u=y(this._aad),d=x(p,m.encode("."),m.encode(u))):d=p;let{ciphertext:w,tag:g,iv:A}=await Ue(a,this._plaintext,s,this._iv,d),E={ciphertext:y(w)};return A&&(E.iv=y(A)),g&&(E.tag=y(g)),i&&(E.encrypted_key=y(i)),u&&(E.aad=u),this._protectedHeader&&(E.protected=b.decode(p)),this._sharedUnprotectedHeader&&(E.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(E.header=this._unprotectedHeader),E}};var et=class{parent;unprotectedHeader;key;options;constructor(t,r,n){this.parent=t,this.key=r,this.options=n;}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},tt=class{_plaintext;_recipients=[];_protectedHeader;_unprotectedHeader;_aad;constructor(t){this._plaintext=t;}addRecipient(t,r){let n=new et(this,t,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(){if(!this._recipients.length)throw new c("at least one recipient must be added");if(this._recipients.length===1){let[o]=this._recipients,a=await new $(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(o.unprotectedHeader).encrypt(o.key,{...o.options}),i={ciphertext:a.ciphertext,iv:a.iv,recipients:[{}],tag:a.tag};return a.aad&&(i.aad=a.aad),a.protected&&(i.protected=a.protected),a.unprotected&&(i.unprotected=a.unprotected),a.encrypted_key&&(i.recipients[0].encrypted_key=a.encrypted_key),a.header&&(i.recipients[0].header=a.header),i}let t;for(let o=0;o{let r=`SHA-${e.slice(-3)}`;switch(e){case "HS256":case "HS384":case "HS512":return {hash:r,name:"HMAC"};case "PS256":case "PS384":case "PS512":return {hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case "RS256":case "RS384":case "RS512":return {hash:r,name:"RSASSA-PKCS1-v1_5"};case "ES256":case "ES384":case "ES512":return {hash:r,name:"ECDSA",namedCurve:t.namedCurve};case "Ed25519":case "EdDSA":return {name:"Ed25519"};default:throw new f(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};var Be=async(e,t,r)=>{if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(v(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},false,[r])}return wt(t,e,r),t};var Xt=async(e,t,r,n)=>{let o=await Be(e,t,"verify");q(e,o);let a=Ne(e,o.algorithm);try{return await crypto.subtle.verify(a,o,r,n)}catch{return false}};async function ge(e,t,r){if(!l(e))throw new h("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new h('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new h("JWS Protected Header incorrect type");if(e.payload===void 0)throw new h("JWS Payload missing");if(typeof e.signature!="string")throw new h("JWS Signature missing or incorrect type");if(e.header!==void 0&&!l(e.header))throw new h("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{let M=S(e.protected);n=JSON.parse(b.decode(M));}catch{throw new h("JWS Protected Header is invalid")}if(!R(n,e.header))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...n,...e.header},a=D(h,new Map([["b64",true]]),r?.crit,n,o),i=true;if(a.has("b64")&&(i=n.b64,typeof i!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');let d=r&&we("algorithms",r.algorithms);if(d&&!d.has(s))throw new L('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof e.payload!="string")throw new h("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new h("JWS Payload must be a string or an Uint8Array instance");let p=false;typeof t=="function"&&(t=await t(n,e),p=true),U(s,t,"verify");let u=x(m.encode(e.protected??""),m.encode("."),typeof e.payload=="string"?m.encode(e.payload):e.payload),w;try{w=S(e.signature);}catch{throw new h("Failed to base64url decode the signature")}let g=await T(t,s);if(!await Xt(s,g,w,u))throw new z;let E;if(i)try{E=S(e.payload);}catch{throw new h("Failed to base64url decode the payload")}else typeof e.payload=="string"?E=m.encode(e.payload):E=e.payload;let H={payload:E};return e.protected!==void 0&&(H.protectedHeader=n),e.header!==void 0&&(H.unprotectedHeader=e.header),p?{...H,key:g}:H}async function rt(e,t,r){if(e instanceof Uint8Array&&(e=b.decode(e)),typeof e!="string")throw new h("Compact JWS must be a string or Uint8Array");let{0:n,1:o,2:a,length:i}=e.split(".");if(i!==3)throw new h("Invalid Compact JWS");let s=await ge({payload:o,protected:n,signature:a},t,r),d={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t=="function"?{...d,key:s.key}:d}async function Hr(e,t,r){if(!l(e))throw new h("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(l))throw new h("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await ge({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new z}var k=e=>Math.floor(e.getTime()/1e3);var xr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,j=e=>{let t=xr.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),o;switch(n){case "sec":case "secs":case "second":case "seconds":case "s":o=Math.round(r);break;case "minute":case "minutes":case "min":case "mins":case "m":o=Math.round(r*60);break;case "hour":case "hours":case "hr":case "hrs":case "h":o=Math.round(r*3600);break;case "day":case "days":case "d":o=Math.round(r*86400);break;case "week":case "weeks":case "w":o=Math.round(r*604800);break;default:o=Math.round(r*31557600);break}return t[1]==="-"||t[4]==="ago"?-o:o};var Yt=e=>e.toLowerCase().replace(/^application\//,""),Cr=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):false,de=(e,t,r={})=>{let n;try{n=JSON.parse(b.decode(t));}catch{}if(!l(n))throw new K("JWT Claims Set must be a top-level JSON object");let{typ:o}=r;if(o&&(typeof e.typ!="string"||Yt(e.typ)!==Yt(o)))throw new C('unexpected "typ" JWT header value',n,"typ","check_failed");let{requiredClaims:a=[],issuer:i,subject:s,audience:d,maxTokenAge:p}=r,u=[...a];p!==void 0&&u.push("iat"),d!==void 0&&u.push("aud"),s!==void 0&&u.push("sub"),i!==void 0&&u.push("iss");for(let E of new Set(u.reverse()))if(!(E in n))throw new C(`missing required "${E}" claim`,n,E,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(n.iss))throw new C('unexpected "iss" claim value',n,"iss","check_failed");if(s&&n.sub!==s)throw new C('unexpected "sub" claim value',n,"sub","check_failed");if(d&&!Cr(n.aud,typeof d=="string"?[d]:d))throw new C('unexpected "aud" claim value',n,"aud","check_failed");let w;switch(typeof r.clockTolerance){case "string":w=j(r.clockTolerance);break;case "number":w=r.clockTolerance;break;case "undefined":w=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:g}=r,A=k(g||new Date);if((n.iat!==void 0||p)&&typeof n.iat!="number")throw new C('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new C('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>A+w)throw new C('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new C('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=A-w)throw new oe('"exp" claim timestamp check failed',n,"exp","check_failed")}if(p){let E=A-n.iat,H=typeof p=="number"?p:j(p);if(E-w>H)throw new oe('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(E<0-w)throw new C('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Pr(e,t,r){let n=await rt(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===false)throw new K("JWTs MUST NOT use unencoded payload");let a={payload:de(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof t=="function"?{...a,key:n.key}:a}async function Wr(e,t,r){let n=await Qe(e,t,r),o=de(n.protectedHeader,n.plaintext,r),{protectedHeader:a}=n;if(a.iss!==void 0&&a.iss!==o.iss)throw new C('replicated "iss" claim header parameter mismatch',o,"iss","mismatch");if(a.sub!==void 0&&a.sub!==o.sub)throw new C('replicated "sub" claim header parameter mismatch',o,"sub","mismatch");if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(o.aud))throw new C('replicated "aud" claim header parameter mismatch',o,"aud","mismatch");let i={payload:o,protectedHeader:a};return typeof t=="function"?{...i,key:n.key}:i}var Ae=class{_flattened;constructor(t){this._flattened=new $(t);}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return [n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}};var qt=async(e,t,r)=>{let n=await Be(e,t,"sign");q(e,n);let o=await crypto.subtle.sign(Ne(e,n.algorithm),n,r);return new Uint8Array(o)};var ee=class{_payload;_protectedHeader;_unprotectedHeader;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t;}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new h("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!R(this._protectedHeader,this._unprotectedHeader))throw new h("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},o=D(h,new Map([["b64",true]]),r?.crit,this._protectedHeader,n),a=true;if(o.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new h('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new h('JWS "alg" (Algorithm) Header Parameter missing or invalid');U(i,t,"sign");let s=this._payload;a&&(s=m.encode(y(s)));let d;this._protectedHeader?d=m.encode(y(JSON.stringify(this._protectedHeader))):d=m.encode("");let p=x(d,m.encode("."),s),u=await T(t,i),w=await qt(i,u,p),g={signature:y(w),payload:""};return a&&(g.payload=b.decode(s)),this._unprotectedHeader&&(g.header=this._unprotectedHeader),this._protectedHeader&&(g.protected=b.decode(d)),g}};var be=class{_flattened;constructor(t){this._flattened=new ee(t);}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return `${n.protected}.${n.payload}.${n.signature}`}};var nt=class{parent;protectedHeader;unprotectedHeader;options;key;constructor(t,r,n){this.parent=t,this.key=r,this.options=n;}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},ot=class{_payload;_signatures=[];constructor(t){this._payload=t;}addSignature(t,r){let n=new nt(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new h("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r"u"?this._payload={...this._payload,iat:k(new Date)}:t instanceof Date?this._payload={...this._payload,iat:te("setIssuedAt",k(t))}:typeof t=="string"?this._payload={...this._payload,iat:te("setIssuedAt",k(new Date)+j(t))}:this._payload={...this._payload,iat:te("setIssuedAt",t)},this}};var at=class extends G{_protectedHeader;setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){let n=new be(m.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===false)throw new K("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};var it=class extends G{_cek;_iv;_keyManagementParameters;_protectedHeader;_replicateIssuerAsHeader;_replicateSubjectAsHeader;_replicateAudienceAsHeader;setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=true,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=true,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=true,this}async encrypt(t,r){let n=new Ae(m.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}};var F=(e,t)=>{if(typeof e!="string"||!e)throw new pe(`${t} missing or invalid`)};async function Zt(e,t){let r;if(Q(e))r=e;else if(he(e))r=await Se(e);else throw new TypeError(v(e,"CryptoKey","KeyObject","JSON Web Key"));if(t??="sha256",t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let n;switch(r.kty){case "EC":F(r.crv,'"crv" (Curve) Parameter'),F(r.x,'"x" (X Coordinate) Parameter'),F(r.y,'"y" (Y Coordinate) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x,y:r.y};break;case "OKP":F(r.crv,'"crv" (Subtype of Key Pair) Parameter'),F(r.x,'"x" (Public Key) Parameter'),n={crv:r.crv,kty:r.kty,x:r.x};break;case "RSA":F(r.e,'"e" (Exponent) Parameter'),F(r.n,'"n" (Modulus) Parameter'),n={e:r.e,kty:r.kty,n:r.n};break;case "oct":F(r.k,'"k" (Key Value) Parameter'),n={k:r.k,kty:r.kty};break;default:throw new f('"kty" (Key Type) Parameter missing or unsupported')}let o=m.encode(JSON.stringify(n));return y(await Te(t,o))}async function vr(e,t){t??="sha256";let r=await Zt(e,t);return `urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}async function Jr(e,t){let r={...e,...t?.header};if(!l(r.jwk))throw new h('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await Z({...r.jwk,ext:true},r.alg);if(n instanceof Uint8Array||n.type!=="public")throw new h('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}function Tr(e){switch(typeof e=="string"&&e.slice(0,2)){case "RS":case "PS":return "RSA";case "ES":return "EC";case "Ed":return "OKP";default:throw new f('Unsupported "alg" value for a JSON Web Key Set')}}function Ir(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(Rr)}function Rr(e){return l(e)}function jt(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var st=class{_jwks;_cached=new WeakMap;constructor(t){if(!Ir(t))throw new ae("JSON Web Key Set malformed");this._jwks=jt(t);}async getKey(t,r){let{alg:n,kid:o}={...t,...r?.header},a=Tr(n),i=this._jwks.keys.filter(p=>{let u=a===p.kty;if(u&&typeof o=="string"&&(u=o===p.kid),u&&typeof p.alg=="string"&&(u=n===p.alg),u&&typeof p.use=="string"&&(u=p.use==="sig"),u&&Array.isArray(p.key_ops)&&(u=p.key_ops.includes("verify")),u)switch(n){case "ES256":u=p.crv==="P-256";break;case "ES384":u=p.crv==="P-384";break;case "ES512":u=p.crv==="P-521";break;case "Ed25519":case "EdDSA":u=p.crv==="Ed25519";break}return u}),{0:s,length:d}=i;if(d===0)throw new V;if(d!==1){let p=new fe,{_cached:u}=this;throw p[Symbol.asyncIterator]=async function*(){for(let w of i)try{yield await Qt(u,w,n);}catch{}},p}return Qt(this._cached,s,n)}};async function Qt(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let o=await Z({...t,ext:true},r);if(o instanceof Uint8Array||o.type!=="public")throw new ae("JSON Web Key Set members must be public keys");n[r]=o;}return n[r]}function Le(e){let t=new st(e),r=async(n,o)=>t.getKey(n,o);return Object.defineProperties(r,{jwks:{value:()=>jt(t._jwks),enumerable:true,configurable:false,writable:false}}),r}function Or(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var ct;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ct="jose/v6.0.1");var Dr=Symbol();async function Ur(e,t){let r=await(t?.[Dr]||fetch)(e,{method:"GET",signal:t.signal,redirect:"manual",headers:t.headers}).catch(n=>{throw n.name==="TimeoutError"?new ue:n});if(r.status!==200)throw new _("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await r.json()}catch{throw new _("Failed to parse the JSON Web Key Set HTTP response as JSON")}}var $e=Symbol();function kr(e,t){return !(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!l(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,l))}var dt=class{_url;_timeoutDuration;_cooldownDuration;_cacheMaxAge;_jwksTimestamp;_pendingFetch;_options;_local;_cache;constructor(t,r){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={headers:r?.headers},this._timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this._cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this._cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5,r?.[$e]!==void 0&&(this._cache=r?.[$e],kr(r?.[$e],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Le(this._cache.jwks)));}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now(){this._local=Le(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0;}).catch(r=>{throw this._pendingFetch=void 0,r}),await this._pendingFetch;}};function Mr(e,t){let r=new dt(e,t),n=async(o,a)=>r.getKey(o,a);return Object.defineProperties(n,{coolingDown:{get:()=>r.coolingDown(),enumerable:true,configurable:false},fresh:{get:()=>r.fresh(),enumerable:true,configurable:false},reload:{value:()=>r.reload(),enumerable:true,configurable:false,writable:false},reloading:{get:()=>!!r._pendingFetch,enumerable:true,configurable:false},jwks:{value:()=>r._local?.jwks(),enumerable:true,configurable:false,writable:false}}),n}var pt=class extends G{encode(){let t=y(JSON.stringify({alg:"none"})),r=y(JSON.stringify(this._payload));return `${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new K("Unsecured JWT must be a string");let{0:n,1:o,2:a,length:i}=t.split(".");if(i!==3||a!=="")throw new K("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(b.decode(S(n))),s.alg!=="none")throw new Error}catch{throw new K("Invalid Unsecured JWT")}return {payload:de(s,S(o),r),header:s}}};var er={};ht(er,{decode:()=>Ke,encode:()=>Nr});var Nr=y,Ke=S;function Br(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r);}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(b.decode(Ke(t)));if(!l(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}function Lr(e){if(typeof e!="string")throw new K("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new K("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new K("Invalid JWT");if(!t)throw new K("JWTs must contain a payload");let n;try{n=Ke(t);}catch{throw new K("Failed to base64url decode the payload")}let o;try{o=JSON.parse(b.decode(n));}catch{throw new K("Failed to parse the decoded payload as JSON")}if(!l(o))throw new K("Invalid JWT Claims Set");return o}function ft(e){let t=e?.modulusLength??2048;if(typeof t!="number"||t<2048)throw new f("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}async function $r(e,t){let r,n;switch(e){case "PS256":case "PS384":case "PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:ft(t)},n=["sign","verify"];break;case "RS256":case "RS384":case "RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:ft(t)},n=["sign","verify"];break;case "RSA-OAEP":case "RSA-OAEP-256":case "RSA-OAEP-384":case "RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:ft(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case "ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case "ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case "ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case "Ed25519":case "EdDSA":{n=["sign","verify"],r={name:"Ed25519"};break}case "ECDH-ES":case "ECDH-ES+A128KW":case "ECDH-ES+A192KW":case "ECDH-ES+A256KW":{n=["deriveBits"];let o=t?.crv??"P-256";switch(o){case "P-256":case "P-384":case "P-521":{r={name:"ECDH",namedCurve:o};break}case "X25519":r={name:"X25519"};break;default:throw new f("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519")}break}default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(r,t?.extractable??false,n)}async function Gr(e,t){let r,n,o;switch(e){case "HS256":case "HS384":case "HS512":r=parseInt(e.slice(-3),10),n={name:"HMAC",hash:`SHA-${r}`,length:r},o=["sign","verify"];break;case "A128CBC-HS256":case "A192CBC-HS384":case "A256CBC-HS512":return r=parseInt(e.slice(-3),10),crypto.getRandomValues(new Uint8Array(r>>3));case "A128KW":case "A192KW":case "A256KW":r=parseInt(e.slice(1,4),10),n={name:"AES-KW",length:r},o=["wrapKey","unwrapKey"];break;case "A128GCMKW":case "A192GCMKW":case "A256GCMKW":case "A128GCM":case "A192GCM":case "A256GCM":r=parseInt(e.slice(1,4),10),n={name:"AES-GCM",length:r},o=["encrypt","decrypt"];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return crypto.subtle.generateKey(n,t?.extractable??false,o)}var Us="WebCryptoAPI";
+exports.CompactEncrypt=Ae;exports.CompactSign=be;exports.EmbeddedJWK=Jr;exports.EncryptJWT=it;exports.FlattenedEncrypt=$;exports.FlattenedSign=ee;exports.GeneralEncrypt=tt;exports.GeneralSign=ot;exports.SignJWT=at;exports.UnsecuredJWT=pt;exports.base64url=er;exports.calculateJwkThumbprint=Zt;exports.calculateJwkThumbprintUri=vr;exports.compactDecrypt=Qe;exports.compactVerify=rt;exports.createLocalJWKSet=Le;exports.createRemoteJWKSet=Mr;exports.cryptoRuntime=Us;exports.decodeJwt=Lr;exports.decodeProtectedHeader=Br;exports.errors=lt;exports.exportJWK=Se;exports.exportPKCS8=_r;exports.exportSPKI=Kr;exports.flattenedDecrypt=Ee;exports.flattenedVerify=ge;exports.generalDecrypt=br;exports.generalVerify=Hr;exports.generateKeyPair=$r;exports.generateSecret=Gr;exports.importJWK=Z;exports.importPKCS8=mr;exports.importSPKI=hr;exports.importX509=lr;exports.jwksCache=$e;exports.jwtDecrypt=Wr;exports.jwtVerify=Pr;}));
\ No newline at end of file
diff --git a/dist/webapi/jwe/compact/decrypt.js b/dist/webapi/jwe/compact/decrypt.js
new file mode 100644
index 0000000000..d74a67b134
--- /dev/null
+++ b/dist/webapi/jwe/compact/decrypt.js
@@ -0,0 +1,27 @@
+import { flattenedDecrypt } from '../flattened/decrypt.js';
+import { JWEInvalid } from '../../util/errors.js';
+import { decoder } from '../../lib/buffer_utils.js';
+export async function compactDecrypt(jwe, key, options) {
+ if (jwe instanceof Uint8Array) {
+ jwe = decoder.decode(jwe);
+ }
+ if (typeof jwe !== 'string') {
+ throw new JWEInvalid('Compact JWE must be a string or Uint8Array');
+ }
+ const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.');
+ if (length !== 5) {
+ throw new JWEInvalid('Invalid Compact JWE');
+ }
+ const decrypted = await flattenedDecrypt({
+ ciphertext,
+ iv: iv || undefined,
+ protected: protectedHeader,
+ tag: tag || undefined,
+ encrypted_key: encryptedKey || undefined,
+ }, key, options);
+ const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };
+ if (typeof key === 'function') {
+ return { ...result, key: decrypted.key };
+ }
+ return result;
+}
diff --git a/dist/webapi/jwe/compact/encrypt.js b/dist/webapi/jwe/compact/encrypt.js
new file mode 100644
index 0000000000..e4a44d0cee
--- /dev/null
+++ b/dist/webapi/jwe/compact/encrypt.js
@@ -0,0 +1,27 @@
+import { FlattenedEncrypt } from '../flattened/encrypt.js';
+export class CompactEncrypt {
+ _flattened;
+ constructor(plaintext) {
+ this._flattened = new FlattenedEncrypt(plaintext);
+ }
+ setContentEncryptionKey(cek) {
+ this._flattened.setContentEncryptionKey(cek);
+ return this;
+ }
+ setInitializationVector(iv) {
+ this._flattened.setInitializationVector(iv);
+ return this;
+ }
+ setProtectedHeader(protectedHeader) {
+ this._flattened.setProtectedHeader(protectedHeader);
+ return this;
+ }
+ setKeyManagementParameters(parameters) {
+ this._flattened.setKeyManagementParameters(parameters);
+ return this;
+ }
+ async encrypt(key, options) {
+ const jwe = await this._flattened.encrypt(key, options);
+ return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.');
+ }
+}
diff --git a/dist/webapi/jwe/flattened/decrypt.js b/dist/webapi/jwe/flattened/decrypt.js
new file mode 100644
index 0000000000..eb1497e046
--- /dev/null
+++ b/dist/webapi/jwe/flattened/decrypt.js
@@ -0,0 +1,165 @@
+import { decode as base64url } from '../../lib/base64url.js';
+import decrypt from '../../lib/decrypt.js';
+import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js';
+import isDisjoint from '../../lib/is_disjoint.js';
+import isObject from '../../lib/is_object.js';
+import decryptKeyManagement from '../../lib/decrypt_key_management.js';
+import { encoder, decoder, concat } from '../../lib/buffer_utils.js';
+import generateCek from '../../lib/cek.js';
+import validateCrit from '../../lib/validate_crit.js';
+import validateAlgorithms from '../../lib/validate_algorithms.js';
+import normalizeKey from '../../lib/normalize_key.js';
+import checkKeyType from '../../lib/check_key_type.js';
+export async function flattenedDecrypt(jwe, key, options) {
+ if (!isObject(jwe)) {
+ throw new JWEInvalid('Flattened JWE must be an object');
+ }
+ if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {
+ throw new JWEInvalid('JOSE Header missing');
+ }
+ if (jwe.iv !== undefined && typeof jwe.iv !== 'string') {
+ throw new JWEInvalid('JWE Initialization Vector incorrect type');
+ }
+ if (typeof jwe.ciphertext !== 'string') {
+ throw new JWEInvalid('JWE Ciphertext missing or incorrect type');
+ }
+ if (jwe.tag !== undefined && typeof jwe.tag !== 'string') {
+ throw new JWEInvalid('JWE Authentication Tag incorrect type');
+ }
+ if (jwe.protected !== undefined && typeof jwe.protected !== 'string') {
+ throw new JWEInvalid('JWE Protected Header incorrect type');
+ }
+ if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') {
+ throw new JWEInvalid('JWE Encrypted Key incorrect type');
+ }
+ if (jwe.aad !== undefined && typeof jwe.aad !== 'string') {
+ throw new JWEInvalid('JWE AAD incorrect type');
+ }
+ if (jwe.header !== undefined && !isObject(jwe.header)) {
+ throw new JWEInvalid('JWE Shared Unprotected Header incorrect type');
+ }
+ if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) {
+ throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type');
+ }
+ let parsedProt;
+ if (jwe.protected) {
+ try {
+ const protectedHeader = base64url(jwe.protected);
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
+ }
+ catch {
+ throw new JWEInvalid('JWE Protected Header is invalid');
+ }
+ }
+ if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {
+ throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint');
+ }
+ const joseHeader = {
+ ...parsedProt,
+ ...jwe.header,
+ ...jwe.unprotected,
+ };
+ validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader);
+ if (joseHeader.zip !== undefined) {
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+ }
+ const { alg, enc } = joseHeader;
+ if (typeof alg !== 'string' || !alg) {
+ throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header');
+ }
+ if (typeof enc !== 'string' || !enc) {
+ throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header');
+ }
+ const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms);
+ const contentEncryptionAlgorithms = options &&
+ validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);
+ if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||
+ (!keyManagementAlgorithms && alg.startsWith('PBES2'))) {
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
+ }
+ if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
+ throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
+ }
+ let encryptedKey;
+ if (jwe.encrypted_key !== undefined) {
+ try {
+ encryptedKey = base64url(jwe.encrypted_key);
+ }
+ catch {
+ throw new JWEInvalid('Failed to base64url decode the encrypted_key');
+ }
+ }
+ let resolvedKey = false;
+ if (typeof key === 'function') {
+ key = await key(parsedProt, jwe);
+ resolvedKey = true;
+ }
+ checkKeyType(alg === 'dir' ? enc : alg, key, 'decrypt');
+ const k = await normalizeKey(key, alg);
+ let cek;
+ try {
+ cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options);
+ }
+ catch (err) {
+ if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
+ throw err;
+ }
+ cek = generateCek(enc);
+ }
+ let iv;
+ let tag;
+ if (jwe.iv !== undefined) {
+ try {
+ iv = base64url(jwe.iv);
+ }
+ catch {
+ throw new JWEInvalid('Failed to base64url decode the iv');
+ }
+ }
+ if (jwe.tag !== undefined) {
+ try {
+ tag = base64url(jwe.tag);
+ }
+ catch {
+ throw new JWEInvalid('Failed to base64url decode the tag');
+ }
+ }
+ const protectedHeader = encoder.encode(jwe.protected ?? '');
+ let additionalData;
+ if (jwe.aad !== undefined) {
+ additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad));
+ }
+ else {
+ additionalData = protectedHeader;
+ }
+ let ciphertext;
+ try {
+ ciphertext = base64url(jwe.ciphertext);
+ }
+ catch {
+ throw new JWEInvalid('Failed to base64url decode the ciphertext');
+ }
+ const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData);
+ const result = { plaintext };
+ if (jwe.protected !== undefined) {
+ result.protectedHeader = parsedProt;
+ }
+ if (jwe.aad !== undefined) {
+ try {
+ result.additionalAuthenticatedData = base64url(jwe.aad);
+ }
+ catch {
+ throw new JWEInvalid('Failed to base64url decode the aad');
+ }
+ }
+ if (jwe.unprotected !== undefined) {
+ result.sharedUnprotectedHeader = jwe.unprotected;
+ }
+ if (jwe.header !== undefined) {
+ result.unprotectedHeader = jwe.header;
+ }
+ if (resolvedKey) {
+ return { ...result, key: k };
+ }
+ return result;
+}
diff --git a/dist/webapi/jwe/flattened/encrypt.js b/dist/webapi/jwe/flattened/encrypt.js
new file mode 100644
index 0000000000..7b582b9fb8
--- /dev/null
+++ b/dist/webapi/jwe/flattened/encrypt.js
@@ -0,0 +1,165 @@
+import { encode as base64url } from '../../lib/base64url.js';
+import { unprotected } from '../../lib/private_symbols.js';
+import encrypt from '../../lib/encrypt.js';
+import encryptKeyManagement from '../../lib/encrypt_key_management.js';
+import { JOSENotSupported, JWEInvalid } from '../../util/errors.js';
+import isDisjoint from '../../lib/is_disjoint.js';
+import { encoder, decoder, concat } from '../../lib/buffer_utils.js';
+import validateCrit from '../../lib/validate_crit.js';
+import normalizeKey from '../../lib/normalize_key.js';
+import checkKeyType from '../../lib/check_key_type.js';
+export class FlattenedEncrypt {
+ _plaintext;
+ _protectedHeader;
+ _sharedUnprotectedHeader;
+ _unprotectedHeader;
+ _aad;
+ _cek;
+ _iv;
+ _keyManagementParameters;
+ constructor(plaintext) {
+ if (!(plaintext instanceof Uint8Array)) {
+ throw new TypeError('plaintext must be an instance of Uint8Array');
+ }
+ this._plaintext = plaintext;
+ }
+ setKeyManagementParameters(parameters) {
+ if (this._keyManagementParameters) {
+ throw new TypeError('setKeyManagementParameters can only be called once');
+ }
+ this._keyManagementParameters = parameters;
+ return this;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError('setProtectedHeader can only be called once');
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setSharedUnprotectedHeader(sharedUnprotectedHeader) {
+ if (this._sharedUnprotectedHeader) {
+ throw new TypeError('setSharedUnprotectedHeader can only be called once');
+ }
+ this._sharedUnprotectedHeader = sharedUnprotectedHeader;
+ return this;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this._unprotectedHeader) {
+ throw new TypeError('setUnprotectedHeader can only be called once');
+ }
+ this._unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ setAdditionalAuthenticatedData(aad) {
+ this._aad = aad;
+ return this;
+ }
+ setContentEncryptionKey(cek) {
+ if (this._cek) {
+ throw new TypeError('setContentEncryptionKey can only be called once');
+ }
+ this._cek = cek;
+ return this;
+ }
+ setInitializationVector(iv) {
+ if (this._iv) {
+ throw new TypeError('setInitializationVector can only be called once');
+ }
+ this._iv = iv;
+ return this;
+ }
+ async encrypt(key, options) {
+ if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {
+ throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');
+ }
+ if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) {
+ throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
+ }
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...this._sharedUnprotectedHeader,
+ };
+ validateCrit(JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader);
+ if (joseHeader.zip !== undefined) {
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+ }
+ const { alg, enc } = joseHeader;
+ if (typeof alg !== 'string' || !alg) {
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ if (typeof enc !== 'string' || !enc) {
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
+ }
+ let encryptedKey;
+ if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) {
+ throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
+ }
+ checkKeyType(alg === 'dir' ? enc : alg, key, 'encrypt');
+ let cek;
+ {
+ let parameters;
+ const k = await normalizeKey(key, alg);
+ ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, this._cek, this._keyManagementParameters));
+ if (parameters) {
+ if (options && unprotected in options) {
+ if (!this._unprotectedHeader) {
+ this.setUnprotectedHeader(parameters);
+ }
+ else {
+ this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters };
+ }
+ }
+ else if (!this._protectedHeader) {
+ this.setProtectedHeader(parameters);
+ }
+ else {
+ this._protectedHeader = { ...this._protectedHeader, ...parameters };
+ }
+ }
+ }
+ let additionalData;
+ let protectedHeader;
+ let aadMember;
+ if (this._protectedHeader) {
+ protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));
+ }
+ else {
+ protectedHeader = encoder.encode('');
+ }
+ if (this._aad) {
+ aadMember = base64url(this._aad);
+ additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember));
+ }
+ else {
+ additionalData = protectedHeader;
+ }
+ const { ciphertext, tag, iv } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData);
+ const jwe = {
+ ciphertext: base64url(ciphertext),
+ };
+ if (iv) {
+ jwe.iv = base64url(iv);
+ }
+ if (tag) {
+ jwe.tag = base64url(tag);
+ }
+ if (encryptedKey) {
+ jwe.encrypted_key = base64url(encryptedKey);
+ }
+ if (aadMember) {
+ jwe.aad = aadMember;
+ }
+ if (this._protectedHeader) {
+ jwe.protected = decoder.decode(protectedHeader);
+ }
+ if (this._sharedUnprotectedHeader) {
+ jwe.unprotected = this._sharedUnprotectedHeader;
+ }
+ if (this._unprotectedHeader) {
+ jwe.header = this._unprotectedHeader;
+ }
+ return jwe;
+ }
+}
diff --git a/dist/webapi/jwe/general/decrypt.js b/dist/webapi/jwe/general/decrypt.js
new file mode 100644
index 0000000000..659958a8bc
--- /dev/null
+++ b/dist/webapi/jwe/general/decrypt.js
@@ -0,0 +1,31 @@
+import { flattenedDecrypt } from '../flattened/decrypt.js';
+import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js';
+import isObject from '../../lib/is_object.js';
+export async function generalDecrypt(jwe, key, options) {
+ if (!isObject(jwe)) {
+ throw new JWEInvalid('General JWE must be an object');
+ }
+ if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) {
+ throw new JWEInvalid('JWE Recipients missing or incorrect type');
+ }
+ if (!jwe.recipients.length) {
+ throw new JWEInvalid('JWE Recipients has no members');
+ }
+ for (const recipient of jwe.recipients) {
+ try {
+ return await flattenedDecrypt({
+ aad: jwe.aad,
+ ciphertext: jwe.ciphertext,
+ encrypted_key: recipient.encrypted_key,
+ header: recipient.header,
+ iv: jwe.iv,
+ protected: jwe.protected,
+ tag: jwe.tag,
+ unprotected: jwe.unprotected,
+ }, key, options);
+ }
+ catch {
+ }
+ }
+ throw new JWEDecryptionFailed();
+}
diff --git a/dist/webapi/jwe/general/encrypt.js b/dist/webapi/jwe/general/encrypt.js
new file mode 100644
index 0000000000..dc7ce0e407
--- /dev/null
+++ b/dist/webapi/jwe/general/encrypt.js
@@ -0,0 +1,187 @@
+import { FlattenedEncrypt } from '../flattened/encrypt.js';
+import { unprotected } from '../../lib/private_symbols.js';
+import { JOSENotSupported, JWEInvalid } from '../../util/errors.js';
+import generateCek from '../../lib/cek.js';
+import isDisjoint from '../../lib/is_disjoint.js';
+import encryptKeyManagement from '../../lib/encrypt_key_management.js';
+import { encode as base64url } from '../../lib/base64url.js';
+import validateCrit from '../../lib/validate_crit.js';
+import normalizeKey from '../../lib/normalize_key.js';
+import checkKeyType from '../../lib/check_key_type.js';
+class IndividualRecipient {
+ parent;
+ unprotectedHeader;
+ key;
+ options;
+ constructor(enc, key, options) {
+ this.parent = enc;
+ this.key = key;
+ this.options = options;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this.unprotectedHeader) {
+ throw new TypeError('setUnprotectedHeader can only be called once');
+ }
+ this.unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ addRecipient(...args) {
+ return this.parent.addRecipient(...args);
+ }
+ encrypt(...args) {
+ return this.parent.encrypt(...args);
+ }
+ done() {
+ return this.parent;
+ }
+}
+export class GeneralEncrypt {
+ _plaintext;
+ _recipients = [];
+ _protectedHeader;
+ _unprotectedHeader;
+ _aad;
+ constructor(plaintext) {
+ this._plaintext = plaintext;
+ }
+ addRecipient(key, options) {
+ const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
+ this._recipients.push(recipient);
+ return recipient;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError('setProtectedHeader can only be called once');
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setSharedUnprotectedHeader(sharedUnprotectedHeader) {
+ if (this._unprotectedHeader) {
+ throw new TypeError('setSharedUnprotectedHeader can only be called once');
+ }
+ this._unprotectedHeader = sharedUnprotectedHeader;
+ return this;
+ }
+ setAdditionalAuthenticatedData(aad) {
+ this._aad = aad;
+ return this;
+ }
+ async encrypt() {
+ if (!this._recipients.length) {
+ throw new JWEInvalid('at least one recipient must be added');
+ }
+ if (this._recipients.length === 1) {
+ const [recipient] = this._recipients;
+ const flattened = await new FlattenedEncrypt(this._plaintext)
+ .setAdditionalAuthenticatedData(this._aad)
+ .setProtectedHeader(this._protectedHeader)
+ .setSharedUnprotectedHeader(this._unprotectedHeader)
+ .setUnprotectedHeader(recipient.unprotectedHeader)
+ .encrypt(recipient.key, { ...recipient.options });
+ const jwe = {
+ ciphertext: flattened.ciphertext,
+ iv: flattened.iv,
+ recipients: [{}],
+ tag: flattened.tag,
+ };
+ if (flattened.aad)
+ jwe.aad = flattened.aad;
+ if (flattened.protected)
+ jwe.protected = flattened.protected;
+ if (flattened.unprotected)
+ jwe.unprotected = flattened.unprotected;
+ if (flattened.encrypted_key)
+ jwe.recipients[0].encrypted_key = flattened.encrypted_key;
+ if (flattened.header)
+ jwe.recipients[0].header = flattened.header;
+ return jwe;
+ }
+ let enc;
+ for (let i = 0; i < this._recipients.length; i++) {
+ const recipient = this._recipients[i];
+ if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) {
+ throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
+ }
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...recipient.unprotectedHeader,
+ };
+ const { alg } = joseHeader;
+ if (typeof alg !== 'string' || !alg) {
+ throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ if (alg === 'dir' || alg === 'ECDH-ES') {
+ throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');
+ }
+ if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) {
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
+ }
+ if (!enc) {
+ enc = joseHeader.enc;
+ }
+ else if (enc !== joseHeader.enc) {
+ throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');
+ }
+ validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader);
+ if (joseHeader.zip !== undefined) {
+ throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
+ }
+ }
+ const cek = generateCek(enc);
+ const jwe = {
+ ciphertext: '',
+ iv: '',
+ recipients: [],
+ tag: '',
+ };
+ for (let i = 0; i < this._recipients.length; i++) {
+ const recipient = this._recipients[i];
+ const target = {};
+ jwe.recipients.push(target);
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ ...recipient.unprotectedHeader,
+ };
+ const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined;
+ if (i === 0) {
+ const flattened = await new FlattenedEncrypt(this._plaintext)
+ .setAdditionalAuthenticatedData(this._aad)
+ .setContentEncryptionKey(cek)
+ .setProtectedHeader(this._protectedHeader)
+ .setSharedUnprotectedHeader(this._unprotectedHeader)
+ .setUnprotectedHeader(recipient.unprotectedHeader)
+ .setKeyManagementParameters({ p2c })
+ .encrypt(recipient.key, {
+ ...recipient.options,
+ [unprotected]: true,
+ });
+ jwe.ciphertext = flattened.ciphertext;
+ jwe.iv = flattened.iv;
+ jwe.tag = flattened.tag;
+ if (flattened.aad)
+ jwe.aad = flattened.aad;
+ if (flattened.protected)
+ jwe.protected = flattened.protected;
+ if (flattened.unprotected)
+ jwe.unprotected = flattened.unprotected;
+ target.encrypted_key = flattened.encrypted_key;
+ if (flattened.header)
+ target.header = flattened.header;
+ continue;
+ }
+ const alg = recipient.unprotectedHeader?.alg ||
+ this._protectedHeader?.alg ||
+ this._unprotectedHeader?.alg;
+ checkKeyType(alg === 'dir' ? enc : alg, recipient.key, 'encrypt');
+ const k = await normalizeKey(recipient.key, alg);
+ const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, { p2c });
+ target.encrypted_key = base64url(encryptedKey);
+ if (recipient.unprotectedHeader || parameters)
+ target.header = { ...recipient.unprotectedHeader, ...parameters };
+ }
+ return jwe;
+ }
+}
diff --git a/dist/webapi/jwk/embedded.js b/dist/webapi/jwk/embedded.js
new file mode 100644
index 0000000000..aa43b2ff75
--- /dev/null
+++ b/dist/webapi/jwk/embedded.js
@@ -0,0 +1,17 @@
+import { importJWK } from '../key/import.js';
+import isObject from '../lib/is_object.js';
+import { JWSInvalid } from '../util/errors.js';
+export async function EmbeddedJWK(protectedHeader, token) {
+ const joseHeader = {
+ ...protectedHeader,
+ ...token?.header,
+ };
+ if (!isObject(joseHeader.jwk)) {
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');
+ }
+ const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
+ if (key instanceof Uint8Array || key.type !== 'public') {
+ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');
+ }
+ return key;
+}
diff --git a/dist/webapi/jwk/thumbprint.js b/dist/webapi/jwk/thumbprint.js
new file mode 100644
index 0000000000..721c58f498
--- /dev/null
+++ b/dist/webapi/jwk/thumbprint.js
@@ -0,0 +1,63 @@
+import digest from '../lib/digest.js';
+import { encode as base64url } from '../lib/base64url.js';
+import { JOSENotSupported, JWKInvalid } from '../util/errors.js';
+import { encoder } from '../lib/buffer_utils.js';
+import isKeyLike from '../lib/is_key_like.js';
+import { isJWK } from '../lib/is_jwk.js';
+import { exportJWK } from '../key/export.js';
+import invalidKeyInput from '../lib/invalid_key_input.js';
+const check = (value, description) => {
+ if (typeof value !== 'string' || !value) {
+ throw new JWKInvalid(`${description} missing or invalid`);
+ }
+};
+export async function calculateJwkThumbprint(key, digestAlgorithm) {
+ let jwk;
+ if (isJWK(key)) {
+ jwk = key;
+ }
+ else if (isKeyLike(key)) {
+ jwk = await exportJWK(key);
+ }
+ else {
+ throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));
+ }
+ digestAlgorithm ??= 'sha256';
+ if (digestAlgorithm !== 'sha256' &&
+ digestAlgorithm !== 'sha384' &&
+ digestAlgorithm !== 'sha512') {
+ throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
+ }
+ let components;
+ switch (jwk.kty) {
+ case 'EC':
+ check(jwk.crv, '"crv" (Curve) Parameter');
+ check(jwk.x, '"x" (X Coordinate) Parameter');
+ check(jwk.y, '"y" (Y Coordinate) Parameter');
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
+ break;
+ case 'OKP':
+ check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
+ check(jwk.x, '"x" (Public Key) Parameter');
+ components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
+ break;
+ case 'RSA':
+ check(jwk.e, '"e" (Exponent) Parameter');
+ check(jwk.n, '"n" (Modulus) Parameter');
+ components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
+ break;
+ case 'oct':
+ check(jwk.k, '"k" (Key Value) Parameter');
+ components = { k: jwk.k, kty: jwk.kty };
+ break;
+ default:
+ throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
+ }
+ const data = encoder.encode(JSON.stringify(components));
+ return base64url(await digest(digestAlgorithm, data));
+}
+export async function calculateJwkThumbprintUri(key, digestAlgorithm) {
+ digestAlgorithm ??= 'sha256';
+ const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm);
+ return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
+}
diff --git a/dist/webapi/jwks/local.js b/dist/webapi/jwks/local.js
new file mode 100644
index 0000000000..d92a592e47
--- /dev/null
+++ b/dist/webapi/jwks/local.js
@@ -0,0 +1,120 @@
+import { importJWK } from '../key/import.js';
+import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js';
+import isObject from '../lib/is_object.js';
+function getKtyFromAlg(alg) {
+ switch (typeof alg === 'string' && alg.slice(0, 2)) {
+ case 'RS':
+ case 'PS':
+ return 'RSA';
+ case 'ES':
+ return 'EC';
+ case 'Ed':
+ return 'OKP';
+ default:
+ throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
+ }
+}
+function isJWKSLike(jwks) {
+ return (jwks &&
+ typeof jwks === 'object' &&
+ Array.isArray(jwks.keys) &&
+ jwks.keys.every(isJWKLike));
+}
+function isJWKLike(key) {
+ return isObject(key);
+}
+function clone(obj) {
+ if (typeof structuredClone === 'function') {
+ return structuredClone(obj);
+ }
+ return JSON.parse(JSON.stringify(obj));
+}
+class LocalJWKSet {
+ _jwks;
+ _cached = new WeakMap();
+ constructor(jwks) {
+ if (!isJWKSLike(jwks)) {
+ throw new JWKSInvalid('JSON Web Key Set malformed');
+ }
+ this._jwks = clone(jwks);
+ }
+ async getKey(protectedHeader, token) {
+ const { alg, kid } = { ...protectedHeader, ...token?.header };
+ const kty = getKtyFromAlg(alg);
+ const candidates = this._jwks.keys.filter((jwk) => {
+ let candidate = kty === jwk.kty;
+ if (candidate && typeof kid === 'string') {
+ candidate = kid === jwk.kid;
+ }
+ if (candidate && typeof jwk.alg === 'string') {
+ candidate = alg === jwk.alg;
+ }
+ if (candidate && typeof jwk.use === 'string') {
+ candidate = jwk.use === 'sig';
+ }
+ if (candidate && Array.isArray(jwk.key_ops)) {
+ candidate = jwk.key_ops.includes('verify');
+ }
+ if (candidate) {
+ switch (alg) {
+ case 'ES256':
+ candidate = jwk.crv === 'P-256';
+ break;
+ case 'ES384':
+ candidate = jwk.crv === 'P-384';
+ break;
+ case 'ES512':
+ candidate = jwk.crv === 'P-521';
+ break;
+ case 'Ed25519':
+ case 'EdDSA':
+ candidate = jwk.crv === 'Ed25519';
+ break;
+ }
+ }
+ return candidate;
+ });
+ const { 0: jwk, length } = candidates;
+ if (length === 0) {
+ throw new JWKSNoMatchingKey();
+ }
+ if (length !== 1) {
+ const error = new JWKSMultipleMatchingKeys();
+ const { _cached } = this;
+ error[Symbol.asyncIterator] = async function* () {
+ for (const jwk of candidates) {
+ try {
+ yield await importWithAlgCache(_cached, jwk, alg);
+ }
+ catch { }
+ }
+ };
+ throw error;
+ }
+ return importWithAlgCache(this._cached, jwk, alg);
+ }
+}
+async function importWithAlgCache(cache, jwk, alg) {
+ const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
+ if (cached[alg] === undefined) {
+ const key = await importJWK({ ...jwk, ext: true }, alg);
+ if (key instanceof Uint8Array || key.type !== 'public') {
+ throw new JWKSInvalid('JSON Web Key Set members must be public keys');
+ }
+ cached[alg] = key;
+ }
+ return cached[alg];
+}
+export function createLocalJWKSet(jwks) {
+ const set = new LocalJWKSet(jwks);
+ const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
+ Object.defineProperties(localJWKSet, {
+ jwks: {
+ value: () => clone(set._jwks),
+ enumerable: true,
+ configurable: false,
+ writable: false,
+ },
+ });
+ return localJWKSet;
+}
diff --git a/dist/webapi/jwks/remote.js b/dist/webapi/jwks/remote.js
new file mode 100644
index 0000000000..64a8352f33
--- /dev/null
+++ b/dist/webapi/jwks/remote.js
@@ -0,0 +1,176 @@
+import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from '../util/errors.js';
+import { createLocalJWKSet } from './local.js';
+import isObject from '../lib/is_object.js';
+function isCloudflareWorkers() {
+ return (typeof WebSocketPair !== 'undefined' ||
+ (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
+ (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
+}
+let USER_AGENT;
+if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
+ const NAME = 'jose';
+ const VERSION = 'v6.0.1';
+ USER_AGENT = `${NAME}/${VERSION}`;
+}
+export const customFetch = Symbol();
+async function fetchJwks(url, options) {
+ const response = await (options?.[customFetch] || fetch)(url, {
+ method: 'GET',
+ signal: options.signal,
+ redirect: 'manual',
+ headers: options.headers,
+ }).catch((err) => {
+ if (err.name === 'TimeoutError') {
+ throw new JWKSTimeout();
+ }
+ throw err;
+ });
+ if (response.status !== 200) {
+ throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');
+ }
+ try {
+ return await response.json();
+ }
+ catch {
+ throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');
+ }
+}
+export const jwksCache = Symbol();
+function isFreshJwksCache(input, cacheMaxAge) {
+ if (typeof input !== 'object' || input === null) {
+ return false;
+ }
+ if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {
+ return false;
+ }
+ if (!('jwks' in input) ||
+ !isObject(input.jwks) ||
+ !Array.isArray(input.jwks.keys) ||
+ !Array.prototype.every.call(input.jwks.keys, isObject)) {
+ return false;
+ }
+ return true;
+}
+class RemoteJWKSet {
+ _url;
+ _timeoutDuration;
+ _cooldownDuration;
+ _cacheMaxAge;
+ _jwksTimestamp;
+ _pendingFetch;
+ _options;
+ _local;
+ _cache;
+ constructor(url, options) {
+ if (!(url instanceof URL)) {
+ throw new TypeError('url must be an instance of URL');
+ }
+ this._url = new URL(url.href);
+ this._options = { headers: options?.headers };
+ this._timeoutDuration =
+ typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;
+ this._cooldownDuration =
+ typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;
+ this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;
+ if (options?.[jwksCache] !== undefined) {
+ this._cache = options?.[jwksCache];
+ if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) {
+ this._jwksTimestamp = this._cache.uat;
+ this._local = createLocalJWKSet(this._cache.jwks);
+ }
+ }
+ }
+ coolingDown() {
+ return typeof this._jwksTimestamp === 'number'
+ ? Date.now() < this._jwksTimestamp + this._cooldownDuration
+ : false;
+ }
+ fresh() {
+ return typeof this._jwksTimestamp === 'number'
+ ? Date.now() < this._jwksTimestamp + this._cacheMaxAge
+ : false;
+ }
+ async getKey(protectedHeader, token) {
+ if (!this._local || !this.fresh()) {
+ await this.reload();
+ }
+ try {
+ return await this._local(protectedHeader, token);
+ }
+ catch (err) {
+ if (err instanceof JWKSNoMatchingKey) {
+ if (this.coolingDown() === false) {
+ await this.reload();
+ return this._local(protectedHeader, token);
+ }
+ }
+ throw err;
+ }
+ }
+ async reload() {
+ if (this._pendingFetch && isCloudflareWorkers()) {
+ this._pendingFetch = undefined;
+ }
+ const headers = new Headers(this._options.headers);
+ if (USER_AGENT && !headers.has('User-Agent')) {
+ headers.set('User-Agent', USER_AGENT);
+ this._options.headers = Object.fromEntries(headers.entries());
+ }
+ if (!headers.has('accept')) {
+ headers.set('accept', 'application/json');
+ headers.append('accept', 'application/jwk-set+json');
+ }
+ this._pendingFetch ||= fetchJwks(this._url.href, {
+ headers,
+ signal: AbortSignal.timeout(this._timeoutDuration),
+ })
+ .then((json) => {
+ this._local = createLocalJWKSet(json);
+ if (this._cache) {
+ this._cache.uat = Date.now();
+ this._cache.jwks = json;
+ }
+ this._jwksTimestamp = Date.now();
+ this._pendingFetch = undefined;
+ })
+ .catch((err) => {
+ this._pendingFetch = undefined;
+ throw err;
+ });
+ await this._pendingFetch;
+ }
+}
+export function createRemoteJWKSet(url, options) {
+ const set = new RemoteJWKSet(url, options);
+ const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
+ Object.defineProperties(remoteJWKSet, {
+ coolingDown: {
+ get: () => set.coolingDown(),
+ enumerable: true,
+ configurable: false,
+ },
+ fresh: {
+ get: () => set.fresh(),
+ enumerable: true,
+ configurable: false,
+ },
+ reload: {
+ value: () => set.reload(),
+ enumerable: true,
+ configurable: false,
+ writable: false,
+ },
+ reloading: {
+ get: () => !!set._pendingFetch,
+ enumerable: true,
+ configurable: false,
+ },
+ jwks: {
+ value: () => set._local?.jwks(),
+ enumerable: true,
+ configurable: false,
+ writable: false,
+ },
+ });
+ return remoteJWKSet;
+}
diff --git a/dist/webapi/jws/compact/sign.js b/dist/webapi/jws/compact/sign.js
new file mode 100644
index 0000000000..ff40853643
--- /dev/null
+++ b/dist/webapi/jws/compact/sign.js
@@ -0,0 +1,18 @@
+import { FlattenedSign } from '../flattened/sign.js';
+export class CompactSign {
+ _flattened;
+ constructor(payload) {
+ this._flattened = new FlattenedSign(payload);
+ }
+ setProtectedHeader(protectedHeader) {
+ this._flattened.setProtectedHeader(protectedHeader);
+ return this;
+ }
+ async sign(key, options) {
+ const jws = await this._flattened.sign(key, options);
+ if (jws.payload === undefined) {
+ throw new TypeError('use the flattened module for creating JWS with b64: false');
+ }
+ return `${jws.protected}.${jws.payload}.${jws.signature}`;
+ }
+}
diff --git a/dist/webapi/jws/compact/verify.js b/dist/webapi/jws/compact/verify.js
new file mode 100644
index 0000000000..c651ffb944
--- /dev/null
+++ b/dist/webapi/jws/compact/verify.js
@@ -0,0 +1,21 @@
+import { flattenedVerify } from '../flattened/verify.js';
+import { JWSInvalid } from '../../util/errors.js';
+import { decoder } from '../../lib/buffer_utils.js';
+export async function compactVerify(jws, key, options) {
+ if (jws instanceof Uint8Array) {
+ jws = decoder.decode(jws);
+ }
+ if (typeof jws !== 'string') {
+ throw new JWSInvalid('Compact JWS must be a string or Uint8Array');
+ }
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');
+ if (length !== 3) {
+ throw new JWSInvalid('Invalid Compact JWS');
+ }
+ const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
+ const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
+ if (typeof key === 'function') {
+ return { ...result, key: verified.key };
+ }
+ return result;
+}
diff --git a/dist/webapi/jws/flattened/sign.js b/dist/webapi/jws/flattened/sign.js
new file mode 100644
index 0000000000..0f5d96f6df
--- /dev/null
+++ b/dist/webapi/jws/flattened/sign.js
@@ -0,0 +1,86 @@
+import { encode as base64url } from '../../lib/base64url.js';
+import sign from '../../lib/sign.js';
+import isDisjoint from '../../lib/is_disjoint.js';
+import { JWSInvalid } from '../../util/errors.js';
+import { encoder, decoder, concat } from '../../lib/buffer_utils.js';
+import checkKeyType from '../../lib/check_key_type.js';
+import validateCrit from '../../lib/validate_crit.js';
+import normalizeKey from '../../lib/normalize_key.js';
+export class FlattenedSign {
+ _payload;
+ _protectedHeader;
+ _unprotectedHeader;
+ constructor(payload) {
+ if (!(payload instanceof Uint8Array)) {
+ throw new TypeError('payload must be an instance of Uint8Array');
+ }
+ this._payload = payload;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError('setProtectedHeader can only be called once');
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this._unprotectedHeader) {
+ throw new TypeError('setUnprotectedHeader can only be called once');
+ }
+ this._unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ async sign(key, options) {
+ if (!this._protectedHeader && !this._unprotectedHeader) {
+ throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');
+ }
+ if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) {
+ throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
+ }
+ const joseHeader = {
+ ...this._protectedHeader,
+ ...this._unprotectedHeader,
+ };
+ const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader);
+ let b64 = true;
+ if (extensions.has('b64')) {
+ b64 = this._protectedHeader.b64;
+ if (typeof b64 !== 'boolean') {
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
+ }
+ }
+ const { alg } = joseHeader;
+ if (typeof alg !== 'string' || !alg) {
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ checkKeyType(alg, key, 'sign');
+ let payload = this._payload;
+ if (b64) {
+ payload = encoder.encode(base64url(payload));
+ }
+ let protectedHeader;
+ if (this._protectedHeader) {
+ protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));
+ }
+ else {
+ protectedHeader = encoder.encode('');
+ }
+ const data = concat(protectedHeader, encoder.encode('.'), payload);
+ const k = await normalizeKey(key, alg);
+ const signature = await sign(alg, k, data);
+ const jws = {
+ signature: base64url(signature),
+ payload: '',
+ };
+ if (b64) {
+ jws.payload = decoder.decode(payload);
+ }
+ if (this._unprotectedHeader) {
+ jws.header = this._unprotectedHeader;
+ }
+ if (this._protectedHeader) {
+ jws.protected = decoder.decode(protectedHeader);
+ }
+ return jws;
+ }
+}
diff --git a/dist/webapi/jws/flattened/verify.js b/dist/webapi/jws/flattened/verify.js
new file mode 100644
index 0000000000..fc1beaf0cf
--- /dev/null
+++ b/dist/webapi/jws/flattened/verify.js
@@ -0,0 +1,116 @@
+import { decode as base64url } from '../../lib/base64url.js';
+import verify from '../../lib/verify.js';
+import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';
+import { concat, encoder, decoder } from '../../lib/buffer_utils.js';
+import isDisjoint from '../../lib/is_disjoint.js';
+import isObject from '../../lib/is_object.js';
+import checkKeyType from '../../lib/check_key_type.js';
+import validateCrit from '../../lib/validate_crit.js';
+import validateAlgorithms from '../../lib/validate_algorithms.js';
+import normalizeKey from '../../lib/normalize_key.js';
+export async function flattenedVerify(jws, key, options) {
+ if (!isObject(jws)) {
+ throw new JWSInvalid('Flattened JWS must be an object');
+ }
+ if (jws.protected === undefined && jws.header === undefined) {
+ throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
+ }
+ if (jws.protected !== undefined && typeof jws.protected !== 'string') {
+ throw new JWSInvalid('JWS Protected Header incorrect type');
+ }
+ if (jws.payload === undefined) {
+ throw new JWSInvalid('JWS Payload missing');
+ }
+ if (typeof jws.signature !== 'string') {
+ throw new JWSInvalid('JWS Signature missing or incorrect type');
+ }
+ if (jws.header !== undefined && !isObject(jws.header)) {
+ throw new JWSInvalid('JWS Unprotected Header incorrect type');
+ }
+ let parsedProt = {};
+ if (jws.protected) {
+ try {
+ const protectedHeader = base64url(jws.protected);
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
+ }
+ catch {
+ throw new JWSInvalid('JWS Protected Header is invalid');
+ }
+ }
+ if (!isDisjoint(parsedProt, jws.header)) {
+ throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
+ }
+ const joseHeader = {
+ ...parsedProt,
+ ...jws.header,
+ };
+ const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);
+ let b64 = true;
+ if (extensions.has('b64')) {
+ b64 = parsedProt.b64;
+ if (typeof b64 !== 'boolean') {
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
+ }
+ }
+ const { alg } = joseHeader;
+ if (typeof alg !== 'string' || !alg) {
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
+ }
+ const algorithms = options && validateAlgorithms('algorithms', options.algorithms);
+ if (algorithms && !algorithms.has(alg)) {
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
+ }
+ if (b64) {
+ if (typeof jws.payload !== 'string') {
+ throw new JWSInvalid('JWS Payload must be a string');
+ }
+ }
+ else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {
+ throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');
+ }
+ let resolvedKey = false;
+ if (typeof key === 'function') {
+ key = await key(parsedProt, jws);
+ resolvedKey = true;
+ }
+ checkKeyType(alg, key, 'verify');
+ const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload);
+ let signature;
+ try {
+ signature = base64url(jws.signature);
+ }
+ catch {
+ throw new JWSInvalid('Failed to base64url decode the signature');
+ }
+ const k = await normalizeKey(key, alg);
+ const verified = await verify(alg, k, signature, data);
+ if (!verified) {
+ throw new JWSSignatureVerificationFailed();
+ }
+ let payload;
+ if (b64) {
+ try {
+ payload = base64url(jws.payload);
+ }
+ catch {
+ throw new JWSInvalid('Failed to base64url decode the payload');
+ }
+ }
+ else if (typeof jws.payload === 'string') {
+ payload = encoder.encode(jws.payload);
+ }
+ else {
+ payload = jws.payload;
+ }
+ const result = { payload };
+ if (jws.protected !== undefined) {
+ result.protectedHeader = parsedProt;
+ }
+ if (jws.header !== undefined) {
+ result.unprotectedHeader = jws.header;
+ }
+ if (resolvedKey) {
+ return { ...result, key: k };
+ }
+ return result;
+}
diff --git a/dist/webapi/jws/general/sign.js b/dist/webapi/jws/general/sign.js
new file mode 100644
index 0000000000..620dd48fe3
--- /dev/null
+++ b/dist/webapi/jws/general/sign.js
@@ -0,0 +1,73 @@
+import { FlattenedSign } from '../flattened/sign.js';
+import { JWSInvalid } from '../../util/errors.js';
+class IndividualSignature {
+ parent;
+ protectedHeader;
+ unprotectedHeader;
+ options;
+ key;
+ constructor(sig, key, options) {
+ this.parent = sig;
+ this.key = key;
+ this.options = options;
+ }
+ setProtectedHeader(protectedHeader) {
+ if (this.protectedHeader) {
+ throw new TypeError('setProtectedHeader can only be called once');
+ }
+ this.protectedHeader = protectedHeader;
+ return this;
+ }
+ setUnprotectedHeader(unprotectedHeader) {
+ if (this.unprotectedHeader) {
+ throw new TypeError('setUnprotectedHeader can only be called once');
+ }
+ this.unprotectedHeader = unprotectedHeader;
+ return this;
+ }
+ addSignature(...args) {
+ return this.parent.addSignature(...args);
+ }
+ sign(...args) {
+ return this.parent.sign(...args);
+ }
+ done() {
+ return this.parent;
+ }
+}
+export class GeneralSign {
+ _payload;
+ _signatures = [];
+ constructor(payload) {
+ this._payload = payload;
+ }
+ addSignature(key, options) {
+ const signature = new IndividualSignature(this, key, options);
+ this._signatures.push(signature);
+ return signature;
+ }
+ async sign() {
+ if (!this._signatures.length) {
+ throw new JWSInvalid('at least one signature must be added');
+ }
+ const jws = {
+ signatures: [],
+ payload: '',
+ };
+ for (let i = 0; i < this._signatures.length; i++) {
+ const signature = this._signatures[i];
+ const flattened = new FlattenedSign(this._payload);
+ flattened.setProtectedHeader(signature.protectedHeader);
+ flattened.setUnprotectedHeader(signature.unprotectedHeader);
+ const { payload, ...rest } = await flattened.sign(signature.key, signature.options);
+ if (i === 0) {
+ jws.payload = payload;
+ }
+ else if (jws.payload !== payload) {
+ throw new JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)');
+ }
+ jws.signatures.push(rest);
+ }
+ return jws;
+ }
+}
diff --git a/dist/webapi/jws/general/verify.js b/dist/webapi/jws/general/verify.js
new file mode 100644
index 0000000000..c511b722dc
--- /dev/null
+++ b/dist/webapi/jws/general/verify.js
@@ -0,0 +1,24 @@
+import { flattenedVerify } from '../flattened/verify.js';
+import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';
+import isObject from '../../lib/is_object.js';
+export async function generalVerify(jws, key, options) {
+ if (!isObject(jws)) {
+ throw new JWSInvalid('General JWS must be an object');
+ }
+ if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) {
+ throw new JWSInvalid('JWS Signatures missing or incorrect type');
+ }
+ for (const signature of jws.signatures) {
+ try {
+ return await flattenedVerify({
+ header: signature.header,
+ payload: jws.payload,
+ protected: signature.protected,
+ signature: signature.signature,
+ }, key, options);
+ }
+ catch {
+ }
+ }
+ throw new JWSSignatureVerificationFailed();
+}
diff --git a/dist/webapi/jwt/decrypt.js b/dist/webapi/jwt/decrypt.js
new file mode 100644
index 0000000000..c3a85fe5af
--- /dev/null
+++ b/dist/webapi/jwt/decrypt.js
@@ -0,0 +1,23 @@
+import { compactDecrypt } from '../jwe/compact/decrypt.js';
+import jwtPayload from '../lib/jwt_claims_set.js';
+import { JWTClaimValidationFailed } from '../util/errors.js';
+export async function jwtDecrypt(jwt, key, options) {
+ const decrypted = await compactDecrypt(jwt, key, options);
+ const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options);
+ const { protectedHeader } = decrypted;
+ if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) {
+ throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, 'iss', 'mismatch');
+ }
+ if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) {
+ throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, 'sub', 'mismatch');
+ }
+ if (protectedHeader.aud !== undefined &&
+ JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
+ throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, 'aud', 'mismatch');
+ }
+ const result = { payload, protectedHeader };
+ if (typeof key === 'function') {
+ return { ...result, key: decrypted.key };
+ }
+ return result;
+}
diff --git a/dist/webapi/jwt/encrypt.js b/dist/webapi/jwt/encrypt.js
new file mode 100644
index 0000000000..2035989810
--- /dev/null
+++ b/dist/webapi/jwt/encrypt.js
@@ -0,0 +1,75 @@
+import { CompactEncrypt } from '../jwe/compact/encrypt.js';
+import { encoder } from '../lib/buffer_utils.js';
+import { ProduceJWT } from './produce.js';
+export class EncryptJWT extends ProduceJWT {
+ _cek;
+ _iv;
+ _keyManagementParameters;
+ _protectedHeader;
+ _replicateIssuerAsHeader;
+ _replicateSubjectAsHeader;
+ _replicateAudienceAsHeader;
+ setProtectedHeader(protectedHeader) {
+ if (this._protectedHeader) {
+ throw new TypeError('setProtectedHeader can only be called once');
+ }
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ setKeyManagementParameters(parameters) {
+ if (this._keyManagementParameters) {
+ throw new TypeError('setKeyManagementParameters can only be called once');
+ }
+ this._keyManagementParameters = parameters;
+ return this;
+ }
+ setContentEncryptionKey(cek) {
+ if (this._cek) {
+ throw new TypeError('setContentEncryptionKey can only be called once');
+ }
+ this._cek = cek;
+ return this;
+ }
+ setInitializationVector(iv) {
+ if (this._iv) {
+ throw new TypeError('setInitializationVector can only be called once');
+ }
+ this._iv = iv;
+ return this;
+ }
+ replicateIssuerAsHeader() {
+ this._replicateIssuerAsHeader = true;
+ return this;
+ }
+ replicateSubjectAsHeader() {
+ this._replicateSubjectAsHeader = true;
+ return this;
+ }
+ replicateAudienceAsHeader() {
+ this._replicateAudienceAsHeader = true;
+ return this;
+ }
+ async encrypt(key, options) {
+ const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload)));
+ if (this._replicateIssuerAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss };
+ }
+ if (this._replicateSubjectAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub };
+ }
+ if (this._replicateAudienceAsHeader) {
+ this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud };
+ }
+ enc.setProtectedHeader(this._protectedHeader);
+ if (this._iv) {
+ enc.setInitializationVector(this._iv);
+ }
+ if (this._cek) {
+ enc.setContentEncryptionKey(this._cek);
+ }
+ if (this._keyManagementParameters) {
+ enc.setKeyManagementParameters(this._keyManagementParameters);
+ }
+ return enc.encrypt(key, options);
+ }
+}
diff --git a/dist/webapi/jwt/produce.js b/dist/webapi/jwt/produce.js
new file mode 100644
index 0000000000..7954c65b8c
--- /dev/null
+++ b/dist/webapi/jwt/produce.js
@@ -0,0 +1,76 @@
+import epoch from '../lib/epoch.js';
+import isObject from '../lib/is_object.js';
+import secs from '../lib/secs.js';
+function validateInput(label, input) {
+ if (!Number.isFinite(input)) {
+ throw new TypeError(`Invalid ${label} input`);
+ }
+ return input;
+}
+export class ProduceJWT {
+ _payload;
+ constructor(payload = {}) {
+ if (!isObject(payload)) {
+ throw new TypeError('JWT Claims Set MUST be an object');
+ }
+ this._payload = payload;
+ }
+ setIssuer(issuer) {
+ this._payload = { ...this._payload, iss: issuer };
+ return this;
+ }
+ setSubject(subject) {
+ this._payload = { ...this._payload, sub: subject };
+ return this;
+ }
+ setAudience(audience) {
+ this._payload = { ...this._payload, aud: audience };
+ return this;
+ }
+ setJti(jwtId) {
+ this._payload = { ...this._payload, jti: jwtId };
+ return this;
+ }
+ setNotBefore(input) {
+ if (typeof input === 'number') {
+ this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) };
+ }
+ else if (input instanceof Date) {
+ this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) };
+ }
+ else {
+ this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) };
+ }
+ return this;
+ }
+ setExpirationTime(input) {
+ if (typeof input === 'number') {
+ this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) };
+ }
+ else if (input instanceof Date) {
+ this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) };
+ }
+ else {
+ this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) };
+ }
+ return this;
+ }
+ setIssuedAt(input) {
+ if (typeof input === 'undefined') {
+ this._payload = { ...this._payload, iat: epoch(new Date()) };
+ }
+ else if (input instanceof Date) {
+ this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) };
+ }
+ else if (typeof input === 'string') {
+ this._payload = {
+ ...this._payload,
+ iat: validateInput('setIssuedAt', epoch(new Date()) + secs(input)),
+ };
+ }
+ else {
+ this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) };
+ }
+ return this;
+ }
+}
diff --git a/dist/webapi/jwt/sign.js b/dist/webapi/jwt/sign.js
new file mode 100644
index 0000000000..16bf9f4360
--- /dev/null
+++ b/dist/webapi/jwt/sign.js
@@ -0,0 +1,21 @@
+import { CompactSign } from '../jws/compact/sign.js';
+import { JWTInvalid } from '../util/errors.js';
+import { encoder } from '../lib/buffer_utils.js';
+import { ProduceJWT } from './produce.js';
+export class SignJWT extends ProduceJWT {
+ _protectedHeader;
+ setProtectedHeader(protectedHeader) {
+ this._protectedHeader = protectedHeader;
+ return this;
+ }
+ async sign(key, options) {
+ const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)));
+ sig.setProtectedHeader(this._protectedHeader);
+ if (Array.isArray(this._protectedHeader?.crit) &&
+ this._protectedHeader.crit.includes('b64') &&
+ this._protectedHeader.b64 === false) {
+ throw new JWTInvalid('JWTs MUST NOT use unencoded payload');
+ }
+ return sig.sign(key, options);
+ }
+}
diff --git a/dist/webapi/jwt/unsecured.js b/dist/webapi/jwt/unsecured.js
new file mode 100644
index 0000000000..fdebc8463f
--- /dev/null
+++ b/dist/webapi/jwt/unsecured.js
@@ -0,0 +1,32 @@
+import * as base64url from '../lib/base64url.js';
+import { decoder } from '../lib/buffer_utils.js';
+import { JWTInvalid } from '../util/errors.js';
+import jwtPayload from '../lib/jwt_claims_set.js';
+import { ProduceJWT } from './produce.js';
+export class UnsecuredJWT extends ProduceJWT {
+ encode() {
+ const header = base64url.encode(JSON.stringify({ alg: 'none' }));
+ const payload = base64url.encode(JSON.stringify(this._payload));
+ return `${header}.${payload}.`;
+ }
+ static decode(jwt, options) {
+ if (typeof jwt !== 'string') {
+ throw new JWTInvalid('Unsecured JWT must be a string');
+ }
+ const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.');
+ if (length !== 3 || signature !== '') {
+ throw new JWTInvalid('Invalid Unsecured JWT');
+ }
+ let header;
+ try {
+ header = JSON.parse(decoder.decode(base64url.decode(encodedHeader)));
+ if (header.alg !== 'none')
+ throw new Error();
+ }
+ catch {
+ throw new JWTInvalid('Invalid Unsecured JWT');
+ }
+ const payload = jwtPayload(header, base64url.decode(encodedPayload), options);
+ return { payload, header };
+ }
+}
diff --git a/dist/webapi/jwt/verify.js b/dist/webapi/jwt/verify.js
new file mode 100644
index 0000000000..f5d99d06b5
--- /dev/null
+++ b/dist/webapi/jwt/verify.js
@@ -0,0 +1,15 @@
+import { compactVerify } from '../jws/compact/verify.js';
+import jwtPayload from '../lib/jwt_claims_set.js';
+import { JWTInvalid } from '../util/errors.js';
+export async function jwtVerify(jwt, key, options) {
+ const verified = await compactVerify(jwt, key, options);
+ if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
+ throw new JWTInvalid('JWTs MUST NOT use unencoded payload');
+ }
+ const payload = jwtPayload(verified.protectedHeader, verified.payload, options);
+ const result = { payload, protectedHeader: verified.protectedHeader };
+ if (typeof key === 'function') {
+ return { ...result, key: verified.key };
+ }
+ return result;
+}
diff --git a/dist/webapi/key/export.js b/dist/webapi/key/export.js
new file mode 100644
index 0000000000..0bc3355dc4
--- /dev/null
+++ b/dist/webapi/key/export.js
@@ -0,0 +1,11 @@
+import { toSPKI as exportPublic, toPKCS8 as exportPrivate } from '../lib/asn1.js';
+import keyToJWK from '../lib/key_to_jwk.js';
+export async function exportSPKI(key) {
+ return exportPublic(key);
+}
+export async function exportPKCS8(key) {
+ return exportPrivate(key);
+}
+export async function exportJWK(key) {
+ return keyToJWK(key);
+}
diff --git a/dist/webapi/key/generate_key_pair.js b/dist/webapi/key/generate_key_pair.js
new file mode 100644
index 0000000000..547a23d0e6
--- /dev/null
+++ b/dist/webapi/key/generate_key_pair.js
@@ -0,0 +1,90 @@
+import { JOSENotSupported } from '../util/errors.js';
+function getModulusLengthOption(options) {
+ const modulusLength = options?.modulusLength ?? 2048;
+ if (typeof modulusLength !== 'number' || modulusLength < 2048) {
+ throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');
+ }
+ return modulusLength;
+}
+export async function generateKeyPair(alg, options) {
+ let algorithm;
+ let keyUsages;
+ switch (alg) {
+ case 'PS256':
+ case 'PS384':
+ case 'PS512':
+ algorithm = {
+ name: 'RSA-PSS',
+ hash: `SHA-${alg.slice(-3)}`,
+ publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
+ modulusLength: getModulusLengthOption(options),
+ };
+ keyUsages = ['sign', 'verify'];
+ break;
+ case 'RS256':
+ case 'RS384':
+ case 'RS512':
+ algorithm = {
+ name: 'RSASSA-PKCS1-v1_5',
+ hash: `SHA-${alg.slice(-3)}`,
+ publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
+ modulusLength: getModulusLengthOption(options),
+ };
+ keyUsages = ['sign', 'verify'];
+ break;
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512':
+ algorithm = {
+ name: 'RSA-OAEP',
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
+ publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
+ modulusLength: getModulusLengthOption(options),
+ };
+ keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey'];
+ break;
+ case 'ES256':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
+ keyUsages = ['sign', 'verify'];
+ break;
+ case 'ES384':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-384' };
+ keyUsages = ['sign', 'verify'];
+ break;
+ case 'ES512':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-521' };
+ keyUsages = ['sign', 'verify'];
+ break;
+ case 'Ed25519':
+ case 'EdDSA': {
+ keyUsages = ['sign', 'verify'];
+ algorithm = { name: 'Ed25519' };
+ break;
+ }
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW': {
+ keyUsages = ['deriveBits'];
+ const crv = options?.crv ?? 'P-256';
+ switch (crv) {
+ case 'P-256':
+ case 'P-384':
+ case 'P-521': {
+ algorithm = { name: 'ECDH', namedCurve: crv };
+ break;
+ }
+ case 'X25519':
+ algorithm = { name: 'X25519' };
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519');
+ }
+ break;
+ }
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
+}
diff --git a/dist/webapi/key/generate_secret.js b/dist/webapi/key/generate_secret.js
new file mode 100644
index 0000000000..0fe2a12b13
--- /dev/null
+++ b/dist/webapi/key/generate_secret.js
@@ -0,0 +1,40 @@
+import { JOSENotSupported } from '../util/errors.js';
+export async function generateSecret(alg, options) {
+ let length;
+ let algorithm;
+ let keyUsages;
+ switch (alg) {
+ case 'HS256':
+ case 'HS384':
+ case 'HS512':
+ length = parseInt(alg.slice(-3), 10);
+ algorithm = { name: 'HMAC', hash: `SHA-${length}`, length };
+ keyUsages = ['sign', 'verify'];
+ break;
+ case 'A128CBC-HS256':
+ case 'A192CBC-HS384':
+ case 'A256CBC-HS512':
+ length = parseInt(alg.slice(-3), 10);
+ return crypto.getRandomValues(new Uint8Array(length >> 3));
+ case 'A128KW':
+ case 'A192KW':
+ case 'A256KW':
+ length = parseInt(alg.slice(1, 4), 10);
+ algorithm = { name: 'AES-KW', length };
+ keyUsages = ['wrapKey', 'unwrapKey'];
+ break;
+ case 'A128GCMKW':
+ case 'A192GCMKW':
+ case 'A256GCMKW':
+ case 'A128GCM':
+ case 'A192GCM':
+ case 'A256GCM':
+ length = parseInt(alg.slice(1, 4), 10);
+ algorithm = { name: 'AES-GCM', length };
+ keyUsages = ['encrypt', 'decrypt'];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
+}
diff --git a/dist/webapi/key/import.js b/dist/webapi/key/import.js
new file mode 100644
index 0000000000..366d9884f7
--- /dev/null
+++ b/dist/webapi/key/import.js
@@ -0,0 +1,47 @@
+import { decode as decodeBase64URL } from '../lib/base64url.js';
+import { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js';
+import toCryptoKey from '../lib/jwk_to_key.js';
+import { JOSENotSupported } from '../util/errors.js';
+import isObject from '../lib/is_object.js';
+export async function importSPKI(spki, alg, options) {
+ if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {
+ throw new TypeError('"spki" must be SPKI formatted string');
+ }
+ return fromSPKI(spki, alg, options);
+}
+export async function importX509(x509, alg, options) {
+ if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {
+ throw new TypeError('"x509" must be X.509 formatted string');
+ }
+ return fromX509(x509, alg, options);
+}
+export async function importPKCS8(pkcs8, alg, options) {
+ if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {
+ throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
+ }
+ return fromPKCS8(pkcs8, alg, options);
+}
+export async function importJWK(jwk, alg, options) {
+ if (!isObject(jwk)) {
+ throw new TypeError('JWK must be an object');
+ }
+ let ext;
+ alg ??= jwk.alg;
+ ext ??= options?.extractable ?? jwk.ext;
+ switch (jwk.kty) {
+ case 'oct':
+ if (typeof jwk.k !== 'string' || !jwk.k) {
+ throw new TypeError('missing "k" (Key Value) Parameter value');
+ }
+ return decodeBase64URL(jwk.k);
+ case 'RSA':
+ if ('oth' in jwk && jwk.oth !== undefined) {
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
+ }
+ case 'EC':
+ case 'OKP':
+ return toCryptoKey({ ...jwk, alg, ext });
+ default:
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
+ }
+}
diff --git a/dist/webapi/lib/aesgcmkw.js b/dist/webapi/lib/aesgcmkw.js
new file mode 100644
index 0000000000..a1a34e9f59
--- /dev/null
+++ b/dist/webapi/lib/aesgcmkw.js
@@ -0,0 +1,16 @@
+import encrypt from './encrypt.js';
+import decrypt from './decrypt.js';
+import { encode as base64url } from '../lib/base64url.js';
+export async function wrap(alg, key, cek, iv) {
+ const jweAlgorithm = alg.slice(0, 7);
+ const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0));
+ return {
+ encryptedKey: wrapped.ciphertext,
+ iv: base64url(wrapped.iv),
+ tag: base64url(wrapped.tag),
+ };
+}
+export async function unwrap(alg, key, encryptedKey, iv, tag) {
+ const jweAlgorithm = alg.slice(0, 7);
+ return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0));
+}
diff --git a/dist/webapi/lib/aeskw.js b/dist/webapi/lib/aeskw.js
new file mode 100644
index 0000000000..666b69cae9
--- /dev/null
+++ b/dist/webapi/lib/aeskw.js
@@ -0,0 +1,25 @@
+import { checkEncCryptoKey } from './crypto_key.js';
+function checkKeySize(key, alg) {
+ if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {
+ throw new TypeError(`Invalid key size for alg: ${alg}`);
+ }
+}
+function getCryptoKey(key, alg, usage) {
+ if (key instanceof Uint8Array) {
+ return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]);
+ }
+ checkEncCryptoKey(key, alg, usage);
+ return key;
+}
+export async function wrap(alg, key, cek) {
+ const cryptoKey = await getCryptoKey(key, alg, 'wrapKey');
+ checkKeySize(cryptoKey, alg);
+ const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, { hash: 'SHA-256', name: 'HMAC' }, true, ['sign']);
+ return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW'));
+}
+export async function unwrap(alg, key, encryptedKey) {
+ const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey');
+ checkKeySize(cryptoKey, alg);
+ const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', { hash: 'SHA-256', name: 'HMAC' }, true, ['sign']);
+ return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));
+}
diff --git a/dist/webapi/lib/asn1.js b/dist/webapi/lib/asn1.js
new file mode 100644
index 0000000000..16fba34200
--- /dev/null
+++ b/dist/webapi/lib/asn1.js
@@ -0,0 +1,209 @@
+import invalidKeyInput from './invalid_key_input.js';
+import { encodeBase64, decodeBase64 } from './base64url.js';
+import { JOSENotSupported } from '../util/errors.js';
+import { isCryptoKey, isKeyObject } from './is_key_like.js';
+const formatPEM = (b64, descriptor) => {
+ const newlined = (b64.match(/.{1,64}/g) || []).join('\n');
+ return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`;
+};
+const genericExport = async (keyType, keyFormat, key) => {
+ if (isKeyObject(key)) {
+ if (key.type !== keyType) {
+ throw new TypeError(`key is not a ${keyType} key`);
+ }
+ return key.export({ format: 'pem', type: keyFormat });
+ }
+ if (!isCryptoKey(key)) {
+ throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject'));
+ }
+ if (!key.extractable) {
+ throw new TypeError('CryptoKey is not extractable');
+ }
+ if (key.type !== keyType) {
+ throw new TypeError(`key is not a ${keyType} key`);
+ }
+ return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
+};
+export const toSPKI = (key) => {
+ return genericExport('public', 'spki', key);
+};
+export const toPKCS8 = (key) => {
+ return genericExport('private', 'pkcs8', key);
+};
+const findOid = (keyData, oid, from = 0) => {
+ if (from === 0) {
+ oid.unshift(oid.length);
+ oid.unshift(0x06);
+ }
+ const i = keyData.indexOf(oid[0], from);
+ if (i === -1)
+ return false;
+ const sub = keyData.subarray(i, i + oid.length);
+ if (sub.length !== oid.length)
+ return false;
+ return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1);
+};
+const getNamedCurve = (keyData) => {
+ switch (true) {
+ case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]):
+ return 'P-256';
+ case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]):
+ return 'P-384';
+ case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]):
+ return 'P-521';
+ default:
+ return undefined;
+ }
+};
+const genericImport = async (replace, keyFormat, pem, alg, options) => {
+ let algorithm;
+ let keyUsages;
+ const keyData = new Uint8Array(atob(pem.replace(replace, ''))
+ .split('')
+ .map((c) => c.charCodeAt(0)));
+ const isPublic = keyFormat === 'spki';
+ switch (alg) {
+ case 'PS256':
+ case 'PS384':
+ case 'PS512':
+ algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };
+ keyUsages = isPublic ? ['verify'] : ['sign'];
+ break;
+ case 'RS256':
+ case 'RS384':
+ case 'RS512':
+ algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };
+ keyUsages = isPublic ? ['verify'] : ['sign'];
+ break;
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512':
+ algorithm = {
+ name: 'RSA-OAEP',
+ hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
+ };
+ keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'];
+ break;
+ case 'ES256':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
+ keyUsages = isPublic ? ['verify'] : ['sign'];
+ break;
+ case 'ES384':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-384' };
+ keyUsages = isPublic ? ['verify'] : ['sign'];
+ break;
+ case 'ES512':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-521' };
+ keyUsages = isPublic ? ['verify'] : ['sign'];
+ break;
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW': {
+ const namedCurve = getNamedCurve(keyData);
+ algorithm = namedCurve?.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: 'X25519' };
+ keyUsages = isPublic ? [] : ['deriveBits'];
+ break;
+ }
+ case 'Ed25519':
+ case 'EdDSA':
+ algorithm = { name: 'Ed25519' };
+ keyUsages = isPublic ? ['verify'] : ['sign'];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
+ }
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);
+};
+export const fromPKCS8 = (pem, alg, options) => {
+ return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options);
+};
+export const fromSPKI = (pem, alg, options) => {
+ return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, 'spki', pem, alg, options);
+};
+function getElement(seq) {
+ const result = [];
+ let next = 0;
+ while (next < seq.length) {
+ const nextPart = parseElement(seq.subarray(next));
+ result.push(nextPart);
+ next += nextPart.byteLength;
+ }
+ return result;
+}
+function parseElement(bytes) {
+ let position = 0;
+ let tag = bytes[0] & 0x1f;
+ position++;
+ if (tag === 0x1f) {
+ tag = 0;
+ while (bytes[position] >= 0x80) {
+ tag = tag * 128 + bytes[position] - 0x80;
+ position++;
+ }
+ tag = tag * 128 + bytes[position] - 0x80;
+ position++;
+ }
+ let length = 0;
+ if (bytes[position] < 0x80) {
+ length = bytes[position];
+ position++;
+ }
+ else if (length === 0x80) {
+ length = 0;
+ while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) {
+ if (length > bytes.byteLength) {
+ throw new TypeError('invalid indefinite form length');
+ }
+ length++;
+ }
+ const byteLength = position + length + 2;
+ return {
+ byteLength,
+ contents: bytes.subarray(position, position + length),
+ raw: bytes.subarray(0, byteLength),
+ };
+ }
+ else {
+ const numberOfDigits = bytes[position] & 0x7f;
+ position++;
+ length = 0;
+ for (let i = 0; i < numberOfDigits; i++) {
+ length = length * 256 + bytes[position];
+ position++;
+ }
+ }
+ const byteLength = position + length;
+ return {
+ byteLength,
+ contents: bytes.subarray(position, byteLength),
+ raw: bytes.subarray(0, byteLength),
+ };
+}
+function spkiFromX509(buf) {
+ const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents);
+ return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw);
+}
+let X509Certificate;
+function getSPKI(x509) {
+ if ((X509Certificate ||= globalThis.process?.getBuiltinModule?.('node:crypto')?.X509Certificate)) {
+ try {
+ return new X509Certificate(x509).publicKey.export({ format: 'pem', type: 'spki' });
+ }
+ catch { }
+ }
+ const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '');
+ const raw = decodeBase64(pem);
+ return formatPEM(spkiFromX509(raw), 'PUBLIC KEY');
+}
+export const fromX509 = (pem, alg, options) => {
+ let spki;
+ try {
+ spki = getSPKI(pem);
+ }
+ catch (cause) {
+ throw new TypeError('Failed to parse the X.509 certificate', { cause });
+ }
+ return fromSPKI(spki, alg, options);
+};
diff --git a/dist/webapi/lib/base64url.js b/dist/webapi/lib/base64url.js
new file mode 100644
index 0000000000..8b4bd1e9d4
--- /dev/null
+++ b/dist/webapi/lib/base64url.js
@@ -0,0 +1,45 @@
+import { encoder, decoder, Buffer } from '../lib/buffer_utils.js';
+export function encodeBase64(input) {
+ if (Buffer)
+ return Buffer.from(input).toString('base64');
+ let unencoded = input;
+ if (typeof unencoded === 'string') {
+ unencoded = encoder.encode(unencoded);
+ }
+ const CHUNK_SIZE = 0x8000;
+ const arr = [];
+ for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {
+ arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));
+ }
+ return btoa(arr.join(''));
+}
+export function encode(input) {
+ if (Buffer)
+ return Buffer.from(input).toString('base64url');
+ return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
+}
+export function decodeBase64(encoded) {
+ if (Buffer)
+ return Buffer.from(encoded, 'base64');
+ const binary = atob(encoded);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i++) {
+ bytes[i] = binary.charCodeAt(i);
+ }
+ return bytes;
+}
+export function decode(input) {
+ let encoded = input;
+ if (encoded instanceof Uint8Array) {
+ encoded = decoder.decode(encoded);
+ }
+ if (Buffer)
+ return Buffer.from(encoded, 'base64url');
+ encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
+ try {
+ return decodeBase64(encoded);
+ }
+ catch {
+ throw new TypeError('The input to be decoded is not correctly encoded.');
+ }
+}
diff --git a/dist/webapi/lib/buffer_utils.js b/dist/webapi/lib/buffer_utils.js
new file mode 100644
index 0000000000..a2ecfaabe4
--- /dev/null
+++ b/dist/webapi/lib/buffer_utils.js
@@ -0,0 +1,36 @@
+export const encoder = new TextEncoder();
+export const decoder = new TextDecoder();
+const MAX_INT32 = 2 ** 32;
+const Buffer = globalThis.process?.getBuiltinModule?.('node:buffer')?.Buffer;
+export { Buffer };
+export function concat(...buffers) {
+ if (Buffer)
+ return Buffer.concat(buffers);
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
+ const buf = new Uint8Array(size);
+ let i = 0;
+ for (const buffer of buffers) {
+ buf.set(buffer, i);
+ i += buffer.length;
+ }
+ return buf;
+}
+function writeUInt32BE(buf, value, offset) {
+ if (value < 0 || value >= MAX_INT32) {
+ throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);
+ }
+ buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);
+}
+export function uint64be(value) {
+ const high = Math.floor(value / MAX_INT32);
+ const low = value % MAX_INT32;
+ const buf = new Uint8Array(8);
+ writeUInt32BE(buf, high, 0);
+ writeUInt32BE(buf, low, 4);
+ return buf;
+}
+export function uint32be(value) {
+ const buf = new Uint8Array(4);
+ writeUInt32BE(buf, value);
+ return buf;
+}
diff --git a/dist/webapi/lib/cek.js b/dist/webapi/lib/cek.js
new file mode 100644
index 0000000000..4565e6e262
--- /dev/null
+++ b/dist/webapi/lib/cek.js
@@ -0,0 +1,19 @@
+import { JOSENotSupported } from '../util/errors.js';
+export function bitLength(alg) {
+ switch (alg) {
+ case 'A128GCM':
+ return 128;
+ case 'A192GCM':
+ return 192;
+ case 'A256GCM':
+ case 'A128CBC-HS256':
+ return 256;
+ case 'A192CBC-HS384':
+ return 384;
+ case 'A256CBC-HS512':
+ return 512;
+ default:
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
+ }
+}
+export default (alg) => crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3));
diff --git a/dist/webapi/lib/check_cek_length.js b/dist/webapi/lib/check_cek_length.js
new file mode 100644
index 0000000000..ba4c08e46a
--- /dev/null
+++ b/dist/webapi/lib/check_cek_length.js
@@ -0,0 +1,7 @@
+import { JWEInvalid } from '../util/errors.js';
+export default (cek, expected) => {
+ const actual = cek.byteLength << 3;
+ if (actual !== expected) {
+ throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
+ }
+};
diff --git a/dist/webapi/lib/check_iv_length.js b/dist/webapi/lib/check_iv_length.js
new file mode 100644
index 0000000000..b233db7dd5
--- /dev/null
+++ b/dist/webapi/lib/check_iv_length.js
@@ -0,0 +1,7 @@
+import { JWEInvalid } from '../util/errors.js';
+import { bitLength } from './iv.js';
+export default (enc, iv) => {
+ if (iv.length << 3 !== bitLength(enc)) {
+ throw new JWEInvalid('Invalid Initialization Vector length');
+ }
+};
diff --git a/dist/webapi/lib/check_key_length.js b/dist/webapi/lib/check_key_length.js
new file mode 100644
index 0000000000..33970068fe
--- /dev/null
+++ b/dist/webapi/lib/check_key_length.js
@@ -0,0 +1,8 @@
+export default (alg, key) => {
+ if (alg.startsWith('RS') || alg.startsWith('PS')) {
+ const { modulusLength } = key.algorithm;
+ if (typeof modulusLength !== 'number' || modulusLength < 2048) {
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
+ }
+ }
+};
diff --git a/dist/webapi/lib/check_key_type.js b/dist/webapi/lib/check_key_type.js
new file mode 100644
index 0000000000..376e9f6523
--- /dev/null
+++ b/dist/webapi/lib/check_key_type.js
@@ -0,0 +1,126 @@
+import { withAlg as invalidKeyInput } from './invalid_key_input.js';
+import isKeyLike from './is_key_like.js';
+import * as jwk from './is_jwk.js';
+const tag = (key) => key?.[Symbol.toStringTag];
+const jwkMatchesOp = (alg, key, usage) => {
+ if (key.use !== undefined) {
+ let expected;
+ switch (usage) {
+ case 'sign':
+ case 'verify':
+ expected = 'sig';
+ break;
+ case 'encrypt':
+ case 'decrypt':
+ expected = 'enc';
+ break;
+ }
+ if (key.use !== expected) {
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
+ }
+ }
+ if (key.alg !== undefined && key.alg !== alg) {
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
+ }
+ if (Array.isArray(key.key_ops)) {
+ let expectedKeyOp;
+ switch (true) {
+ case usage === 'sign' || usage === 'verify':
+ case alg === 'dir':
+ case alg.includes('CBC-HS'):
+ expectedKeyOp = usage;
+ break;
+ case alg.startsWith('PBES2'):
+ expectedKeyOp = 'deriveBits';
+ break;
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
+ if (!alg.includes('GCM') && alg.endsWith('KW')) {
+ expectedKeyOp = usage === 'encrypt' ? 'wrapKey' : 'unwrapKey';
+ }
+ else {
+ expectedKeyOp = usage;
+ }
+ break;
+ case usage === 'encrypt' && alg.startsWith('RSA'):
+ expectedKeyOp = 'wrapKey';
+ break;
+ case usage === 'decrypt':
+ expectedKeyOp = alg.startsWith('RSA') ? 'unwrapKey' : 'deriveBits';
+ break;
+ }
+ if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
+ }
+ }
+ return true;
+};
+const symmetricTypeCheck = (alg, key, usage) => {
+ if (key instanceof Uint8Array)
+ return;
+ if (jwk.isJWK(key)) {
+ if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
+ return;
+ throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
+ }
+ if (!isKeyLike(key)) {
+ throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key', 'Uint8Array'));
+ }
+ if (key.type !== 'secret') {
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
+ }
+};
+const asymmetricTypeCheck = (alg, key, usage) => {
+ if (jwk.isJWK(key)) {
+ switch (usage) {
+ case 'decrypt':
+ case 'sign':
+ if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
+ return;
+ throw new TypeError(`JSON Web Key for this operation be a private JWK`);
+ case 'encrypt':
+ case 'verify':
+ if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
+ return;
+ throw new TypeError(`JSON Web Key for this operation be a public JWK`);
+ }
+ }
+ if (!isKeyLike(key)) {
+ throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));
+ }
+ if (key.type === 'secret') {
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
+ }
+ if (key.type === 'public') {
+ switch (usage) {
+ case 'sign':
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
+ case 'decrypt':
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
+ default:
+ break;
+ }
+ }
+ if (key.type === 'private') {
+ switch (usage) {
+ case 'verify':
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
+ case 'encrypt':
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
+ default:
+ break;
+ }
+ }
+};
+export default (alg, key, usage) => {
+ const symmetric = alg.startsWith('HS') ||
+ alg === 'dir' ||
+ alg.startsWith('PBES2') ||
+ /^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(alg) ||
+ /^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(alg);
+ if (symmetric) {
+ symmetricTypeCheck(alg, key, usage);
+ }
+ else {
+ asymmetricTypeCheck(alg, key, usage);
+ }
+};
diff --git a/dist/webapi/lib/crypto_key.js b/dist/webapi/lib/crypto_key.js
new file mode 100644
index 0000000000..69ebbf4d1c
--- /dev/null
+++ b/dist/webapi/lib/crypto_key.js
@@ -0,0 +1,140 @@
+function unusable(name, prop = 'algorithm.name') {
+ return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
+}
+function isAlgorithm(algorithm, name) {
+ return algorithm.name === name;
+}
+function getHashLength(hash) {
+ return parseInt(hash.name.slice(4), 10);
+}
+function getNamedCurve(alg) {
+ switch (alg) {
+ case 'ES256':
+ return 'P-256';
+ case 'ES384':
+ return 'P-384';
+ case 'ES512':
+ return 'P-521';
+ default:
+ throw new Error('unreachable');
+ }
+}
+function checkUsage(key, usage) {
+ if (usage && !key.usages.includes(usage)) {
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
+ }
+}
+export function checkSigCryptoKey(key, alg, usage) {
+ switch (alg) {
+ case 'HS256':
+ case 'HS384':
+ case 'HS512': {
+ if (!isAlgorithm(key.algorithm, 'HMAC'))
+ throw unusable('HMAC');
+ const expected = parseInt(alg.slice(2), 10);
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, 'algorithm.hash');
+ break;
+ }
+ case 'RS256':
+ case 'RS384':
+ case 'RS512': {
+ if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))
+ throw unusable('RSASSA-PKCS1-v1_5');
+ const expected = parseInt(alg.slice(2), 10);
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, 'algorithm.hash');
+ break;
+ }
+ case 'PS256':
+ case 'PS384':
+ case 'PS512': {
+ if (!isAlgorithm(key.algorithm, 'RSA-PSS'))
+ throw unusable('RSA-PSS');
+ const expected = parseInt(alg.slice(2), 10);
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, 'algorithm.hash');
+ break;
+ }
+ case 'Ed25519':
+ case 'EdDSA': {
+ if (!isAlgorithm(key.algorithm, 'Ed25519'))
+ throw unusable('Ed25519');
+ break;
+ }
+ case 'ES256':
+ case 'ES384':
+ case 'ES512': {
+ if (!isAlgorithm(key.algorithm, 'ECDSA'))
+ throw unusable('ECDSA');
+ const expected = getNamedCurve(alg);
+ const actual = key.algorithm.namedCurve;
+ if (actual !== expected)
+ throw unusable(expected, 'algorithm.namedCurve');
+ break;
+ }
+ default:
+ throw new TypeError('CryptoKey does not support this operation');
+ }
+ checkUsage(key, usage);
+}
+export function checkEncCryptoKey(key, alg, usage) {
+ switch (alg) {
+ case 'A128GCM':
+ case 'A192GCM':
+ case 'A256GCM': {
+ if (!isAlgorithm(key.algorithm, 'AES-GCM'))
+ throw unusable('AES-GCM');
+ const expected = parseInt(alg.slice(1, 4), 10);
+ const actual = key.algorithm.length;
+ if (actual !== expected)
+ throw unusable(expected, 'algorithm.length');
+ break;
+ }
+ case 'A128KW':
+ case 'A192KW':
+ case 'A256KW': {
+ if (!isAlgorithm(key.algorithm, 'AES-KW'))
+ throw unusable('AES-KW');
+ const expected = parseInt(alg.slice(1, 4), 10);
+ const actual = key.algorithm.length;
+ if (actual !== expected)
+ throw unusable(expected, 'algorithm.length');
+ break;
+ }
+ case 'ECDH': {
+ switch (key.algorithm.name) {
+ case 'ECDH':
+ case 'X25519':
+ break;
+ default:
+ throw unusable('ECDH or X25519');
+ }
+ break;
+ }
+ case 'PBES2-HS256+A128KW':
+ case 'PBES2-HS384+A192KW':
+ case 'PBES2-HS512+A256KW':
+ if (!isAlgorithm(key.algorithm, 'PBKDF2'))
+ throw unusable('PBKDF2');
+ break;
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512': {
+ if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))
+ throw unusable('RSA-OAEP');
+ const expected = parseInt(alg.slice(9), 10) || 1;
+ const actual = getHashLength(key.algorithm.hash);
+ if (actual !== expected)
+ throw unusable(`SHA-${expected}`, 'algorithm.hash');
+ break;
+ }
+ default:
+ throw new TypeError('CryptoKey does not support this operation');
+ }
+ checkUsage(key, usage);
+}
diff --git a/dist/webapi/lib/decrypt.js b/dist/webapi/lib/decrypt.js
new file mode 100644
index 0000000000..581ea30942
--- /dev/null
+++ b/dist/webapi/lib/decrypt.js
@@ -0,0 +1,107 @@
+import { concat, uint64be } from './buffer_utils.js';
+import checkIvLength from './check_iv_length.js';
+import checkCekLength from './check_cek_length.js';
+import { JOSENotSupported, JWEDecryptionFailed, JWEInvalid } from '../util/errors.js';
+import { checkEncCryptoKey } from './crypto_key.js';
+import invalidKeyInput from './invalid_key_input.js';
+import { isCryptoKey } from './is_key_like.js';
+let timingSafeEqual = globalThis.process?.getBuiltinModule?.('node:crypto')?.timingSafeEqual;
+timingSafeEqual ||= (a, b) => {
+ if (!(a instanceof Uint8Array)) {
+ throw new TypeError('First argument must be a buffer');
+ }
+ if (!(b instanceof Uint8Array)) {
+ throw new TypeError('Second argument must be a buffer');
+ }
+ if (a.length !== b.length) {
+ throw new TypeError('Input buffers must have the same length');
+ }
+ const len = a.length;
+ let out = 0;
+ let i = -1;
+ while (++i < len) {
+ out |= a[i] ^ b[i];
+ }
+ return out === 0;
+};
+async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
+ if (!(cek instanceof Uint8Array)) {
+ throw new TypeError(invalidKeyInput(cek, 'Uint8Array'));
+ }
+ const keySize = parseInt(enc.slice(1, 4), 10);
+ const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['decrypt']);
+ const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {
+ hash: `SHA-${keySize << 1}`,
+ name: 'HMAC',
+ }, false, ['sign']);
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
+ const expectedTag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));
+ let macCheckPassed;
+ try {
+ macCheckPassed = timingSafeEqual(tag, expectedTag);
+ }
+ catch {
+ }
+ if (!macCheckPassed) {
+ throw new JWEDecryptionFailed();
+ }
+ let plaintext;
+ try {
+ plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext));
+ }
+ catch {
+ }
+ if (!plaintext) {
+ throw new JWEDecryptionFailed();
+ }
+ return plaintext;
+}
+async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {
+ let encKey;
+ if (cek instanceof Uint8Array) {
+ encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']);
+ }
+ else {
+ checkEncCryptoKey(cek, enc, 'decrypt');
+ encKey = cek;
+ }
+ try {
+ return new Uint8Array(await crypto.subtle.decrypt({
+ additionalData: aad,
+ iv,
+ name: 'AES-GCM',
+ tagLength: 128,
+ }, encKey, concat(ciphertext, tag)));
+ }
+ catch {
+ throw new JWEDecryptionFailed();
+ }
+}
+export default async (enc, cek, ciphertext, iv, tag, aad) => {
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
+ throw new TypeError(invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key'));
+ }
+ if (!iv) {
+ throw new JWEInvalid('JWE Initialization Vector missing');
+ }
+ if (!tag) {
+ throw new JWEInvalid('JWE Authentication Tag missing');
+ }
+ checkIvLength(enc, iv);
+ switch (enc) {
+ case 'A128CBC-HS256':
+ case 'A192CBC-HS384':
+ case 'A256CBC-HS512':
+ if (cek instanceof Uint8Array)
+ checkCekLength(cek, parseInt(enc.slice(-3), 10));
+ return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad);
+ case 'A128GCM':
+ case 'A192GCM':
+ case 'A256GCM':
+ if (cek instanceof Uint8Array)
+ checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
+ return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad);
+ default:
+ throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
+ }
+};
diff --git a/dist/webapi/lib/decrypt_key_management.js b/dist/webapi/lib/decrypt_key_management.js
new file mode 100644
index 0000000000..e2d155dae2
--- /dev/null
+++ b/dist/webapi/lib/decrypt_key_management.js
@@ -0,0 +1,127 @@
+import * as aeskw from './aeskw.js';
+import * as ecdhes from './ecdhes.js';
+import * as pbes2kw from './pbes2kw.js';
+import * as rsaes from './rsaes.js';
+import * as base64url from '../lib/base64url.js';
+import { JOSENotSupported, JWEInvalid } from '../util/errors.js';
+import { bitLength as cekLength } from '../lib/cek.js';
+import { importJWK } from '../key/import.js';
+import isObject from './is_object.js';
+import { unwrap as aesGcmKw } from './aesgcmkw.js';
+import { assertCryptoKey } from './is_key_like.js';
+export default async (alg, key, encryptedKey, joseHeader, options) => {
+ switch (alg) {
+ case 'dir': {
+ if (encryptedKey !== undefined)
+ throw new JWEInvalid('Encountered unexpected JWE Encrypted Key');
+ return key;
+ }
+ case 'ECDH-ES':
+ if (encryptedKey !== undefined)
+ throw new JWEInvalid('Encountered unexpected JWE Encrypted Key');
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW': {
+ if (!isObject(joseHeader.epk))
+ throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
+ assertCryptoKey(key);
+ if (!ecdhes.allowed(key))
+ throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');
+ const epk = await importJWK(joseHeader.epk, alg);
+ assertCryptoKey(epk);
+ let partyUInfo;
+ let partyVInfo;
+ if (joseHeader.apu !== undefined) {
+ if (typeof joseHeader.apu !== 'string')
+ throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
+ try {
+ partyUInfo = base64url.decode(joseHeader.apu);
+ }
+ catch {
+ throw new JWEInvalid('Failed to base64url decode the apu');
+ }
+ }
+ if (joseHeader.apv !== undefined) {
+ if (typeof joseHeader.apv !== 'string')
+ throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
+ try {
+ partyVInfo = base64url.decode(joseHeader.apv);
+ }
+ catch {
+ throw new JWEInvalid('Failed to base64url decode the apv');
+ }
+ }
+ const sharedSecret = await ecdhes.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
+ if (alg === 'ECDH-ES')
+ return sharedSecret;
+ if (encryptedKey === undefined)
+ throw new JWEInvalid('JWE Encrypted Key missing');
+ return aeskw.unwrap(alg.slice(-6), sharedSecret, encryptedKey);
+ }
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512': {
+ if (encryptedKey === undefined)
+ throw new JWEInvalid('JWE Encrypted Key missing');
+ assertCryptoKey(key);
+ return rsaes.decrypt(alg, key, encryptedKey);
+ }
+ case 'PBES2-HS256+A128KW':
+ case 'PBES2-HS384+A192KW':
+ case 'PBES2-HS512+A256KW': {
+ if (encryptedKey === undefined)
+ throw new JWEInvalid('JWE Encrypted Key missing');
+ if (typeof joseHeader.p2c !== 'number')
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
+ const p2cLimit = options?.maxPBES2Count || 10_000;
+ if (joseHeader.p2c > p2cLimit)
+ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
+ if (typeof joseHeader.p2s !== 'string')
+ throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
+ let p2s;
+ try {
+ p2s = base64url.decode(joseHeader.p2s);
+ }
+ catch {
+ throw new JWEInvalid('Failed to base64url decode the p2s');
+ }
+ return pbes2kw.unwrap(alg, key, encryptedKey, joseHeader.p2c, p2s);
+ }
+ case 'A128KW':
+ case 'A192KW':
+ case 'A256KW': {
+ if (encryptedKey === undefined)
+ throw new JWEInvalid('JWE Encrypted Key missing');
+ return aeskw.unwrap(alg, key, encryptedKey);
+ }
+ case 'A128GCMKW':
+ case 'A192GCMKW':
+ case 'A256GCMKW': {
+ if (encryptedKey === undefined)
+ throw new JWEInvalid('JWE Encrypted Key missing');
+ if (typeof joseHeader.iv !== 'string')
+ throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
+ if (typeof joseHeader.tag !== 'string')
+ throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
+ let iv;
+ try {
+ iv = base64url.decode(joseHeader.iv);
+ }
+ catch {
+ throw new JWEInvalid('Failed to base64url decode the iv');
+ }
+ let tag;
+ try {
+ tag = base64url.decode(joseHeader.tag);
+ }
+ catch {
+ throw new JWEInvalid('Failed to base64url decode the tag');
+ }
+ return aesGcmKw(alg, key, encryptedKey, iv, tag);
+ }
+ default: {
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
+ }
+ }
+};
diff --git a/dist/webapi/lib/digest.js b/dist/webapi/lib/digest.js
new file mode 100644
index 0000000000..e2a9a208ad
--- /dev/null
+++ b/dist/webapi/lib/digest.js
@@ -0,0 +1,4 @@
+export default async (algorithm, data) => {
+ const subtleDigest = `SHA-${algorithm.slice(-3)}`;
+ return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
+};
diff --git a/dist/webapi/lib/ecdhes.js b/dist/webapi/lib/ecdhes.js
new file mode 100644
index 0000000000..1e476d93b1
--- /dev/null
+++ b/dist/webapi/lib/ecdhes.js
@@ -0,0 +1,46 @@
+import { encoder, concat, uint32be } from './buffer_utils.js';
+import { checkEncCryptoKey } from './crypto_key.js';
+import digest from './digest.js';
+function lengthAndInput(input) {
+ return concat(uint32be(input.length), input);
+}
+async function concatKdf(secret, bits, value) {
+ const iterations = Math.ceil((bits >> 3) / 32);
+ const res = new Uint8Array(iterations * 32);
+ for (let iter = 0; iter < iterations; iter++) {
+ const buf = new Uint8Array(4 + secret.length + value.length);
+ buf.set(uint32be(iter + 1));
+ buf.set(secret, 4);
+ buf.set(value, 4 + secret.length);
+ res.set(await digest('sha256', buf), iter * 32);
+ }
+ return res.slice(0, bits >> 3);
+}
+export async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
+ checkEncCryptoKey(publicKey, 'ECDH');
+ checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits');
+ const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength));
+ let length;
+ if (publicKey.algorithm.name === 'X25519') {
+ length = 256;
+ }
+ else {
+ length =
+ Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3;
+ }
+ const sharedSecret = new Uint8Array(await crypto.subtle.deriveBits({
+ name: publicKey.algorithm.name,
+ public: publicKey,
+ }, privateKey, length));
+ return concatKdf(sharedSecret, keyLength, value);
+}
+export function allowed(key) {
+ switch (key.algorithm.namedCurve) {
+ case 'P-256':
+ case 'P-384':
+ case 'P-521':
+ return true;
+ default:
+ return key.algorithm.name === 'X25519';
+ }
+}
diff --git a/dist/webapi/lib/encrypt.js b/dist/webapi/lib/encrypt.js
new file mode 100644
index 0000000000..b0e96a730f
--- /dev/null
+++ b/dist/webapi/lib/encrypt.js
@@ -0,0 +1,74 @@
+import { concat, uint64be } from './buffer_utils.js';
+import checkIvLength from './check_iv_length.js';
+import checkCekLength from './check_cek_length.js';
+import { checkEncCryptoKey } from './crypto_key.js';
+import invalidKeyInput from './invalid_key_input.js';
+import generateIv from './iv.js';
+import { JOSENotSupported } from '../util/errors.js';
+import { isCryptoKey } from './is_key_like.js';
+async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
+ if (!(cek instanceof Uint8Array)) {
+ throw new TypeError(invalidKeyInput(cek, 'Uint8Array'));
+ }
+ const keySize = parseInt(enc.slice(1, 4), 10);
+ const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['encrypt']);
+ const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {
+ hash: `SHA-${keySize << 1}`,
+ name: 'HMAC',
+ }, false, ['sign']);
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
+ iv,
+ name: 'AES-CBC',
+ }, encKey, plaintext));
+ const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
+ const tag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));
+ return { ciphertext, tag, iv };
+}
+async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
+ let encKey;
+ if (cek instanceof Uint8Array) {
+ encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);
+ }
+ else {
+ checkEncCryptoKey(cek, enc, 'encrypt');
+ encKey = cek;
+ }
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({
+ additionalData: aad,
+ iv,
+ name: 'AES-GCM',
+ tagLength: 128,
+ }, encKey, plaintext));
+ const tag = encrypted.slice(-16);
+ const ciphertext = encrypted.slice(0, -16);
+ return { ciphertext, tag, iv };
+}
+export default async (enc, plaintext, cek, iv, aad) => {
+ if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
+ throw new TypeError(invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key'));
+ }
+ if (iv) {
+ checkIvLength(enc, iv);
+ }
+ else {
+ iv = generateIv(enc);
+ }
+ switch (enc) {
+ case 'A128CBC-HS256':
+ case 'A192CBC-HS384':
+ case 'A256CBC-HS512':
+ if (cek instanceof Uint8Array) {
+ checkCekLength(cek, parseInt(enc.slice(-3), 10));
+ }
+ return cbcEncrypt(enc, plaintext, cek, iv, aad);
+ case 'A128GCM':
+ case 'A192GCM':
+ case 'A256GCM':
+ if (cek instanceof Uint8Array) {
+ checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
+ }
+ return gcmEncrypt(enc, plaintext, cek, iv, aad);
+ default:
+ throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
+ }
+};
diff --git a/dist/webapi/lib/encrypt_key_management.js b/dist/webapi/lib/encrypt_key_management.js
new file mode 100644
index 0000000000..7b07e5e16a
--- /dev/null
+++ b/dist/webapi/lib/encrypt_key_management.js
@@ -0,0 +1,92 @@
+import * as aeskw from './aeskw.js';
+import * as ecdhes from './ecdhes.js';
+import * as pbes2kw from './pbes2kw.js';
+import * as rsaes from './rsaes.js';
+import * as base64url from '../lib/base64url.js';
+import normalizeKey from './normalize_key.js';
+import generateCek, { bitLength as cekLength } from '../lib/cek.js';
+import { JOSENotSupported } from '../util/errors.js';
+import { exportJWK } from '../key/export.js';
+import { wrap as aesGcmKw } from './aesgcmkw.js';
+import { assertCryptoKey } from './is_key_like.js';
+export default async (alg, enc, key, providedCek, providedParameters = {}) => {
+ let encryptedKey;
+ let parameters;
+ let cek;
+ switch (alg) {
+ case 'dir': {
+ cek = key;
+ break;
+ }
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW': {
+ assertCryptoKey(key);
+ if (!ecdhes.allowed(key)) {
+ throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');
+ }
+ const { apu, apv } = providedParameters;
+ let ephemeralKey;
+ if (providedParameters.epk) {
+ ephemeralKey = (await normalizeKey(providedParameters.epk, alg));
+ }
+ else {
+ ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ['deriveBits'])).privateKey;
+ }
+ const { x, y, crv, kty } = await exportJWK(ephemeralKey);
+ const sharedSecret = await ecdhes.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
+ parameters = { epk: { x, crv, kty } };
+ if (kty === 'EC')
+ parameters.epk.y = y;
+ if (apu)
+ parameters.apu = base64url.encode(apu);
+ if (apv)
+ parameters.apv = base64url.encode(apv);
+ if (alg === 'ECDH-ES') {
+ cek = sharedSecret;
+ break;
+ }
+ cek = providedCek || generateCek(enc);
+ const kwAlg = alg.slice(-6);
+ encryptedKey = await aeskw.wrap(kwAlg, sharedSecret, cek);
+ break;
+ }
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512': {
+ cek = providedCek || generateCek(enc);
+ assertCryptoKey(key);
+ encryptedKey = await rsaes.encrypt(alg, key, cek);
+ break;
+ }
+ case 'PBES2-HS256+A128KW':
+ case 'PBES2-HS384+A192KW':
+ case 'PBES2-HS512+A256KW': {
+ cek = providedCek || generateCek(enc);
+ const { p2c, p2s } = providedParameters;
+ ({ encryptedKey, ...parameters } = await pbes2kw.wrap(alg, key, cek, p2c, p2s));
+ break;
+ }
+ case 'A128KW':
+ case 'A192KW':
+ case 'A256KW': {
+ cek = providedCek || generateCek(enc);
+ encryptedKey = await aeskw.wrap(alg, key, cek);
+ break;
+ }
+ case 'A128GCMKW':
+ case 'A192GCMKW':
+ case 'A256GCMKW': {
+ cek = providedCek || generateCek(enc);
+ const { iv } = providedParameters;
+ ({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv));
+ break;
+ }
+ default: {
+ throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
+ }
+ }
+ return { cek, encryptedKey, parameters };
+};
diff --git a/dist/webapi/lib/epoch.js b/dist/webapi/lib/epoch.js
new file mode 100644
index 0000000000..e405e4b2df
--- /dev/null
+++ b/dist/webapi/lib/epoch.js
@@ -0,0 +1 @@
+export default (date) => Math.floor(date.getTime() / 1000);
diff --git a/dist/webapi/lib/get_sign_verify_key.js b/dist/webapi/lib/get_sign_verify_key.js
new file mode 100644
index 0000000000..0651a00015
--- /dev/null
+++ b/dist/webapi/lib/get_sign_verify_key.js
@@ -0,0 +1,12 @@
+import { checkSigCryptoKey } from './crypto_key.js';
+import invalidKeyInput from './invalid_key_input.js';
+export default async (alg, key, usage) => {
+ if (key instanceof Uint8Array) {
+ if (!alg.startsWith('HS')) {
+ throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));
+ }
+ return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);
+ }
+ checkSigCryptoKey(key, alg, usage);
+ return key;
+};
diff --git a/dist/webapi/lib/invalid_key_input.js b/dist/webapi/lib/invalid_key_input.js
new file mode 100644
index 0000000000..5796a2eb69
--- /dev/null
+++ b/dist/webapi/lib/invalid_key_input.js
@@ -0,0 +1,31 @@
+function message(msg, actual, ...types) {
+ types = types.filter(Boolean);
+ if (types.length > 2) {
+ const last = types.pop();
+ msg += `one of type ${types.join(', ')}, or ${last}.`;
+ }
+ else if (types.length === 2) {
+ msg += `one of type ${types[0]} or ${types[1]}.`;
+ }
+ else {
+ msg += `of type ${types[0]}.`;
+ }
+ if (actual == null) {
+ msg += ` Received ${actual}`;
+ }
+ else if (typeof actual === 'function' && actual.name) {
+ msg += ` Received function ${actual.name}`;
+ }
+ else if (typeof actual === 'object' && actual != null) {
+ if (actual.constructor?.name) {
+ msg += ` Received an instance of ${actual.constructor.name}`;
+ }
+ }
+ return msg;
+}
+export default (actual, ...types) => {
+ return message('Key must be ', actual, ...types);
+};
+export function withAlg(alg, actual, ...types) {
+ return message(`Key for the ${alg} algorithm must be `, actual, ...types);
+}
diff --git a/dist/webapi/lib/is_disjoint.js b/dist/webapi/lib/is_disjoint.js
new file mode 100644
index 0000000000..50320512bc
--- /dev/null
+++ b/dist/webapi/lib/is_disjoint.js
@@ -0,0 +1,21 @@
+export default (...headers) => {
+ const sources = headers.filter(Boolean);
+ if (sources.length === 0 || sources.length === 1) {
+ return true;
+ }
+ let acc;
+ for (const header of sources) {
+ const parameters = Object.keys(header);
+ if (!acc || acc.size === 0) {
+ acc = new Set(parameters);
+ continue;
+ }
+ for (const parameter of parameters) {
+ if (acc.has(parameter)) {
+ return false;
+ }
+ acc.add(parameter);
+ }
+ }
+ return true;
+};
diff --git a/dist/webapi/lib/is_jwk.js b/dist/webapi/lib/is_jwk.js
new file mode 100644
index 0000000000..cf9868cefb
--- /dev/null
+++ b/dist/webapi/lib/is_jwk.js
@@ -0,0 +1,13 @@
+import isObject from './is_object.js';
+export function isJWK(key) {
+ return isObject(key) && typeof key.kty === 'string';
+}
+export function isPrivateJWK(key) {
+ return key.kty !== 'oct' && typeof key.d === 'string';
+}
+export function isPublicJWK(key) {
+ return key.kty !== 'oct' && typeof key.d === 'undefined';
+}
+export function isSecretJWK(key) {
+ return key.kty === 'oct' && typeof key.k === 'string';
+}
diff --git a/dist/webapi/lib/is_key_like.js b/dist/webapi/lib/is_key_like.js
new file mode 100644
index 0000000000..d9ff4f23c3
--- /dev/null
+++ b/dist/webapi/lib/is_key_like.js
@@ -0,0 +1,14 @@
+export function assertCryptoKey(key) {
+ if (!isCryptoKey(key)) {
+ throw new Error('CryptoKey instance expected');
+ }
+}
+export function isCryptoKey(key) {
+ return key?.[Symbol.toStringTag] === 'CryptoKey';
+}
+export function isKeyObject(key) {
+ return key?.[Symbol.toStringTag] === 'KeyObject';
+}
+export default (key) => {
+ return isCryptoKey(key) || isKeyObject(key);
+};
diff --git a/dist/webapi/lib/is_object.js b/dist/webapi/lib/is_object.js
new file mode 100644
index 0000000000..902b672552
--- /dev/null
+++ b/dist/webapi/lib/is_object.js
@@ -0,0 +1,16 @@
+function isObjectLike(value) {
+ return typeof value === 'object' && value !== null;
+}
+export default (input) => {
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {
+ return false;
+ }
+ if (Object.getPrototypeOf(input) === null) {
+ return true;
+ }
+ let proto = input;
+ while (Object.getPrototypeOf(proto) !== null) {
+ proto = Object.getPrototypeOf(proto);
+ }
+ return Object.getPrototypeOf(input) === proto;
+};
diff --git a/dist/webapi/lib/iv.js b/dist/webapi/lib/iv.js
new file mode 100644
index 0000000000..f45d9ca769
--- /dev/null
+++ b/dist/webapi/lib/iv.js
@@ -0,0 +1,19 @@
+import { JOSENotSupported } from '../util/errors.js';
+export function bitLength(alg) {
+ switch (alg) {
+ case 'A128GCM':
+ case 'A128GCMKW':
+ case 'A192GCM':
+ case 'A192GCMKW':
+ case 'A256GCM':
+ case 'A256GCMKW':
+ return 96;
+ case 'A128CBC-HS256':
+ case 'A192CBC-HS384':
+ case 'A256CBC-HS512':
+ return 128;
+ default:
+ throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
+ }
+}
+export default (alg) => crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3));
diff --git a/dist/webapi/lib/jwk_to_key.js b/dist/webapi/lib/jwk_to_key.js
new file mode 100644
index 0000000000..8e1bb2eac3
--- /dev/null
+++ b/dist/webapi/lib/jwk_to_key.js
@@ -0,0 +1,94 @@
+import { JOSENotSupported } from '../util/errors.js';
+function subtleMapping(jwk) {
+ let algorithm;
+ let keyUsages;
+ switch (jwk.kty) {
+ case 'RSA': {
+ switch (jwk.alg) {
+ case 'PS256':
+ case 'PS384':
+ case 'PS512':
+ algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
+ break;
+ case 'RS256':
+ case 'RS384':
+ case 'RS512':
+ algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
+ break;
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512':
+ algorithm = {
+ name: 'RSA-OAEP',
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,
+ };
+ keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ break;
+ }
+ case 'EC': {
+ switch (jwk.alg) {
+ case 'ES256':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
+ break;
+ case 'ES384':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-384' };
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
+ break;
+ case 'ES512':
+ algorithm = { name: 'ECDSA', namedCurve: 'P-521' };
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
+ break;
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW':
+ algorithm = { name: 'ECDH', namedCurve: jwk.crv };
+ keyUsages = jwk.d ? ['deriveBits'] : [];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ break;
+ }
+ case 'OKP': {
+ switch (jwk.alg) {
+ case 'Ed25519':
+ case 'EdDSA':
+ algorithm = { name: 'Ed25519' };
+ keyUsages = jwk.d ? ['sign'] : ['verify'];
+ break;
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW':
+ algorithm = { name: jwk.crv };
+ keyUsages = jwk.d ? ['deriveBits'] : [];
+ break;
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
+ }
+ break;
+ }
+ default:
+ throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
+ }
+ return { algorithm, keyUsages };
+}
+export default async (jwk) => {
+ if (!jwk.alg) {
+ throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
+ }
+ const { algorithm, keyUsages } = subtleMapping(jwk);
+ const keyData = { ...jwk };
+ delete keyData.alg;
+ delete keyData.use;
+ return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d ? false : true), jwk.key_ops ?? keyUsages);
+};
diff --git a/dist/webapi/lib/jwt_claims_set.js b/dist/webapi/lib/jwt_claims_set.js
new file mode 100644
index 0000000000..68d183a06d
--- /dev/null
+++ b/dist/webapi/lib/jwt_claims_set.js
@@ -0,0 +1,104 @@
+import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';
+import { decoder } from './buffer_utils.js';
+import epoch from './epoch.js';
+import secs from './secs.js';
+import isObject from './is_object.js';
+const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, '');
+const checkAudiencePresence = (audPayload, audOption) => {
+ if (typeof audPayload === 'string') {
+ return audOption.includes(audPayload);
+ }
+ if (Array.isArray(audPayload)) {
+ return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
+ }
+ return false;
+};
+export default (protectedHeader, encodedPayload, options = {}) => {
+ let payload;
+ try {
+ payload = JSON.parse(decoder.decode(encodedPayload));
+ }
+ catch {
+ }
+ if (!isObject(payload)) {
+ throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');
+ }
+ const { typ } = options;
+ if (typ &&
+ (typeof protectedHeader.typ !== 'string' ||
+ normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
+ throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed');
+ }
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
+ const presenceCheck = [...requiredClaims];
+ if (maxTokenAge !== undefined)
+ presenceCheck.push('iat');
+ if (audience !== undefined)
+ presenceCheck.push('aud');
+ if (subject !== undefined)
+ presenceCheck.push('sub');
+ if (issuer !== undefined)
+ presenceCheck.push('iss');
+ for (const claim of new Set(presenceCheck.reverse())) {
+ if (!(claim in payload)) {
+ throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing');
+ }
+ }
+ if (issuer &&
+ !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
+ throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed');
+ }
+ if (subject && payload.sub !== subject) {
+ throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed');
+ }
+ if (audience &&
+ !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {
+ throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed');
+ }
+ let tolerance;
+ switch (typeof options.clockTolerance) {
+ case 'string':
+ tolerance = secs(options.clockTolerance);
+ break;
+ case 'number':
+ tolerance = options.clockTolerance;
+ break;
+ case 'undefined':
+ tolerance = 0;
+ break;
+ default:
+ throw new TypeError('Invalid clockTolerance option type');
+ }
+ const { currentDate } = options;
+ const now = epoch(currentDate || new Date());
+ if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {
+ throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid');
+ }
+ if (payload.nbf !== undefined) {
+ if (typeof payload.nbf !== 'number') {
+ throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid');
+ }
+ if (payload.nbf > now + tolerance) {
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed');
+ }
+ }
+ if (payload.exp !== undefined) {
+ if (typeof payload.exp !== 'number') {
+ throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid');
+ }
+ if (payload.exp <= now - tolerance) {
+ throw new JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed');
+ }
+ }
+ if (maxTokenAge) {
+ const age = now - payload.iat;
+ const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);
+ if (age - tolerance > max) {
+ throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');
+ }
+ if (age < 0 - tolerance) {
+ throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');
+ }
+ }
+ return payload;
+};
diff --git a/dist/webapi/lib/key_to_jwk.js b/dist/webapi/lib/key_to_jwk.js
new file mode 100644
index 0000000000..e74b731bcf
--- /dev/null
+++ b/dist/webapi/lib/key_to_jwk.js
@@ -0,0 +1,27 @@
+import invalidKeyInput from './invalid_key_input.js';
+import { encode as base64url } from './base64url.js';
+import { isCryptoKey, isKeyObject } from './is_key_like.js';
+export default async function keyToJWK(key) {
+ if (isKeyObject(key)) {
+ if (key.type === 'secret') {
+ key = key.export();
+ }
+ else {
+ return key.export({ format: 'jwk' });
+ }
+ }
+ if (key instanceof Uint8Array) {
+ return {
+ kty: 'oct',
+ k: base64url(key),
+ };
+ }
+ if (!isCryptoKey(key)) {
+ throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'Uint8Array'));
+ }
+ if (!key.extractable) {
+ throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK');
+ }
+ const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key);
+ return jwk;
+}
diff --git a/dist/webapi/lib/normalize_key.js b/dist/webapi/lib/normalize_key.js
new file mode 100644
index 0000000000..7b272fa89f
--- /dev/null
+++ b/dist/webapi/lib/normalize_key.js
@@ -0,0 +1,164 @@
+import { isJWK } from './is_jwk.js';
+import { decode } from './base64url.js';
+import importJWK from './jwk_to_key.js';
+import { isCryptoKey, isKeyObject } from './is_key_like.js';
+let cache;
+const handleJWK = async (key, jwk, alg, freeze = false) => {
+ cache ||= new WeakMap();
+ let cached = cache.get(key);
+ if (cached?.[alg]) {
+ return cached[alg];
+ }
+ const cryptoKey = await importJWK({ ...jwk, alg });
+ if (freeze)
+ Object.freeze(key);
+ if (!cached) {
+ cache.set(key, { [alg]: cryptoKey });
+ }
+ else {
+ cached[alg] = cryptoKey;
+ }
+ return cryptoKey;
+};
+const handleKeyObject = (keyObject, alg) => {
+ cache ||= new WeakMap();
+ let cached = cache.get(keyObject);
+ if (cached?.[alg]) {
+ return cached[alg];
+ }
+ const isPublic = keyObject.type === 'public';
+ const extractable = isPublic ? true : false;
+ let cryptoKey;
+ if (keyObject.asymmetricKeyType === 'x25519') {
+ switch (alg) {
+ case 'ECDH-ES':
+ case 'ECDH-ES+A128KW':
+ case 'ECDH-ES+A192KW':
+ case 'ECDH-ES+A256KW':
+ break;
+ default:
+ throw new TypeError('given KeyObject instance cannot be used for this algorithm');
+ }
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ['deriveBits']);
+ }
+ if (keyObject.asymmetricKeyType === 'ed25519') {
+ if (alg !== 'EdDSA' && alg !== 'Ed25519') {
+ throw new TypeError('given KeyObject instance cannot be used for this algorithm');
+ }
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
+ isPublic ? 'verify' : 'sign',
+ ]);
+ }
+ if (keyObject.asymmetricKeyType === 'rsa') {
+ let hash;
+ switch (alg) {
+ case 'RSA-OAEP':
+ hash = 'SHA-1';
+ break;
+ case 'RS256':
+ case 'PS256':
+ case 'RSA-OAEP-256':
+ hash = 'SHA-256';
+ break;
+ case 'RS384':
+ case 'PS384':
+ case 'RSA-OAEP-384':
+ hash = 'SHA-384';
+ break;
+ case 'RS512':
+ case 'PS512':
+ case 'RSA-OAEP-512':
+ hash = 'SHA-512';
+ break;
+ default:
+ throw new TypeError('given KeyObject instance cannot be used for this algorithm');
+ }
+ if (alg.startsWith('RSA-OAEP')) {
+ return keyObject.toCryptoKey({
+ name: 'RSA-OAEP',
+ hash,
+ }, extractable, isPublic ? ['encrypt'] : ['decrypt']);
+ }
+ cryptoKey = keyObject.toCryptoKey({
+ name: alg.startsWith('PS') ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5',
+ hash,
+ }, extractable, [isPublic ? 'verify' : 'sign']);
+ }
+ if (keyObject.asymmetricKeyType === 'ec') {
+ const nist = new Map([
+ ['prime256v1', 'P-256'],
+ ['secp384r1', 'P-384'],
+ ['secp521r1', 'P-521'],
+ ]);
+ const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
+ if (!namedCurve) {
+ throw new TypeError('given KeyObject instance cannot be used for this algorithm');
+ }
+ if (alg === 'ES256' && namedCurve === 'P-256') {
+ cryptoKey = keyObject.toCryptoKey({
+ name: 'ECDSA',
+ namedCurve,
+ }, extractable, [isPublic ? 'verify' : 'sign']);
+ }
+ if (alg === 'ES384' && namedCurve === 'P-384') {
+ cryptoKey = keyObject.toCryptoKey({
+ name: 'ECDSA',
+ namedCurve,
+ }, extractable, [isPublic ? 'verify' : 'sign']);
+ }
+ if (alg === 'ES512' && namedCurve === 'P-521') {
+ cryptoKey = keyObject.toCryptoKey({
+ name: 'ECDSA',
+ namedCurve,
+ }, extractable, [isPublic ? 'verify' : 'sign']);
+ }
+ if (alg.startsWith('ECDH-ES')) {
+ cryptoKey = keyObject.toCryptoKey({
+ name: 'ECDH',
+ namedCurve,
+ }, extractable, isPublic ? [] : ['deriveBits']);
+ }
+ }
+ if (!cryptoKey) {
+ throw new TypeError('given KeyObject instance cannot be used for this algorithm');
+ }
+ if (!cached) {
+ cache.set(keyObject, { [alg]: cryptoKey });
+ }
+ else {
+ cached[alg] = cryptoKey;
+ }
+ return cryptoKey;
+};
+export default async (key, alg) => {
+ if (key instanceof Uint8Array) {
+ return key;
+ }
+ if (isCryptoKey(key)) {
+ return key;
+ }
+ if (isKeyObject(key)) {
+ if (key.type === 'secret') {
+ return key.export();
+ }
+ if ('toCryptoKey' in key && typeof key.toCryptoKey === 'function') {
+ try {
+ return handleKeyObject(key, alg);
+ }
+ catch (err) {
+ if (err instanceof TypeError) {
+ throw err;
+ }
+ }
+ }
+ let jwk = key.export({ format: 'jwk' });
+ return handleJWK(key, jwk, alg);
+ }
+ if (isJWK(key)) {
+ if (key.k) {
+ return decode(key.k);
+ }
+ return handleJWK(key, key, alg, true);
+ }
+ throw new Error('unreachable');
+};
diff --git a/dist/webapi/lib/pbes2kw.js b/dist/webapi/lib/pbes2kw.js
new file mode 100644
index 0000000000..afa696ca02
--- /dev/null
+++ b/dist/webapi/lib/pbes2kw.js
@@ -0,0 +1,37 @@
+import { encode as base64url } from './base64url.js';
+import * as aeskw from './aeskw.js';
+import { checkEncCryptoKey } from './crypto_key.js';
+import { concat, encoder } from './buffer_utils.js';
+import { JWEInvalid } from '../util/errors.js';
+function getCryptoKey(key, alg) {
+ if (key instanceof Uint8Array) {
+ return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']);
+ }
+ checkEncCryptoKey(key, alg, 'deriveBits');
+ return key;
+}
+const concatSalt = (alg, p2sInput) => concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);
+async function deriveKey(p2s, alg, p2c, key) {
+ if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
+ throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets');
+ }
+ const salt = concatSalt(alg, p2s);
+ const keylen = parseInt(alg.slice(13, 16), 10);
+ const subtleAlg = {
+ hash: `SHA-${alg.slice(8, 11)}`,
+ iterations: p2c,
+ name: 'PBKDF2',
+ salt,
+ };
+ const cryptoKey = await getCryptoKey(key, alg);
+ return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
+}
+export async function wrap(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {
+ const derived = await deriveKey(p2s, alg, p2c, key);
+ const encryptedKey = await aeskw.wrap(alg.slice(-6), derived, cek);
+ return { encryptedKey, p2c, p2s: base64url(p2s) };
+}
+export async function unwrap(alg, key, encryptedKey, p2c, p2s) {
+ const derived = await deriveKey(p2s, alg, p2c, key);
+ return aeskw.unwrap(alg.slice(-6), derived, encryptedKey);
+}
diff --git a/dist/webapi/lib/private_symbols.js b/dist/webapi/lib/private_symbols.js
new file mode 100644
index 0000000000..fce302b11e
--- /dev/null
+++ b/dist/webapi/lib/private_symbols.js
@@ -0,0 +1 @@
+export const unprotected = Symbol();
diff --git a/dist/webapi/lib/rsaes.js b/dist/webapi/lib/rsaes.js
new file mode 100644
index 0000000000..ed635860fd
--- /dev/null
+++ b/dist/webapi/lib/rsaes.js
@@ -0,0 +1,24 @@
+import { checkEncCryptoKey } from './crypto_key.js';
+import checkKeyLength from './check_key_length.js';
+import { JOSENotSupported } from '../util/errors.js';
+const subtleAlgorithm = (alg) => {
+ switch (alg) {
+ case 'RSA-OAEP':
+ case 'RSA-OAEP-256':
+ case 'RSA-OAEP-384':
+ case 'RSA-OAEP-512':
+ return 'RSA-OAEP';
+ default:
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+ }
+};
+export async function encrypt(alg, key, cek) {
+ checkEncCryptoKey(key, alg, 'encrypt');
+ checkKeyLength(alg, key);
+ return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));
+}
+export async function decrypt(alg, key, encryptedKey) {
+ checkEncCryptoKey(key, alg, 'decrypt');
+ checkKeyLength(alg, key);
+ return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));
+}
diff --git a/dist/webapi/lib/secs.js b/dist/webapi/lib/secs.js
new file mode 100644
index 0000000000..c99507450a
--- /dev/null
+++ b/dist/webapi/lib/secs.js
@@ -0,0 +1,55 @@
+const minute = 60;
+const hour = minute * 60;
+const day = hour * 24;
+const week = day * 7;
+const year = day * 365.25;
+const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
+export default (str) => {
+ const matched = REGEX.exec(str);
+ if (!matched || (matched[4] && matched[1])) {
+ throw new TypeError('Invalid time period format');
+ }
+ const value = parseFloat(matched[2]);
+ const unit = matched[3].toLowerCase();
+ let numericDate;
+ switch (unit) {
+ case 'sec':
+ case 'secs':
+ case 'second':
+ case 'seconds':
+ case 's':
+ numericDate = Math.round(value);
+ break;
+ case 'minute':
+ case 'minutes':
+ case 'min':
+ case 'mins':
+ case 'm':
+ numericDate = Math.round(value * minute);
+ break;
+ case 'hour':
+ case 'hours':
+ case 'hr':
+ case 'hrs':
+ case 'h':
+ numericDate = Math.round(value * hour);
+ break;
+ case 'day':
+ case 'days':
+ case 'd':
+ numericDate = Math.round(value * day);
+ break;
+ case 'week':
+ case 'weeks':
+ case 'w':
+ numericDate = Math.round(value * week);
+ break;
+ default:
+ numericDate = Math.round(value * year);
+ break;
+ }
+ if (matched[1] === '-' || matched[4] === 'ago') {
+ return -numericDate;
+ }
+ return numericDate;
+};
diff --git a/dist/webapi/lib/sign.js b/dist/webapi/lib/sign.js
new file mode 100644
index 0000000000..44d6c78a98
--- /dev/null
+++ b/dist/webapi/lib/sign.js
@@ -0,0 +1,9 @@
+import subtleAlgorithm from './subtle_dsa.js';
+import checkKeyLength from './check_key_length.js';
+import getSignKey from './get_sign_verify_key.js';
+export default async (alg, key, data) => {
+ const cryptoKey = await getSignKey(alg, key, 'sign');
+ checkKeyLength(alg, cryptoKey);
+ const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
+ return new Uint8Array(signature);
+};
diff --git a/dist/webapi/lib/subtle_dsa.js b/dist/webapi/lib/subtle_dsa.js
new file mode 100644
index 0000000000..ec3ee0730a
--- /dev/null
+++ b/dist/webapi/lib/subtle_dsa.js
@@ -0,0 +1,27 @@
+import { JOSENotSupported } from '../util/errors.js';
+export default (alg, algorithm) => {
+ const hash = `SHA-${alg.slice(-3)}`;
+ switch (alg) {
+ case 'HS256':
+ case 'HS384':
+ case 'HS512':
+ return { hash, name: 'HMAC' };
+ case 'PS256':
+ case 'PS384':
+ case 'PS512':
+ return { hash, name: 'RSA-PSS', saltLength: parseInt(alg.slice(-3), 10) >> 3 };
+ case 'RS256':
+ case 'RS384':
+ case 'RS512':
+ return { hash, name: 'RSASSA-PKCS1-v1_5' };
+ case 'ES256':
+ case 'ES384':
+ case 'ES512':
+ return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };
+ case 'Ed25519':
+ case 'EdDSA':
+ return { name: 'Ed25519' };
+ default:
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
+ }
+};
diff --git a/dist/webapi/lib/validate_algorithms.js b/dist/webapi/lib/validate_algorithms.js
new file mode 100644
index 0000000000..7edf916080
--- /dev/null
+++ b/dist/webapi/lib/validate_algorithms.js
@@ -0,0 +1,10 @@
+export default (option, algorithms) => {
+ if (algorithms !== undefined &&
+ (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {
+ throw new TypeError(`"${option}" option must be an array of strings`);
+ }
+ if (!algorithms) {
+ return undefined;
+ }
+ return new Set(algorithms);
+};
diff --git a/dist/webapi/lib/validate_crit.js b/dist/webapi/lib/validate_crit.js
new file mode 100644
index 0000000000..d09b5dd1be
--- /dev/null
+++ b/dist/webapi/lib/validate_crit.js
@@ -0,0 +1,33 @@
+import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.js';
+export default (Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) => {
+ if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
+ }
+ if (!protectedHeader || protectedHeader.crit === undefined) {
+ return new Set();
+ }
+ if (!Array.isArray(protectedHeader.crit) ||
+ protectedHeader.crit.length === 0 ||
+ protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
+ }
+ let recognized;
+ if (recognizedOption !== undefined) {
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
+ }
+ else {
+ recognized = recognizedDefault;
+ }
+ for (const parameter of protectedHeader.crit) {
+ if (!recognized.has(parameter)) {
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
+ }
+ if (joseHeader[parameter] === undefined) {
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
+ }
+ if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
+ }
+ }
+ return new Set(protectedHeader.crit);
+};
diff --git a/dist/webapi/lib/verify.js b/dist/webapi/lib/verify.js
new file mode 100644
index 0000000000..710151dbe3
--- /dev/null
+++ b/dist/webapi/lib/verify.js
@@ -0,0 +1,14 @@
+import subtleAlgorithm from './subtle_dsa.js';
+import checkKeyLength from './check_key_length.js';
+import getVerifyKey from './get_sign_verify_key.js';
+export default async (alg, key, signature, data) => {
+ const cryptoKey = await getVerifyKey(alg, key, 'verify');
+ checkKeyLength(alg, cryptoKey);
+ const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
+ try {
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
+ }
+ catch {
+ return false;
+ }
+};
diff --git a/dist/webapi/util/base64url.js b/dist/webapi/util/base64url.js
new file mode 100644
index 0000000000..0ad2f06447
--- /dev/null
+++ b/dist/webapi/util/base64url.js
@@ -0,0 +1,3 @@
+import * as base64url from '../lib/base64url.js';
+export const encode = base64url.encode;
+export const decode = base64url.decode;
diff --git a/dist/webapi/util/decode_jwt.js b/dist/webapi/util/decode_jwt.js
new file mode 100644
index 0000000000..b6f2602f95
--- /dev/null
+++ b/dist/webapi/util/decode_jwt.js
@@ -0,0 +1,32 @@
+import { decode as base64url } from './base64url.js';
+import { decoder } from '../lib/buffer_utils.js';
+import isObject from '../lib/is_object.js';
+import { JWTInvalid } from './errors.js';
+export function decodeJwt(jwt) {
+ if (typeof jwt !== 'string')
+ throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string');
+ const { 1: payload, length } = jwt.split('.');
+ if (length === 5)
+ throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded');
+ if (length !== 3)
+ throw new JWTInvalid('Invalid JWT');
+ if (!payload)
+ throw new JWTInvalid('JWTs must contain a payload');
+ let decoded;
+ try {
+ decoded = base64url(payload);
+ }
+ catch {
+ throw new JWTInvalid('Failed to base64url decode the payload');
+ }
+ let result;
+ try {
+ result = JSON.parse(decoder.decode(decoded));
+ }
+ catch {
+ throw new JWTInvalid('Failed to parse the decoded payload as JSON');
+ }
+ if (!isObject(result))
+ throw new JWTInvalid('Invalid JWT Claims Set');
+ return result;
+}
diff --git a/dist/webapi/util/decode_protected_header.js b/dist/webapi/util/decode_protected_header.js
new file mode 100644
index 0000000000..04be31d8f2
--- /dev/null
+++ b/dist/webapi/util/decode_protected_header.js
@@ -0,0 +1,34 @@
+import { decode as base64url } from './base64url.js';
+import { decoder } from '../lib/buffer_utils.js';
+import isObject from '../lib/is_object.js';
+export function decodeProtectedHeader(token) {
+ let protectedB64u;
+ if (typeof token === 'string') {
+ const parts = token.split('.');
+ if (parts.length === 3 || parts.length === 5) {
+ ;
+ [protectedB64u] = parts;
+ }
+ }
+ else if (typeof token === 'object' && token) {
+ if ('protected' in token) {
+ protectedB64u = token.protected;
+ }
+ else {
+ throw new TypeError('Token does not contain a Protected Header');
+ }
+ }
+ try {
+ if (typeof protectedB64u !== 'string' || !protectedB64u) {
+ throw new Error();
+ }
+ const result = JSON.parse(decoder.decode(base64url(protectedB64u)));
+ if (!isObject(result)) {
+ throw new Error();
+ }
+ return result;
+ }
+ catch {
+ throw new TypeError('Invalid Token or Protected Header formatting');
+ }
+}
diff --git a/dist/webapi/util/errors.js b/dist/webapi/util/errors.js
new file mode 100644
index 0000000000..6fa9568dd1
--- /dev/null
+++ b/dist/webapi/util/errors.js
@@ -0,0 +1,99 @@
+export class JOSEError extends Error {
+ static code = 'ERR_JOSE_GENERIC';
+ code = 'ERR_JOSE_GENERIC';
+ constructor(message, options) {
+ super(message, options);
+ this.name = this.constructor.name;
+ Error.captureStackTrace?.(this, this.constructor);
+ }
+}
+export class JWTClaimValidationFailed extends JOSEError {
+ static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
+ code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
+ claim;
+ reason;
+ payload;
+ constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {
+ super(message, { cause: { claim, reason, payload } });
+ this.claim = claim;
+ this.reason = reason;
+ this.payload = payload;
+ }
+}
+export class JWTExpired extends JOSEError {
+ static code = 'ERR_JWT_EXPIRED';
+ code = 'ERR_JWT_EXPIRED';
+ claim;
+ reason;
+ payload;
+ constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {
+ super(message, { cause: { claim, reason, payload } });
+ this.claim = claim;
+ this.reason = reason;
+ this.payload = payload;
+ }
+}
+export class JOSEAlgNotAllowed extends JOSEError {
+ static code = 'ERR_JOSE_ALG_NOT_ALLOWED';
+ code = 'ERR_JOSE_ALG_NOT_ALLOWED';
+}
+export class JOSENotSupported extends JOSEError {
+ static code = 'ERR_JOSE_NOT_SUPPORTED';
+ code = 'ERR_JOSE_NOT_SUPPORTED';
+}
+export class JWEDecryptionFailed extends JOSEError {
+ static code = 'ERR_JWE_DECRYPTION_FAILED';
+ code = 'ERR_JWE_DECRYPTION_FAILED';
+ constructor(message = 'decryption operation failed', options) {
+ super(message, options);
+ }
+}
+export class JWEInvalid extends JOSEError {
+ static code = 'ERR_JWE_INVALID';
+ code = 'ERR_JWE_INVALID';
+}
+export class JWSInvalid extends JOSEError {
+ static code = 'ERR_JWS_INVALID';
+ code = 'ERR_JWS_INVALID';
+}
+export class JWTInvalid extends JOSEError {
+ static code = 'ERR_JWT_INVALID';
+ code = 'ERR_JWT_INVALID';
+}
+export class JWKInvalid extends JOSEError {
+ static code = 'ERR_JWK_INVALID';
+ code = 'ERR_JWK_INVALID';
+}
+export class JWKSInvalid extends JOSEError {
+ static code = 'ERR_JWKS_INVALID';
+ code = 'ERR_JWKS_INVALID';
+}
+export class JWKSNoMatchingKey extends JOSEError {
+ static code = 'ERR_JWKS_NO_MATCHING_KEY';
+ code = 'ERR_JWKS_NO_MATCHING_KEY';
+ constructor(message = 'no applicable key found in the JSON Web Key Set', options) {
+ super(message, options);
+ }
+}
+export class JWKSMultipleMatchingKeys extends JOSEError {
+ [Symbol.asyncIterator];
+ static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
+ code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
+ constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {
+ super(message, options);
+ }
+}
+export class JWKSTimeout extends JOSEError {
+ static code = 'ERR_JWKS_TIMEOUT';
+ code = 'ERR_JWKS_TIMEOUT';
+ constructor(message = 'request timed out', options) {
+ super(message, options);
+ }
+}
+export class JWSSignatureVerificationFailed extends JOSEError {
+ static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
+ code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
+ constructor(message = 'signature verification failed', options) {
+ super(message, options);
+ }
+}
diff --git a/jsr.json b/jsr.json
index 924f43a30b..97c09e5910 100644
--- a/jsr.json
+++ b/jsr.json
@@ -1,7 +1,7 @@
{
"$schema": "https://jsr.io/schema/config-file.v1.json",
"name": "@panva/jose",
- "version": "6.0.0",
+ "version": "6.0.1",
"exports": {
".": "./src/index.ts",
"./jwk/embedded": "./src/jwk/embedded.ts",
diff --git a/package-lock.json b/package-lock.json
index 6253464f1f..40448ae328 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "jose",
- "version": "6.0.0",
+ "version": "6.0.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "jose",
- "version": "6.0.0",
+ "version": "6.0.1",
"license": "MIT",
"devDependencies": {
"@types/node": "^22.13.5",
diff --git a/package.json b/package.json
index e3749906b6..9fe6ceea90 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "jose",
- "version": "6.0.0",
+ "version": "6.0.1",
"description": "JWA, JWS, JWE, JWT, JWK, JWKS for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes",
"keywords": [
"browser",
diff --git a/src/jwks/remote.ts b/src/jwks/remote.ts
index 756d9aee2f..59ec851457 100644
--- a/src/jwks/remote.ts
+++ b/src/jwks/remote.ts
@@ -22,7 +22,7 @@ let USER_AGENT: string
// @ts-ignore
if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
const NAME = 'jose'
- const VERSION = 'v6.0.0'
+ const VERSION = 'v6.0.1'
USER_AGENT = `${NAME}/${VERSION}`
}