修改后台权限

This commit is contained in:
yoyuzh
2026-03-24 14:30:59 +08:00
parent 00f902f475
commit b2d9db7be9
9310 changed files with 1246063 additions and 48 deletions

55
node_modules/jose/dist/types/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,55 @@
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 { 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, customFetch } from './jwks/remote.js';
export type { RemoteJWKSetOptions, JWKSCacheInput, ExportedJWKSCache, 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';
import * as errors from './util/errors.js';
export { errors };
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';
import * as base64url from './util/base64url.js';
export { base64url };
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, ProduceJWT, ResolvedKey, SignOptions, VerifyOptions, } from './types.d.ts';
/**
* In prior releases this indicated whether a Node.js-specific build was loaded, this is now fixed
* to `"WebCryptoAPI"`
*
* @deprecated
*/
export declare const cryptoRuntime = "WebCryptoAPI";

31
node_modules/jose/dist/types/jwe/compact/decrypt.d.ts generated vendored Normal file
View File

@@ -0,0 +1,31 @@
/**
* Decrypting JSON Web Encryption (JWE) in Compact Serialization
*
* @module
*/
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<types.CompactJWEHeaderParameters, types.FlattenedJWE> {
}
/**
* 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<types.CompactDecryptResult>;
/**
* @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<types.CompactDecryptResult & types.ResolvedKey>;

65
node_modules/jose/dist/types/jwe/compact/encrypt.d.ts generated vendored Normal file
View File

@@ -0,0 +1,65 @@
/**
* Encrypting JSON Web Encryption (JWE) in Compact Serialization
*
* @module
*/
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;
/**
* {@link CompactEncrypt} constructor
*
* @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.
*
* (ECDH-ES) Use of this method is needed for ECDH based algorithms to set the "apu" (Agreement
* PartyUInfo) or "apv" (Agreement PartyVInfo) parameters.
*
* @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<string>;
}

View File

@@ -0,0 +1,31 @@
/**
* Decrypting JSON Web Encryption (JWE) in Flattened JSON Serialization
*
* @module
*/
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<types.JWEHeaderParameters | undefined, types.FlattenedJWE> {
}
/**
* 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<types.FlattenedDecryptResult>;
/**
* @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<types.FlattenedDecryptResult & types.ResolvedKey>;

View File

@@ -0,0 +1,83 @@
/**
* Encrypting JSON Web Encryption (JWE) in Flattened JSON Serialization
*
* @module
*/
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;
/**
* {@link FlattenedEncrypt} constructor
*
* @param plaintext Binary representation of the plaintext to encrypt.
*/
constructor(plaintext: Uint8Array);
/**
* Sets the JWE Key Management parameters to be used when encrypting.
*
* (ECDH-ES) Use of this method is needed for ECDH based algorithms to set the "apu" (Agreement
* PartyUInfo) or "apv" (Agreement PartyVInfo) parameters.
*
* @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<types.FlattenedJWE>;
}

38
node_modules/jose/dist/types/jwe/general/decrypt.d.ts generated vendored Normal file
View File

@@ -0,0 +1,38 @@
/**
* Decrypting JSON Web Encryption (JWE) in General JSON Serialization
*
* @module
*/
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<types.JWEHeaderParameters, types.FlattenedJWE> {
}
/**
* 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'`.
*
* > [!NOTE]\
* > The function iterates over the `recipients` array in the General JWE and returns the decryption
* > result of the first recipient entry that can be successfully decrypted. The result only contains
* > the plaintext and headers of that successfully decrypted recipient entry. Other recipient entries
* > in the General JWE are not validated, and their headers are not included in the returned result.
* > Recipients of a General JWE should only rely on the returned (decrypted) data.
*
* @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<types.GeneralDecryptResult>;
/**
* @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<types.GeneralDecryptResult & types.ResolvedKey>;

74
node_modules/jose/dist/types/jwe/general/encrypt.d.ts generated vendored Normal file
View File

@@ -0,0 +1,74 @@
/**
* Encrypting JSON Web Encryption (JWE) in General JSON Serialization
*
* @module
*/
import type * as types from '../../types.d.ts';
/** Used to build General JWE object's individual recipients. */
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;
/**
* Sets the JWE Key Management parameters to be used when encrypting.
*
* (ECDH-ES) Use of this method is needed for ECDH based algorithms to set the "apu" (Agreement
* PartyUInfo) or "apv" (Agreement PartyVInfo) parameters.
*
* @param parameters JWE Key Management parameters.
*/
setKeyManagementParameters(parameters: types.JWEKeyManagementHeaderParameters): Recipient;
/** A shorthand for calling addRecipient() on the enclosing {@link GeneralEncrypt} instance */
addRecipient(...args: Parameters<GeneralEncrypt['addRecipient']>): Recipient;
/** A shorthand for calling encrypt() on the enclosing {@link GeneralEncrypt} instance */
encrypt(...args: Parameters<GeneralEncrypt['encrypt']>): Promise<types.GeneralJWE>;
/** Returns the enclosing {@link GeneralEncrypt} instance */
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;
/**
* {@link GeneralEncrypt} constructor
*
* @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<types.GeneralJWE>;
}

17
node_modules/jose/dist/types/jwk/embedded.d.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
/**
* Verification using a JWK Embedded in a JWS Header
*
* @module
*/
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<types.CryptoKey>;

32
node_modules/jose/dist/types/jwk/thumbprint.d.ts generated vendored Normal file
View File

@@ -0,0 +1,32 @@
/**
* JSON Web Key Thumbprint and JSON Web Key Thumbprint URI
*
* @module
*/
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<string>;
/**
* 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<string>;

29
node_modules/jose/dist/types/jwks/local.d.ts generated vendored Normal file
View File

@@ -0,0 +1,29 @@
/**
* Verification using a JSON Web Key Set (JWKS) available locally
*
* @module
*/
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<types.CryptoKey>;

237
node_modules/jose/dist/types/jwks/remote.d.ts generated vendored Normal file
View File

@@ -0,0 +1,237 @@
/**
* Verification using a JSON Web Key Set (JWKS) available on an HTTP(S) URL
*
* @module
*/
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.
*
* > [!NOTE]\
* > Known caveat: Expect Type-related issues when passing the inputs through to fetch-like modules,
* > they hardly ever get their typings inline with actual fetch, you should `@ts-expect-error` them.
*
* 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;
/** See {@link customFetch}. */
export type FetchImplementation = (
/** URL the request is being made sent to {@link !fetch} as the `resource` argument */
url: string,
/** Options otherwise sent to {@link !fetch} as the `options` argument */
options: {
/** HTTP Headers */
headers: Headers;
/** The {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods request method} */
method: 'GET';
/** See {@link !Request.redirect} */
redirect: 'manual';
signal: AbortSignal;
}) => Promise<Response>;
/**
* > [!WARNING]\
* > 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<jose.ExportedJWKSCache>
* let storeNewJWKScache!: (cache: jose.ExportedJWKSCache) => Promise<void>
*
* // 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<string, string>;
/** See {@link jwksCache}. */
[jwksCache]?: JWKSCacheInput;
/** See {@link customFetch}. */
[customFetch]?: FetchImplementation;
}
/** See {@link jwksCache}. */
export interface ExportedJWKSCache {
/** Current cached JSON Web Key Set */
jwks: types.JSONWebKeySet;
/** Last updated at timestamp (seconds since epoch) */
uat: number;
}
/** See {@link jwksCache}. */
export type JWKSCacheInput = ExportedJWKSCache | Record<string, never>;
/**
* 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<types.CryptoKey>;
/** @ignore */
coolingDown: boolean;
/** @ignore */
fresh: boolean;
/** @ignore */
reloading: boolean;
/** @ignore */
reload: () => Promise<void>;
/** @ignore */
jwks: () => types.JSONWebKeySet | undefined;
};

36
node_modules/jose/dist/types/jws/compact/sign.d.ts generated vendored Normal file
View File

@@ -0,0 +1,36 @@
/**
* Signing JSON Web Signature (JWS) in Compact Serialization
*
* @module
*/
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;
/**
* {@link CompactSign} constructor
*
* @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<string>;
}

33
node_modules/jose/dist/types/jws/compact/verify.d.ts generated vendored Normal file
View File

@@ -0,0 +1,33 @@
/**
* Verifying JSON Web Signature (JWS) in Compact Serialization
*
* @module
*/
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<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 declare function compactVerify(jws: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.VerifyOptions): Promise<types.CompactVerifyResult>;
/**
* @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<types.CompactVerifyResult & types.ResolvedKey>;

42
node_modules/jose/dist/types/jws/flattened/sign.d.ts generated vendored Normal file
View File

@@ -0,0 +1,42 @@
/**
* Signing JSON Web Signature (JWS) in Flattened JSON Serialization
*
* @module
*/
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;
/**
* {@link FlattenedSign} constructor
*
* @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<types.FlattenedJWS>;
}

33
node_modules/jose/dist/types/jws/flattened/verify.d.ts generated vendored Normal file
View File

@@ -0,0 +1,33 @@
/**
* Verifying JSON Web Signature (JWS) in Flattened JSON Serialization
*
* @module
*/
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<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 declare function flattenedVerify(jws: types.FlattenedJWSInput, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: types.VerifyOptions): Promise<types.FlattenedVerifyResult>;
/**
* @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<types.FlattenedVerifyResult & types.ResolvedKey>;

53
node_modules/jose/dist/types/jws/general/sign.d.ts generated vendored Normal file
View File

@@ -0,0 +1,53 @@
/**
* Signing JSON Web Signature (JWS) in General JSON Serialization
*
* @module
*/
import type * as types from '../../types.d.ts';
/** Used to build General JWS object's individual signatures. */
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 {@link GeneralSign} instance */
addSignature(...args: Parameters<GeneralSign['addSignature']>): Signature;
/** A shorthand for calling encrypt() on the enclosing {@link GeneralSign} instance */
sign(...args: Parameters<GeneralSign['sign']>): Promise<types.GeneralJWS>;
/** Returns the enclosing {@link GeneralSign} instance */
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;
/**
* {@link GeneralSign} constructor
*
* @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<types.GeneralJWS>;
}

41
node_modules/jose/dist/types/jws/general/verify.d.ts generated vendored Normal file
View File

@@ -0,0 +1,41 @@
/**
* Verifying JSON Web Signature (JWS) in General JSON Serialization
*
* @module
*/
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<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'`.
*
* > [!NOTE]\
* > The function iterates over the `signatures` array in the General JWS and returns the verification
* > result of the first signature entry that can be successfully verified. The result only contains
* > the payload, protected header, and unprotected header of that successfully verified signature
* > entry. Other signature entries in the General JWS are not validated, and their headers are not
* > included in the returned result. Recipients of a General JWS should only rely on the returned
* > (verified) data.
*
* @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<types.GeneralVerifyResult>;
/**
* @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<types.GeneralVerifyResult & types.ResolvedKey>;

35
node_modules/jose/dist/types/jwt/decrypt.d.ts generated vendored Normal file
View File

@@ -0,0 +1,35 @@
/**
* JSON Web Token (JWT) Decryption (JWT is in JWE format)
*
* @module
*/
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<types.CompactJWEHeaderParameters, types.FlattenedJWE> {
}
/**
* 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<PayloadType = types.JWTPayload>(jwt: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: JWTDecryptOptions): Promise<types.JWTDecryptResult<PayloadType>>;
/**
* @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<PayloadType = types.JWTPayload>(jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions): Promise<types.JWTDecryptResult<PayloadType> & types.ResolvedKey>;

91
node_modules/jose/dist/types/jwt/encrypt.d.ts generated vendored Normal file
View File

@@ -0,0 +1,91 @@
/**
* JSON Web Token (JWT) Encryption (JWT is in JWE format)
*
* @module
*/
import type * as types from '../types.d.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 declare class EncryptJWT implements types.ProduceJWT {
#private;
/**
* {@link EncryptJWT} constructor
*
* @param payload The JWT Claims Set object. Defaults to an empty object.
*/
constructor(payload?: types.JWTPayload);
setIssuer(issuer: string): this;
setSubject(subject: string): this;
setAudience(audience: string | string[]): this;
setJti(jwtId: string): this;
setNotBefore(input: number | string | Date): this;
setExpirationTime(input: number | string | Date): this;
setIssuedAt(input?: number | string | Date): this;
/**
* 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.
*
* (ECDH-ES) Use of this method is needed for ECDH based algorithms to set the "apu" (Agreement
* PartyUInfo) or "apv" (Agreement PartyVInfo) parameters.
*
* @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<string>;
}

43
node_modules/jose/dist/types/jwt/sign.d.ts generated vendored Normal file
View File

@@ -0,0 +1,43 @@
/**
* JSON Web Token (JWT) Signing (JWT is in JWS format)
*
* @module
*/
import type * as types from '../types.d.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 declare class SignJWT implements types.ProduceJWT {
#private;
/**
* {@link SignJWT} constructor
*
* @param payload The JWT Claims Set object. Defaults to an empty object.
*/
constructor(payload?: types.JWTPayload);
setIssuer(issuer: string): this;
setSubject(subject: string): this;
setAudience(audience: string | string[]): this;
setJti(jwtId: string): this;
setNotBefore(input: number | string | Date): this;
setExpirationTime(input: number | string | Date): this;
setIssuedAt(input?: number | string | Date): this;
/**
* 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<string>;
}

43
node_modules/jose/dist/types/jwt/unsecured.d.ts generated vendored Normal file
View File

@@ -0,0 +1,43 @@
/**
* Unsecured (unsigned & unencrypted) JSON Web Tokens (JWT)
*
* @module
*/
import type * as types from '../types.d.ts';
/** Result of decoding an Unsecured JWT. */
export interface UnsecuredResult<PayloadType = types.JWTPayload> {
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 implements types.ProduceJWT {
#private;
/**
* {@link UnsecuredJWT} constructor
*
* @param payload The JWT Claims Set object. Defaults to an empty object.
*/
constructor(payload?: types.JWTPayload);
/** Encodes the Unsecured JWT. */
encode(): string;
setIssuer(issuer: string): this;
setSubject(subject: string): this;
setAudience(audience: string | string[]): this;
setJti(jwtId: string): this;
setNotBefore(input: number | string | Date): this;
setExpirationTime(input: number | string | Date): this;
setIssuedAt(input?: number | string | Date): this;
/**
* Decodes an unsecured JWT.
*
* @param jwt Unsecured JWT to decode the payload of.
* @param options JWT Claims Set validation options.
*/
static decode<PayloadType = types.JWTPayload>(jwt: string, options?: types.JWTClaimVerificationOptions): UnsecuredResult<PayloadType>;
}

37
node_modules/jose/dist/types/jwt/verify.d.ts generated vendored Normal file
View File

@@ -0,0 +1,37 @@
/**
* JSON Web Token (JWT) Verification (JWT is in JWS format)
*
* @module
*/
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<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 declare function jwtVerify<PayloadType = types.JWTPayload>(jwt: string | Uint8Array, key: types.CryptoKey | types.KeyObject | types.JWK | Uint8Array, options?: JWTVerifyOptions): Promise<types.JWTVerifyResult<PayloadType>>;
/**
* @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<PayloadType = types.JWTPayload>(jwt: string | Uint8Array, getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): Promise<types.JWTVerifyResult<PayloadType> & types.ResolvedKey>;

33
node_modules/jose/dist/types/key/export.d.ts generated vendored Normal file
View File

@@ -0,0 +1,33 @@
/**
* Cryptographic key export functions
*
* @module
*/
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<string>;
/**
* 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<string>;
/**
* 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<types.JWK>;

View File

@@ -0,0 +1,47 @@
/**
* Asymmetric key generation
*
* @module
*/
import type * as types from '../types.d.ts';
/** Asymmetric key pair generation function result. */
export interface GenerateKeyPairResult {
/** The generated Private Key. */
privateKey: types.CryptoKey;
/** Public Key corresponding to the generated Private Key. */
publicKey: types.CryptoKey;
}
/** Asymmetric key pair generation function options. */
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<GenerateKeyPairResult>;

35
node_modules/jose/dist/types/key/generate_secret.d.ts generated vendored Normal file
View File

@@ -0,0 +1,35 @@
/**
* Symmetric key generation
*
* @module
*/
import type * as types from '../types.d.ts';
/** Secret generation function options. */
export interface GenerateSecretOptions {
/**
* The value to use as {@link !SubtleCrypto.generateKey} `extractable` argument. Default is false.
*
* > [!NOTE]\
* > Because A128CBC-HS256, A192CBC-HS384, and A256CBC-HS512 secrets cannot be represented as
* > {@link !CryptoKey} this option has no effect for them.
*/
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.
*
* > [!NOTE]\
* > Because A128CBC-HS256, A192CBC-HS384, and A256CBC-HS512 secrets cannot be represented as
* > {@link !CryptoKey} this method yields a {@link !Uint8Array} for them instead.
*
* 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<types.CryptoKey | Uint8Array>;

83
node_modules/jose/dist/types/key/import.d.ts generated vendored Normal file
View File

@@ -0,0 +1,83 @@
/**
* Cryptographic key import functions
*
* @module
*/
import type * as types from '../types.d.ts';
/** Key Import Function options. */
export interface KeyImportOptions {
/**
* The value to use as {@link !SubtleCrypto.importKey} `extractable` argument. Default is false for
* private 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<types.CryptoKey>;
/**
* 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<types.CryptoKey>;
/**
* 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<types.CryptoKey>;
/**
* Imports a JWK to a {@link !CryptoKey}. Either the JWK "alg" (Algorithm) Parameter, or the optional
* "alg" argument, must be present for asymmetric JSON Web Key imports.
*
* > [!NOTE]\
* > The JSON Web Key parameters "use", "key_ops", and "ext" are also used in the {@link !CryptoKey}
* > import process.
*
* > [!NOTE]\
* > Symmetric JSON Web Keys (i.e. `kty: "oct"`) yield back an {@link !Uint8Array} instead of a
* > {@link !CryptoKey}.
*
* 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<types.CryptoKey | Uint8Array>;

852
node_modules/jose/dist/types/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,852 @@
/** 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 {
/** OKP JWK "d" (The Private Key) Parameter */
d: string
}
/** Convenience interface for Public AKP JSON Web Keys */
export interface JWK_AKP_Public extends JWKParameters {
/** JWK "alg" (Algorithm) Parameter */
alg: string
/** AKP JWK "pub" (The Public key) Parameter */
pub: string
}
/** Convenience interface for Private AKP JSON Web Keys */
export interface JWK_AKP_Private extends JWK_AKP_Public {
/** AKP JWK "priv" (The Private Key) Parameter */
priv: 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 {
/** 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 {
/** 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", "AKP", and
* "oct" key types are supported.
*
* @see {@link JWK_AKP_Public}
* @see {@link JWK_AKP_Private}
* @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
/** AKP JWK "pub" (Public Key) Parameter */
pub?: string
/** AKP JWK "priv" (Private key) Parameter */
priv?: string
}
/**
* @private
*
* @internal
*/
export interface GenericGetKeyFunction<IProtectedHeader, IToken, ReturnKeyTypes> {
/**
* Dynamic key resolution function. No token components have been verified at the time of this
* function call.
*
* If a suitable key for the token cannot be matched, 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> | 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<IProtectedHeader, IToken> 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<FlattenedJWSInput, 'payload'>[]
}
/**
* Flattened JWS JSON Serialization Syntax token. 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<FlattenedJWSInput> {
payload: string
signature: string
}
/**
* General JWS JSON Serialization Syntax token. 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<FlattenedJWSInput, 'payload'>[]
}
/** Header Parameters common to JWE and JWS */
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<JWK, 'kty' | 'crv' | 'x' | 'y' | 'e' | 'n' | 'alg' | 'pub'>
/** "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 {
/**
* ECDH-ES "apu" (Agreement PartyUInfo). This will be used as a JOSE Header Parameter and will be
* used in ECDH's ConcatKDF.
*/
apu?: Uint8Array
/**
* ECDH-ES "apv" (Agreement PartyVInfo). This will be used as a JOSE Header Parameter and will be
* used in ECDH's ConcatKDF.
*/
apv?: Uint8Array
/**
* @deprecated You should not use this parameter. It is only intended for testing and vector
* validation purposes.
*/
p2c?: number
/**
* @deprecated You should not use this parameter. It is only intended for testing and vector
* validation purposes.
*/
p2s?: Uint8Array
/**
* @deprecated You should not use this parameter. It is only intended for testing and vector
* validation purposes.
*/
iv?: Uint8Array
/**
* @deprecated You should not use this parameter. It is only intended for testing and vector
* validation purposes.
*/
epk?: CryptoKey | KeyObject
}
/** Flattened JWE JSON Serialization Syntax token. */
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
}
/** General JWE JSON Serialization Syntax token. */
export interface GeneralJWE extends Omit<FlattenedJWE, 'encrypted_key' | 'header'> {
recipients: Pick<FlattenedJWE, 'encrypted_key' | 'header'>[]
}
/** 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.
*
* The only supported value is `"DEF"` (DEFLATE). Requires the `CompressionStream` /
* `DecompressionStream` APIs to be available in the runtime.
*
* @see {@link https://www.rfc-editor.org/rfc/rfc7516#section-4.1.3 JWE "zip" Header Parameter}
*/
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
/**
* Maximum allowed size (in bytes) of the decompressed plaintext when the JWE `"zip"` (Compression
* Algorithm) Header Parameter is present. By default this value is set to 250000 (250 KB). The
* value must be `0`, a positive safe integer, or `Infinity`.
*
* Set to `0` to reject all compressed JWEs during decryption.
*
* Set to `Infinity` to disable the decompressed size limit.
*/
maxDecompressedLength?: 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
}
/** Flattened JWE JSON Serialization Syntax decryption result */
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
}
/** General JWE JSON Serialization Syntax decryption result */
export interface GeneralDecryptResult extends FlattenedDecryptResult {}
/** Compact JWE decryption result */
export interface CompactDecryptResult {
/** Plaintext. */
plaintext: Uint8Array
/** JWE Protected Header. */
protectedHeader: CompactJWEHeaderParameters
}
/** Flattened JWS JSON Serialization Syntax verification result */
export interface FlattenedVerifyResult {
/** JWS Payload. */
payload: Uint8Array
/** JWS Protected Header. */
protectedHeader?: JWSHeaderParameters
/** JWS Unprotected Header. */
unprotectedHeader?: JWSHeaderParameters
}
/** General JWS JSON Serialization Syntax verification result */
export interface GeneralVerifyResult extends FlattenedVerifyResult {}
/** Compact JWS verification result */
export interface CompactVerifyResult {
/** JWS Payload. */
payload: Uint8Array
/** JWS Protected Header. */
protectedHeader: CompactJWSHeaderParameters
}
/** Signed JSON Web Token (JWT) verification result */
export interface JWTVerifyResult<PayloadType = JWTPayload> {
/** JWT Claims Set. */
payload: PayloadType & JWTPayload
/** JWS Protected Header. */
protectedHeader: JWTHeaderParameters
}
/** Encrypted JSON Web Token (JWT) decryption result */
export interface JWTDecryptResult<PayloadType = JWTPayload> {
/** JWT Claims Set. */
payload: PayloadType & JWTPayload
/** JWE Protected Header. */
protectedHeader: CompactJWEHeaderParameters
}
/** When key resolver functions are used this becomes part of successful resolves */
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<ReturnType<typeof crypto.subtle.generateKey>>,
{ type: string }
>
/** Generic interface for JWT producing classes. */
export interface ProduceJWT {
/**
* 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
}

9
node_modules/jose/dist/types/util/base64url.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
/**
* Base64URL encoding and decoding utilities
*
* @module
*/
/** Decodes a Base64URL encoded input. */
export declare function decode(input: Uint8Array | string): Uint8Array;
/** Encodes an input using Base64URL with no padding. */
export declare function encode(input: Uint8Array | string): string;

18
node_modules/jose/dist/types/util/decode_jwt.d.ts generated vendored Normal file
View File

@@ -0,0 +1,18 @@
/**
* JSON Web Token (JWT) Claims Set Decoding (no validation, no signature checking)
*
* @module
*/
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<PayloadType = types.JWTPayload>(jwt: string): PayloadType & types.JWTPayload;

View File

@@ -0,0 +1,17 @@
/**
* JOSE Protected Header Decoding (JWE, JWS, all serialization syntaxes)
*
* @module
*/
import type * as types from '../types.d.ts';
/** JWE and JWS Header Parameters */
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;

213
node_modules/jose/dist/types/util/errors.d.ts generated vendored Normal file
View File

@@ -0,0 +1,213 @@
/**
* JOSE module errors and error codes
*
* @module
*/
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 {@link JOSEError}. */
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;
/** A unique error code for {@link JWTClaimValidationFailed}. */
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;
/** A unique error code for {@link JWTExpired}. */
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;
/** A unique error code for {@link JOSEAlgNotAllowed}. */
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;
/** A unique error code for {@link JOSENotSupported}. */
code: string;
}
/**
* An error subclass thrown when a JWE ciphertext decryption fails.
*
*/
export declare class JWEDecryptionFailed extends JOSEError {
/** @ignore */
static code: string;
/** A unique error code for {@link JWEDecryptionFailed}. */
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;
/** A unique error code for {@link JWEInvalid}. */
code: string;
}
/**
* An error subclass thrown when a JWS is invalid.
*
*/
export declare class JWSInvalid extends JOSEError {
/** @ignore */
static code: string;
/** A unique error code for {@link JWSInvalid}. */
code: string;
}
/**
* An error subclass thrown when a JWT is invalid.
*
*/
export declare class JWTInvalid extends JOSEError {
/** @ignore */
static code: string;
/** A unique error code for {@link JWTInvalid}. */
code: string;
}
/**
* An error subclass thrown when a JWK is invalid.
*
*/
export declare class JWKInvalid extends JOSEError {
/** @ignore */
static code: string;
/** A unique error code for {@link JWKInvalid}. */
code: string;
}
/**
* An error subclass thrown when a JWKS is invalid.
*
*/
export declare class JWKSInvalid extends JOSEError {
/** @ignore */
static code: string;
/** A unique error code for {@link JWKSInvalid}. */
code: string;
}
/**
* An error subclass thrown when no keys match from a JWKS.
*
*/
export declare class JWKSNoMatchingKey extends JOSEError {
/** @ignore */
static code: string;
/** A unique error code for {@link JWKSNoMatchingKey}. */
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<types.CryptoKey>;
/** @ignore */
static code: string;
/** A unique error code for {@link JWKSMultipleMatchingKeys}. */
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;
/** A unique error code for {@link JWKSTimeout}. */
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;
/** A unique error code for {@link JWSSignatureVerificationFailed}. */
code: string;
/** @ignore */
constructor(message?: string, options?: {
cause?: unknown;
});
}

32
node_modules/jose/dist/webapi/index.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
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, customFetch } 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';
import * as errors from './util/errors.js';
export { errors };
export { generateKeyPair } from './key/generate_key_pair.js';
export { generateSecret } from './key/generate_secret.js';
import * as base64url from './util/base64url.js';
export { base64url };
export const cryptoRuntime = 'WebCryptoAPI';

27
node_modules/jose/dist/webapi/jwe/compact/decrypt.js generated vendored Normal file
View File

@@ -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;
}

27
node_modules/jose/dist/webapi/jwe/compact/encrypt.js generated vendored Normal file
View File

@@ -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('.');
}
}

159
node_modules/jose/dist/webapi/jwe/flattened/decrypt.js generated vendored Normal file
View File

@@ -0,0 +1,159 @@
import { decode as b64u } from '../../util/base64url.js';
import { decrypt } from '../../lib/content_encryption.js';
import { decodeBase64url } from '../../lib/helpers.js';
import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js';
import { isDisjoint } from '../../lib/type_checks.js';
import { isObject } from '../../lib/type_checks.js';
import { decryptKeyManagement } from '../../lib/key_management.js';
import { decoder, concat, encode } from '../../lib/buffer_utils.js';
import { generateCek } from '../../lib/content_encryption.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';
import { decompress } from '../../lib/deflate.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 = b64u(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 && joseHeader.zip !== 'DEF') {
throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
}
if (joseHeader.zip !== undefined && !parsedProt?.zip) {
throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
}
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) {
encryptedKey = decodeBase64url(jwe.encrypted_key, 'encrypted_key', JWEInvalid);
}
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) {
iv = decodeBase64url(jwe.iv, 'iv', JWEInvalid);
}
if (jwe.tag !== undefined) {
tag = decodeBase64url(jwe.tag, 'tag', JWEInvalid);
}
const protectedHeader = jwe.protected !== undefined ? encode(jwe.protected) : new Uint8Array();
let additionalData;
if (jwe.aad !== undefined) {
additionalData = concat(protectedHeader, encode('.'), encode(jwe.aad));
}
else {
additionalData = protectedHeader;
}
const ciphertext = decodeBase64url(jwe.ciphertext, 'ciphertext', JWEInvalid);
const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData);
const result = { plaintext };
if (joseHeader.zip === 'DEF') {
const maxDecompressedLength = options?.maxDecompressedLength ?? 250_000;
if (maxDecompressedLength === 0) {
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
}
if (maxDecompressedLength !== Infinity &&
(!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) {
throw new TypeError('maxDecompressedLength must be 0, a positive safe integer, or Infinity');
}
result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => {
if (cause instanceof JWEInvalid)
throw cause;
throw new JWEInvalid('Failed to decompress plaintext', { cause });
});
}
if (jwe.protected !== undefined) {
result.protectedHeader = parsedProt;
}
if (jwe.aad !== undefined) {
result.additionalAuthenticatedData = decodeBase64url(jwe.aad, 'aad', JWEInvalid);
}
if (jwe.unprotected !== undefined) {
result.sharedUnprotectedHeader = jwe.unprotected;
}
if (jwe.header !== undefined) {
result.unprotectedHeader = jwe.header;
}
if (resolvedKey) {
return { ...result, key: k };
}
return result;
}

167
node_modules/jose/dist/webapi/jwe/flattened/encrypt.js generated vendored Normal file
View File

@@ -0,0 +1,167 @@
import { encode as b64u } from '../../util/base64url.js';
import { unprotected, assertNotSet } from '../../lib/helpers.js';
import { encrypt } from '../../lib/content_encryption.js';
import { encryptKeyManagement } from '../../lib/key_management.js';
import { JOSENotSupported, JWEInvalid } from '../../util/errors.js';
import { isDisjoint } from '../../lib/type_checks.js';
import { concat, encode } 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';
import { compress } from '../../lib/deflate.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) {
assertNotSet(this.#keyManagementParameters, 'setKeyManagementParameters');
this.#keyManagementParameters = parameters;
return this;
}
setProtectedHeader(protectedHeader) {
assertNotSet(this.#protectedHeader, 'setProtectedHeader');
this.#protectedHeader = protectedHeader;
return this;
}
setSharedUnprotectedHeader(sharedUnprotectedHeader) {
assertNotSet(this.#sharedUnprotectedHeader, 'setSharedUnprotectedHeader');
this.#sharedUnprotectedHeader = sharedUnprotectedHeader;
return this;
}
setUnprotectedHeader(unprotectedHeader) {
assertNotSet(this.#unprotectedHeader, 'setUnprotectedHeader');
this.#unprotectedHeader = unprotectedHeader;
return this;
}
setAdditionalAuthenticatedData(aad) {
this.#aad = aad;
return this;
}
setContentEncryptionKey(cek) {
assertNotSet(this.#cek, 'setContentEncryptionKey');
this.#cek = cek;
return this;
}
setInitializationVector(iv) {
assertNotSet(this.#iv, 'setInitializationVector');
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 && joseHeader.zip !== 'DEF') {
throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
}
if (joseHeader.zip !== undefined && !this.#protectedHeader?.zip) {
throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
}
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 protectedHeaderS;
let protectedHeaderB;
let aadMember;
if (this.#protectedHeader) {
protectedHeaderS = b64u(JSON.stringify(this.#protectedHeader));
protectedHeaderB = encode(protectedHeaderS);
}
else {
protectedHeaderS = '';
protectedHeaderB = new Uint8Array();
}
if (this.#aad) {
aadMember = b64u(this.#aad);
const aadMemberBytes = encode(aadMember);
additionalData = concat(protectedHeaderB, encode('.'), aadMemberBytes);
}
else {
additionalData = protectedHeaderB;
}
let plaintext = this.#plaintext;
if (joseHeader.zip === 'DEF') {
plaintext = await compress(plaintext).catch((cause) => {
throw new JWEInvalid('Failed to compress plaintext', { cause });
});
}
const { ciphertext, tag, iv } = await encrypt(enc, plaintext, cek, this.#iv, additionalData);
const jwe = {
ciphertext: b64u(ciphertext),
};
if (iv) {
jwe.iv = b64u(iv);
}
if (tag) {
jwe.tag = b64u(tag);
}
if (encryptedKey) {
jwe.encrypted_key = b64u(encryptedKey);
}
if (aadMember) {
jwe.aad = aadMember;
}
if (this.#protectedHeader) {
jwe.protected = protectedHeaderS;
}
if (this.#sharedUnprotectedHeader) {
jwe.unprotected = this.#sharedUnprotectedHeader;
}
if (this.#unprotectedHeader) {
jwe.header = this.#unprotectedHeader;
}
return jwe;
}
}

31
node_modules/jose/dist/webapi/jwe/general/decrypt.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
import { flattenedDecrypt } from '../flattened/decrypt.js';
import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js';
import { isObject } from '../../lib/type_checks.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();
}

182
node_modules/jose/dist/webapi/jwe/general/encrypt.js generated vendored Normal file
View File

@@ -0,0 +1,182 @@
import { FlattenedEncrypt } from '../flattened/encrypt.js';
import { unprotected, assertNotSet } from '../../lib/helpers.js';
import { JOSENotSupported, JWEInvalid } from '../../util/errors.js';
import { generateCek } from '../../lib/content_encryption.js';
import { isDisjoint } from '../../lib/type_checks.js';
import { encryptKeyManagement } from '../../lib/key_management.js';
import { encode as b64u } from '../../util/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;
keyManagementParameters;
key;
options;
constructor(enc, key, options) {
this.#parent = enc;
this.key = key;
this.options = options;
}
setUnprotectedHeader(unprotectedHeader) {
assertNotSet(this.unprotectedHeader, 'setUnprotectedHeader');
this.unprotectedHeader = unprotectedHeader;
return this;
}
setKeyManagementParameters(parameters) {
assertNotSet(this.keyManagementParameters, 'setKeyManagementParameters');
this.keyManagementParameters = parameters;
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) {
assertNotSet(this.#protectedHeader, 'setProtectedHeader');
this.#protectedHeader = protectedHeader;
return this;
}
setSharedUnprotectedHeader(sharedUnprotectedHeader) {
assertNotSet(this.#unprotectedHeader, 'setSharedUnprotectedHeader');
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 && joseHeader.zip !== 'DEF') {
throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
}
if (joseHeader.zip !== undefined && !this.#protectedHeader?.zip) {
throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
}
}
const cek = generateCek(enc);
const jwe = {
ciphertext: '',
recipients: [],
};
for (let i = 0; i < this.#recipients.length; i++) {
const recipient = this.#recipients[i];
const target = {};
jwe.recipients.push(target);
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(recipient.keyManagementParameters)
.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, recipient.keyManagementParameters);
target.encrypted_key = b64u(encryptedKey);
if (recipient.unprotectedHeader || parameters)
target.header = { ...recipient.unprotectedHeader, ...parameters };
}
return jwe;
}
}

17
node_modules/jose/dist/webapi/jwk/embedded.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import { importJWK } from '../key/import.js';
import { isObject } from '../lib/type_checks.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;
}

68
node_modules/jose/dist/webapi/jwk/thumbprint.js generated vendored Normal file
View File

@@ -0,0 +1,68 @@
import { digest } from '../lib/helpers.js';
import { encode as b64u } from '../util/base64url.js';
import { JOSENotSupported, JWKInvalid } from '../util/errors.js';
import { encode } from '../lib/buffer_utils.js';
import { isKeyLike } from '../lib/is_key_like.js';
import { isJWK } from '../lib/type_checks.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 'AKP':
check(jwk.alg, '"alg" (Algorithm) Parameter');
check(jwk.pub, '"pub" (Public key) Parameter');
components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
break;
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 = encode(JSON.stringify(components));
return b64u(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}`;
}

119
node_modules/jose/dist/webapi/jwks/local.js generated vendored Normal file
View File

@@ -0,0 +1,119 @@
import { importJWK } from '../key/import.js';
import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js';
import { isObject } from '../lib/type_checks.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';
case 'ML':
return 'AKP';
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);
}
class LocalJWKSet {
#jwks;
#cached = new WeakMap();
constructor(jwks) {
if (!isJWKSLike(jwks)) {
throw new JWKSInvalid('JSON Web Key Set malformed');
}
this.#jwks = structuredClone(jwks);
}
jwks() {
return this.#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' || kty === 'AKP')) {
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.#cached;
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: () => structuredClone(set.jwks()),
enumerable: false,
configurable: false,
writable: false,
},
});
return localJWKSet;
}

179
node_modules/jose/dist/webapi/jwks/remote.js generated vendored Normal file
View File

@@ -0,0 +1,179 @@
import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from '../util/errors.js';
import { createLocalJWKSet } from './local.js';
import { isObject } from '../lib/type_checks.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.2.2';
USER_AGENT = `${NAME}/${VERSION}`;
}
export const customFetch = Symbol();
async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
const response = await fetchImpl(url, {
method: 'GET',
signal,
redirect: 'manual',
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;
#headers;
#customFetch;
#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.#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;
this.#headers = new Headers(options?.headers);
if (USER_AGENT && !this.#headers.has('User-Agent')) {
this.#headers.set('User-Agent', USER_AGENT);
}
if (!this.#headers.has('accept')) {
this.#headers.set('accept', 'application/json');
this.#headers.append('accept', 'application/jwk-set+json');
}
this.#customFetch = options?.[customFetch];
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);
}
}
}
pendingFetch() {
return !!this.#pendingFetch;
}
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;
}
jwks() {
return this.#local?.jwks();
}
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;
}
this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch)
.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.jwks(),
enumerable: true,
configurable: false,
writable: false,
},
});
return remoteJWKSet;
}

18
node_modules/jose/dist/webapi/jws/compact/sign.js generated vendored Normal file
View File

@@ -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}`;
}
}

21
node_modules/jose/dist/webapi/jws/compact/verify.js generated vendored Normal file
View File

@@ -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;
}

89
node_modules/jose/dist/webapi/jws/flattened/sign.js generated vendored Normal file
View File

@@ -0,0 +1,89 @@
import { encode as b64u } from '../../util/base64url.js';
import { sign } from '../../lib/signing.js';
import { isDisjoint } from '../../lib/type_checks.js';
import { JWSInvalid } from '../../util/errors.js';
import { concat, encode } 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';
import { assertNotSet } from '../../lib/helpers.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) {
assertNotSet(this.#protectedHeader, 'setProtectedHeader');
this.#protectedHeader = protectedHeader;
return this;
}
setUnprotectedHeader(unprotectedHeader) {
assertNotSet(this.#unprotectedHeader, 'setUnprotectedHeader');
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 payloadS;
let payloadB;
if (b64) {
payloadS = b64u(this.#payload);
payloadB = encode(payloadS);
}
else {
payloadB = this.#payload;
payloadS = '';
}
let protectedHeaderString;
let protectedHeaderBytes;
if (this.#protectedHeader) {
protectedHeaderString = b64u(JSON.stringify(this.#protectedHeader));
protectedHeaderBytes = encode(protectedHeaderString);
}
else {
protectedHeaderString = '';
protectedHeaderBytes = new Uint8Array();
}
const data = concat(protectedHeaderBytes, encode('.'), payloadB);
const k = await normalizeKey(key, alg);
const signature = await sign(alg, k, data);
const jws = {
signature: b64u(signature),
payload: payloadS,
};
if (this.#unprotectedHeader) {
jws.header = this.#unprotectedHeader;
}
if (this.#protectedHeader) {
jws.protected = protectedHeaderString;
}
return jws;
}
}

110
node_modules/jose/dist/webapi/jws/flattened/verify.js generated vendored Normal file
View File

@@ -0,0 +1,110 @@
import { decode as b64u } from '../../util/base64url.js';
import { verify } from '../../lib/signing.js';
import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';
import { concat, encoder, decoder, encode } from '../../lib/buffer_utils.js';
import { decodeBase64url } from '../../lib/helpers.js';
import { isDisjoint } from '../../lib/type_checks.js';
import { isObject } from '../../lib/type_checks.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 = b64u(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(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array(), encode('.'), typeof jws.payload === 'string'
? b64
? encode(jws.payload)
: encoder.encode(jws.payload)
: jws.payload);
const signature = decodeBase64url(jws.signature, 'signature', JWSInvalid);
const k = await normalizeKey(key, alg);
const verified = await verify(alg, k, signature, data);
if (!verified) {
throw new JWSSignatureVerificationFailed();
}
let payload;
if (b64) {
payload = decodeBase64url(jws.payload, 'payload', JWSInvalid);
}
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;
}

70
node_modules/jose/dist/webapi/jws/general/sign.js generated vendored Normal file
View File

@@ -0,0 +1,70 @@
import { FlattenedSign } from '../flattened/sign.js';
import { JWSInvalid } from '../../util/errors.js';
import { assertNotSet } from '../../lib/helpers.js';
class IndividualSignature {
#parent;
protectedHeader;
unprotectedHeader;
options;
key;
constructor(sig, key, options) {
this.#parent = sig;
this.key = key;
this.options = options;
}
setProtectedHeader(protectedHeader) {
assertNotSet(this.protectedHeader, 'setProtectedHeader');
this.protectedHeader = protectedHeader;
return this;
}
setUnprotectedHeader(unprotectedHeader) {
assertNotSet(this.unprotectedHeader, 'setUnprotectedHeader');
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;
}
}

24
node_modules/jose/dist/webapi/jws/general/verify.js generated vendored Normal file
View File

@@ -0,0 +1,24 @@
import { flattenedVerify } from '../flattened/verify.js';
import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';
import { isObject } from '../../lib/type_checks.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();
}

23
node_modules/jose/dist/webapi/jwt/decrypt.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import { compactDecrypt } from '../jwe/compact/decrypt.js';
import { validateClaimsSet } 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 = validateClaimsSet(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;
}

101
node_modules/jose/dist/webapi/jwt/encrypt.js generated vendored Normal file
View File

@@ -0,0 +1,101 @@
import { CompactEncrypt } from '../jwe/compact/encrypt.js';
import { JWTClaimsBuilder } from '../lib/jwt_claims_set.js';
import { assertNotSet } from '../lib/helpers.js';
export class EncryptJWT {
#cek;
#iv;
#keyManagementParameters;
#protectedHeader;
#replicateIssuerAsHeader;
#replicateSubjectAsHeader;
#replicateAudienceAsHeader;
#jwt;
constructor(payload = {}) {
this.#jwt = new JWTClaimsBuilder(payload);
}
setIssuer(issuer) {
this.#jwt.iss = issuer;
return this;
}
setSubject(subject) {
this.#jwt.sub = subject;
return this;
}
setAudience(audience) {
this.#jwt.aud = audience;
return this;
}
setJti(jwtId) {
this.#jwt.jti = jwtId;
return this;
}
setNotBefore(input) {
this.#jwt.nbf = input;
return this;
}
setExpirationTime(input) {
this.#jwt.exp = input;
return this;
}
setIssuedAt(input) {
this.#jwt.iat = input;
return this;
}
setProtectedHeader(protectedHeader) {
assertNotSet(this.#protectedHeader, 'setProtectedHeader');
this.#protectedHeader = protectedHeader;
return this;
}
setKeyManagementParameters(parameters) {
assertNotSet(this.#keyManagementParameters, 'setKeyManagementParameters');
this.#keyManagementParameters = parameters;
return this;
}
setContentEncryptionKey(cek) {
assertNotSet(this.#cek, 'setContentEncryptionKey');
this.#cek = cek;
return this;
}
setInitializationVector(iv) {
assertNotSet(this.#iv, 'setInitializationVector');
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(this.#jwt.data());
if (this.#protectedHeader &&
(this.#replicateIssuerAsHeader ||
this.#replicateSubjectAsHeader ||
this.#replicateAudienceAsHeader)) {
this.#protectedHeader = {
...this.#protectedHeader,
iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : undefined,
sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : undefined,
aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : undefined,
};
}
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);
}
}

52
node_modules/jose/dist/webapi/jwt/sign.js generated vendored Normal file
View File

@@ -0,0 +1,52 @@
import { CompactSign } from '../jws/compact/sign.js';
import { JWTInvalid } from '../util/errors.js';
import { JWTClaimsBuilder } from '../lib/jwt_claims_set.js';
export class SignJWT {
#protectedHeader;
#jwt;
constructor(payload = {}) {
this.#jwt = new JWTClaimsBuilder(payload);
}
setIssuer(issuer) {
this.#jwt.iss = issuer;
return this;
}
setSubject(subject) {
this.#jwt.sub = subject;
return this;
}
setAudience(audience) {
this.#jwt.aud = audience;
return this;
}
setJti(jwtId) {
this.#jwt.jti = jwtId;
return this;
}
setNotBefore(input) {
this.#jwt.nbf = input;
return this;
}
setExpirationTime(input) {
this.#jwt.exp = input;
return this;
}
setIssuedAt(input) {
this.#jwt.iat = input;
return this;
}
setProtectedHeader(protectedHeader) {
this.#protectedHeader = protectedHeader;
return this;
}
async sign(key, options) {
const sig = new CompactSign(this.#jwt.data());
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);
}
}

63
node_modules/jose/dist/webapi/jwt/unsecured.js generated vendored Normal file
View File

@@ -0,0 +1,63 @@
import * as b64u from '../util/base64url.js';
import { decoder } from '../lib/buffer_utils.js';
import { JWTInvalid } from '../util/errors.js';
import { validateClaimsSet, JWTClaimsBuilder } from '../lib/jwt_claims_set.js';
export class UnsecuredJWT {
#jwt;
constructor(payload = {}) {
this.#jwt = new JWTClaimsBuilder(payload);
}
encode() {
const header = b64u.encode(JSON.stringify({ alg: 'none' }));
const payload = b64u.encode(this.#jwt.data());
return `${header}.${payload}.`;
}
setIssuer(issuer) {
this.#jwt.iss = issuer;
return this;
}
setSubject(subject) {
this.#jwt.sub = subject;
return this;
}
setAudience(audience) {
this.#jwt.aud = audience;
return this;
}
setJti(jwtId) {
this.#jwt.jti = jwtId;
return this;
}
setNotBefore(input) {
this.#jwt.nbf = input;
return this;
}
setExpirationTime(input) {
this.#jwt.exp = input;
return this;
}
setIssuedAt(input) {
this.#jwt.iat = input;
return this;
}
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(b64u.decode(encodedHeader)));
if (header.alg !== 'none')
throw new Error();
}
catch {
throw new JWTInvalid('Invalid Unsecured JWT');
}
const payload = validateClaimsSet(header, b64u.decode(encodedPayload), options);
return { payload, header };
}
}

15
node_modules/jose/dist/webapi/jwt/verify.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
import { compactVerify } from '../jws/compact/verify.js';
import { validateClaimsSet } 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 = validateClaimsSet(verified.protectedHeader, verified.payload, options);
const result = { payload, protectedHeader: verified.protectedHeader };
if (typeof key === 'function') {
return { ...result, key: verified.key };
}
return result;
}

11
node_modules/jose/dist/webapi/key/export.js generated vendored Normal file
View File

@@ -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);
}

97
node_modules/jose/dist/webapi/key/generate_key_pair.js generated vendored Normal file
View File

@@ -0,0 +1,97 @@
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: Uint8Array.of(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: Uint8Array.of(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: Uint8Array.of(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 'ML-DSA-44':
case 'ML-DSA-65':
case 'ML-DSA-87': {
keyUsages = ['sign', 'verify'];
algorithm = { name: alg };
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);
}

40
node_modules/jose/dist/webapi/key/generate_secret.js generated vendored Normal file
View File

@@ -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);
}

57
node_modules/jose/dist/webapi/key/import.js generated vendored Normal file
View File

@@ -0,0 +1,57 @@
import { decode as decodeBase64URL } from '../util/base64url.js';
import { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js';
import { jwkToKey } from '../lib/jwk_to_key.js';
import { JOSENotSupported } from '../util/errors.js';
import { isObject } from '../lib/type_checks.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');
}
return jwkToKey({ ...jwk, alg, ext });
case 'AKP': {
if (typeof jwk.alg !== 'string' || !jwk.alg) {
throw new TypeError('missing "alg" (Algorithm) Parameter value');
}
if (alg !== undefined && alg !== jwk.alg) {
throw new TypeError('JWK alg and alg option value mismatch');
}
return jwkToKey({ ...jwk, ext });
}
case 'EC':
case 'OKP':
return jwkToKey({ ...jwk, alg, ext });
default:
throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
}
}

15
node_modules/jose/dist/webapi/lib/aesgcmkw.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
import { encrypt, decrypt } from './content_encryption.js';
import { encode as b64u } from '../util/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());
return {
encryptedKey: wrapped.ciphertext,
iv: b64u(wrapped.iv),
tag: b64u(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());
}

25
node_modules/jose/dist/webapi/lib/aeskw.js generated vendored Normal file
View File

@@ -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));
}

243
node_modules/jose/dist/webapi/lib/asn1.js generated vendored Normal file
View File

@@ -0,0 +1,243 @@
import { invalidKeyInput } from './invalid_key_input.js';
import { encodeBase64, decodeBase64 } from '../lib/base64.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) => genericExport('public', 'spki', key);
export const toPKCS8 = (key) => genericExport('private', 'pkcs8', key);
const bytesEqual = (a, b) => {
if (a.byteLength !== b.length)
return false;
for (let i = 0; i < a.byteLength; i++) {
if (a[i] !== b[i])
return false;
}
return true;
};
const createASN1State = (data) => ({ data, pos: 0 });
const parseLength = (state) => {
const first = state.data[state.pos++];
if (first & 0x80) {
const lengthOfLen = first & 0x7f;
let length = 0;
for (let i = 0; i < lengthOfLen; i++) {
length = (length << 8) | state.data[state.pos++];
}
return length;
}
return first;
};
const skipElement = (state, count = 1) => {
if (count <= 0)
return;
state.pos++;
const length = parseLength(state);
state.pos += length;
if (count > 1) {
skipElement(state, count - 1);
}
};
const expectTag = (state, expectedTag, errorMessage) => {
if (state.data[state.pos++] !== expectedTag) {
throw new Error(errorMessage);
}
};
const getSubarray = (state, length) => {
const result = state.data.subarray(state.pos, state.pos + length);
state.pos += length;
return result;
};
const parseAlgorithmOID = (state) => {
expectTag(state, 0x06, 'Expected algorithm OID');
const oidLen = parseLength(state);
return getSubarray(state, oidLen);
};
function parsePKCS8Header(state) {
expectTag(state, 0x30, 'Invalid PKCS#8 structure');
parseLength(state);
expectTag(state, 0x02, 'Expected version field');
const verLen = parseLength(state);
state.pos += verLen;
expectTag(state, 0x30, 'Expected algorithm identifier');
const algIdLen = parseLength(state);
const algIdStart = state.pos;
return { algIdStart, algIdLength: algIdLen };
}
function parseSPKIHeader(state) {
expectTag(state, 0x30, 'Invalid SPKI structure');
parseLength(state);
expectTag(state, 0x30, 'Expected algorithm identifier');
const algIdLen = parseLength(state);
const algIdStart = state.pos;
return { algIdStart, algIdLength: algIdLen };
}
const parseECAlgorithmIdentifier = (state) => {
const algOid = parseAlgorithmOID(state);
if (bytesEqual(algOid, [0x2b, 0x65, 0x6e])) {
return 'X25519';
}
if (!bytesEqual(algOid, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01])) {
throw new Error('Unsupported key algorithm');
}
expectTag(state, 0x06, 'Expected curve OID');
const curveOidLen = parseLength(state);
const curveOid = getSubarray(state, curveOidLen);
for (const { name, oid } of [
{ name: 'P-256', oid: [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07] },
{ name: 'P-384', oid: [0x2b, 0x81, 0x04, 0x00, 0x22] },
{ name: 'P-521', oid: [0x2b, 0x81, 0x04, 0x00, 0x23] },
]) {
if (bytesEqual(curveOid, oid)) {
return name;
}
}
throw new Error('Unsupported named curve');
};
const genericImport = async (keyFormat, keyData, alg, options) => {
let algorithm;
let keyUsages;
const isPublic = keyFormat === 'spki';
const getSigUsages = () => (isPublic ? ['verify'] : ['sign']);
const getEncUsages = () => isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'];
switch (alg) {
case 'PS256':
case 'PS384':
case 'PS512':
algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };
keyUsages = getSigUsages();
break;
case 'RS256':
case 'RS384':
case 'RS512':
algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };
keyUsages = getSigUsages();
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 = getEncUsages();
break;
case 'ES256':
case 'ES384':
case 'ES512': {
const curveMap = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' };
algorithm = { name: 'ECDSA', namedCurve: curveMap[alg] };
keyUsages = getSigUsages();
break;
}
case 'ECDH-ES':
case 'ECDH-ES+A128KW':
case 'ECDH-ES+A192KW':
case 'ECDH-ES+A256KW': {
try {
const namedCurve = options.getNamedCurve(keyData);
algorithm = namedCurve === 'X25519' ? { name: 'X25519' } : { name: 'ECDH', namedCurve };
}
catch (cause) {
throw new JOSENotSupported('Invalid or unsupported key format');
}
keyUsages = isPublic ? [] : ['deriveBits'];
break;
}
case 'Ed25519':
case 'EdDSA':
algorithm = { name: 'Ed25519' };
keyUsages = getSigUsages();
break;
case 'ML-DSA-44':
case 'ML-DSA-65':
case 'ML-DSA-87':
algorithm = { name: alg };
keyUsages = getSigUsages();
break;
default:
throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
}
return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);
};
const processPEMData = (pem, pattern) => {
return decodeBase64(pem.replace(pattern, ''));
};
export const fromPKCS8 = (pem, alg, options) => {
const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
let opts = options;
if (alg?.startsWith?.('ECDH-ES')) {
opts ||= {};
opts.getNamedCurve = (keyData) => {
const state = createASN1State(keyData);
parsePKCS8Header(state);
return parseECAlgorithmIdentifier(state);
};
}
return genericImport('pkcs8', keyData, alg, opts);
};
export const fromSPKI = (pem, alg, options) => {
const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g);
let opts = options;
if (alg?.startsWith?.('ECDH-ES')) {
opts ||= {};
opts.getNamedCurve = (keyData) => {
const state = createASN1State(keyData);
parseSPKIHeader(state);
return parseECAlgorithmIdentifier(state);
};
}
return genericImport('spki', keyData, alg, opts);
};
function spkiFromX509(buf) {
const state = createASN1State(buf);
expectTag(state, 0x30, 'Invalid certificate structure');
parseLength(state);
expectTag(state, 0x30, 'Invalid tbsCertificate structure');
parseLength(state);
if (buf[state.pos] === 0xa0) {
skipElement(state, 6);
}
else {
skipElement(state, 5);
}
const spkiStart = state.pos;
expectTag(state, 0x30, 'Invalid SPKI structure');
const spkiContentLen = parseLength(state);
return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart));
}
function extractX509SPKI(x509) {
const derBytes = processPEMData(x509, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g);
return spkiFromX509(derBytes);
}
export const fromX509 = (pem, alg, options) => {
let spki;
try {
spki = extractX509SPKI(pem);
}
catch (cause) {
throw new TypeError('Failed to parse the X.509 certificate', { cause });
}
return fromSPKI(formatPEM(encodeBase64(spki), 'PUBLIC KEY'), alg, options);
};

22
node_modules/jose/dist/webapi/lib/base64.js generated vendored Normal file
View File

@@ -0,0 +1,22 @@
export function encodeBase64(input) {
if (Uint8Array.prototype.toBase64) {
return input.toBase64();
}
const CHUNK_SIZE = 0x8000;
const arr = [];
for (let i = 0; i < input.length; i += CHUNK_SIZE) {
arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
}
return btoa(arr.join(''));
}
export function decodeBase64(encoded) {
if (Uint8Array.fromBase64) {
return Uint8Array.fromBase64(encoded);
}
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;
}

43
node_modules/jose/dist/webapi/lib/buffer_utils.js generated vendored Normal file
View File

@@ -0,0 +1,43 @@
export const encoder = new TextEncoder();
export const decoder = new TextDecoder();
const MAX_INT32 = 2 ** 32;
export function 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;
}
export function encode(string) {
const bytes = new Uint8Array(string.length);
for (let i = 0; i < string.length; i++) {
const code = string.charCodeAt(i);
if (code > 127) {
throw new TypeError('non-ASCII string encountered in encode()');
}
bytes[i] = code;
}
return bytes;
}

122
node_modules/jose/dist/webapi/lib/check_key_type.js generated vendored Normal file
View File

@@ -0,0 +1,122 @@
import { withAlg as invalidKeyInput } from './invalid_key_input.js';
import { isKeyLike } from './is_key_like.js';
import * as jwk from './type_checks.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 must 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 must 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"`);
}
}
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"`);
}
}
};
export function checkKeyType(alg, key, usage) {
switch (alg.substring(0, 2)) {
case 'A1':
case 'A2':
case 'di':
case 'HS':
case 'PB':
symmetricTypeCheck(alg, key, usage);
break;
default:
asymmetricTypeCheck(alg, key, usage);
}
}

217
node_modules/jose/dist/webapi/lib/content_encryption.js generated vendored Normal file
View File

@@ -0,0 +1,217 @@
import { concat, uint64be } from './buffer_utils.js';
import { checkEncCryptoKey } from './crypto_key.js';
import { invalidKeyInput } from './invalid_key_input.js';
import { JOSENotSupported, JWEDecryptionFailed, JWEInvalid } from '../util/errors.js';
import { isCryptoKey } from './is_key_like.js';
export function cekLength(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 const generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3));
function checkCekLength(cek, expected) {
const actual = cek.byteLength << 3;
if (actual !== expected) {
throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
}
}
function ivBitLength(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 const generateIv = (alg) => crypto.getRandomValues(new Uint8Array(ivBitLength(alg) >> 3));
export function checkIvLength(enc, iv) {
if (iv.length << 3 !== ivBitLength(enc)) {
throw new JWEInvalid('Invalid Initialization Vector length');
}
}
async function cbcKeySetup(enc, cek, usage) {
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, [usage]);
const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {
hash: `SHA-${keySize << 1}`,
name: 'HMAC',
}, false, ['sign']);
return { encKey, macKey, keySize };
}
async function cbcHmacTag(macKey, macData, keySize) {
return new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));
}
async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, 'encrypt');
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
iv: iv,
name: 'AES-CBC',
}, encKey, plaintext));
const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
const tag = await cbcHmacTag(macKey, macData, keySize);
return { ciphertext, tag, iv };
}
async function 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');
}
const algorithm = { name: 'HMAC', hash: 'SHA-256' };
const key = (await crypto.subtle.generateKey(algorithm, false, ['sign']));
const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a));
const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b));
let out = 0;
let i = -1;
while (++i < 32) {
out |= aHmac[i] ^ bHmac[i];
}
return out === 0;
}
async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
const { encKey, macKey, keySize } = await cbcKeySetup(enc, cek, 'decrypt');
const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
const expectedTag = await cbcHmacTag(macKey, macData, keySize);
let macCheckPassed;
try {
macCheckPassed = await timingSafeEqual(tag, expectedTag);
}
catch {
}
if (!macCheckPassed) {
throw new JWEDecryptionFailed();
}
let plaintext;
try {
plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv: iv, name: 'AES-CBC' }, encKey, ciphertext));
}
catch {
}
if (!plaintext) {
throw new JWEDecryptionFailed();
}
return plaintext;
}
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: iv,
name: 'AES-GCM',
tagLength: 128,
}, encKey, plaintext));
const tag = encrypted.slice(-16);
const ciphertext = encrypted.slice(0, -16);
return { ciphertext, tag, iv };
}
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: iv,
name: 'AES-GCM',
tagLength: 128,
}, encKey, concat(ciphertext, tag)));
}
catch {
throw new JWEDecryptionFailed();
}
}
const unsupportedEnc = 'Unsupported JWE Content Encryption Algorithm';
export async function encrypt(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(unsupportedEnc);
}
}
export async function decrypt(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(unsupportedEnc);
}
}

136
node_modules/jose/dist/webapi/lib/crypto_key.js generated vendored Normal file
View File

@@ -0,0 +1,136 @@
const unusable = (name, prop = 'algorithm.name') => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
const isAlgorithm = (algorithm, name) => algorithm.name === name;
function getHashLength(hash) {
return parseInt(hash.name.slice(4), 10);
}
function checkHashLength(algorithm, expected) {
const actual = getHashLength(algorithm.hash);
if (actual !== expected)
throw unusable(`SHA-${expected}`, 'algorithm.hash');
}
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');
checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
break;
}
case 'RS256':
case 'RS384':
case 'RS512': {
if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))
throw unusable('RSASSA-PKCS1-v1_5');
checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
break;
}
case 'PS256':
case 'PS384':
case 'PS512': {
if (!isAlgorithm(key.algorithm, 'RSA-PSS'))
throw unusable('RSA-PSS');
checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));
break;
}
case 'Ed25519':
case 'EdDSA': {
if (!isAlgorithm(key.algorithm, 'Ed25519'))
throw unusable('Ed25519');
break;
}
case 'ML-DSA-44':
case 'ML-DSA-65':
case 'ML-DSA-87': {
if (!isAlgorithm(key.algorithm, alg))
throw unusable(alg);
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');
checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1);
break;
}
default:
throw new TypeError('CryptoKey does not support this operation');
}
checkUsage(key, usage);
}

44
node_modules/jose/dist/webapi/lib/deflate.js generated vendored Normal file
View File

@@ -0,0 +1,44 @@
import { JOSENotSupported, JWEInvalid } from '../util/errors.js';
import { concat } from './buffer_utils.js';
function supported(name) {
if (typeof globalThis[name] === 'undefined') {
throw new JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${name} API.`);
}
}
export async function compress(input) {
supported('CompressionStream');
const cs = new CompressionStream('deflate-raw');
const writer = cs.writable.getWriter();
writer.write(input).catch(() => { });
writer.close().catch(() => { });
const chunks = [];
const reader = cs.readable.getReader();
for (;;) {
const { value, done } = await reader.read();
if (done)
break;
chunks.push(value);
}
return concat(...chunks);
}
export async function decompress(input, maxLength) {
supported('DecompressionStream');
const ds = new DecompressionStream('deflate-raw');
const writer = ds.writable.getWriter();
writer.write(input).catch(() => { });
writer.close().catch(() => { });
const chunks = [];
let length = 0;
const reader = ds.readable.getReader();
for (;;) {
const { value, done } = await reader.read();
if (done)
break;
chunks.push(value);
length += value.byteLength;
if (maxLength !== Infinity && length > maxLength) {
throw new JWEInvalid('Decompressed plaintext exceeded the configured limit');
}
}
return concat(...chunks);
}

52
node_modules/jose/dist/webapi/lib/ecdhes.js generated vendored Normal file
View File

@@ -0,0 +1,52 @@
import { encode, concat, uint32be } from './buffer_utils.js';
import { checkEncCryptoKey } from './crypto_key.js';
import { digest } from './helpers.js';
function lengthAndInput(input) {
return concat(uint32be(input.length), input);
}
async function concatKdf(Z, L, OtherInfo) {
const dkLen = L >> 3;
const hashLen = 32;
const reps = Math.ceil(dkLen / hashLen);
const dk = new Uint8Array(reps * hashLen);
for (let i = 1; i <= reps; i++) {
const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length);
hashInput.set(uint32be(i), 0);
hashInput.set(Z, 4);
hashInput.set(OtherInfo, 4 + Z.length);
const hashResult = await digest('sha256', hashInput);
dk.set(hashResult, (i - 1) * hashLen);
}
return dk.slice(0, dkLen);
}
export async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) {
checkEncCryptoKey(publicKey, 'ECDH');
checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits');
const algorithmID = lengthAndInput(encode(algorithm));
const partyUInfo = lengthAndInput(apu);
const partyVInfo = lengthAndInput(apv);
const suppPubInfo = uint32be(keyLength);
const suppPrivInfo = new Uint8Array();
const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);
const Z = new Uint8Array(await crypto.subtle.deriveBits({
name: publicKey.algorithm.name,
public: publicKey,
}, privateKey, getEcdhBitLength(publicKey)));
return concatKdf(Z, keyLength, otherInfo);
}
function getEcdhBitLength(publicKey) {
if (publicKey.algorithm.name === 'X25519') {
return 256;
}
return (Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3);
}
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';
}
}

19
node_modules/jose/dist/webapi/lib/helpers.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import { decode } from '../util/base64url.js';
export const unprotected = Symbol();
export function assertNotSet(value, name) {
if (value) {
throw new TypeError(`${name} can only be called once`);
}
}
export function decodeBase64url(value, label, ErrorClass) {
try {
return decode(value);
}
catch {
throw new ErrorClass(`Failed to base64url decode the ${label}`);
}
}
export async function digest(algorithm, data) {
const subtleDigest = `SHA-${algorithm.slice(-3)}`;
return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
}

27
node_modules/jose/dist/webapi/lib/invalid_key_input.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
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 const invalidKeyInput = (actual, ...types) => message('Key must be ', actual, ...types);
export const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);

17
node_modules/jose/dist/webapi/lib/is_key_like.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
export function assertCryptoKey(key) {
if (!isCryptoKey(key)) {
throw new Error('CryptoKey instance expected');
}
}
export const isCryptoKey = (key) => {
if (key?.[Symbol.toStringTag] === 'CryptoKey')
return true;
try {
return key instanceof CryptoKey;
}
catch {
return false;
}
};
export const isKeyObject = (key) => key?.[Symbol.toStringTag] === 'KeyObject';
export const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);

107
node_modules/jose/dist/webapi/lib/jwk_to_key.js generated vendored Normal file
View File

@@ -0,0 +1,107 @@
import { JOSENotSupported } from '../util/errors.js';
const unsupportedAlg = 'Invalid or unsupported JWK "alg" (Algorithm) Parameter value';
function subtleMapping(jwk) {
let algorithm;
let keyUsages;
switch (jwk.kty) {
case 'AKP': {
switch (jwk.alg) {
case 'ML-DSA-44':
case 'ML-DSA-65':
case 'ML-DSA-87':
algorithm = { name: jwk.alg };
keyUsages = jwk.priv ? ['sign'] : ['verify'];
break;
default:
throw new JOSENotSupported(unsupportedAlg);
}
break;
}
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(unsupportedAlg);
}
break;
}
case 'EC': {
switch (jwk.alg) {
case 'ES256':
case 'ES384':
case 'ES512':
algorithm = {
name: 'ECDSA',
namedCurve: { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' }[jwk.alg],
};
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(unsupportedAlg);
}
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(unsupportedAlg);
}
break;
}
default:
throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
}
return { algorithm, keyUsages };
}
export async function jwkToKey(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 };
if (keyData.kty !== 'AKP') {
delete keyData.alg;
}
delete keyData.use;
return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
}

238
node_modules/jose/dist/webapi/lib/jwt_claims_set.js generated vendored Normal file
View File

@@ -0,0 +1,238 @@
import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';
import { encoder, decoder } from './buffer_utils.js';
import { isObject } from './type_checks.js';
const epoch = (date) => Math.floor(date.getTime() / 1000);
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 function secs(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;
}
function validateInput(label, input) {
if (!Number.isFinite(input)) {
throw new TypeError(`Invalid ${label} input`);
}
return input;
}
const normalizeTyp = (value) => {
if (value.includes('/')) {
return value.toLowerCase();
}
return `application/${value.toLowerCase()}`;
};
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 function validateClaimsSet(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;
}
export class JWTClaimsBuilder {
#payload;
constructor(payload) {
if (!isObject(payload)) {
throw new TypeError('JWT Claims Set MUST be an object');
}
this.#payload = structuredClone(payload);
}
data() {
return encoder.encode(JSON.stringify(this.#payload));
}
get iss() {
return this.#payload.iss;
}
set iss(value) {
this.#payload.iss = value;
}
get sub() {
return this.#payload.sub;
}
set sub(value) {
this.#payload.sub = value;
}
get aud() {
return this.#payload.aud;
}
set aud(value) {
this.#payload.aud = value;
}
set jti(value) {
this.#payload.jti = value;
}
set nbf(value) {
if (typeof value === 'number') {
this.#payload.nbf = validateInput('setNotBefore', value);
}
else if (value instanceof Date) {
this.#payload.nbf = validateInput('setNotBefore', epoch(value));
}
else {
this.#payload.nbf = epoch(new Date()) + secs(value);
}
}
set exp(value) {
if (typeof value === 'number') {
this.#payload.exp = validateInput('setExpirationTime', value);
}
else if (value instanceof Date) {
this.#payload.exp = validateInput('setExpirationTime', epoch(value));
}
else {
this.#payload.exp = epoch(new Date()) + secs(value);
}
}
set iat(value) {
if (value === undefined) {
this.#payload.iat = epoch(new Date());
}
else if (value instanceof Date) {
this.#payload.iat = validateInput('setIssuedAt', epoch(value));
}
else if (typeof value === 'string') {
this.#payload.iat = validateInput('setIssuedAt', epoch(new Date()) + secs(value));
}
else {
this.#payload.iat = validateInput('setIssuedAt', value);
}
}
}

186
node_modules/jose/dist/webapi/lib/key_management.js generated vendored Normal file
View File

@@ -0,0 +1,186 @@
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 { encode as b64u } from '../util/base64url.js';
import { normalizeKey } from './normalize_key.js';
import { JOSENotSupported, JWEInvalid } from '../util/errors.js';
import { decodeBase64url } from './helpers.js';
import { generateCek, cekLength } from './content_encryption.js';
import { importJWK } from '../key/import.js';
import { exportJWK } from '../key/export.js';
import { isObject } from './type_checks.js';
import { wrap as aesGcmKwWrap, unwrap as aesGcmKwUnwrap } from './aesgcmkw.js';
import { assertCryptoKey } from './is_key_like.js';
const unsupportedAlgHeader = 'Invalid or unsupported "alg" (JWE Algorithm) header value';
function assertEncryptedKey(encryptedKey) {
if (encryptedKey === undefined)
throw new JWEInvalid('JWE Encrypted Key missing');
}
export async function decryptKeyManagement(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`);
partyUInfo = decodeBase64url(joseHeader.apu, 'apu', JWEInvalid);
}
if (joseHeader.apv !== undefined) {
if (typeof joseHeader.apv !== 'string')
throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
partyVInfo = decodeBase64url(joseHeader.apv, 'apv', JWEInvalid);
}
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;
assertEncryptedKey(encryptedKey);
return aeskw.unwrap(alg.slice(-6), sharedSecret, encryptedKey);
}
case 'RSA-OAEP':
case 'RSA-OAEP-256':
case 'RSA-OAEP-384':
case 'RSA-OAEP-512': {
assertEncryptedKey(encryptedKey);
assertCryptoKey(key);
return rsaes.decrypt(alg, key, encryptedKey);
}
case 'PBES2-HS256+A128KW':
case 'PBES2-HS384+A192KW':
case 'PBES2-HS512+A256KW': {
assertEncryptedKey(encryptedKey);
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;
p2s = decodeBase64url(joseHeader.p2s, 'p2s', JWEInvalid);
return pbes2kw.unwrap(alg, key, encryptedKey, joseHeader.p2c, p2s);
}
case 'A128KW':
case 'A192KW':
case 'A256KW': {
assertEncryptedKey(encryptedKey);
return aeskw.unwrap(alg, key, encryptedKey);
}
case 'A128GCMKW':
case 'A192GCMKW':
case 'A256GCMKW': {
assertEncryptedKey(encryptedKey);
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;
iv = decodeBase64url(joseHeader.iv, 'iv', JWEInvalid);
let tag;
tag = decodeBase64url(joseHeader.tag, 'tag', JWEInvalid);
return aesGcmKwUnwrap(alg, key, encryptedKey, iv, tag);
}
default: {
throw new JOSENotSupported(unsupportedAlgHeader);
}
}
}
export async function encryptKeyManagement(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 = b64u(apu);
if (apv)
parameters.apv = b64u(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 aesGcmKwWrap(alg, key, cek, iv));
break;
}
default: {
throw new JOSENotSupported(unsupportedAlgHeader);
}
}
return { cek, encryptedKey, parameters };
}

31
node_modules/jose/dist/webapi/lib/key_to_jwk.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
import { invalidKeyInput } from './invalid_key_input.js';
import { encode as b64u } from '../util/base64url.js';
import { isCryptoKey, isKeyObject } from './is_key_like.js';
export 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: b64u(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);
if (jwk.kty === 'AKP') {
;
jwk.alg = alg;
}
return jwk;
}

166
node_modules/jose/dist/webapi/lib/normalize_key.js generated vendored Normal file
View File

@@ -0,0 +1,166 @@
import { isJWK } from './type_checks.js';
import { decode } from '../util/base64url.js';
import { jwkToKey } from './jwk_to_key.js';
import { isCryptoKey, isKeyObject } from './is_key_like.js';
const unusableForAlg = 'given KeyObject instance cannot be used for this algorithm';
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 jwkToKey({ ...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(unusableForAlg);
}
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ['deriveBits']);
}
if (keyObject.asymmetricKeyType === 'ed25519') {
if (alg !== 'EdDSA' && alg !== 'Ed25519') {
throw new TypeError(unusableForAlg);
}
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
isPublic ? 'verify' : 'sign',
]);
}
switch (keyObject.asymmetricKeyType) {
case 'ml-dsa-44':
case 'ml-dsa-65':
case 'ml-dsa-87': {
if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
throw new TypeError(unusableForAlg);
}
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(unusableForAlg);
}
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(unusableForAlg);
}
const expectedCurve = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' };
if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) {
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(unusableForAlg);
}
if (!cached) {
cache.set(keyObject, { [alg]: cryptoKey });
}
else {
cached[alg] = cryptoKey;
}
return cryptoKey;
};
export async function normalizeKey(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');
}

39
node_modules/jose/dist/webapi/lib/pbes2kw.js generated vendored Normal file
View File

@@ -0,0 +1,39 @@
import { encode as b64u } from '../util/base64url.js';
import * as aeskw from './aeskw.js';
import { checkEncCryptoKey } from './crypto_key.js';
import { concat, encode } 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(encode(alg), Uint8Array.of(0x00), 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: b64u(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);
}

24
node_modules/jose/dist/webapi/lib/rsaes.js generated vendored Normal file
View File

@@ -0,0 +1,24 @@
import { checkEncCryptoKey } from './crypto_key.js';
import { checkKeyLength } from './signing.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));
}

68
node_modules/jose/dist/webapi/lib/signing.js generated vendored Normal file
View File

@@ -0,0 +1,68 @@
import { JOSENotSupported } from '../util/errors.js';
import { checkSigCryptoKey } from './crypto_key.js';
import { invalidKeyInput } from './invalid_key_input.js';
export function checkKeyLength(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`);
}
}
}
function subtleAlgorithm(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' };
case 'ML-DSA-44':
case 'ML-DSA-65':
case 'ML-DSA-87':
return { name: alg };
default:
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
}
}
async function getSigKey(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;
}
export async function sign(alg, key, data) {
const cryptoKey = await getSigKey(alg, key, 'sign');
checkKeyLength(alg, cryptoKey);
const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
return new Uint8Array(signature);
}
export async function verify(alg, key, signature, data) {
const cryptoKey = await getSigKey(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;
}
}

40
node_modules/jose/dist/webapi/lib/type_checks.js generated vendored Normal file
View File

@@ -0,0 +1,40 @@
const isObjectLike = (value) => typeof value === 'object' && value !== null;
export function isObject(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;
}
export function isDisjoint(...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;
}
export const isJWK = (key) => isObject(key) && typeof key.kty === 'string';
export const isPrivateJWK = (key) => key.kty !== 'oct' &&
((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string');
export const isPublicJWK = (key) => key.kty !== 'oct' && key.d === undefined && key.priv === undefined;
export const isSecretJWK = (key) => key.kty === 'oct' && typeof key.k === 'string';

View File

@@ -0,0 +1,10 @@
export function validateAlgorithms(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);
}

33
node_modules/jose/dist/webapi/lib/validate_crit.js generated vendored Normal file
View File

@@ -0,0 +1,33 @@
import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.js';
export function validateCrit(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);
}

30
node_modules/jose/dist/webapi/util/base64url.js generated vendored Normal file
View File

@@ -0,0 +1,30 @@
import { encoder, decoder } from '../lib/buffer_utils.js';
import { encodeBase64, decodeBase64 } from '../lib/base64.js';
export function decode(input) {
if (Uint8Array.fromBase64) {
return Uint8Array.fromBase64(typeof input === 'string' ? input : decoder.decode(input), {
alphabet: 'base64url',
});
}
let encoded = input;
if (encoded instanceof Uint8Array) {
encoded = decoder.decode(encoded);
}
encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');
try {
return decodeBase64(encoded);
}
catch {
throw new TypeError('The input to be decoded is not correctly encoded.');
}
}
export function encode(input) {
let unencoded = input;
if (typeof unencoded === 'string') {
unencoded = encoder.encode(unencoded);
}
if (Uint8Array.prototype.toBase64) {
return unencoded.toBase64({ alphabet: 'base64url', omitPadding: true });
}
return encodeBase64(unencoded).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}

32
node_modules/jose/dist/webapi/util/decode_jwt.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
import { decode as b64u } from './base64url.js';
import { decoder } from '../lib/buffer_utils.js';
import { isObject } from '../lib/type_checks.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 = b64u(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;
}

View File

@@ -0,0 +1,34 @@
import { decode as b64u } from './base64url.js';
import { decoder } from '../lib/buffer_utils.js';
import { isObject } from '../lib/type_checks.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(b64u(protectedB64u)));
if (!isObject(result)) {
throw new Error();
}
return result;
}
catch {
throw new TypeError('Invalid Token or Protected Header formatting');
}
}

99
node_modules/jose/dist/webapi/util/errors.js generated vendored Normal file
View File

@@ -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);
}
}