Update app and tooling
This commit is contained in:
parent
3046531bdd
commit
e620ec7349
4950 changed files with 2975120 additions and 10 deletions
21
node_modules/jose/LICENSE.md
generated
vendored
Normal file
21
node_modules/jose/LICENSE.md
generated
vendored
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2018 Filip Skokan
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
149
node_modules/jose/README.md
generated
vendored
Normal file
149
node_modules/jose/README.md
generated
vendored
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
# jose
|
||||
|
||||
`jose` is JavaScript module for JSON Object Signing and Encryption, providing support for JSON Web Tokens (JWT), JSON Web Signature (JWS), JSON Web Encryption (JWE), JSON Web Key (JWK), JSON Web Key Set (JWKS), and more. The module is designed to work across various Web-interoperable runtimes including Node.js, browsers, Cloudflare Workers, Deno, Bun, and others.
|
||||
|
||||
## Sponsor
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="./sponsor/Auth0byOkta_dark.png">
|
||||
<source media="(prefers-color-scheme: light)" srcset="./sponsor/Auth0byOkta_light.png">
|
||||
<img height="65" align="left" alt="Auth0 by Okta" src="./sponsor/Auth0byOkta_light.png">
|
||||
</picture>
|
||||
|
||||
If you want to quickly add JWT authentication to JavaScript apps, feel free to check out Auth0's JavaScript SDK and free plan. [Create an Auth0 account; it's free!][sponsor-auth0]<br><br>
|
||||
|
||||
## [💗 Help the project](https://github.com/sponsors/panva)
|
||||
|
||||
Support from the community to continue maintaining and improving this module is welcome. If you find the module useful, please consider supporting the project by [becoming a sponsor](https://github.com/sponsors/panva).
|
||||
|
||||
## Dependencies: 0
|
||||
|
||||
`jose` has no dependencies and it exports tree-shakeable ESM. CJS is also supported.
|
||||
|
||||
## Documentation
|
||||
|
||||
`jose` is distributed via [npmjs.com](https://www.npmjs.com/package/jose), [deno.land/x](https://deno.land/x/jose), [cdnjs.com](https://cdnjs.com/libraries/jose), [jsdelivr.com](https://www.jsdelivr.com/package/npm/jose), and [github.com](https://github.com/panva/jose).
|
||||
|
||||
**`example`** ESM import
|
||||
```js
|
||||
import * as jose from 'jose'
|
||||
```
|
||||
|
||||
**`example`** CJS require
|
||||
```js
|
||||
const jose = require('jose')
|
||||
```
|
||||
|
||||
### JSON Web Tokens (JWT)
|
||||
|
||||
The `jose` module supports JSON Web Tokens (JWT) and provides functionality for signing and verifying tokens, as well as their JWT Claims Set validation.
|
||||
|
||||
- [JWT Claims Set Validation & Signature Verification](docs/jwt/verify/functions/jwtVerify.md) using the `jwtVerify` function
|
||||
- [Using a remote JSON Web Key Set (JWKS)](docs/jwks/remote/functions/createRemoteJWKSet.md)
|
||||
- [Using a local JSON Web Key Set (JWKS)](docs/jwks/local/functions/createLocalJWKSet.md)
|
||||
- [Signing](docs/jwt/sign/classes/SignJWT.md) using the `SignJWT` class
|
||||
- Utility functions
|
||||
- [Decoding Token's Protected Header](docs/util/decode_protected_header/functions/decodeProtectedHeader.md)
|
||||
- [Decoding JWT Claims Set](docs/util/decode_jwt/functions/decodeJwt.md) prior to its validation
|
||||
|
||||
### Encrypted JSON Web Tokens
|
||||
|
||||
The `jose` module supports encrypted JSON Web Tokens and provides functionality for encrypting and decrypting tokens, as well as their JWT Claims Set validation.
|
||||
|
||||
- [Decryption & JWT Claims Set Validation](docs/jwt/decrypt/functions/jwtDecrypt.md) using the `jwtDecrypt` function
|
||||
- [Encryption](docs/jwt/encrypt/classes/EncryptJWT.md) using the `EncryptJWT` class
|
||||
- Utility functions
|
||||
- [Decoding Token's Protected Header](docs/util/decode_protected_header/functions/decodeProtectedHeader.md)
|
||||
|
||||
### Key Utilities
|
||||
|
||||
The `jose` module supports importing, exporting, and generating keys and secrets in various formats, including PEM formats like SPKI, X.509 certificate, and PKCS #8, as well as JSON Web Key (JWK).
|
||||
|
||||
- Key Import Functions
|
||||
- [JWK Import](docs/key/import/functions/importJWK.md)
|
||||
- [Public Key Import (SPKI)](docs/key/import/functions/importSPKI.md)
|
||||
- [Public Key Import (X.509 Certificate)](docs/key/import/functions/importX509.md)
|
||||
- [Private Key Import (PKCS #8)](docs/key/import/functions/importPKCS8.md)
|
||||
- Key and Secret Generation Functions
|
||||
- [Asymmetric Key Pair Generation](docs/key/generate_key_pair/functions/generateKeyPair.md)
|
||||
- [Symmetric Secret Generation](docs/key/generate_secret/functions/generateSecret.md)
|
||||
- Key Export Functions
|
||||
- [JWK Export](docs/key/export/functions/exportJWK.md)
|
||||
- [Private Key Export](docs/key/export/functions/exportPKCS8.md)
|
||||
- [Public Key Export](docs/key/export/functions/exportSPKI.md)
|
||||
|
||||
### JSON Web Signature (JWS)
|
||||
|
||||
The `jose` module supports signing and verification of JWS messages with arbitrary payloads in Compact, Flattened JSON, and General JSON serialization syntaxes.
|
||||
|
||||
- Signing - [Compact](docs/jws/compact/sign/classes/CompactSign.md), [Flattened JSON](docs/jws/flattened/sign/classes/FlattenedSign.md), [General JSON](docs/jws/general/sign/classes/GeneralSign.md)
|
||||
- Verification - [Compact](docs/jws/compact/verify/functions/compactVerify.md), [Flattened JSON](docs/jws/flattened/verify/functions/flattenedVerify.md), [General JSON](docs/jws/general/verify/functions/generalVerify.md)
|
||||
- [Using a remote JSON Web Key Set (JWKS)](docs/jwks/remote/functions/createRemoteJWKSet.md)
|
||||
- [Using a local JSON Web Key Set (JWKS)](docs/jwks/local/functions/createLocalJWKSet.md)
|
||||
- Utility functions
|
||||
- [Decoding Token's Protected Header](docs/util/decode_protected_header/functions/decodeProtectedHeader.md)
|
||||
|
||||
### JSON Web Encryption (JWE)
|
||||
|
||||
The `jose` module supports encryption and decryption of JWE messages with arbitrary plaintext in Compact, Flattened JSON, and General JSON serialization syntaxes.
|
||||
|
||||
- Encryption - [Compact](docs/jwe/compact/encrypt/classes/CompactEncrypt.md), [Flattened JSON](docs/jwe/flattened/encrypt/classes/FlattenedEncrypt.md), [General JSON](docs/jwe/general/encrypt/classes/GeneralEncrypt.md)
|
||||
- Decryption - [Compact](docs/jwe/compact/decrypt/functions/compactDecrypt.md), [Flattened JSON](docs/jwe/flattened/decrypt/functions/flattenedDecrypt.md), [General JSON](docs/jwe/general/decrypt/functions/generalDecrypt.md)
|
||||
- Utility functions
|
||||
- [Decoding Token's Protected Header](docs/util/decode_protected_header/functions/decodeProtectedHeader.md)
|
||||
|
||||
### Other
|
||||
|
||||
The following are additional features and utilities provided by the `jose` module:
|
||||
|
||||
- [Calculating JWK Thumbprint](docs/jwk/thumbprint/functions/calculateJwkThumbprint.md)
|
||||
- [Calculating JWK Thumbprint URI](docs/jwk/thumbprint/functions/calculateJwkThumbprintUri.md)
|
||||
- [Verification using a JWK Embedded in a JWS Header](docs/jwk/embedded/functions/EmbeddedJWK.md)
|
||||
- [Unsecured JWT](docs/jwt/unsecured/classes/UnsecuredJWT.md)
|
||||
- [JOSE Errors](docs/util/errors/README.md)
|
||||
|
||||
## Supported Runtimes
|
||||
|
||||
The `jose` module is compatible with JavaScript runtimes that support the utilized Web API globals and standard built-in objects or are Node.js.
|
||||
|
||||
The following runtimes are supported _(this is not an exhaustive list)_:
|
||||
- [Bun](https://github.com/panva/jose/issues/471)
|
||||
- [Browsers](https://github.com/panva/jose/issues/263)
|
||||
- [Cloudflare Workers](https://github.com/panva/jose/issues/265)
|
||||
- [Deno](https://github.com/panva/jose/issues/266)
|
||||
- [Electron](https://github.com/panva/jose/issues/264)
|
||||
- [Node.js](https://github.com/panva/jose/issues/262)
|
||||
- [Vercel's Edge Runtime](https://github.com/panva/jose/issues/301)
|
||||
|
||||
Please note that certain algorithms may not be available depending on the runtime used. You can find a list of available algorithms for each runtime in the specific issue links provided above.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
| Version | Security Fixes 🔑 | Other Bug Fixes 🐞 | New Features ⭐ |
|
||||
| ------- | --------- | -------- | -------- |
|
||||
| [v5.x](https://github.com/panva/jose/tree/v5.x) | ✅ | ✅ | ✅ |
|
||||
| [v4.x](https://github.com/panva/jose/tree/v4.x) | ✅ | ❌ | ❌ |
|
||||
| [v2.x](https://github.com/panva/jose/tree/v2.x) | ✅ | ❌ | ❌ |
|
||||
|
||||
## Specifications
|
||||
|
||||
<details>
|
||||
<summary>Details</summary>
|
||||
|
||||
- JSON Web Signature (JWS) - [RFC7515](https://www.rfc-editor.org/rfc/rfc7515)
|
||||
- JSON Web Encryption (JWE) - [RFC7516](https://www.rfc-editor.org/rfc/rfc7516)
|
||||
- JSON Web Key (JWK) - [RFC7517](https://www.rfc-editor.org/rfc/rfc7517)
|
||||
- JSON Web Algorithms (JWA) - [RFC7518](https://www.rfc-editor.org/rfc/rfc7518)
|
||||
- JSON Web Token (JWT) - [RFC7519](https://www.rfc-editor.org/rfc/rfc7519)
|
||||
- JSON Web Key Thumbprint - [RFC7638](https://www.rfc-editor.org/rfc/rfc7638)
|
||||
- JSON Web Key Thumbprint URI - [RFC9278](https://www.rfc-editor.org/rfc/rfc9278)
|
||||
- JWS Unencoded Payload Option - [RFC7797](https://www.rfc-editor.org/rfc/rfc7797)
|
||||
- CFRG Elliptic Curve ECDH and Signatures - [RFC8037](https://www.rfc-editor.org/rfc/rfc8037)
|
||||
- secp256k1 EC Key curve support - [RFC8812](https://www.rfc-editor.org/rfc/rfc8812)
|
||||
|
||||
The algorithm implementations in `jose` have been tested using test vectors from their respective specifications as well as [RFC7520](https://www.rfc-editor.org/rfc/rfc7520).
|
||||
|
||||
|
||||
</details>
|
||||
|
||||
[sponsor-auth0]: https://auth0.com/signup?utm_source=external_sites&utm_medium=panva&utm_campaign=devn_signup
|
||||
30
node_modules/jose/dist/browser/index.js
generated
vendored
Normal file
30
node_modules/jose/dist/browser/index.js
generated
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
export { compactDecrypt } from './jwe/compact/decrypt.js';
|
||||
export { flattenedDecrypt } from './jwe/flattened/decrypt.js';
|
||||
export { generalDecrypt } from './jwe/general/decrypt.js';
|
||||
export { GeneralEncrypt } from './jwe/general/encrypt.js';
|
||||
export { compactVerify } from './jws/compact/verify.js';
|
||||
export { flattenedVerify } from './jws/flattened/verify.js';
|
||||
export { generalVerify } from './jws/general/verify.js';
|
||||
export { jwtVerify } from './jwt/verify.js';
|
||||
export { jwtDecrypt } from './jwt/decrypt.js';
|
||||
export { CompactEncrypt } from './jwe/compact/encrypt.js';
|
||||
export { FlattenedEncrypt } from './jwe/flattened/encrypt.js';
|
||||
export { CompactSign } from './jws/compact/sign.js';
|
||||
export { FlattenedSign } from './jws/flattened/sign.js';
|
||||
export { GeneralSign } from './jws/general/sign.js';
|
||||
export { SignJWT } from './jwt/sign.js';
|
||||
export { EncryptJWT } from './jwt/encrypt.js';
|
||||
export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js';
|
||||
export { EmbeddedJWK } from './jwk/embedded.js';
|
||||
export { createLocalJWKSet } from './jwks/local.js';
|
||||
export { createRemoteJWKSet, jwksCache, experimental_jwksCache } from './jwks/remote.js';
|
||||
export { UnsecuredJWT } from './jwt/unsecured.js';
|
||||
export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js';
|
||||
export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js';
|
||||
export { decodeProtectedHeader } from './util/decode_protected_header.js';
|
||||
export { decodeJwt } from './util/decode_jwt.js';
|
||||
export * as errors from './util/errors.js';
|
||||
export { generateKeyPair } from './key/generate_key_pair.js';
|
||||
export { generateSecret } from './key/generate_secret.js';
|
||||
export * as base64url from './util/base64url.js';
|
||||
export { default as cryptoRuntime } from './util/runtime.js';
|
||||
27
node_modules/jose/dist/browser/jwe/compact/decrypt.js
generated
vendored
Normal file
27
node_modules/jose/dist/browser/jwe/compact/decrypt.js
generated
vendored
Normal 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;
|
||||
}
|
||||
26
node_modules/jose/dist/browser/jwe/compact/encrypt.js
generated
vendored
Normal file
26
node_modules/jose/dist/browser/jwe/compact/encrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { FlattenedEncrypt } from '../flattened/encrypt.js';
|
||||
export class CompactEncrypt {
|
||||
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('.');
|
||||
}
|
||||
}
|
||||
161
node_modules/jose/dist/browser/jwe/flattened/decrypt.js
generated
vendored
Normal file
161
node_modules/jose/dist/browser/jwe/flattened/decrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
import { decode as base64url } from '../../runtime/base64url.js';
|
||||
import decrypt from '../../runtime/decrypt.js';
|
||||
import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js';
|
||||
import isDisjoint from '../../lib/is_disjoint.js';
|
||||
import isObject from '../../lib/is_object.js';
|
||||
import decryptKeyManagement from '../../lib/decrypt_key_management.js';
|
||||
import { encoder, decoder, concat } from '../../lib/buffer_utils.js';
|
||||
import generateCek from '../../lib/cek.js';
|
||||
import validateCrit from '../../lib/validate_crit.js';
|
||||
import validateAlgorithms from '../../lib/validate_algorithms.js';
|
||||
export async function flattenedDecrypt(jwe, key, options) {
|
||||
if (!isObject(jwe)) {
|
||||
throw new JWEInvalid('Flattened JWE must be an object');
|
||||
}
|
||||
if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {
|
||||
throw new JWEInvalid('JOSE Header missing');
|
||||
}
|
||||
if (jwe.iv !== undefined && typeof jwe.iv !== 'string') {
|
||||
throw new JWEInvalid('JWE Initialization Vector incorrect type');
|
||||
}
|
||||
if (typeof jwe.ciphertext !== 'string') {
|
||||
throw new JWEInvalid('JWE Ciphertext missing or incorrect type');
|
||||
}
|
||||
if (jwe.tag !== undefined && typeof jwe.tag !== 'string') {
|
||||
throw new JWEInvalid('JWE Authentication Tag incorrect type');
|
||||
}
|
||||
if (jwe.protected !== undefined && typeof jwe.protected !== 'string') {
|
||||
throw new JWEInvalid('JWE Protected Header incorrect type');
|
||||
}
|
||||
if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') {
|
||||
throw new JWEInvalid('JWE Encrypted Key incorrect type');
|
||||
}
|
||||
if (jwe.aad !== undefined && typeof jwe.aad !== 'string') {
|
||||
throw new JWEInvalid('JWE AAD incorrect type');
|
||||
}
|
||||
if (jwe.header !== undefined && !isObject(jwe.header)) {
|
||||
throw new JWEInvalid('JWE Shared Unprotected Header incorrect type');
|
||||
}
|
||||
if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) {
|
||||
throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type');
|
||||
}
|
||||
let parsedProt;
|
||||
if (jwe.protected) {
|
||||
try {
|
||||
const protectedHeader = base64url(jwe.protected);
|
||||
parsedProt = JSON.parse(decoder.decode(protectedHeader));
|
||||
}
|
||||
catch {
|
||||
throw new JWEInvalid('JWE Protected Header is invalid');
|
||||
}
|
||||
}
|
||||
if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {
|
||||
throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint');
|
||||
}
|
||||
const joseHeader = {
|
||||
...parsedProt,
|
||||
...jwe.header,
|
||||
...jwe.unprotected,
|
||||
};
|
||||
validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader);
|
||||
if (joseHeader.zip !== undefined) {
|
||||
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
|
||||
}
|
||||
const { alg, enc } = joseHeader;
|
||||
if (typeof alg !== 'string' || !alg) {
|
||||
throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header');
|
||||
}
|
||||
if (typeof enc !== 'string' || !enc) {
|
||||
throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header');
|
||||
}
|
||||
const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms);
|
||||
const contentEncryptionAlgorithms = options &&
|
||||
validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);
|
||||
if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||
|
||||
(!keyManagementAlgorithms && alg.startsWith('PBES2'))) {
|
||||
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
|
||||
}
|
||||
if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
|
||||
throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
|
||||
}
|
||||
let encryptedKey;
|
||||
if (jwe.encrypted_key !== undefined) {
|
||||
try {
|
||||
encryptedKey = base64url(jwe.encrypted_key);
|
||||
}
|
||||
catch {
|
||||
throw new JWEInvalid('Failed to base64url decode the encrypted_key');
|
||||
}
|
||||
}
|
||||
let resolvedKey = false;
|
||||
if (typeof key === 'function') {
|
||||
key = await key(parsedProt, jwe);
|
||||
resolvedKey = true;
|
||||
}
|
||||
let cek;
|
||||
try {
|
||||
cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options);
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
|
||||
throw err;
|
||||
}
|
||||
cek = generateCek(enc);
|
||||
}
|
||||
let iv;
|
||||
let tag;
|
||||
if (jwe.iv !== undefined) {
|
||||
try {
|
||||
iv = base64url(jwe.iv);
|
||||
}
|
||||
catch {
|
||||
throw new JWEInvalid('Failed to base64url decode the iv');
|
||||
}
|
||||
}
|
||||
if (jwe.tag !== undefined) {
|
||||
try {
|
||||
tag = base64url(jwe.tag);
|
||||
}
|
||||
catch {
|
||||
throw new JWEInvalid('Failed to base64url decode the tag');
|
||||
}
|
||||
}
|
||||
const protectedHeader = encoder.encode(jwe.protected ?? '');
|
||||
let additionalData;
|
||||
if (jwe.aad !== undefined) {
|
||||
additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad));
|
||||
}
|
||||
else {
|
||||
additionalData = protectedHeader;
|
||||
}
|
||||
let ciphertext;
|
||||
try {
|
||||
ciphertext = base64url(jwe.ciphertext);
|
||||
}
|
||||
catch {
|
||||
throw new JWEInvalid('Failed to base64url decode the ciphertext');
|
||||
}
|
||||
const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData);
|
||||
const result = { plaintext };
|
||||
if (jwe.protected !== undefined) {
|
||||
result.protectedHeader = parsedProt;
|
||||
}
|
||||
if (jwe.aad !== undefined) {
|
||||
try {
|
||||
result.additionalAuthenticatedData = base64url(jwe.aad);
|
||||
}
|
||||
catch {
|
||||
throw new JWEInvalid('Failed to base64url decode the aad');
|
||||
}
|
||||
}
|
||||
if (jwe.unprotected !== undefined) {
|
||||
result.sharedUnprotectedHeader = jwe.unprotected;
|
||||
}
|
||||
if (jwe.header !== undefined) {
|
||||
result.unprotectedHeader = jwe.header;
|
||||
}
|
||||
if (resolvedKey) {
|
||||
return { ...result, key };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
153
node_modules/jose/dist/browser/jwe/flattened/encrypt.js
generated
vendored
Normal file
153
node_modules/jose/dist/browser/jwe/flattened/encrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
import { encode as base64url } from '../../runtime/base64url.js';
|
||||
import { unprotected } from '../../lib/private_symbols.js';
|
||||
import encrypt from '../../runtime/encrypt.js';
|
||||
import encryptKeyManagement from '../../lib/encrypt_key_management.js';
|
||||
import { JOSENotSupported, JWEInvalid } from '../../util/errors.js';
|
||||
import isDisjoint from '../../lib/is_disjoint.js';
|
||||
import { encoder, decoder, concat } from '../../lib/buffer_utils.js';
|
||||
import validateCrit from '../../lib/validate_crit.js';
|
||||
export class FlattenedEncrypt {
|
||||
constructor(plaintext) {
|
||||
if (!(plaintext instanceof Uint8Array)) {
|
||||
throw new TypeError('plaintext must be an instance of Uint8Array');
|
||||
}
|
||||
this._plaintext = plaintext;
|
||||
}
|
||||
setKeyManagementParameters(parameters) {
|
||||
if (this._keyManagementParameters) {
|
||||
throw new TypeError('setKeyManagementParameters can only be called once');
|
||||
}
|
||||
this._keyManagementParameters = parameters;
|
||||
return this;
|
||||
}
|
||||
setProtectedHeader(protectedHeader) {
|
||||
if (this._protectedHeader) {
|
||||
throw new TypeError('setProtectedHeader can only be called once');
|
||||
}
|
||||
this._protectedHeader = protectedHeader;
|
||||
return this;
|
||||
}
|
||||
setSharedUnprotectedHeader(sharedUnprotectedHeader) {
|
||||
if (this._sharedUnprotectedHeader) {
|
||||
throw new TypeError('setSharedUnprotectedHeader can only be called once');
|
||||
}
|
||||
this._sharedUnprotectedHeader = sharedUnprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
setUnprotectedHeader(unprotectedHeader) {
|
||||
if (this._unprotectedHeader) {
|
||||
throw new TypeError('setUnprotectedHeader can only be called once');
|
||||
}
|
||||
this._unprotectedHeader = unprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
setAdditionalAuthenticatedData(aad) {
|
||||
this._aad = aad;
|
||||
return this;
|
||||
}
|
||||
setContentEncryptionKey(cek) {
|
||||
if (this._cek) {
|
||||
throw new TypeError('setContentEncryptionKey can only be called once');
|
||||
}
|
||||
this._cek = cek;
|
||||
return this;
|
||||
}
|
||||
setInitializationVector(iv) {
|
||||
if (this._iv) {
|
||||
throw new TypeError('setInitializationVector can only be called once');
|
||||
}
|
||||
this._iv = iv;
|
||||
return this;
|
||||
}
|
||||
async encrypt(key, options) {
|
||||
if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {
|
||||
throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');
|
||||
}
|
||||
if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) {
|
||||
throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
|
||||
}
|
||||
const joseHeader = {
|
||||
...this._protectedHeader,
|
||||
...this._unprotectedHeader,
|
||||
...this._sharedUnprotectedHeader,
|
||||
};
|
||||
validateCrit(JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader);
|
||||
if (joseHeader.zip !== undefined) {
|
||||
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
|
||||
}
|
||||
const { alg, enc } = joseHeader;
|
||||
if (typeof alg !== 'string' || !alg) {
|
||||
throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
|
||||
}
|
||||
if (typeof enc !== 'string' || !enc) {
|
||||
throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
|
||||
}
|
||||
let encryptedKey;
|
||||
if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) {
|
||||
throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg}`);
|
||||
}
|
||||
let cek;
|
||||
{
|
||||
let parameters;
|
||||
({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, key, this._cek, this._keyManagementParameters));
|
||||
if (parameters) {
|
||||
if (options && unprotected in options) {
|
||||
if (!this._unprotectedHeader) {
|
||||
this.setUnprotectedHeader(parameters);
|
||||
}
|
||||
else {
|
||||
this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters };
|
||||
}
|
||||
}
|
||||
else if (!this._protectedHeader) {
|
||||
this.setProtectedHeader(parameters);
|
||||
}
|
||||
else {
|
||||
this._protectedHeader = { ...this._protectedHeader, ...parameters };
|
||||
}
|
||||
}
|
||||
}
|
||||
let additionalData;
|
||||
let protectedHeader;
|
||||
let aadMember;
|
||||
if (this._protectedHeader) {
|
||||
protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));
|
||||
}
|
||||
else {
|
||||
protectedHeader = encoder.encode('');
|
||||
}
|
||||
if (this._aad) {
|
||||
aadMember = base64url(this._aad);
|
||||
additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember));
|
||||
}
|
||||
else {
|
||||
additionalData = protectedHeader;
|
||||
}
|
||||
const { ciphertext, tag, iv } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData);
|
||||
const jwe = {
|
||||
ciphertext: base64url(ciphertext),
|
||||
};
|
||||
if (iv) {
|
||||
jwe.iv = base64url(iv);
|
||||
}
|
||||
if (tag) {
|
||||
jwe.tag = base64url(tag);
|
||||
}
|
||||
if (encryptedKey) {
|
||||
jwe.encrypted_key = base64url(encryptedKey);
|
||||
}
|
||||
if (aadMember) {
|
||||
jwe.aad = aadMember;
|
||||
}
|
||||
if (this._protectedHeader) {
|
||||
jwe.protected = decoder.decode(protectedHeader);
|
||||
}
|
||||
if (this._sharedUnprotectedHeader) {
|
||||
jwe.unprotected = this._sharedUnprotectedHeader;
|
||||
}
|
||||
if (this._unprotectedHeader) {
|
||||
jwe.header = this._unprotectedHeader;
|
||||
}
|
||||
return jwe;
|
||||
}
|
||||
}
|
||||
31
node_modules/jose/dist/browser/jwe/general/decrypt.js
generated
vendored
Normal file
31
node_modules/jose/dist/browser/jwe/general/decrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { flattenedDecrypt } from '../flattened/decrypt.js';
|
||||
import { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js';
|
||||
import isObject from '../../lib/is_object.js';
|
||||
export async function generalDecrypt(jwe, key, options) {
|
||||
if (!isObject(jwe)) {
|
||||
throw new JWEInvalid('General JWE must be an object');
|
||||
}
|
||||
if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) {
|
||||
throw new JWEInvalid('JWE Recipients missing or incorrect type');
|
||||
}
|
||||
if (!jwe.recipients.length) {
|
||||
throw new JWEInvalid('JWE Recipients has no members');
|
||||
}
|
||||
for (const recipient of jwe.recipients) {
|
||||
try {
|
||||
return await flattenedDecrypt({
|
||||
aad: jwe.aad,
|
||||
ciphertext: jwe.ciphertext,
|
||||
encrypted_key: recipient.encrypted_key,
|
||||
header: recipient.header,
|
||||
iv: jwe.iv,
|
||||
protected: jwe.protected,
|
||||
tag: jwe.tag,
|
||||
unprotected: jwe.unprotected,
|
||||
}, key, options);
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
throw new JWEDecryptionFailed();
|
||||
}
|
||||
174
node_modules/jose/dist/browser/jwe/general/encrypt.js
generated
vendored
Normal file
174
node_modules/jose/dist/browser/jwe/general/encrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
import { FlattenedEncrypt } from '../flattened/encrypt.js';
|
||||
import { unprotected } from '../../lib/private_symbols.js';
|
||||
import { JOSENotSupported, JWEInvalid } from '../../util/errors.js';
|
||||
import generateCek from '../../lib/cek.js';
|
||||
import isDisjoint from '../../lib/is_disjoint.js';
|
||||
import encryptKeyManagement from '../../lib/encrypt_key_management.js';
|
||||
import { encode as base64url } from '../../runtime/base64url.js';
|
||||
import validateCrit from '../../lib/validate_crit.js';
|
||||
class IndividualRecipient {
|
||||
constructor(enc, key, options) {
|
||||
this.parent = enc;
|
||||
this.key = key;
|
||||
this.options = options;
|
||||
}
|
||||
setUnprotectedHeader(unprotectedHeader) {
|
||||
if (this.unprotectedHeader) {
|
||||
throw new TypeError('setUnprotectedHeader can only be called once');
|
||||
}
|
||||
this.unprotectedHeader = unprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
addRecipient(...args) {
|
||||
return this.parent.addRecipient(...args);
|
||||
}
|
||||
encrypt(...args) {
|
||||
return this.parent.encrypt(...args);
|
||||
}
|
||||
done() {
|
||||
return this.parent;
|
||||
}
|
||||
}
|
||||
export class GeneralEncrypt {
|
||||
constructor(plaintext) {
|
||||
this._recipients = [];
|
||||
this._plaintext = plaintext;
|
||||
}
|
||||
addRecipient(key, options) {
|
||||
const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
|
||||
this._recipients.push(recipient);
|
||||
return recipient;
|
||||
}
|
||||
setProtectedHeader(protectedHeader) {
|
||||
if (this._protectedHeader) {
|
||||
throw new TypeError('setProtectedHeader can only be called once');
|
||||
}
|
||||
this._protectedHeader = protectedHeader;
|
||||
return this;
|
||||
}
|
||||
setSharedUnprotectedHeader(sharedUnprotectedHeader) {
|
||||
if (this._unprotectedHeader) {
|
||||
throw new TypeError('setSharedUnprotectedHeader can only be called once');
|
||||
}
|
||||
this._unprotectedHeader = sharedUnprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
setAdditionalAuthenticatedData(aad) {
|
||||
this._aad = aad;
|
||||
return this;
|
||||
}
|
||||
async encrypt() {
|
||||
if (!this._recipients.length) {
|
||||
throw new JWEInvalid('at least one recipient must be added');
|
||||
}
|
||||
if (this._recipients.length === 1) {
|
||||
const [recipient] = this._recipients;
|
||||
const flattened = await new FlattenedEncrypt(this._plaintext)
|
||||
.setAdditionalAuthenticatedData(this._aad)
|
||||
.setProtectedHeader(this._protectedHeader)
|
||||
.setSharedUnprotectedHeader(this._unprotectedHeader)
|
||||
.setUnprotectedHeader(recipient.unprotectedHeader)
|
||||
.encrypt(recipient.key, { ...recipient.options });
|
||||
const jwe = {
|
||||
ciphertext: flattened.ciphertext,
|
||||
iv: flattened.iv,
|
||||
recipients: [{}],
|
||||
tag: flattened.tag,
|
||||
};
|
||||
if (flattened.aad)
|
||||
jwe.aad = flattened.aad;
|
||||
if (flattened.protected)
|
||||
jwe.protected = flattened.protected;
|
||||
if (flattened.unprotected)
|
||||
jwe.unprotected = flattened.unprotected;
|
||||
if (flattened.encrypted_key)
|
||||
jwe.recipients[0].encrypted_key = flattened.encrypted_key;
|
||||
if (flattened.header)
|
||||
jwe.recipients[0].header = flattened.header;
|
||||
return jwe;
|
||||
}
|
||||
let enc;
|
||||
for (let i = 0; i < this._recipients.length; i++) {
|
||||
const recipient = this._recipients[i];
|
||||
if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) {
|
||||
throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
|
||||
}
|
||||
const joseHeader = {
|
||||
...this._protectedHeader,
|
||||
...this._unprotectedHeader,
|
||||
...recipient.unprotectedHeader,
|
||||
};
|
||||
const { alg } = joseHeader;
|
||||
if (typeof alg !== 'string' || !alg) {
|
||||
throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
|
||||
}
|
||||
if (alg === 'dir' || alg === 'ECDH-ES') {
|
||||
throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');
|
||||
}
|
||||
if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) {
|
||||
throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
|
||||
}
|
||||
if (!enc) {
|
||||
enc = joseHeader.enc;
|
||||
}
|
||||
else if (enc !== joseHeader.enc) {
|
||||
throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');
|
||||
}
|
||||
validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader);
|
||||
if (joseHeader.zip !== undefined) {
|
||||
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
|
||||
}
|
||||
}
|
||||
const cek = generateCek(enc);
|
||||
const jwe = {
|
||||
ciphertext: '',
|
||||
iv: '',
|
||||
recipients: [],
|
||||
tag: '',
|
||||
};
|
||||
for (let i = 0; i < this._recipients.length; i++) {
|
||||
const recipient = this._recipients[i];
|
||||
const target = {};
|
||||
jwe.recipients.push(target);
|
||||
const joseHeader = {
|
||||
...this._protectedHeader,
|
||||
...this._unprotectedHeader,
|
||||
...recipient.unprotectedHeader,
|
||||
};
|
||||
const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined;
|
||||
if (i === 0) {
|
||||
const flattened = await new FlattenedEncrypt(this._plaintext)
|
||||
.setAdditionalAuthenticatedData(this._aad)
|
||||
.setContentEncryptionKey(cek)
|
||||
.setProtectedHeader(this._protectedHeader)
|
||||
.setSharedUnprotectedHeader(this._unprotectedHeader)
|
||||
.setUnprotectedHeader(recipient.unprotectedHeader)
|
||||
.setKeyManagementParameters({ p2c })
|
||||
.encrypt(recipient.key, {
|
||||
...recipient.options,
|
||||
[unprotected]: true,
|
||||
});
|
||||
jwe.ciphertext = flattened.ciphertext;
|
||||
jwe.iv = flattened.iv;
|
||||
jwe.tag = flattened.tag;
|
||||
if (flattened.aad)
|
||||
jwe.aad = flattened.aad;
|
||||
if (flattened.protected)
|
||||
jwe.protected = flattened.protected;
|
||||
if (flattened.unprotected)
|
||||
jwe.unprotected = flattened.unprotected;
|
||||
target.encrypted_key = flattened.encrypted_key;
|
||||
if (flattened.header)
|
||||
target.header = flattened.header;
|
||||
continue;
|
||||
}
|
||||
const { encryptedKey, parameters } = await encryptKeyManagement(recipient.unprotectedHeader?.alg ||
|
||||
this._protectedHeader?.alg ||
|
||||
this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c });
|
||||
target.encrypted_key = base64url(encryptedKey);
|
||||
if (recipient.unprotectedHeader || parameters)
|
||||
target.header = { ...recipient.unprotectedHeader, ...parameters };
|
||||
}
|
||||
return jwe;
|
||||
}
|
||||
}
|
||||
17
node_modules/jose/dist/browser/jwk/embedded.js
generated
vendored
Normal file
17
node_modules/jose/dist/browser/jwk/embedded.js
generated
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { importJWK } from '../key/import.js';
|
||||
import isObject from '../lib/is_object.js';
|
||||
import { JWSInvalid } from '../util/errors.js';
|
||||
export async function EmbeddedJWK(protectedHeader, token) {
|
||||
const joseHeader = {
|
||||
...protectedHeader,
|
||||
...token?.header,
|
||||
};
|
||||
if (!isObject(joseHeader.jwk)) {
|
||||
throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');
|
||||
}
|
||||
const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
|
||||
if (key instanceof Uint8Array || key.type !== 'public') {
|
||||
throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');
|
||||
}
|
||||
return key;
|
||||
}
|
||||
53
node_modules/jose/dist/browser/jwk/thumbprint.js
generated
vendored
Normal file
53
node_modules/jose/dist/browser/jwk/thumbprint.js
generated
vendored
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import digest from '../runtime/digest.js';
|
||||
import { encode as base64url } from '../runtime/base64url.js';
|
||||
import { JOSENotSupported, JWKInvalid } from '../util/errors.js';
|
||||
import { encoder } from '../lib/buffer_utils.js';
|
||||
import isObject from '../lib/is_object.js';
|
||||
const check = (value, description) => {
|
||||
if (typeof value !== 'string' || !value) {
|
||||
throw new JWKInvalid(`${description} missing or invalid`);
|
||||
}
|
||||
};
|
||||
export async function calculateJwkThumbprint(jwk, digestAlgorithm) {
|
||||
if (!isObject(jwk)) {
|
||||
throw new TypeError('JWK must be an object');
|
||||
}
|
||||
digestAlgorithm ?? (digestAlgorithm = 'sha256');
|
||||
if (digestAlgorithm !== 'sha256' &&
|
||||
digestAlgorithm !== 'sha384' &&
|
||||
digestAlgorithm !== 'sha512') {
|
||||
throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
|
||||
}
|
||||
let components;
|
||||
switch (jwk.kty) {
|
||||
case 'EC':
|
||||
check(jwk.crv, '"crv" (Curve) Parameter');
|
||||
check(jwk.x, '"x" (X Coordinate) Parameter');
|
||||
check(jwk.y, '"y" (Y Coordinate) Parameter');
|
||||
components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
|
||||
break;
|
||||
case 'OKP':
|
||||
check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
|
||||
check(jwk.x, '"x" (Public Key) Parameter');
|
||||
components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
|
||||
break;
|
||||
case 'RSA':
|
||||
check(jwk.e, '"e" (Exponent) Parameter');
|
||||
check(jwk.n, '"n" (Modulus) Parameter');
|
||||
components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
|
||||
break;
|
||||
case 'oct':
|
||||
check(jwk.k, '"k" (Key Value) Parameter');
|
||||
components = { k: jwk.k, kty: jwk.kty };
|
||||
break;
|
||||
default:
|
||||
throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
|
||||
}
|
||||
const data = encoder.encode(JSON.stringify(components));
|
||||
return base64url(await digest(digestAlgorithm, data));
|
||||
}
|
||||
export async function calculateJwkThumbprintUri(jwk, digestAlgorithm) {
|
||||
digestAlgorithm ?? (digestAlgorithm = 'sha256');
|
||||
const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);
|
||||
return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
|
||||
}
|
||||
121
node_modules/jose/dist/browser/jwks/local.js
generated
vendored
Normal file
121
node_modules/jose/dist/browser/jwks/local.js
generated
vendored
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import { importJWK } from '../key/import.js';
|
||||
import { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js';
|
||||
import isObject from '../lib/is_object.js';
|
||||
function getKtyFromAlg(alg) {
|
||||
switch (typeof alg === 'string' && alg.slice(0, 2)) {
|
||||
case 'RS':
|
||||
case 'PS':
|
||||
return 'RSA';
|
||||
case 'ES':
|
||||
return 'EC';
|
||||
case 'Ed':
|
||||
return 'OKP';
|
||||
default:
|
||||
throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set');
|
||||
}
|
||||
}
|
||||
function isJWKSLike(jwks) {
|
||||
return (jwks &&
|
||||
typeof jwks === 'object' &&
|
||||
Array.isArray(jwks.keys) &&
|
||||
jwks.keys.every(isJWKLike));
|
||||
}
|
||||
function isJWKLike(key) {
|
||||
return isObject(key);
|
||||
}
|
||||
function clone(obj) {
|
||||
if (typeof structuredClone === 'function') {
|
||||
return structuredClone(obj);
|
||||
}
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
}
|
||||
class LocalJWKSet {
|
||||
constructor(jwks) {
|
||||
this._cached = new WeakMap();
|
||||
if (!isJWKSLike(jwks)) {
|
||||
throw new JWKSInvalid('JSON Web Key Set malformed');
|
||||
}
|
||||
this._jwks = clone(jwks);
|
||||
}
|
||||
async getKey(protectedHeader, token) {
|
||||
const { alg, kid } = { ...protectedHeader, ...token?.header };
|
||||
const kty = getKtyFromAlg(alg);
|
||||
const candidates = this._jwks.keys.filter((jwk) => {
|
||||
let candidate = kty === jwk.kty;
|
||||
if (candidate && typeof kid === 'string') {
|
||||
candidate = kid === jwk.kid;
|
||||
}
|
||||
if (candidate && typeof jwk.alg === 'string') {
|
||||
candidate = alg === jwk.alg;
|
||||
}
|
||||
if (candidate && typeof jwk.use === 'string') {
|
||||
candidate = jwk.use === 'sig';
|
||||
}
|
||||
if (candidate && Array.isArray(jwk.key_ops)) {
|
||||
candidate = jwk.key_ops.includes('verify');
|
||||
}
|
||||
if (candidate && alg === 'EdDSA') {
|
||||
candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448';
|
||||
}
|
||||
if (candidate) {
|
||||
switch (alg) {
|
||||
case 'ES256':
|
||||
candidate = jwk.crv === 'P-256';
|
||||
break;
|
||||
case 'ES256K':
|
||||
candidate = jwk.crv === 'secp256k1';
|
||||
break;
|
||||
case 'ES384':
|
||||
candidate = jwk.crv === 'P-384';
|
||||
break;
|
||||
case 'ES512':
|
||||
candidate = jwk.crv === 'P-521';
|
||||
break;
|
||||
}
|
||||
}
|
||||
return candidate;
|
||||
});
|
||||
const { 0: jwk, length } = candidates;
|
||||
if (length === 0) {
|
||||
throw new JWKSNoMatchingKey();
|
||||
}
|
||||
if (length !== 1) {
|
||||
const error = new JWKSMultipleMatchingKeys();
|
||||
const { _cached } = this;
|
||||
error[Symbol.asyncIterator] = async function* () {
|
||||
for (const jwk of candidates) {
|
||||
try {
|
||||
yield await importWithAlgCache(_cached, jwk, alg);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
};
|
||||
throw error;
|
||||
}
|
||||
return importWithAlgCache(this._cached, jwk, alg);
|
||||
}
|
||||
}
|
||||
async function importWithAlgCache(cache, jwk, alg) {
|
||||
const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
|
||||
if (cached[alg] === undefined) {
|
||||
const key = await importJWK({ ...jwk, ext: true }, alg);
|
||||
if (key instanceof Uint8Array || key.type !== 'public') {
|
||||
throw new JWKSInvalid('JSON Web Key Set members must be public keys');
|
||||
}
|
||||
cached[alg] = key;
|
||||
}
|
||||
return cached[alg];
|
||||
}
|
||||
export function createLocalJWKSet(jwks) {
|
||||
const set = new LocalJWKSet(jwks);
|
||||
const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
|
||||
Object.defineProperties(localJWKSet, {
|
||||
jwks: {
|
||||
value: () => clone(set._jwks),
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
writable: false,
|
||||
},
|
||||
});
|
||||
return localJWKSet;
|
||||
}
|
||||
139
node_modules/jose/dist/browser/jwks/remote.js
generated
vendored
Normal file
139
node_modules/jose/dist/browser/jwks/remote.js
generated
vendored
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
import fetchJwks from '../runtime/fetch_jwks.js';
|
||||
import { JWKSNoMatchingKey } from '../util/errors.js';
|
||||
import { createLocalJWKSet } from './local.js';
|
||||
import isObject from '../lib/is_object.js';
|
||||
function isCloudflareWorkers() {
|
||||
return (typeof WebSocketPair !== 'undefined' ||
|
||||
(typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
|
||||
(typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
|
||||
}
|
||||
let USER_AGENT;
|
||||
if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
|
||||
const NAME = 'jose';
|
||||
const VERSION = 'v5.9.6';
|
||||
USER_AGENT = `${NAME}/${VERSION}`;
|
||||
}
|
||||
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 {
|
||||
constructor(url, options) {
|
||||
if (!(url instanceof URL)) {
|
||||
throw new TypeError('url must be an instance of URL');
|
||||
}
|
||||
this._url = new URL(url.href);
|
||||
this._options = { agent: options?.agent, headers: options?.headers };
|
||||
this._timeoutDuration =
|
||||
typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;
|
||||
this._cooldownDuration =
|
||||
typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;
|
||||
this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;
|
||||
if (options?.[jwksCache] !== undefined) {
|
||||
this._cache = options?.[jwksCache];
|
||||
if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) {
|
||||
this._jwksTimestamp = this._cache.uat;
|
||||
this._local = createLocalJWKSet(this._cache.jwks);
|
||||
}
|
||||
}
|
||||
}
|
||||
coolingDown() {
|
||||
return typeof this._jwksTimestamp === 'number'
|
||||
? Date.now() < this._jwksTimestamp + this._cooldownDuration
|
||||
: false;
|
||||
}
|
||||
fresh() {
|
||||
return typeof this._jwksTimestamp === 'number'
|
||||
? Date.now() < this._jwksTimestamp + this._cacheMaxAge
|
||||
: false;
|
||||
}
|
||||
async getKey(protectedHeader, token) {
|
||||
if (!this._local || !this.fresh()) {
|
||||
await this.reload();
|
||||
}
|
||||
try {
|
||||
return await this._local(protectedHeader, token);
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof JWKSNoMatchingKey) {
|
||||
if (this.coolingDown() === false) {
|
||||
await this.reload();
|
||||
return this._local(protectedHeader, token);
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
async reload() {
|
||||
if (this._pendingFetch && isCloudflareWorkers()) {
|
||||
this._pendingFetch = undefined;
|
||||
}
|
||||
const headers = new Headers(this._options.headers);
|
||||
if (USER_AGENT && !headers.has('User-Agent')) {
|
||||
headers.set('User-Agent', USER_AGENT);
|
||||
this._options.headers = Object.fromEntries(headers.entries());
|
||||
}
|
||||
this._pendingFetch || (this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options)
|
||||
.then((json) => {
|
||||
this._local = createLocalJWKSet(json);
|
||||
if (this._cache) {
|
||||
this._cache.uat = Date.now();
|
||||
this._cache.jwks = json;
|
||||
}
|
||||
this._jwksTimestamp = Date.now();
|
||||
this._pendingFetch = undefined;
|
||||
})
|
||||
.catch((err) => {
|
||||
this._pendingFetch = undefined;
|
||||
throw err;
|
||||
}));
|
||||
await this._pendingFetch;
|
||||
}
|
||||
}
|
||||
export function createRemoteJWKSet(url, options) {
|
||||
const set = new RemoteJWKSet(url, options);
|
||||
const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
|
||||
Object.defineProperties(remoteJWKSet, {
|
||||
coolingDown: {
|
||||
get: () => set.coolingDown(),
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
},
|
||||
fresh: {
|
||||
get: () => set.fresh(),
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
},
|
||||
reload: {
|
||||
value: () => set.reload(),
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
writable: false,
|
||||
},
|
||||
reloading: {
|
||||
get: () => !!set._pendingFetch,
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
},
|
||||
jwks: {
|
||||
value: () => set._local?.jwks(),
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
writable: false,
|
||||
},
|
||||
});
|
||||
return remoteJWKSet;
|
||||
}
|
||||
export const experimental_jwksCache = jwksCache;
|
||||
17
node_modules/jose/dist/browser/jws/compact/sign.js
generated
vendored
Normal file
17
node_modules/jose/dist/browser/jws/compact/sign.js
generated
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { FlattenedSign } from '../flattened/sign.js';
|
||||
export class CompactSign {
|
||||
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/browser/jws/compact/verify.js
generated
vendored
Normal file
21
node_modules/jose/dist/browser/jws/compact/verify.js
generated
vendored
Normal 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;
|
||||
}
|
||||
81
node_modules/jose/dist/browser/jws/flattened/sign.js
generated
vendored
Normal file
81
node_modules/jose/dist/browser/jws/flattened/sign.js
generated
vendored
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import { encode as base64url } from '../../runtime/base64url.js';
|
||||
import sign from '../../runtime/sign.js';
|
||||
import isDisjoint from '../../lib/is_disjoint.js';
|
||||
import { JWSInvalid } from '../../util/errors.js';
|
||||
import { encoder, decoder, concat } from '../../lib/buffer_utils.js';
|
||||
import { checkKeyTypeWithJwk } from '../../lib/check_key_type.js';
|
||||
import validateCrit from '../../lib/validate_crit.js';
|
||||
export class FlattenedSign {
|
||||
constructor(payload) {
|
||||
if (!(payload instanceof Uint8Array)) {
|
||||
throw new TypeError('payload must be an instance of Uint8Array');
|
||||
}
|
||||
this._payload = payload;
|
||||
}
|
||||
setProtectedHeader(protectedHeader) {
|
||||
if (this._protectedHeader) {
|
||||
throw new TypeError('setProtectedHeader can only be called once');
|
||||
}
|
||||
this._protectedHeader = protectedHeader;
|
||||
return this;
|
||||
}
|
||||
setUnprotectedHeader(unprotectedHeader) {
|
||||
if (this._unprotectedHeader) {
|
||||
throw new TypeError('setUnprotectedHeader can only be called once');
|
||||
}
|
||||
this._unprotectedHeader = unprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
async sign(key, options) {
|
||||
if (!this._protectedHeader && !this._unprotectedHeader) {
|
||||
throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');
|
||||
}
|
||||
if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) {
|
||||
throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
|
||||
}
|
||||
const joseHeader = {
|
||||
...this._protectedHeader,
|
||||
...this._unprotectedHeader,
|
||||
};
|
||||
const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader);
|
||||
let b64 = true;
|
||||
if (extensions.has('b64')) {
|
||||
b64 = this._protectedHeader.b64;
|
||||
if (typeof b64 !== 'boolean') {
|
||||
throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
|
||||
}
|
||||
}
|
||||
const { alg } = joseHeader;
|
||||
if (typeof alg !== 'string' || !alg) {
|
||||
throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
||||
}
|
||||
checkKeyTypeWithJwk(alg, key, 'sign');
|
||||
let payload = this._payload;
|
||||
if (b64) {
|
||||
payload = encoder.encode(base64url(payload));
|
||||
}
|
||||
let protectedHeader;
|
||||
if (this._protectedHeader) {
|
||||
protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));
|
||||
}
|
||||
else {
|
||||
protectedHeader = encoder.encode('');
|
||||
}
|
||||
const data = concat(protectedHeader, encoder.encode('.'), payload);
|
||||
const signature = await sign(alg, key, data);
|
||||
const jws = {
|
||||
signature: base64url(signature),
|
||||
payload: '',
|
||||
};
|
||||
if (b64) {
|
||||
jws.payload = decoder.decode(payload);
|
||||
}
|
||||
if (this._unprotectedHeader) {
|
||||
jws.header = this._unprotectedHeader;
|
||||
}
|
||||
if (this._protectedHeader) {
|
||||
jws.protected = decoder.decode(protectedHeader);
|
||||
}
|
||||
return jws;
|
||||
}
|
||||
}
|
||||
122
node_modules/jose/dist/browser/jws/flattened/verify.js
generated
vendored
Normal file
122
node_modules/jose/dist/browser/jws/flattened/verify.js
generated
vendored
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
import { decode as base64url } from '../../runtime/base64url.js';
|
||||
import verify from '../../runtime/verify.js';
|
||||
import { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';
|
||||
import { concat, encoder, decoder } from '../../lib/buffer_utils.js';
|
||||
import isDisjoint from '../../lib/is_disjoint.js';
|
||||
import isObject from '../../lib/is_object.js';
|
||||
import { checkKeyTypeWithJwk } from '../../lib/check_key_type.js';
|
||||
import validateCrit from '../../lib/validate_crit.js';
|
||||
import validateAlgorithms from '../../lib/validate_algorithms.js';
|
||||
import { isJWK } from '../../lib/is_jwk.js';
|
||||
import { importJWK } from '../../key/import.js';
|
||||
export async function flattenedVerify(jws, key, options) {
|
||||
if (!isObject(jws)) {
|
||||
throw new JWSInvalid('Flattened JWS must be an object');
|
||||
}
|
||||
if (jws.protected === undefined && jws.header === undefined) {
|
||||
throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
|
||||
}
|
||||
if (jws.protected !== undefined && typeof jws.protected !== 'string') {
|
||||
throw new JWSInvalid('JWS Protected Header incorrect type');
|
||||
}
|
||||
if (jws.payload === undefined) {
|
||||
throw new JWSInvalid('JWS Payload missing');
|
||||
}
|
||||
if (typeof jws.signature !== 'string') {
|
||||
throw new JWSInvalid('JWS Signature missing or incorrect type');
|
||||
}
|
||||
if (jws.header !== undefined && !isObject(jws.header)) {
|
||||
throw new JWSInvalid('JWS Unprotected Header incorrect type');
|
||||
}
|
||||
let parsedProt = {};
|
||||
if (jws.protected) {
|
||||
try {
|
||||
const protectedHeader = base64url(jws.protected);
|
||||
parsedProt = JSON.parse(decoder.decode(protectedHeader));
|
||||
}
|
||||
catch {
|
||||
throw new JWSInvalid('JWS Protected Header is invalid');
|
||||
}
|
||||
}
|
||||
if (!isDisjoint(parsedProt, jws.header)) {
|
||||
throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
|
||||
}
|
||||
const joseHeader = {
|
||||
...parsedProt,
|
||||
...jws.header,
|
||||
};
|
||||
const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);
|
||||
let b64 = true;
|
||||
if (extensions.has('b64')) {
|
||||
b64 = parsedProt.b64;
|
||||
if (typeof b64 !== 'boolean') {
|
||||
throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
|
||||
}
|
||||
}
|
||||
const { alg } = joseHeader;
|
||||
if (typeof alg !== 'string' || !alg) {
|
||||
throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
||||
}
|
||||
const algorithms = options && validateAlgorithms('algorithms', options.algorithms);
|
||||
if (algorithms && !algorithms.has(alg)) {
|
||||
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
|
||||
}
|
||||
if (b64) {
|
||||
if (typeof jws.payload !== 'string') {
|
||||
throw new JWSInvalid('JWS Payload must be a string');
|
||||
}
|
||||
}
|
||||
else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {
|
||||
throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');
|
||||
}
|
||||
let resolvedKey = false;
|
||||
if (typeof key === 'function') {
|
||||
key = await key(parsedProt, jws);
|
||||
resolvedKey = true;
|
||||
checkKeyTypeWithJwk(alg, key, 'verify');
|
||||
if (isJWK(key)) {
|
||||
key = await importJWK(key, alg);
|
||||
}
|
||||
}
|
||||
else {
|
||||
checkKeyTypeWithJwk(alg, key, 'verify');
|
||||
}
|
||||
const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload);
|
||||
let signature;
|
||||
try {
|
||||
signature = base64url(jws.signature);
|
||||
}
|
||||
catch {
|
||||
throw new JWSInvalid('Failed to base64url decode the signature');
|
||||
}
|
||||
const verified = await verify(alg, key, signature, data);
|
||||
if (!verified) {
|
||||
throw new JWSSignatureVerificationFailed();
|
||||
}
|
||||
let payload;
|
||||
if (b64) {
|
||||
try {
|
||||
payload = base64url(jws.payload);
|
||||
}
|
||||
catch {
|
||||
throw new JWSInvalid('Failed to base64url decode the payload');
|
||||
}
|
||||
}
|
||||
else if (typeof jws.payload === 'string') {
|
||||
payload = encoder.encode(jws.payload);
|
||||
}
|
||||
else {
|
||||
payload = jws.payload;
|
||||
}
|
||||
const result = { payload };
|
||||
if (jws.protected !== undefined) {
|
||||
result.protectedHeader = parsedProt;
|
||||
}
|
||||
if (jws.header !== undefined) {
|
||||
result.unprotectedHeader = jws.header;
|
||||
}
|
||||
if (resolvedKey) {
|
||||
return { ...result, key };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
67
node_modules/jose/dist/browser/jws/general/sign.js
generated
vendored
Normal file
67
node_modules/jose/dist/browser/jws/general/sign.js
generated
vendored
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import { FlattenedSign } from '../flattened/sign.js';
|
||||
import { JWSInvalid } from '../../util/errors.js';
|
||||
class IndividualSignature {
|
||||
constructor(sig, key, options) {
|
||||
this.parent = sig;
|
||||
this.key = key;
|
||||
this.options = options;
|
||||
}
|
||||
setProtectedHeader(protectedHeader) {
|
||||
if (this.protectedHeader) {
|
||||
throw new TypeError('setProtectedHeader can only be called once');
|
||||
}
|
||||
this.protectedHeader = protectedHeader;
|
||||
return this;
|
||||
}
|
||||
setUnprotectedHeader(unprotectedHeader) {
|
||||
if (this.unprotectedHeader) {
|
||||
throw new TypeError('setUnprotectedHeader can only be called once');
|
||||
}
|
||||
this.unprotectedHeader = unprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
addSignature(...args) {
|
||||
return this.parent.addSignature(...args);
|
||||
}
|
||||
sign(...args) {
|
||||
return this.parent.sign(...args);
|
||||
}
|
||||
done() {
|
||||
return this.parent;
|
||||
}
|
||||
}
|
||||
export class GeneralSign {
|
||||
constructor(payload) {
|
||||
this._signatures = [];
|
||||
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/browser/jws/general/verify.js
generated
vendored
Normal file
24
node_modules/jose/dist/browser/jws/general/verify.js
generated
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { flattenedVerify } from '../flattened/verify.js';
|
||||
import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';
|
||||
import isObject from '../../lib/is_object.js';
|
||||
export async function generalVerify(jws, key, options) {
|
||||
if (!isObject(jws)) {
|
||||
throw new JWSInvalid('General JWS must be an object');
|
||||
}
|
||||
if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) {
|
||||
throw new JWSInvalid('JWS Signatures missing or incorrect type');
|
||||
}
|
||||
for (const signature of jws.signatures) {
|
||||
try {
|
||||
return await flattenedVerify({
|
||||
header: signature.header,
|
||||
payload: jws.payload,
|
||||
protected: signature.protected,
|
||||
signature: signature.signature,
|
||||
}, key, options);
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
throw new JWSSignatureVerificationFailed();
|
||||
}
|
||||
23
node_modules/jose/dist/browser/jwt/decrypt.js
generated
vendored
Normal file
23
node_modules/jose/dist/browser/jwt/decrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { compactDecrypt } from '../jwe/compact/decrypt.js';
|
||||
import jwtPayload from '../lib/jwt_claims_set.js';
|
||||
import { JWTClaimValidationFailed } from '../util/errors.js';
|
||||
export async function jwtDecrypt(jwt, key, options) {
|
||||
const decrypted = await compactDecrypt(jwt, key, options);
|
||||
const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options);
|
||||
const { protectedHeader } = decrypted;
|
||||
if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) {
|
||||
throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, 'iss', 'mismatch');
|
||||
}
|
||||
if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) {
|
||||
throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, 'sub', 'mismatch');
|
||||
}
|
||||
if (protectedHeader.aud !== undefined &&
|
||||
JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
|
||||
throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, 'aud', 'mismatch');
|
||||
}
|
||||
const result = { payload, protectedHeader };
|
||||
if (typeof key === 'function') {
|
||||
return { ...result, key: decrypted.key };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
68
node_modules/jose/dist/browser/jwt/encrypt.js
generated
vendored
Normal file
68
node_modules/jose/dist/browser/jwt/encrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { CompactEncrypt } from '../jwe/compact/encrypt.js';
|
||||
import { encoder } from '../lib/buffer_utils.js';
|
||||
import { ProduceJWT } from './produce.js';
|
||||
export class EncryptJWT extends ProduceJWT {
|
||||
setProtectedHeader(protectedHeader) {
|
||||
if (this._protectedHeader) {
|
||||
throw new TypeError('setProtectedHeader can only be called once');
|
||||
}
|
||||
this._protectedHeader = protectedHeader;
|
||||
return this;
|
||||
}
|
||||
setKeyManagementParameters(parameters) {
|
||||
if (this._keyManagementParameters) {
|
||||
throw new TypeError('setKeyManagementParameters can only be called once');
|
||||
}
|
||||
this._keyManagementParameters = parameters;
|
||||
return this;
|
||||
}
|
||||
setContentEncryptionKey(cek) {
|
||||
if (this._cek) {
|
||||
throw new TypeError('setContentEncryptionKey can only be called once');
|
||||
}
|
||||
this._cek = cek;
|
||||
return this;
|
||||
}
|
||||
setInitializationVector(iv) {
|
||||
if (this._iv) {
|
||||
throw new TypeError('setInitializationVector can only be called once');
|
||||
}
|
||||
this._iv = iv;
|
||||
return this;
|
||||
}
|
||||
replicateIssuerAsHeader() {
|
||||
this._replicateIssuerAsHeader = true;
|
||||
return this;
|
||||
}
|
||||
replicateSubjectAsHeader() {
|
||||
this._replicateSubjectAsHeader = true;
|
||||
return this;
|
||||
}
|
||||
replicateAudienceAsHeader() {
|
||||
this._replicateAudienceAsHeader = true;
|
||||
return this;
|
||||
}
|
||||
async encrypt(key, options) {
|
||||
const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload)));
|
||||
if (this._replicateIssuerAsHeader) {
|
||||
this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss };
|
||||
}
|
||||
if (this._replicateSubjectAsHeader) {
|
||||
this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub };
|
||||
}
|
||||
if (this._replicateAudienceAsHeader) {
|
||||
this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud };
|
||||
}
|
||||
enc.setProtectedHeader(this._protectedHeader);
|
||||
if (this._iv) {
|
||||
enc.setInitializationVector(this._iv);
|
||||
}
|
||||
if (this._cek) {
|
||||
enc.setContentEncryptionKey(this._cek);
|
||||
}
|
||||
if (this._keyManagementParameters) {
|
||||
enc.setKeyManagementParameters(this._keyManagementParameters);
|
||||
}
|
||||
return enc.encrypt(key, options);
|
||||
}
|
||||
}
|
||||
75
node_modules/jose/dist/browser/jwt/produce.js
generated
vendored
Normal file
75
node_modules/jose/dist/browser/jwt/produce.js
generated
vendored
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import epoch from '../lib/epoch.js';
|
||||
import isObject from '../lib/is_object.js';
|
||||
import secs from '../lib/secs.js';
|
||||
function validateInput(label, input) {
|
||||
if (!Number.isFinite(input)) {
|
||||
throw new TypeError(`Invalid ${label} input`);
|
||||
}
|
||||
return input;
|
||||
}
|
||||
export class ProduceJWT {
|
||||
constructor(payload = {}) {
|
||||
if (!isObject(payload)) {
|
||||
throw new TypeError('JWT Claims Set MUST be an object');
|
||||
}
|
||||
this._payload = payload;
|
||||
}
|
||||
setIssuer(issuer) {
|
||||
this._payload = { ...this._payload, iss: issuer };
|
||||
return this;
|
||||
}
|
||||
setSubject(subject) {
|
||||
this._payload = { ...this._payload, sub: subject };
|
||||
return this;
|
||||
}
|
||||
setAudience(audience) {
|
||||
this._payload = { ...this._payload, aud: audience };
|
||||
return this;
|
||||
}
|
||||
setJti(jwtId) {
|
||||
this._payload = { ...this._payload, jti: jwtId };
|
||||
return this;
|
||||
}
|
||||
setNotBefore(input) {
|
||||
if (typeof input === 'number') {
|
||||
this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) };
|
||||
}
|
||||
else if (input instanceof Date) {
|
||||
this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) };
|
||||
}
|
||||
else {
|
||||
this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) };
|
||||
}
|
||||
return this;
|
||||
}
|
||||
setExpirationTime(input) {
|
||||
if (typeof input === 'number') {
|
||||
this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) };
|
||||
}
|
||||
else if (input instanceof Date) {
|
||||
this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) };
|
||||
}
|
||||
else {
|
||||
this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) };
|
||||
}
|
||||
return this;
|
||||
}
|
||||
setIssuedAt(input) {
|
||||
if (typeof input === 'undefined') {
|
||||
this._payload = { ...this._payload, iat: epoch(new Date()) };
|
||||
}
|
||||
else if (input instanceof Date) {
|
||||
this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) };
|
||||
}
|
||||
else if (typeof input === 'string') {
|
||||
this._payload = {
|
||||
...this._payload,
|
||||
iat: validateInput('setIssuedAt', epoch(new Date()) + secs(input)),
|
||||
};
|
||||
}
|
||||
else {
|
||||
this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) };
|
||||
}
|
||||
return this;
|
||||
}
|
||||
}
|
||||
20
node_modules/jose/dist/browser/jwt/sign.js
generated
vendored
Normal file
20
node_modules/jose/dist/browser/jwt/sign.js
generated
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { CompactSign } from '../jws/compact/sign.js';
|
||||
import { JWTInvalid } from '../util/errors.js';
|
||||
import { encoder } from '../lib/buffer_utils.js';
|
||||
import { ProduceJWT } from './produce.js';
|
||||
export class SignJWT extends ProduceJWT {
|
||||
setProtectedHeader(protectedHeader) {
|
||||
this._protectedHeader = protectedHeader;
|
||||
return this;
|
||||
}
|
||||
async sign(key, options) {
|
||||
const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)));
|
||||
sig.setProtectedHeader(this._protectedHeader);
|
||||
if (Array.isArray(this._protectedHeader?.crit) &&
|
||||
this._protectedHeader.crit.includes('b64') &&
|
||||
this._protectedHeader.b64 === false) {
|
||||
throw new JWTInvalid('JWTs MUST NOT use unencoded payload');
|
||||
}
|
||||
return sig.sign(key, options);
|
||||
}
|
||||
}
|
||||
32
node_modules/jose/dist/browser/jwt/unsecured.js
generated
vendored
Normal file
32
node_modules/jose/dist/browser/jwt/unsecured.js
generated
vendored
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import * as base64url from '../runtime/base64url.js';
|
||||
import { decoder } from '../lib/buffer_utils.js';
|
||||
import { JWTInvalid } from '../util/errors.js';
|
||||
import jwtPayload from '../lib/jwt_claims_set.js';
|
||||
import { ProduceJWT } from './produce.js';
|
||||
export class UnsecuredJWT extends ProduceJWT {
|
||||
encode() {
|
||||
const header = base64url.encode(JSON.stringify({ alg: 'none' }));
|
||||
const payload = base64url.encode(JSON.stringify(this._payload));
|
||||
return `${header}.${payload}.`;
|
||||
}
|
||||
static decode(jwt, options) {
|
||||
if (typeof jwt !== 'string') {
|
||||
throw new JWTInvalid('Unsecured JWT must be a string');
|
||||
}
|
||||
const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.');
|
||||
if (length !== 3 || signature !== '') {
|
||||
throw new JWTInvalid('Invalid Unsecured JWT');
|
||||
}
|
||||
let header;
|
||||
try {
|
||||
header = JSON.parse(decoder.decode(base64url.decode(encodedHeader)));
|
||||
if (header.alg !== 'none')
|
||||
throw new Error();
|
||||
}
|
||||
catch {
|
||||
throw new JWTInvalid('Invalid Unsecured JWT');
|
||||
}
|
||||
const payload = jwtPayload(header, base64url.decode(encodedPayload), options);
|
||||
return { payload, header };
|
||||
}
|
||||
}
|
||||
15
node_modules/jose/dist/browser/jwt/verify.js
generated
vendored
Normal file
15
node_modules/jose/dist/browser/jwt/verify.js
generated
vendored
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { compactVerify } from '../jws/compact/verify.js';
|
||||
import jwtPayload from '../lib/jwt_claims_set.js';
|
||||
import { JWTInvalid } from '../util/errors.js';
|
||||
export async function jwtVerify(jwt, key, options) {
|
||||
const verified = await compactVerify(jwt, key, options);
|
||||
if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
|
||||
throw new JWTInvalid('JWTs MUST NOT use unencoded payload');
|
||||
}
|
||||
const payload = jwtPayload(verified.protectedHeader, verified.payload, options);
|
||||
const result = { payload, protectedHeader: verified.protectedHeader };
|
||||
if (typeof key === 'function') {
|
||||
return { ...result, key: verified.key };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
12
node_modules/jose/dist/browser/key/export.js
generated
vendored
Normal file
12
node_modules/jose/dist/browser/key/export.js
generated
vendored
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { toSPKI as exportPublic } from '../runtime/asn1.js';
|
||||
import { toPKCS8 as exportPrivate } from '../runtime/asn1.js';
|
||||
import keyToJWK from '../runtime/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);
|
||||
}
|
||||
4
node_modules/jose/dist/browser/key/generate_key_pair.js
generated
vendored
Normal file
4
node_modules/jose/dist/browser/key/generate_key_pair.js
generated
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import { generateKeyPair as generate } from '../runtime/generate.js';
|
||||
export async function generateKeyPair(alg, options) {
|
||||
return generate(alg, options);
|
||||
}
|
||||
4
node_modules/jose/dist/browser/key/generate_secret.js
generated
vendored
Normal file
4
node_modules/jose/dist/browser/key/generate_secret.js
generated
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
import { generateSecret as generate } from '../runtime/generate.js';
|
||||
export async function generateSecret(alg, options) {
|
||||
return generate(alg, options);
|
||||
}
|
||||
45
node_modules/jose/dist/browser/key/import.js
generated
vendored
Normal file
45
node_modules/jose/dist/browser/key/import.js
generated
vendored
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
import { decode as decodeBase64URL } from '../runtime/base64url.js';
|
||||
import { fromSPKI, fromPKCS8, fromX509 } from '../runtime/asn1.js';
|
||||
import asKeyObject from '../runtime/jwk_to_key.js';
|
||||
import { JOSENotSupported } from '../util/errors.js';
|
||||
import isObject from '../lib/is_object.js';
|
||||
export async function importSPKI(spki, alg, options) {
|
||||
if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {
|
||||
throw new TypeError('"spki" must be SPKI formatted string');
|
||||
}
|
||||
return fromSPKI(spki, alg, options);
|
||||
}
|
||||
export async function importX509(x509, alg, options) {
|
||||
if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {
|
||||
throw new TypeError('"x509" must be X.509 formatted string');
|
||||
}
|
||||
return fromX509(x509, alg, options);
|
||||
}
|
||||
export async function importPKCS8(pkcs8, alg, options) {
|
||||
if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {
|
||||
throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
|
||||
}
|
||||
return fromPKCS8(pkcs8, alg, options);
|
||||
}
|
||||
export async function importJWK(jwk, alg) {
|
||||
if (!isObject(jwk)) {
|
||||
throw new TypeError('JWK must be an object');
|
||||
}
|
||||
alg || (alg = jwk.alg);
|
||||
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 (jwk.oth !== undefined) {
|
||||
throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
|
||||
}
|
||||
case 'EC':
|
||||
case 'OKP':
|
||||
return asKeyObject({ ...jwk, alg });
|
||||
default:
|
||||
throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
|
||||
}
|
||||
}
|
||||
16
node_modules/jose/dist/browser/lib/aesgcmkw.js
generated
vendored
Normal file
16
node_modules/jose/dist/browser/lib/aesgcmkw.js
generated
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import encrypt from '../runtime/encrypt.js';
|
||||
import decrypt from '../runtime/decrypt.js';
|
||||
import { encode as base64url } from '../runtime/base64url.js';
|
||||
export async function wrap(alg, key, cek, iv) {
|
||||
const jweAlgorithm = alg.slice(0, 7);
|
||||
const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0));
|
||||
return {
|
||||
encryptedKey: wrapped.ciphertext,
|
||||
iv: base64url(wrapped.iv),
|
||||
tag: base64url(wrapped.tag),
|
||||
};
|
||||
}
|
||||
export async function unwrap(alg, key, encryptedKey, iv, tag) {
|
||||
const jweAlgorithm = alg.slice(0, 7);
|
||||
return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0));
|
||||
}
|
||||
51
node_modules/jose/dist/browser/lib/buffer_utils.js
generated
vendored
Normal file
51
node_modules/jose/dist/browser/lib/buffer_utils.js
generated
vendored
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import digest from '../runtime/digest.js';
|
||||
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;
|
||||
}
|
||||
export function p2s(alg, p2sInput) {
|
||||
return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);
|
||||
}
|
||||
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 lengthAndInput(input) {
|
||||
return concat(uint32be(input.length), input);
|
||||
}
|
||||
export async function concatKdf(secret, bits, value) {
|
||||
const iterations = Math.ceil((bits >> 3) / 32);
|
||||
const res = new Uint8Array(iterations * 32);
|
||||
for (let iter = 0; iter < iterations; iter++) {
|
||||
const buf = new Uint8Array(4 + secret.length + value.length);
|
||||
buf.set(uint32be(iter + 1));
|
||||
buf.set(secret, 4);
|
||||
buf.set(value, 4 + secret.length);
|
||||
res.set(await digest('sha256', buf), iter * 32);
|
||||
}
|
||||
return res.slice(0, bits >> 3);
|
||||
}
|
||||
20
node_modules/jose/dist/browser/lib/cek.js
generated
vendored
Normal file
20
node_modules/jose/dist/browser/lib/cek.js
generated
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { JOSENotSupported } from '../util/errors.js';
|
||||
import random from '../runtime/random.js';
|
||||
export function bitLength(alg) {
|
||||
switch (alg) {
|
||||
case 'A128GCM':
|
||||
return 128;
|
||||
case 'A192GCM':
|
||||
return 192;
|
||||
case 'A256GCM':
|
||||
case 'A128CBC-HS256':
|
||||
return 256;
|
||||
case 'A192CBC-HS384':
|
||||
return 384;
|
||||
case 'A256CBC-HS512':
|
||||
return 512;
|
||||
default:
|
||||
throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
|
||||
}
|
||||
}
|
||||
export default (alg) => random(new Uint8Array(bitLength(alg) >> 3));
|
||||
8
node_modules/jose/dist/browser/lib/check_iv_length.js
generated
vendored
Normal file
8
node_modules/jose/dist/browser/lib/check_iv_length.js
generated
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { JWEInvalid } from '../util/errors.js';
|
||||
import { bitLength } from './iv.js';
|
||||
const checkIvLength = (enc, iv) => {
|
||||
if (iv.length << 3 !== bitLength(enc)) {
|
||||
throw new JWEInvalid('Invalid Initialization Vector length');
|
||||
}
|
||||
};
|
||||
export default checkIvLength;
|
||||
77
node_modules/jose/dist/browser/lib/check_key_type.js
generated
vendored
Normal file
77
node_modules/jose/dist/browser/lib/check_key_type.js
generated
vendored
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import { withAlg as invalidKeyInput } from './invalid_key_input.js';
|
||||
import isKeyLike, { types } from '../runtime/is_key_like.js';
|
||||
import * as jwk from './is_jwk.js';
|
||||
const tag = (key) => key?.[Symbol.toStringTag];
|
||||
const jwkMatchesOp = (alg, key, usage) => {
|
||||
if (key.use !== undefined && key.use !== 'sig') {
|
||||
throw new TypeError('Invalid key for this operation, when present its use must be sig');
|
||||
}
|
||||
if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) {
|
||||
throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`);
|
||||
}
|
||||
if (key.alg !== undefined && key.alg !== alg) {
|
||||
throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const symmetricTypeCheck = (alg, key, usage, allowJwk) => {
|
||||
if (key instanceof Uint8Array)
|
||||
return;
|
||||
if (allowJwk && 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, ...types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null));
|
||||
}
|
||||
if (key.type !== 'secret') {
|
||||
throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
|
||||
}
|
||||
};
|
||||
const asymmetricTypeCheck = (alg, key, usage, allowJwk) => {
|
||||
if (allowJwk && jwk.isJWK(key)) {
|
||||
switch (usage) {
|
||||
case 'sign':
|
||||
if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
|
||||
return;
|
||||
throw new TypeError(`JSON Web Key for this operation be a private JWK`);
|
||||
case 'verify':
|
||||
if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
|
||||
return;
|
||||
throw new TypeError(`JSON Web Key for this operation be a public JWK`);
|
||||
}
|
||||
}
|
||||
if (!isKeyLike(key)) {
|
||||
throw new TypeError(invalidKeyInput(alg, key, ...types, allowJwk ? 'JSON Web Key' : null));
|
||||
}
|
||||
if (key.type === 'secret') {
|
||||
throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
|
||||
}
|
||||
if (usage === 'sign' && key.type === 'public') {
|
||||
throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
|
||||
}
|
||||
if (usage === 'decrypt' && key.type === 'public') {
|
||||
throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
|
||||
}
|
||||
if (key.algorithm && usage === 'verify' && key.type === 'private') {
|
||||
throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
|
||||
}
|
||||
if (key.algorithm && usage === 'encrypt' && key.type === 'private') {
|
||||
throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
|
||||
}
|
||||
};
|
||||
function checkKeyType(allowJwk, alg, key, usage) {
|
||||
const symmetric = alg.startsWith('HS') ||
|
||||
alg === 'dir' ||
|
||||
alg.startsWith('PBES2') ||
|
||||
/^A\d{3}(?:GCM)?KW$/.test(alg);
|
||||
if (symmetric) {
|
||||
symmetricTypeCheck(alg, key, usage, allowJwk);
|
||||
}
|
||||
else {
|
||||
asymmetricTypeCheck(alg, key, usage, allowJwk);
|
||||
}
|
||||
}
|
||||
export default checkKeyType.bind(undefined, false);
|
||||
export const checkKeyTypeWithJwk = checkKeyType.bind(undefined, true);
|
||||
6
node_modules/jose/dist/browser/lib/check_p2s.js
generated
vendored
Normal file
6
node_modules/jose/dist/browser/lib/check_p2s.js
generated
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
import { JWEInvalid } from '../util/errors.js';
|
||||
export default function checkP2s(p2s) {
|
||||
if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
|
||||
throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets');
|
||||
}
|
||||
}
|
||||
152
node_modules/jose/dist/browser/lib/crypto_key.js
generated
vendored
Normal file
152
node_modules/jose/dist/browser/lib/crypto_key.js
generated
vendored
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
function unusable(name, prop = 'algorithm.name') {
|
||||
return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
|
||||
}
|
||||
function isAlgorithm(algorithm, name) {
|
||||
return algorithm.name === name;
|
||||
}
|
||||
function getHashLength(hash) {
|
||||
return parseInt(hash.name.slice(4), 10);
|
||||
}
|
||||
function getNamedCurve(alg) {
|
||||
switch (alg) {
|
||||
case 'ES256':
|
||||
return 'P-256';
|
||||
case 'ES384':
|
||||
return 'P-384';
|
||||
case 'ES512':
|
||||
return 'P-521';
|
||||
default:
|
||||
throw new Error('unreachable');
|
||||
}
|
||||
}
|
||||
function checkUsage(key, usages) {
|
||||
if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {
|
||||
let msg = 'CryptoKey does not support this operation, its usages must include ';
|
||||
if (usages.length > 2) {
|
||||
const last = usages.pop();
|
||||
msg += `one of ${usages.join(', ')}, or ${last}.`;
|
||||
}
|
||||
else if (usages.length === 2) {
|
||||
msg += `one of ${usages[0]} or ${usages[1]}.`;
|
||||
}
|
||||
else {
|
||||
msg += `${usages[0]}.`;
|
||||
}
|
||||
throw new TypeError(msg);
|
||||
}
|
||||
}
|
||||
export function checkSigCryptoKey(key, alg, ...usages) {
|
||||
switch (alg) {
|
||||
case 'HS256':
|
||||
case 'HS384':
|
||||
case 'HS512': {
|
||||
if (!isAlgorithm(key.algorithm, 'HMAC'))
|
||||
throw unusable('HMAC');
|
||||
const expected = parseInt(alg.slice(2), 10);
|
||||
const actual = getHashLength(key.algorithm.hash);
|
||||
if (actual !== expected)
|
||||
throw unusable(`SHA-${expected}`, 'algorithm.hash');
|
||||
break;
|
||||
}
|
||||
case 'RS256':
|
||||
case 'RS384':
|
||||
case 'RS512': {
|
||||
if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))
|
||||
throw unusable('RSASSA-PKCS1-v1_5');
|
||||
const expected = parseInt(alg.slice(2), 10);
|
||||
const actual = getHashLength(key.algorithm.hash);
|
||||
if (actual !== expected)
|
||||
throw unusable(`SHA-${expected}`, 'algorithm.hash');
|
||||
break;
|
||||
}
|
||||
case 'PS256':
|
||||
case 'PS384':
|
||||
case 'PS512': {
|
||||
if (!isAlgorithm(key.algorithm, 'RSA-PSS'))
|
||||
throw unusable('RSA-PSS');
|
||||
const expected = parseInt(alg.slice(2), 10);
|
||||
const actual = getHashLength(key.algorithm.hash);
|
||||
if (actual !== expected)
|
||||
throw unusable(`SHA-${expected}`, 'algorithm.hash');
|
||||
break;
|
||||
}
|
||||
case 'EdDSA': {
|
||||
if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {
|
||||
throw unusable('Ed25519 or Ed448');
|
||||
}
|
||||
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, usages);
|
||||
}
|
||||
export function checkEncCryptoKey(key, alg, ...usages) {
|
||||
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':
|
||||
case 'X448':
|
||||
break;
|
||||
default:
|
||||
throw unusable('ECDH, X25519, or X448');
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'PBES2-HS256+A128KW':
|
||||
case 'PBES2-HS384+A192KW':
|
||||
case 'PBES2-HS512+A256KW':
|
||||
if (!isAlgorithm(key.algorithm, 'PBKDF2'))
|
||||
throw unusable('PBKDF2');
|
||||
break;
|
||||
case 'RSA-OAEP':
|
||||
case 'RSA-OAEP-256':
|
||||
case 'RSA-OAEP-384':
|
||||
case 'RSA-OAEP-512': {
|
||||
if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))
|
||||
throw unusable('RSA-OAEP');
|
||||
const expected = parseInt(alg.slice(9), 10) || 1;
|
||||
const actual = getHashLength(key.algorithm.hash);
|
||||
if (actual !== expected)
|
||||
throw unusable(`SHA-${expected}`, 'algorithm.hash');
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new TypeError('CryptoKey does not support this operation');
|
||||
}
|
||||
checkUsage(key, usages);
|
||||
}
|
||||
129
node_modules/jose/dist/browser/lib/decrypt_key_management.js
generated
vendored
Normal file
129
node_modules/jose/dist/browser/lib/decrypt_key_management.js
generated
vendored
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
import { unwrap as aesKw } from '../runtime/aeskw.js';
|
||||
import * as ECDH from '../runtime/ecdhes.js';
|
||||
import { decrypt as pbes2Kw } from '../runtime/pbes2kw.js';
|
||||
import { decrypt as rsaEs } from '../runtime/rsaes.js';
|
||||
import { decode as base64url } from '../runtime/base64url.js';
|
||||
import normalize from '../runtime/normalize_key.js';
|
||||
import { JOSENotSupported, JWEInvalid } from '../util/errors.js';
|
||||
import { bitLength as cekLength } from '../lib/cek.js';
|
||||
import { importJWK } from '../key/import.js';
|
||||
import checkKeyType from './check_key_type.js';
|
||||
import isObject from './is_object.js';
|
||||
import { unwrap as aesGcmKw } from './aesgcmkw.js';
|
||||
async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {
|
||||
checkKeyType(alg, key, 'decrypt');
|
||||
key = (await normalize.normalizePrivateKey?.(key, alg)) || key;
|
||||
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`);
|
||||
if (!ECDH.ecdhAllowed(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);
|
||||
let partyUInfo;
|
||||
let partyVInfo;
|
||||
if (joseHeader.apu !== undefined) {
|
||||
if (typeof joseHeader.apu !== 'string')
|
||||
throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
|
||||
try {
|
||||
partyUInfo = base64url(joseHeader.apu);
|
||||
}
|
||||
catch {
|
||||
throw new JWEInvalid('Failed to base64url decode the apu');
|
||||
}
|
||||
}
|
||||
if (joseHeader.apv !== undefined) {
|
||||
if (typeof joseHeader.apv !== 'string')
|
||||
throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
|
||||
try {
|
||||
partyVInfo = base64url(joseHeader.apv);
|
||||
}
|
||||
catch {
|
||||
throw new JWEInvalid('Failed to base64url decode the apv');
|
||||
}
|
||||
}
|
||||
const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
|
||||
if (alg === 'ECDH-ES')
|
||||
return sharedSecret;
|
||||
if (encryptedKey === undefined)
|
||||
throw new JWEInvalid('JWE Encrypted Key missing');
|
||||
return aesKw(alg.slice(-6), sharedSecret, encryptedKey);
|
||||
}
|
||||
case 'RSA1_5':
|
||||
case 'RSA-OAEP':
|
||||
case 'RSA-OAEP-256':
|
||||
case 'RSA-OAEP-384':
|
||||
case 'RSA-OAEP-512': {
|
||||
if (encryptedKey === undefined)
|
||||
throw new JWEInvalid('JWE Encrypted Key missing');
|
||||
return rsaEs(alg, key, encryptedKey);
|
||||
}
|
||||
case 'PBES2-HS256+A128KW':
|
||||
case 'PBES2-HS384+A192KW':
|
||||
case 'PBES2-HS512+A256KW': {
|
||||
if (encryptedKey === undefined)
|
||||
throw new JWEInvalid('JWE Encrypted Key missing');
|
||||
if (typeof joseHeader.p2c !== 'number')
|
||||
throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
|
||||
const p2cLimit = options?.maxPBES2Count || 10000;
|
||||
if (joseHeader.p2c > p2cLimit)
|
||||
throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
|
||||
if (typeof joseHeader.p2s !== 'string')
|
||||
throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
|
||||
let p2s;
|
||||
try {
|
||||
p2s = base64url(joseHeader.p2s);
|
||||
}
|
||||
catch {
|
||||
throw new JWEInvalid('Failed to base64url decode the p2s');
|
||||
}
|
||||
return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, p2s);
|
||||
}
|
||||
case 'A128KW':
|
||||
case 'A192KW':
|
||||
case 'A256KW': {
|
||||
if (encryptedKey === undefined)
|
||||
throw new JWEInvalid('JWE Encrypted Key missing');
|
||||
return aesKw(alg, key, encryptedKey);
|
||||
}
|
||||
case 'A128GCMKW':
|
||||
case 'A192GCMKW':
|
||||
case 'A256GCMKW': {
|
||||
if (encryptedKey === undefined)
|
||||
throw new JWEInvalid('JWE Encrypted Key missing');
|
||||
if (typeof joseHeader.iv !== 'string')
|
||||
throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
|
||||
if (typeof joseHeader.tag !== 'string')
|
||||
throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
|
||||
let iv;
|
||||
try {
|
||||
iv = base64url(joseHeader.iv);
|
||||
}
|
||||
catch {
|
||||
throw new JWEInvalid('Failed to base64url decode the iv');
|
||||
}
|
||||
let tag;
|
||||
try {
|
||||
tag = base64url(joseHeader.tag);
|
||||
}
|
||||
catch {
|
||||
throw new JWEInvalid('Failed to base64url decode the tag');
|
||||
}
|
||||
return aesGcmKw(alg, key, encryptedKey, iv, tag);
|
||||
}
|
||||
default: {
|
||||
throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
|
||||
}
|
||||
}
|
||||
}
|
||||
export default decryptKeyManagement;
|
||||
89
node_modules/jose/dist/browser/lib/encrypt_key_management.js
generated
vendored
Normal file
89
node_modules/jose/dist/browser/lib/encrypt_key_management.js
generated
vendored
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
import { wrap as aesKw } from '../runtime/aeskw.js';
|
||||
import * as ECDH from '../runtime/ecdhes.js';
|
||||
import { encrypt as pbes2Kw } from '../runtime/pbes2kw.js';
|
||||
import { encrypt as rsaEs } from '../runtime/rsaes.js';
|
||||
import { encode as base64url } from '../runtime/base64url.js';
|
||||
import normalize from '../runtime/normalize_key.js';
|
||||
import generateCek, { bitLength as cekLength } from '../lib/cek.js';
|
||||
import { JOSENotSupported } from '../util/errors.js';
|
||||
import { exportJWK } from '../key/export.js';
|
||||
import checkKeyType from './check_key_type.js';
|
||||
import { wrap as aesGcmKw } from './aesgcmkw.js';
|
||||
async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {
|
||||
let encryptedKey;
|
||||
let parameters;
|
||||
let cek;
|
||||
checkKeyType(alg, key, 'encrypt');
|
||||
key = (await normalize.normalizePublicKey?.(key, alg)) || key;
|
||||
switch (alg) {
|
||||
case 'dir': {
|
||||
cek = key;
|
||||
break;
|
||||
}
|
||||
case 'ECDH-ES':
|
||||
case 'ECDH-ES+A128KW':
|
||||
case 'ECDH-ES+A192KW':
|
||||
case 'ECDH-ES+A256KW': {
|
||||
if (!ECDH.ecdhAllowed(key)) {
|
||||
throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');
|
||||
}
|
||||
const { apu, apv } = providedParameters;
|
||||
let { epk: ephemeralKey } = providedParameters;
|
||||
ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey);
|
||||
const { x, y, crv, kty } = await exportJWK(ephemeralKey);
|
||||
const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
|
||||
parameters = { epk: { x, crv, kty } };
|
||||
if (kty === 'EC')
|
||||
parameters.epk.y = y;
|
||||
if (apu)
|
||||
parameters.apu = base64url(apu);
|
||||
if (apv)
|
||||
parameters.apv = base64url(apv);
|
||||
if (alg === 'ECDH-ES') {
|
||||
cek = sharedSecret;
|
||||
break;
|
||||
}
|
||||
cek = providedCek || generateCek(enc);
|
||||
const kwAlg = alg.slice(-6);
|
||||
encryptedKey = await aesKw(kwAlg, sharedSecret, cek);
|
||||
break;
|
||||
}
|
||||
case 'RSA1_5':
|
||||
case 'RSA-OAEP':
|
||||
case 'RSA-OAEP-256':
|
||||
case 'RSA-OAEP-384':
|
||||
case 'RSA-OAEP-512': {
|
||||
cek = providedCek || generateCek(enc);
|
||||
encryptedKey = await rsaEs(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(alg, key, cek, p2c, p2s));
|
||||
break;
|
||||
}
|
||||
case 'A128KW':
|
||||
case 'A192KW':
|
||||
case 'A256KW': {
|
||||
cek = providedCek || generateCek(enc);
|
||||
encryptedKey = await aesKw(alg, key, cek);
|
||||
break;
|
||||
}
|
||||
case 'A128GCMKW':
|
||||
case 'A192GCMKW':
|
||||
case 'A256GCMKW': {
|
||||
cek = providedCek || generateCek(enc);
|
||||
const { iv } = providedParameters;
|
||||
({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv));
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
|
||||
}
|
||||
}
|
||||
return { cek, encryptedKey, parameters };
|
||||
}
|
||||
export default encryptKeyManagement;
|
||||
1
node_modules/jose/dist/browser/lib/epoch.js
generated
vendored
Normal file
1
node_modules/jose/dist/browser/lib/epoch.js
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export default (date) => Math.floor(date.getTime() / 1000);
|
||||
4
node_modules/jose/dist/browser/lib/format_pem.js
generated
vendored
Normal file
4
node_modules/jose/dist/browser/lib/format_pem.js
generated
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
export default (b64, descriptor) => {
|
||||
const newlined = (b64.match(/.{1,64}/g) || []).join('\n');
|
||||
return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`;
|
||||
};
|
||||
31
node_modules/jose/dist/browser/lib/invalid_key_input.js
generated
vendored
Normal file
31
node_modules/jose/dist/browser/lib/invalid_key_input.js
generated
vendored
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
function message(msg, actual, ...types) {
|
||||
types = types.filter(Boolean);
|
||||
if (types.length > 2) {
|
||||
const last = types.pop();
|
||||
msg += `one of type ${types.join(', ')}, or ${last}.`;
|
||||
}
|
||||
else if (types.length === 2) {
|
||||
msg += `one of type ${types[0]} or ${types[1]}.`;
|
||||
}
|
||||
else {
|
||||
msg += `of type ${types[0]}.`;
|
||||
}
|
||||
if (actual == null) {
|
||||
msg += ` Received ${actual}`;
|
||||
}
|
||||
else if (typeof actual === 'function' && actual.name) {
|
||||
msg += ` Received function ${actual.name}`;
|
||||
}
|
||||
else if (typeof actual === 'object' && actual != null) {
|
||||
if (actual.constructor?.name) {
|
||||
msg += ` Received an instance of ${actual.constructor.name}`;
|
||||
}
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
export default (actual, ...types) => {
|
||||
return message('Key must be ', actual, ...types);
|
||||
};
|
||||
export function withAlg(alg, actual, ...types) {
|
||||
return message(`Key for the ${alg} algorithm must be `, actual, ...types);
|
||||
}
|
||||
22
node_modules/jose/dist/browser/lib/is_disjoint.js
generated
vendored
Normal file
22
node_modules/jose/dist/browser/lib/is_disjoint.js
generated
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
const 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 default isDisjoint;
|
||||
13
node_modules/jose/dist/browser/lib/is_jwk.js
generated
vendored
Normal file
13
node_modules/jose/dist/browser/lib/is_jwk.js
generated
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import isObject from './is_object.js';
|
||||
export function isJWK(key) {
|
||||
return isObject(key) && typeof key.kty === 'string';
|
||||
}
|
||||
export function isPrivateJWK(key) {
|
||||
return key.kty !== 'oct' && typeof key.d === 'string';
|
||||
}
|
||||
export function isPublicJWK(key) {
|
||||
return key.kty !== 'oct' && typeof key.d === 'undefined';
|
||||
}
|
||||
export function isSecretJWK(key) {
|
||||
return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string';
|
||||
}
|
||||
16
node_modules/jose/dist/browser/lib/is_object.js
generated
vendored
Normal file
16
node_modules/jose/dist/browser/lib/is_object.js
generated
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
function isObjectLike(value) {
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
export default 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;
|
||||
}
|
||||
20
node_modules/jose/dist/browser/lib/iv.js
generated
vendored
Normal file
20
node_modules/jose/dist/browser/lib/iv.js
generated
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { JOSENotSupported } from '../util/errors.js';
|
||||
import random from '../runtime/random.js';
|
||||
export function bitLength(alg) {
|
||||
switch (alg) {
|
||||
case 'A128GCM':
|
||||
case 'A128GCMKW':
|
||||
case 'A192GCM':
|
||||
case 'A192GCMKW':
|
||||
case 'A256GCM':
|
||||
case 'A256GCMKW':
|
||||
return 96;
|
||||
case 'A128CBC-HS256':
|
||||
case 'A192CBC-HS384':
|
||||
case 'A256CBC-HS512':
|
||||
return 128;
|
||||
default:
|
||||
throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
|
||||
}
|
||||
}
|
||||
export default (alg) => random(new Uint8Array(bitLength(alg) >> 3));
|
||||
104
node_modules/jose/dist/browser/lib/jwt_claims_set.js
generated
vendored
Normal file
104
node_modules/jose/dist/browser/lib/jwt_claims_set.js
generated
vendored
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';
|
||||
import { decoder } from './buffer_utils.js';
|
||||
import epoch from './epoch.js';
|
||||
import secs from './secs.js';
|
||||
import isObject from './is_object.js';
|
||||
const normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, '');
|
||||
const checkAudiencePresence = (audPayload, audOption) => {
|
||||
if (typeof audPayload === 'string') {
|
||||
return audOption.includes(audPayload);
|
||||
}
|
||||
if (Array.isArray(audPayload)) {
|
||||
return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
|
||||
}
|
||||
return false;
|
||||
};
|
||||
export default (protectedHeader, encodedPayload, options = {}) => {
|
||||
let payload;
|
||||
try {
|
||||
payload = JSON.parse(decoder.decode(encodedPayload));
|
||||
}
|
||||
catch {
|
||||
}
|
||||
if (!isObject(payload)) {
|
||||
throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');
|
||||
}
|
||||
const { typ } = options;
|
||||
if (typ &&
|
||||
(typeof protectedHeader.typ !== 'string' ||
|
||||
normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
|
||||
throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed');
|
||||
}
|
||||
const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
|
||||
const presenceCheck = [...requiredClaims];
|
||||
if (maxTokenAge !== undefined)
|
||||
presenceCheck.push('iat');
|
||||
if (audience !== undefined)
|
||||
presenceCheck.push('aud');
|
||||
if (subject !== undefined)
|
||||
presenceCheck.push('sub');
|
||||
if (issuer !== undefined)
|
||||
presenceCheck.push('iss');
|
||||
for (const claim of new Set(presenceCheck.reverse())) {
|
||||
if (!(claim in payload)) {
|
||||
throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing');
|
||||
}
|
||||
}
|
||||
if (issuer &&
|
||||
!(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
|
||||
throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed');
|
||||
}
|
||||
if (subject && payload.sub !== subject) {
|
||||
throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed');
|
||||
}
|
||||
if (audience &&
|
||||
!checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {
|
||||
throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed');
|
||||
}
|
||||
let tolerance;
|
||||
switch (typeof options.clockTolerance) {
|
||||
case 'string':
|
||||
tolerance = secs(options.clockTolerance);
|
||||
break;
|
||||
case 'number':
|
||||
tolerance = options.clockTolerance;
|
||||
break;
|
||||
case 'undefined':
|
||||
tolerance = 0;
|
||||
break;
|
||||
default:
|
||||
throw new TypeError('Invalid clockTolerance option type');
|
||||
}
|
||||
const { currentDate } = options;
|
||||
const now = epoch(currentDate || new Date());
|
||||
if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {
|
||||
throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid');
|
||||
}
|
||||
if (payload.nbf !== undefined) {
|
||||
if (typeof payload.nbf !== 'number') {
|
||||
throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid');
|
||||
}
|
||||
if (payload.nbf > now + tolerance) {
|
||||
throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed');
|
||||
}
|
||||
}
|
||||
if (payload.exp !== undefined) {
|
||||
if (typeof payload.exp !== 'number') {
|
||||
throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid');
|
||||
}
|
||||
if (payload.exp <= now - tolerance) {
|
||||
throw new JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed');
|
||||
}
|
||||
}
|
||||
if (maxTokenAge) {
|
||||
const age = now - payload.iat;
|
||||
const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);
|
||||
if (age - tolerance > max) {
|
||||
throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');
|
||||
}
|
||||
if (age < 0 - tolerance) {
|
||||
throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');
|
||||
}
|
||||
}
|
||||
return payload;
|
||||
};
|
||||
1
node_modules/jose/dist/browser/lib/private_symbols.js
generated
vendored
Normal file
1
node_modules/jose/dist/browser/lib/private_symbols.js
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export const unprotected = Symbol();
|
||||
55
node_modules/jose/dist/browser/lib/secs.js
generated
vendored
Normal file
55
node_modules/jose/dist/browser/lib/secs.js
generated
vendored
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
const minute = 60;
|
||||
const hour = minute * 60;
|
||||
const day = hour * 24;
|
||||
const week = day * 7;
|
||||
const year = day * 365.25;
|
||||
const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
|
||||
export default (str) => {
|
||||
const matched = REGEX.exec(str);
|
||||
if (!matched || (matched[4] && matched[1])) {
|
||||
throw new TypeError('Invalid time period format');
|
||||
}
|
||||
const value = parseFloat(matched[2]);
|
||||
const unit = matched[3].toLowerCase();
|
||||
let numericDate;
|
||||
switch (unit) {
|
||||
case 'sec':
|
||||
case 'secs':
|
||||
case 'second':
|
||||
case 'seconds':
|
||||
case 's':
|
||||
numericDate = Math.round(value);
|
||||
break;
|
||||
case 'minute':
|
||||
case 'minutes':
|
||||
case 'min':
|
||||
case 'mins':
|
||||
case 'm':
|
||||
numericDate = Math.round(value * minute);
|
||||
break;
|
||||
case 'hour':
|
||||
case 'hours':
|
||||
case 'hr':
|
||||
case 'hrs':
|
||||
case 'h':
|
||||
numericDate = Math.round(value * hour);
|
||||
break;
|
||||
case 'day':
|
||||
case 'days':
|
||||
case 'd':
|
||||
numericDate = Math.round(value * day);
|
||||
break;
|
||||
case 'week':
|
||||
case 'weeks':
|
||||
case 'w':
|
||||
numericDate = Math.round(value * week);
|
||||
break;
|
||||
default:
|
||||
numericDate = Math.round(value * year);
|
||||
break;
|
||||
}
|
||||
if (matched[1] === '-' || matched[4] === 'ago') {
|
||||
return -numericDate;
|
||||
}
|
||||
return numericDate;
|
||||
};
|
||||
11
node_modules/jose/dist/browser/lib/validate_algorithms.js
generated
vendored
Normal file
11
node_modules/jose/dist/browser/lib/validate_algorithms.js
generated
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
const 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);
|
||||
};
|
||||
export default validateAlgorithms;
|
||||
34
node_modules/jose/dist/browser/lib/validate_crit.js
generated
vendored
Normal file
34
node_modules/jose/dist/browser/lib/validate_crit.js
generated
vendored
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { JOSENotSupported } from '../util/errors.js';
|
||||
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);
|
||||
}
|
||||
export default validateCrit;
|
||||
1
node_modules/jose/dist/browser/package.json
generated
vendored
Normal file
1
node_modules/jose/dist/browser/package.json
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"type":"module","sideEffects":false}
|
||||
32
node_modules/jose/dist/browser/runtime/aeskw.js
generated
vendored
Normal file
32
node_modules/jose/dist/browser/runtime/aeskw.js
generated
vendored
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import bogusWebCrypto from './bogus.js';
|
||||
import crypto, { isCryptoKey } from './webcrypto.js';
|
||||
import { checkEncCryptoKey } from '../lib/crypto_key.js';
|
||||
import invalidKeyInput from '../lib/invalid_key_input.js';
|
||||
import { types } from './is_key_like.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 (isCryptoKey(key)) {
|
||||
checkEncCryptoKey(key, alg, usage);
|
||||
return key;
|
||||
}
|
||||
if (key instanceof Uint8Array) {
|
||||
return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]);
|
||||
}
|
||||
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
|
||||
}
|
||||
export const wrap = async (alg, key, cek) => {
|
||||
const cryptoKey = await getCryptoKey(key, alg, 'wrapKey');
|
||||
checkKeySize(cryptoKey, alg);
|
||||
const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto);
|
||||
return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW'));
|
||||
};
|
||||
export const unwrap = async (alg, key, encryptedKey) => {
|
||||
const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey');
|
||||
checkKeySize(cryptoKey, alg);
|
||||
const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', ...bogusWebCrypto);
|
||||
return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));
|
||||
};
|
||||
201
node_modules/jose/dist/browser/runtime/asn1.js
generated
vendored
Normal file
201
node_modules/jose/dist/browser/runtime/asn1.js
generated
vendored
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
import crypto, { isCryptoKey } from './webcrypto.js';
|
||||
import invalidKeyInput from '../lib/invalid_key_input.js';
|
||||
import { encodeBase64, decodeBase64 } from './base64url.js';
|
||||
import formatPEM from '../lib/format_pem.js';
|
||||
import { JOSENotSupported } from '../util/errors.js';
|
||||
import { types } from './is_key_like.js';
|
||||
const genericExport = async (keyType, keyFormat, key) => {
|
||||
if (!isCryptoKey(key)) {
|
||||
throw new TypeError(invalidKeyInput(key, ...types));
|
||||
}
|
||||
if (!key.extractable) {
|
||||
throw new TypeError('CryptoKey is not extractable');
|
||||
}
|
||||
if (key.type !== keyType) {
|
||||
throw new TypeError(`key is not a ${keyType} key`);
|
||||
}
|
||||
return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
|
||||
};
|
||||
export const toSPKI = (key) => {
|
||||
return genericExport('public', 'spki', key);
|
||||
};
|
||||
export const toPKCS8 = (key) => {
|
||||
return genericExport('private', 'pkcs8', key);
|
||||
};
|
||||
const findOid = (keyData, oid, from = 0) => {
|
||||
if (from === 0) {
|
||||
oid.unshift(oid.length);
|
||||
oid.unshift(0x06);
|
||||
}
|
||||
const i = keyData.indexOf(oid[0], from);
|
||||
if (i === -1)
|
||||
return false;
|
||||
const sub = keyData.subarray(i, i + oid.length);
|
||||
if (sub.length !== oid.length)
|
||||
return false;
|
||||
return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1);
|
||||
};
|
||||
const getNamedCurve = (keyData) => {
|
||||
switch (true) {
|
||||
case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]):
|
||||
return 'P-256';
|
||||
case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]):
|
||||
return 'P-384';
|
||||
case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]):
|
||||
return 'P-521';
|
||||
case findOid(keyData, [0x2b, 0x65, 0x6e]):
|
||||
return 'X25519';
|
||||
case findOid(keyData, [0x2b, 0x65, 0x6f]):
|
||||
return 'X448';
|
||||
case findOid(keyData, [0x2b, 0x65, 0x70]):
|
||||
return 'Ed25519';
|
||||
case findOid(keyData, [0x2b, 0x65, 0x71]):
|
||||
return 'Ed448';
|
||||
default:
|
||||
throw new JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type');
|
||||
}
|
||||
};
|
||||
const genericImport = async (replace, keyFormat, pem, alg, options) => {
|
||||
let algorithm;
|
||||
let keyUsages;
|
||||
const keyData = new Uint8Array(atob(pem.replace(replace, ''))
|
||||
.split('')
|
||||
.map((c) => c.charCodeAt(0)));
|
||||
const isPublic = keyFormat === 'spki';
|
||||
switch (alg) {
|
||||
case 'PS256':
|
||||
case 'PS384':
|
||||
case 'PS512':
|
||||
algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };
|
||||
keyUsages = isPublic ? ['verify'] : ['sign'];
|
||||
break;
|
||||
case 'RS256':
|
||||
case 'RS384':
|
||||
case 'RS512':
|
||||
algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };
|
||||
keyUsages = isPublic ? ['verify'] : ['sign'];
|
||||
break;
|
||||
case 'RSA-OAEP':
|
||||
case 'RSA-OAEP-256':
|
||||
case 'RSA-OAEP-384':
|
||||
case 'RSA-OAEP-512':
|
||||
algorithm = {
|
||||
name: 'RSA-OAEP',
|
||||
hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
|
||||
};
|
||||
keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'];
|
||||
break;
|
||||
case 'ES256':
|
||||
algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
|
||||
keyUsages = isPublic ? ['verify'] : ['sign'];
|
||||
break;
|
||||
case 'ES384':
|
||||
algorithm = { name: 'ECDSA', namedCurve: 'P-384' };
|
||||
keyUsages = isPublic ? ['verify'] : ['sign'];
|
||||
break;
|
||||
case 'ES512':
|
||||
algorithm = { name: 'ECDSA', namedCurve: 'P-521' };
|
||||
keyUsages = isPublic ? ['verify'] : ['sign'];
|
||||
break;
|
||||
case 'ECDH-ES':
|
||||
case 'ECDH-ES+A128KW':
|
||||
case 'ECDH-ES+A192KW':
|
||||
case 'ECDH-ES+A256KW': {
|
||||
const namedCurve = getNamedCurve(keyData);
|
||||
algorithm = namedCurve.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: namedCurve };
|
||||
keyUsages = isPublic ? [] : ['deriveBits'];
|
||||
break;
|
||||
}
|
||||
case 'EdDSA':
|
||||
algorithm = { name: getNamedCurve(keyData) };
|
||||
keyUsages = isPublic ? ['verify'] : ['sign'];
|
||||
break;
|
||||
default:
|
||||
throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
|
||||
}
|
||||
return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? false, keyUsages);
|
||||
};
|
||||
export const fromPKCS8 = (pem, alg, options) => {
|
||||
return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options);
|
||||
};
|
||||
export const fromSPKI = (pem, alg, options) => {
|
||||
return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, 'spki', pem, alg, options);
|
||||
};
|
||||
function getElement(seq) {
|
||||
const result = [];
|
||||
let next = 0;
|
||||
while (next < seq.length) {
|
||||
const nextPart = parseElement(seq.subarray(next));
|
||||
result.push(nextPart);
|
||||
next += nextPart.byteLength;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function parseElement(bytes) {
|
||||
let position = 0;
|
||||
let tag = bytes[0] & 0x1f;
|
||||
position++;
|
||||
if (tag === 0x1f) {
|
||||
tag = 0;
|
||||
while (bytes[position] >= 0x80) {
|
||||
tag = tag * 128 + bytes[position] - 0x80;
|
||||
position++;
|
||||
}
|
||||
tag = tag * 128 + bytes[position] - 0x80;
|
||||
position++;
|
||||
}
|
||||
let length = 0;
|
||||
if (bytes[position] < 0x80) {
|
||||
length = bytes[position];
|
||||
position++;
|
||||
}
|
||||
else if (length === 0x80) {
|
||||
length = 0;
|
||||
while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) {
|
||||
if (length > bytes.byteLength) {
|
||||
throw new TypeError('invalid indefinite form length');
|
||||
}
|
||||
length++;
|
||||
}
|
||||
const byteLength = position + length + 2;
|
||||
return {
|
||||
byteLength,
|
||||
contents: bytes.subarray(position, position + length),
|
||||
raw: bytes.subarray(0, byteLength),
|
||||
};
|
||||
}
|
||||
else {
|
||||
const numberOfDigits = bytes[position] & 0x7f;
|
||||
position++;
|
||||
length = 0;
|
||||
for (let i = 0; i < numberOfDigits; i++) {
|
||||
length = length * 256 + bytes[position];
|
||||
position++;
|
||||
}
|
||||
}
|
||||
const byteLength = position + length;
|
||||
return {
|
||||
byteLength,
|
||||
contents: bytes.subarray(position, byteLength),
|
||||
raw: bytes.subarray(0, byteLength),
|
||||
};
|
||||
}
|
||||
function spkiFromX509(buf) {
|
||||
const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents);
|
||||
return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw);
|
||||
}
|
||||
function getSPKI(x509) {
|
||||
const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '');
|
||||
const raw = decodeBase64(pem);
|
||||
return formatPEM(spkiFromX509(raw), 'PUBLIC KEY');
|
||||
}
|
||||
export const fromX509 = (pem, alg, options) => {
|
||||
let spki;
|
||||
try {
|
||||
spki = getSPKI(pem);
|
||||
}
|
||||
catch (cause) {
|
||||
throw new TypeError('Failed to parse the X.509 certificate', { cause });
|
||||
}
|
||||
return fromSPKI(spki, alg, options);
|
||||
};
|
||||
37
node_modules/jose/dist/browser/runtime/base64url.js
generated
vendored
Normal file
37
node_modules/jose/dist/browser/runtime/base64url.js
generated
vendored
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import { encoder, decoder } from '../lib/buffer_utils.js';
|
||||
export const encodeBase64 = (input) => {
|
||||
let unencoded = input;
|
||||
if (typeof unencoded === 'string') {
|
||||
unencoded = encoder.encode(unencoded);
|
||||
}
|
||||
const CHUNK_SIZE = 0x8000;
|
||||
const arr = [];
|
||||
for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {
|
||||
arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));
|
||||
}
|
||||
return btoa(arr.join(''));
|
||||
};
|
||||
export const encode = (input) => {
|
||||
return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
};
|
||||
export const decodeBase64 = (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;
|
||||
};
|
||||
export const decode = (input) => {
|
||||
let encoded = input;
|
||||
if (encoded instanceof Uint8Array) {
|
||||
encoded = decoder.decode(encoded);
|
||||
}
|
||||
encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
|
||||
try {
|
||||
return decodeBase64(encoded);
|
||||
}
|
||||
catch {
|
||||
throw new TypeError('The input to be decoded is not correctly encoded.');
|
||||
}
|
||||
};
|
||||
6
node_modules/jose/dist/browser/runtime/bogus.js
generated
vendored
Normal file
6
node_modules/jose/dist/browser/runtime/bogus.js
generated
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
const bogusWebCrypto = [
|
||||
{ hash: 'SHA-256', name: 'HMAC' },
|
||||
true,
|
||||
['sign'],
|
||||
];
|
||||
export default bogusWebCrypto;
|
||||
8
node_modules/jose/dist/browser/runtime/check_cek_length.js
generated
vendored
Normal file
8
node_modules/jose/dist/browser/runtime/check_cek_length.js
generated
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { JWEInvalid } from '../util/errors.js';
|
||||
const 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`);
|
||||
}
|
||||
};
|
||||
export default checkCekLength;
|
||||
8
node_modules/jose/dist/browser/runtime/check_key_length.js
generated
vendored
Normal file
8
node_modules/jose/dist/browser/runtime/check_key_length.js
generated
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
export default (alg, key) => {
|
||||
if (alg.startsWith('RS') || alg.startsWith('PS')) {
|
||||
const { modulusLength } = key.algorithm;
|
||||
if (typeof modulusLength !== 'number' || modulusLength < 2048) {
|
||||
throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
|
||||
}
|
||||
}
|
||||
};
|
||||
91
node_modules/jose/dist/browser/runtime/decrypt.js
generated
vendored
Normal file
91
node_modules/jose/dist/browser/runtime/decrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { concat, uint64be } from '../lib/buffer_utils.js';
|
||||
import checkIvLength from '../lib/check_iv_length.js';
|
||||
import checkCekLength from './check_cek_length.js';
|
||||
import timingSafeEqual from './timing_safe_equal.js';
|
||||
import { JOSENotSupported, JWEDecryptionFailed, JWEInvalid } from '../util/errors.js';
|
||||
import crypto, { isCryptoKey } from './webcrypto.js';
|
||||
import { checkEncCryptoKey } from '../lib/crypto_key.js';
|
||||
import invalidKeyInput from '../lib/invalid_key_input.js';
|
||||
import { types } from './is_key_like.js';
|
||||
async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
|
||||
if (!(cek instanceof Uint8Array)) {
|
||||
throw new TypeError(invalidKeyInput(cek, 'Uint8Array'));
|
||||
}
|
||||
const keySize = parseInt(enc.slice(1, 4), 10);
|
||||
const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['decrypt']);
|
||||
const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {
|
||||
hash: `SHA-${keySize << 1}`,
|
||||
name: 'HMAC',
|
||||
}, false, ['sign']);
|
||||
const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
|
||||
const expectedTag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));
|
||||
let macCheckPassed;
|
||||
try {
|
||||
macCheckPassed = timingSafeEqual(tag, expectedTag);
|
||||
}
|
||||
catch {
|
||||
}
|
||||
if (!macCheckPassed) {
|
||||
throw new JWEDecryptionFailed();
|
||||
}
|
||||
let plaintext;
|
||||
try {
|
||||
plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext));
|
||||
}
|
||||
catch {
|
||||
}
|
||||
if (!plaintext) {
|
||||
throw new JWEDecryptionFailed();
|
||||
}
|
||||
return plaintext;
|
||||
}
|
||||
async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {
|
||||
let encKey;
|
||||
if (cek instanceof Uint8Array) {
|
||||
encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']);
|
||||
}
|
||||
else {
|
||||
checkEncCryptoKey(cek, enc, 'decrypt');
|
||||
encKey = cek;
|
||||
}
|
||||
try {
|
||||
return new Uint8Array(await crypto.subtle.decrypt({
|
||||
additionalData: aad,
|
||||
iv,
|
||||
name: 'AES-GCM',
|
||||
tagLength: 128,
|
||||
}, encKey, concat(ciphertext, tag)));
|
||||
}
|
||||
catch {
|
||||
throw new JWEDecryptionFailed();
|
||||
}
|
||||
}
|
||||
const decrypt = async (enc, cek, ciphertext, iv, tag, aad) => {
|
||||
if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
|
||||
throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array'));
|
||||
}
|
||||
if (!iv) {
|
||||
throw new JWEInvalid('JWE Initialization Vector missing');
|
||||
}
|
||||
if (!tag) {
|
||||
throw new JWEInvalid('JWE Authentication Tag missing');
|
||||
}
|
||||
checkIvLength(enc, iv);
|
||||
switch (enc) {
|
||||
case 'A128CBC-HS256':
|
||||
case 'A192CBC-HS384':
|
||||
case 'A256CBC-HS512':
|
||||
if (cek instanceof Uint8Array)
|
||||
checkCekLength(cek, parseInt(enc.slice(-3), 10));
|
||||
return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad);
|
||||
case 'A128GCM':
|
||||
case 'A192GCM':
|
||||
case 'A256GCM':
|
||||
if (cek instanceof Uint8Array)
|
||||
checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
|
||||
return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad);
|
||||
default:
|
||||
throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
|
||||
}
|
||||
};
|
||||
export default decrypt;
|
||||
6
node_modules/jose/dist/browser/runtime/digest.js
generated
vendored
Normal file
6
node_modules/jose/dist/browser/runtime/digest.js
generated
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
import crypto from './webcrypto.js';
|
||||
const digest = async (algorithm, data) => {
|
||||
const subtleDigest = `SHA-${algorithm.slice(-3)}`;
|
||||
return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
|
||||
};
|
||||
export default digest;
|
||||
47
node_modules/jose/dist/browser/runtime/ecdhes.js
generated
vendored
Normal file
47
node_modules/jose/dist/browser/runtime/ecdhes.js
generated
vendored
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js';
|
||||
import crypto, { isCryptoKey } from './webcrypto.js';
|
||||
import { checkEncCryptoKey } from '../lib/crypto_key.js';
|
||||
import invalidKeyInput from '../lib/invalid_key_input.js';
|
||||
import { types } from './is_key_like.js';
|
||||
export async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
|
||||
if (!isCryptoKey(publicKey)) {
|
||||
throw new TypeError(invalidKeyInput(publicKey, ...types));
|
||||
}
|
||||
checkEncCryptoKey(publicKey, 'ECDH');
|
||||
if (!isCryptoKey(privateKey)) {
|
||||
throw new TypeError(invalidKeyInput(privateKey, ...types));
|
||||
}
|
||||
checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits');
|
||||
const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength));
|
||||
let length;
|
||||
if (publicKey.algorithm.name === 'X25519') {
|
||||
length = 256;
|
||||
}
|
||||
else if (publicKey.algorithm.name === 'X448') {
|
||||
length = 448;
|
||||
}
|
||||
else {
|
||||
length =
|
||||
Math.ceil(parseInt(publicKey.algorithm.namedCurve.substr(-3), 10) / 8) <<
|
||||
3;
|
||||
}
|
||||
const sharedSecret = new Uint8Array(await crypto.subtle.deriveBits({
|
||||
name: publicKey.algorithm.name,
|
||||
public: publicKey,
|
||||
}, privateKey, length));
|
||||
return concatKdf(sharedSecret, keyLength, value);
|
||||
}
|
||||
export async function generateEpk(key) {
|
||||
if (!isCryptoKey(key)) {
|
||||
throw new TypeError(invalidKeyInput(key, ...types));
|
||||
}
|
||||
return crypto.subtle.generateKey(key.algorithm, true, ['deriveBits']);
|
||||
}
|
||||
export function ecdhAllowed(key) {
|
||||
if (!isCryptoKey(key)) {
|
||||
throw new TypeError(invalidKeyInput(key, ...types));
|
||||
}
|
||||
return (['P-256', 'P-384', 'P-521'].includes(key.algorithm.namedCurve) ||
|
||||
key.algorithm.name === 'X25519' ||
|
||||
key.algorithm.name === 'X448');
|
||||
}
|
||||
76
node_modules/jose/dist/browser/runtime/encrypt.js
generated
vendored
Normal file
76
node_modules/jose/dist/browser/runtime/encrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { concat, uint64be } from '../lib/buffer_utils.js';
|
||||
import checkIvLength from '../lib/check_iv_length.js';
|
||||
import checkCekLength from './check_cek_length.js';
|
||||
import crypto, { isCryptoKey } from './webcrypto.js';
|
||||
import { checkEncCryptoKey } from '../lib/crypto_key.js';
|
||||
import invalidKeyInput from '../lib/invalid_key_input.js';
|
||||
import generateIv from '../lib/iv.js';
|
||||
import { JOSENotSupported } from '../util/errors.js';
|
||||
import { types } from './is_key_like.js';
|
||||
async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
|
||||
if (!(cek instanceof Uint8Array)) {
|
||||
throw new TypeError(invalidKeyInput(cek, 'Uint8Array'));
|
||||
}
|
||||
const keySize = parseInt(enc.slice(1, 4), 10);
|
||||
const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['encrypt']);
|
||||
const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {
|
||||
hash: `SHA-${keySize << 1}`,
|
||||
name: 'HMAC',
|
||||
}, false, ['sign']);
|
||||
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
|
||||
iv,
|
||||
name: 'AES-CBC',
|
||||
}, encKey, plaintext));
|
||||
const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
|
||||
const tag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));
|
||||
return { ciphertext, tag, iv };
|
||||
}
|
||||
async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
|
||||
let encKey;
|
||||
if (cek instanceof Uint8Array) {
|
||||
encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);
|
||||
}
|
||||
else {
|
||||
checkEncCryptoKey(cek, enc, 'encrypt');
|
||||
encKey = cek;
|
||||
}
|
||||
const encrypted = new Uint8Array(await crypto.subtle.encrypt({
|
||||
additionalData: aad,
|
||||
iv,
|
||||
name: 'AES-GCM',
|
||||
tagLength: 128,
|
||||
}, encKey, plaintext));
|
||||
const tag = encrypted.slice(-16);
|
||||
const ciphertext = encrypted.slice(0, -16);
|
||||
return { ciphertext, tag, iv };
|
||||
}
|
||||
const encrypt = async (enc, plaintext, cek, iv, aad) => {
|
||||
if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
|
||||
throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array'));
|
||||
}
|
||||
if (iv) {
|
||||
checkIvLength(enc, iv);
|
||||
}
|
||||
else {
|
||||
iv = generateIv(enc);
|
||||
}
|
||||
switch (enc) {
|
||||
case 'A128CBC-HS256':
|
||||
case 'A192CBC-HS384':
|
||||
case 'A256CBC-HS512':
|
||||
if (cek instanceof Uint8Array) {
|
||||
checkCekLength(cek, parseInt(enc.slice(-3), 10));
|
||||
}
|
||||
return cbcEncrypt(enc, plaintext, cek, iv, aad);
|
||||
case 'A128GCM':
|
||||
case 'A192GCM':
|
||||
case 'A256GCM':
|
||||
if (cek instanceof Uint8Array) {
|
||||
checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
|
||||
}
|
||||
return gcmEncrypt(enc, plaintext, cek, iv, aad);
|
||||
default:
|
||||
throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
|
||||
}
|
||||
};
|
||||
export default encrypt;
|
||||
34
node_modules/jose/dist/browser/runtime/fetch_jwks.js
generated
vendored
Normal file
34
node_modules/jose/dist/browser/runtime/fetch_jwks.js
generated
vendored
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { JOSEError, JWKSTimeout } from '../util/errors.js';
|
||||
const fetchJwks = async (url, timeout, options) => {
|
||||
let controller;
|
||||
let id;
|
||||
let timedOut = false;
|
||||
if (typeof AbortController === 'function') {
|
||||
controller = new AbortController();
|
||||
id = setTimeout(() => {
|
||||
timedOut = true;
|
||||
controller.abort();
|
||||
}, timeout);
|
||||
}
|
||||
const response = await fetch(url.href, {
|
||||
signal: controller ? controller.signal : undefined,
|
||||
redirect: 'manual',
|
||||
headers: options.headers,
|
||||
}).catch((err) => {
|
||||
if (timedOut)
|
||||
throw new JWKSTimeout();
|
||||
throw err;
|
||||
});
|
||||
if (id !== undefined)
|
||||
clearTimeout(id);
|
||||
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 default fetchJwks;
|
||||
139
node_modules/jose/dist/browser/runtime/generate.js
generated
vendored
Normal file
139
node_modules/jose/dist/browser/runtime/generate.js
generated
vendored
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
import crypto from './webcrypto.js';
|
||||
import { JOSENotSupported } from '../util/errors.js';
|
||||
import random from './random.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 random(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);
|
||||
}
|
||||
function getModulusLengthOption(options) {
|
||||
const modulusLength = options?.modulusLength ?? 2048;
|
||||
if (typeof modulusLength !== 'number' || modulusLength < 2048) {
|
||||
throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');
|
||||
}
|
||||
return modulusLength;
|
||||
}
|
||||
export async function generateKeyPair(alg, options) {
|
||||
let algorithm;
|
||||
let keyUsages;
|
||||
switch (alg) {
|
||||
case 'PS256':
|
||||
case 'PS384':
|
||||
case 'PS512':
|
||||
algorithm = {
|
||||
name: 'RSA-PSS',
|
||||
hash: `SHA-${alg.slice(-3)}`,
|
||||
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
||||
modulusLength: getModulusLengthOption(options),
|
||||
};
|
||||
keyUsages = ['sign', 'verify'];
|
||||
break;
|
||||
case 'RS256':
|
||||
case 'RS384':
|
||||
case 'RS512':
|
||||
algorithm = {
|
||||
name: 'RSASSA-PKCS1-v1_5',
|
||||
hash: `SHA-${alg.slice(-3)}`,
|
||||
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
||||
modulusLength: getModulusLengthOption(options),
|
||||
};
|
||||
keyUsages = ['sign', 'verify'];
|
||||
break;
|
||||
case 'RSA-OAEP':
|
||||
case 'RSA-OAEP-256':
|
||||
case 'RSA-OAEP-384':
|
||||
case 'RSA-OAEP-512':
|
||||
algorithm = {
|
||||
name: 'RSA-OAEP',
|
||||
hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
|
||||
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
|
||||
modulusLength: getModulusLengthOption(options),
|
||||
};
|
||||
keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey'];
|
||||
break;
|
||||
case 'ES256':
|
||||
algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
|
||||
keyUsages = ['sign', 'verify'];
|
||||
break;
|
||||
case 'ES384':
|
||||
algorithm = { name: 'ECDSA', namedCurve: 'P-384' };
|
||||
keyUsages = ['sign', 'verify'];
|
||||
break;
|
||||
case 'ES512':
|
||||
algorithm = { name: 'ECDSA', namedCurve: 'P-521' };
|
||||
keyUsages = ['sign', 'verify'];
|
||||
break;
|
||||
case 'EdDSA': {
|
||||
keyUsages = ['sign', 'verify'];
|
||||
const crv = options?.crv ?? 'Ed25519';
|
||||
switch (crv) {
|
||||
case 'Ed25519':
|
||||
case 'Ed448':
|
||||
algorithm = { name: crv };
|
||||
break;
|
||||
default:
|
||||
throw new JOSENotSupported('Invalid or unsupported crv option provided');
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'ECDH-ES':
|
||||
case 'ECDH-ES+A128KW':
|
||||
case 'ECDH-ES+A192KW':
|
||||
case 'ECDH-ES+A256KW': {
|
||||
keyUsages = ['deriveKey', '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':
|
||||
case 'X448':
|
||||
algorithm = { name: crv };
|
||||
break;
|
||||
default:
|
||||
throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448');
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
||||
}
|
||||
return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
|
||||
}
|
||||
24
node_modules/jose/dist/browser/runtime/get_sign_verify_key.js
generated
vendored
Normal file
24
node_modules/jose/dist/browser/runtime/get_sign_verify_key.js
generated
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import crypto, { isCryptoKey } from './webcrypto.js';
|
||||
import { checkSigCryptoKey } from '../lib/crypto_key.js';
|
||||
import invalidKeyInput from '../lib/invalid_key_input.js';
|
||||
import { types } from './is_key_like.js';
|
||||
import normalize from './normalize_key.js';
|
||||
export default async function getCryptoKey(alg, key, usage) {
|
||||
if (usage === 'sign') {
|
||||
key = await normalize.normalizePrivateKey(key, alg);
|
||||
}
|
||||
if (usage === 'verify') {
|
||||
key = await normalize.normalizePublicKey(key, alg);
|
||||
}
|
||||
if (isCryptoKey(key)) {
|
||||
checkSigCryptoKey(key, alg, usage);
|
||||
return key;
|
||||
}
|
||||
if (key instanceof Uint8Array) {
|
||||
if (!alg.startsWith('HS')) {
|
||||
throw new TypeError(invalidKeyInput(key, ...types));
|
||||
}
|
||||
return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);
|
||||
}
|
||||
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array', 'JSON Web Key'));
|
||||
}
|
||||
8
node_modules/jose/dist/browser/runtime/is_key_like.js
generated
vendored
Normal file
8
node_modules/jose/dist/browser/runtime/is_key_like.js
generated
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { isCryptoKey } from './webcrypto.js';
|
||||
export default (key) => {
|
||||
if (isCryptoKey(key)) {
|
||||
return true;
|
||||
}
|
||||
return key?.[Symbol.toStringTag] === 'KeyObject';
|
||||
};
|
||||
export const types = ['CryptoKey'];
|
||||
100
node_modules/jose/dist/browser/runtime/jwk_to_key.js
generated
vendored
Normal file
100
node_modules/jose/dist/browser/runtime/jwk_to_key.js
generated
vendored
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import crypto from './webcrypto.js';
|
||||
import { JOSENotSupported } from '../util/errors.js';
|
||||
function subtleMapping(jwk) {
|
||||
let algorithm;
|
||||
let keyUsages;
|
||||
switch (jwk.kty) {
|
||||
case 'RSA': {
|
||||
switch (jwk.alg) {
|
||||
case 'PS256':
|
||||
case 'PS384':
|
||||
case 'PS512':
|
||||
algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };
|
||||
keyUsages = jwk.d ? ['sign'] : ['verify'];
|
||||
break;
|
||||
case 'RS256':
|
||||
case 'RS384':
|
||||
case 'RS512':
|
||||
algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };
|
||||
keyUsages = jwk.d ? ['sign'] : ['verify'];
|
||||
break;
|
||||
case 'RSA-OAEP':
|
||||
case 'RSA-OAEP-256':
|
||||
case 'RSA-OAEP-384':
|
||||
case 'RSA-OAEP-512':
|
||||
algorithm = {
|
||||
name: 'RSA-OAEP',
|
||||
hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,
|
||||
};
|
||||
keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];
|
||||
break;
|
||||
default:
|
||||
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'EC': {
|
||||
switch (jwk.alg) {
|
||||
case 'ES256':
|
||||
algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
|
||||
keyUsages = jwk.d ? ['sign'] : ['verify'];
|
||||
break;
|
||||
case 'ES384':
|
||||
algorithm = { name: 'ECDSA', namedCurve: 'P-384' };
|
||||
keyUsages = jwk.d ? ['sign'] : ['verify'];
|
||||
break;
|
||||
case 'ES512':
|
||||
algorithm = { name: 'ECDSA', namedCurve: 'P-521' };
|
||||
keyUsages = jwk.d ? ['sign'] : ['verify'];
|
||||
break;
|
||||
case 'ECDH-ES':
|
||||
case 'ECDH-ES+A128KW':
|
||||
case 'ECDH-ES+A192KW':
|
||||
case 'ECDH-ES+A256KW':
|
||||
algorithm = { name: 'ECDH', namedCurve: jwk.crv };
|
||||
keyUsages = jwk.d ? ['deriveBits'] : [];
|
||||
break;
|
||||
default:
|
||||
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'OKP': {
|
||||
switch (jwk.alg) {
|
||||
case 'EdDSA':
|
||||
algorithm = { name: jwk.crv };
|
||||
keyUsages = jwk.d ? ['sign'] : ['verify'];
|
||||
break;
|
||||
case 'ECDH-ES':
|
||||
case 'ECDH-ES+A128KW':
|
||||
case 'ECDH-ES+A192KW':
|
||||
case 'ECDH-ES+A256KW':
|
||||
algorithm = { name: jwk.crv };
|
||||
keyUsages = jwk.d ? ['deriveBits'] : [];
|
||||
break;
|
||||
default:
|
||||
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
|
||||
}
|
||||
return { algorithm, keyUsages };
|
||||
}
|
||||
const parse = async (jwk) => {
|
||||
if (!jwk.alg) {
|
||||
throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
|
||||
}
|
||||
const { algorithm, keyUsages } = subtleMapping(jwk);
|
||||
const rest = [
|
||||
algorithm,
|
||||
jwk.ext ?? false,
|
||||
jwk.key_ops ?? keyUsages,
|
||||
];
|
||||
const keyData = { ...jwk };
|
||||
delete keyData.alg;
|
||||
delete keyData.use;
|
||||
return crypto.subtle.importKey('jwk', keyData, ...rest);
|
||||
};
|
||||
export default parse;
|
||||
21
node_modules/jose/dist/browser/runtime/key_to_jwk.js
generated
vendored
Normal file
21
node_modules/jose/dist/browser/runtime/key_to_jwk.js
generated
vendored
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import crypto, { isCryptoKey } from './webcrypto.js';
|
||||
import invalidKeyInput from '../lib/invalid_key_input.js';
|
||||
import { encode as base64url } from './base64url.js';
|
||||
import { types } from './is_key_like.js';
|
||||
const keyToJWK = async (key) => {
|
||||
if (key instanceof Uint8Array) {
|
||||
return {
|
||||
kty: 'oct',
|
||||
k: base64url(key),
|
||||
};
|
||||
}
|
||||
if (!isCryptoKey(key)) {
|
||||
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
|
||||
}
|
||||
if (!key.extractable) {
|
||||
throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK');
|
||||
}
|
||||
const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key);
|
||||
return jwk;
|
||||
};
|
||||
export default keyToJWK;
|
||||
68
node_modules/jose/dist/browser/runtime/normalize_key.js
generated
vendored
Normal file
68
node_modules/jose/dist/browser/runtime/normalize_key.js
generated
vendored
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { isJWK } from '../lib/is_jwk.js';
|
||||
import { decode } from './base64url.js';
|
||||
import importJWK from './jwk_to_key.js';
|
||||
const exportKeyValue = (k) => decode(k);
|
||||
let privCache;
|
||||
let pubCache;
|
||||
const isKeyObject = (key) => {
|
||||
return key?.[Symbol.toStringTag] === 'KeyObject';
|
||||
};
|
||||
const importAndCache = async (cache, key, jwk, alg, freeze = false) => {
|
||||
let cached = cache.get(key);
|
||||
if (cached?.[alg]) {
|
||||
return cached[alg];
|
||||
}
|
||||
const cryptoKey = await importJWK({ ...jwk, alg });
|
||||
if (freeze)
|
||||
Object.freeze(key);
|
||||
if (!cached) {
|
||||
cache.set(key, { [alg]: cryptoKey });
|
||||
}
|
||||
else {
|
||||
cached[alg] = cryptoKey;
|
||||
}
|
||||
return cryptoKey;
|
||||
};
|
||||
const normalizePublicKey = (key, alg) => {
|
||||
if (isKeyObject(key)) {
|
||||
let jwk = key.export({ format: 'jwk' });
|
||||
delete jwk.d;
|
||||
delete jwk.dp;
|
||||
delete jwk.dq;
|
||||
delete jwk.p;
|
||||
delete jwk.q;
|
||||
delete jwk.qi;
|
||||
if (jwk.k) {
|
||||
return exportKeyValue(jwk.k);
|
||||
}
|
||||
pubCache || (pubCache = new WeakMap());
|
||||
return importAndCache(pubCache, key, jwk, alg);
|
||||
}
|
||||
if (isJWK(key)) {
|
||||
if (key.k)
|
||||
return decode(key.k);
|
||||
pubCache || (pubCache = new WeakMap());
|
||||
const cryptoKey = importAndCache(pubCache, key, key, alg, true);
|
||||
return cryptoKey;
|
||||
}
|
||||
return key;
|
||||
};
|
||||
const normalizePrivateKey = (key, alg) => {
|
||||
if (isKeyObject(key)) {
|
||||
let jwk = key.export({ format: 'jwk' });
|
||||
if (jwk.k) {
|
||||
return exportKeyValue(jwk.k);
|
||||
}
|
||||
privCache || (privCache = new WeakMap());
|
||||
return importAndCache(privCache, key, jwk, alg);
|
||||
}
|
||||
if (isJWK(key)) {
|
||||
if (key.k)
|
||||
return decode(key.k);
|
||||
privCache || (privCache = new WeakMap());
|
||||
const cryptoKey = importAndCache(privCache, key, key, alg, true);
|
||||
return cryptoKey;
|
||||
}
|
||||
return key;
|
||||
};
|
||||
export default { normalizePublicKey, normalizePrivateKey };
|
||||
51
node_modules/jose/dist/browser/runtime/pbes2kw.js
generated
vendored
Normal file
51
node_modules/jose/dist/browser/runtime/pbes2kw.js
generated
vendored
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import random from './random.js';
|
||||
import { p2s as concatSalt } from '../lib/buffer_utils.js';
|
||||
import { encode as base64url } from './base64url.js';
|
||||
import { wrap, unwrap } from './aeskw.js';
|
||||
import checkP2s from '../lib/check_p2s.js';
|
||||
import crypto, { isCryptoKey } from './webcrypto.js';
|
||||
import { checkEncCryptoKey } from '../lib/crypto_key.js';
|
||||
import invalidKeyInput from '../lib/invalid_key_input.js';
|
||||
import { types } from './is_key_like.js';
|
||||
function getCryptoKey(key, alg) {
|
||||
if (key instanceof Uint8Array) {
|
||||
return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']);
|
||||
}
|
||||
if (isCryptoKey(key)) {
|
||||
checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey');
|
||||
return key;
|
||||
}
|
||||
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
|
||||
}
|
||||
async function deriveKey(p2s, alg, p2c, key) {
|
||||
checkP2s(p2s);
|
||||
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 wrapAlg = {
|
||||
length: keylen,
|
||||
name: 'AES-KW',
|
||||
};
|
||||
const cryptoKey = await getCryptoKey(key, alg);
|
||||
if (cryptoKey.usages.includes('deriveBits')) {
|
||||
return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
|
||||
}
|
||||
if (cryptoKey.usages.includes('deriveKey')) {
|
||||
return crypto.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ['wrapKey', 'unwrapKey']);
|
||||
}
|
||||
throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"');
|
||||
}
|
||||
export const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => {
|
||||
const derived = await deriveKey(p2s, alg, p2c, key);
|
||||
const encryptedKey = await wrap(alg.slice(-6), derived, cek);
|
||||
return { encryptedKey, p2c, p2s: base64url(p2s) };
|
||||
};
|
||||
export const decrypt = async (alg, key, encryptedKey, p2c, p2s) => {
|
||||
const derived = await deriveKey(p2s, alg, p2c, key);
|
||||
return unwrap(alg.slice(-6), derived, encryptedKey);
|
||||
};
|
||||
2
node_modules/jose/dist/browser/runtime/random.js
generated
vendored
Normal file
2
node_modules/jose/dist/browser/runtime/random.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import crypto from './webcrypto.js';
|
||||
export default crypto.getRandomValues.bind(crypto);
|
||||
37
node_modules/jose/dist/browser/runtime/rsaes.js
generated
vendored
Normal file
37
node_modules/jose/dist/browser/runtime/rsaes.js
generated
vendored
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import subtleAlgorithm from './subtle_rsaes.js';
|
||||
import bogusWebCrypto from './bogus.js';
|
||||
import crypto, { isCryptoKey } from './webcrypto.js';
|
||||
import { checkEncCryptoKey } from '../lib/crypto_key.js';
|
||||
import checkKeyLength from './check_key_length.js';
|
||||
import invalidKeyInput from '../lib/invalid_key_input.js';
|
||||
import { types } from './is_key_like.js';
|
||||
export const encrypt = async (alg, key, cek) => {
|
||||
if (!isCryptoKey(key)) {
|
||||
throw new TypeError(invalidKeyInput(key, ...types));
|
||||
}
|
||||
checkEncCryptoKey(key, alg, 'encrypt', 'wrapKey');
|
||||
checkKeyLength(alg, key);
|
||||
if (key.usages.includes('encrypt')) {
|
||||
return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));
|
||||
}
|
||||
if (key.usages.includes('wrapKey')) {
|
||||
const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto);
|
||||
return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, key, subtleAlgorithm(alg)));
|
||||
}
|
||||
throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation');
|
||||
};
|
||||
export const decrypt = async (alg, key, encryptedKey) => {
|
||||
if (!isCryptoKey(key)) {
|
||||
throw new TypeError(invalidKeyInput(key, ...types));
|
||||
}
|
||||
checkEncCryptoKey(key, alg, 'decrypt', 'unwrapKey');
|
||||
checkKeyLength(alg, key);
|
||||
if (key.usages.includes('decrypt')) {
|
||||
return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));
|
||||
}
|
||||
if (key.usages.includes('unwrapKey')) {
|
||||
const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, key, subtleAlgorithm(alg), ...bogusWebCrypto);
|
||||
return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));
|
||||
}
|
||||
throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation');
|
||||
};
|
||||
1
node_modules/jose/dist/browser/runtime/runtime.js
generated
vendored
Normal file
1
node_modules/jose/dist/browser/runtime/runtime.js
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
export default 'WebCryptoAPI';
|
||||
11
node_modules/jose/dist/browser/runtime/sign.js
generated
vendored
Normal file
11
node_modules/jose/dist/browser/runtime/sign.js
generated
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import subtleAlgorithm from './subtle_dsa.js';
|
||||
import crypto from './webcrypto.js';
|
||||
import checkKeyLength from './check_key_length.js';
|
||||
import getSignKey from './get_sign_verify_key.js';
|
||||
const sign = async (alg, key, data) => {
|
||||
const cryptoKey = await getSignKey(alg, key, 'sign');
|
||||
checkKeyLength(alg, cryptoKey);
|
||||
const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
|
||||
return new Uint8Array(signature);
|
||||
};
|
||||
export default sign;
|
||||
26
node_modules/jose/dist/browser/runtime/subtle_dsa.js
generated
vendored
Normal file
26
node_modules/jose/dist/browser/runtime/subtle_dsa.js
generated
vendored
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { JOSENotSupported } from '../util/errors.js';
|
||||
export default function subtleDsa(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: alg.slice(-3) >> 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 'EdDSA':
|
||||
return { name: algorithm.name };
|
||||
default:
|
||||
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
|
||||
}
|
||||
}
|
||||
12
node_modules/jose/dist/browser/runtime/subtle_rsaes.js
generated
vendored
Normal file
12
node_modules/jose/dist/browser/runtime/subtle_rsaes.js
generated
vendored
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { JOSENotSupported } from '../util/errors.js';
|
||||
export default function subtleRsaEs(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`);
|
||||
}
|
||||
}
|
||||
19
node_modules/jose/dist/browser/runtime/timing_safe_equal.js
generated
vendored
Normal file
19
node_modules/jose/dist/browser/runtime/timing_safe_equal.js
generated
vendored
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
const timingSafeEqual = (a, b) => {
|
||||
if (!(a instanceof Uint8Array)) {
|
||||
throw new TypeError('First argument must be a buffer');
|
||||
}
|
||||
if (!(b instanceof Uint8Array)) {
|
||||
throw new TypeError('Second argument must be a buffer');
|
||||
}
|
||||
if (a.length !== b.length) {
|
||||
throw new TypeError('Input buffers must have the same length');
|
||||
}
|
||||
const len = a.length;
|
||||
let out = 0;
|
||||
let i = -1;
|
||||
while (++i < len) {
|
||||
out |= a[i] ^ b[i];
|
||||
}
|
||||
return out === 0;
|
||||
};
|
||||
export default timingSafeEqual;
|
||||
16
node_modules/jose/dist/browser/runtime/verify.js
generated
vendored
Normal file
16
node_modules/jose/dist/browser/runtime/verify.js
generated
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import subtleAlgorithm from './subtle_dsa.js';
|
||||
import crypto from './webcrypto.js';
|
||||
import checkKeyLength from './check_key_length.js';
|
||||
import getVerifyKey from './get_sign_verify_key.js';
|
||||
const verify = async (alg, key, signature, data) => {
|
||||
const cryptoKey = await getVerifyKey(alg, key, 'verify');
|
||||
checkKeyLength(alg, cryptoKey);
|
||||
const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
|
||||
try {
|
||||
return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
export default verify;
|
||||
2
node_modules/jose/dist/browser/runtime/webcrypto.js
generated
vendored
Normal file
2
node_modules/jose/dist/browser/runtime/webcrypto.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export default crypto;
|
||||
export const isCryptoKey = (key) => key instanceof CryptoKey;
|
||||
3
node_modules/jose/dist/browser/util/base64url.js
generated
vendored
Normal file
3
node_modules/jose/dist/browser/util/base64url.js
generated
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import * as base64url from '../runtime/base64url.js';
|
||||
export const encode = base64url.encode;
|
||||
export const decode = base64url.decode;
|
||||
32
node_modules/jose/dist/browser/util/decode_jwt.js
generated
vendored
Normal file
32
node_modules/jose/dist/browser/util/decode_jwt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { decode as base64url } from './base64url.js';
|
||||
import { decoder } from '../lib/buffer_utils.js';
|
||||
import isObject from '../lib/is_object.js';
|
||||
import { JWTInvalid } from './errors.js';
|
||||
export function decodeJwt(jwt) {
|
||||
if (typeof jwt !== 'string')
|
||||
throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string');
|
||||
const { 1: payload, length } = jwt.split('.');
|
||||
if (length === 5)
|
||||
throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded');
|
||||
if (length !== 3)
|
||||
throw new JWTInvalid('Invalid JWT');
|
||||
if (!payload)
|
||||
throw new JWTInvalid('JWTs must contain a payload');
|
||||
let decoded;
|
||||
try {
|
||||
decoded = base64url(payload);
|
||||
}
|
||||
catch {
|
||||
throw new JWTInvalid('Failed to base64url decode the payload');
|
||||
}
|
||||
let result;
|
||||
try {
|
||||
result = JSON.parse(decoder.decode(decoded));
|
||||
}
|
||||
catch {
|
||||
throw new JWTInvalid('Failed to parse the decoded payload as JSON');
|
||||
}
|
||||
if (!isObject(result))
|
||||
throw new JWTInvalid('Invalid JWT Claims Set');
|
||||
return result;
|
||||
}
|
||||
34
node_modules/jose/dist/browser/util/decode_protected_header.js
generated
vendored
Normal file
34
node_modules/jose/dist/browser/util/decode_protected_header.js
generated
vendored
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { decode as base64url } from './base64url.js';
|
||||
import { decoder } from '../lib/buffer_utils.js';
|
||||
import isObject from '../lib/is_object.js';
|
||||
export function decodeProtectedHeader(token) {
|
||||
let protectedB64u;
|
||||
if (typeof token === 'string') {
|
||||
const parts = token.split('.');
|
||||
if (parts.length === 3 || parts.length === 5) {
|
||||
;
|
||||
[protectedB64u] = parts;
|
||||
}
|
||||
}
|
||||
else if (typeof token === 'object' && token) {
|
||||
if ('protected' in token) {
|
||||
protectedB64u = token.protected;
|
||||
}
|
||||
else {
|
||||
throw new TypeError('Token does not contain a Protected Header');
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (typeof protectedB64u !== 'string' || !protectedB64u) {
|
||||
throw new Error();
|
||||
}
|
||||
const result = JSON.parse(decoder.decode(base64url(protectedB64u)));
|
||||
if (!isObject(result)) {
|
||||
throw new Error();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
catch {
|
||||
throw new TypeError('Invalid Token or Protected Header formatting');
|
||||
}
|
||||
}
|
||||
114
node_modules/jose/dist/browser/util/errors.js
generated
vendored
Normal file
114
node_modules/jose/dist/browser/util/errors.js
generated
vendored
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
export class JOSEError extends Error {
|
||||
constructor(message, options) {
|
||||
super(message, options);
|
||||
this.code = 'ERR_JOSE_GENERIC';
|
||||
this.name = this.constructor.name;
|
||||
Error.captureStackTrace?.(this, this.constructor);
|
||||
}
|
||||
}
|
||||
JOSEError.code = 'ERR_JOSE_GENERIC';
|
||||
export class JWTClaimValidationFailed extends JOSEError {
|
||||
constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {
|
||||
super(message, { cause: { claim, reason, payload } });
|
||||
this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
|
||||
this.claim = claim;
|
||||
this.reason = reason;
|
||||
this.payload = payload;
|
||||
}
|
||||
}
|
||||
JWTClaimValidationFailed.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
|
||||
export class JWTExpired extends JOSEError {
|
||||
constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {
|
||||
super(message, { cause: { claim, reason, payload } });
|
||||
this.code = 'ERR_JWT_EXPIRED';
|
||||
this.claim = claim;
|
||||
this.reason = reason;
|
||||
this.payload = payload;
|
||||
}
|
||||
}
|
||||
JWTExpired.code = 'ERR_JWT_EXPIRED';
|
||||
export class JOSEAlgNotAllowed extends JOSEError {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.code = 'ERR_JOSE_ALG_NOT_ALLOWED';
|
||||
}
|
||||
}
|
||||
JOSEAlgNotAllowed.code = 'ERR_JOSE_ALG_NOT_ALLOWED';
|
||||
export class JOSENotSupported extends JOSEError {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.code = 'ERR_JOSE_NOT_SUPPORTED';
|
||||
}
|
||||
}
|
||||
JOSENotSupported.code = 'ERR_JOSE_NOT_SUPPORTED';
|
||||
export class JWEDecryptionFailed extends JOSEError {
|
||||
constructor(message = 'decryption operation failed', options) {
|
||||
super(message, options);
|
||||
this.code = 'ERR_JWE_DECRYPTION_FAILED';
|
||||
}
|
||||
}
|
||||
JWEDecryptionFailed.code = 'ERR_JWE_DECRYPTION_FAILED';
|
||||
export class JWEInvalid extends JOSEError {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.code = 'ERR_JWE_INVALID';
|
||||
}
|
||||
}
|
||||
JWEInvalid.code = 'ERR_JWE_INVALID';
|
||||
export class JWSInvalid extends JOSEError {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.code = 'ERR_JWS_INVALID';
|
||||
}
|
||||
}
|
||||
JWSInvalid.code = 'ERR_JWS_INVALID';
|
||||
export class JWTInvalid extends JOSEError {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.code = 'ERR_JWT_INVALID';
|
||||
}
|
||||
}
|
||||
JWTInvalid.code = 'ERR_JWT_INVALID';
|
||||
export class JWKInvalid extends JOSEError {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.code = 'ERR_JWK_INVALID';
|
||||
}
|
||||
}
|
||||
JWKInvalid.code = 'ERR_JWK_INVALID';
|
||||
export class JWKSInvalid extends JOSEError {
|
||||
constructor() {
|
||||
super(...arguments);
|
||||
this.code = 'ERR_JWKS_INVALID';
|
||||
}
|
||||
}
|
||||
JWKSInvalid.code = 'ERR_JWKS_INVALID';
|
||||
export class JWKSNoMatchingKey extends JOSEError {
|
||||
constructor(message = 'no applicable key found in the JSON Web Key Set', options) {
|
||||
super(message, options);
|
||||
this.code = 'ERR_JWKS_NO_MATCHING_KEY';
|
||||
}
|
||||
}
|
||||
JWKSNoMatchingKey.code = 'ERR_JWKS_NO_MATCHING_KEY';
|
||||
export class JWKSMultipleMatchingKeys extends JOSEError {
|
||||
constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {
|
||||
super(message, options);
|
||||
this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
|
||||
}
|
||||
}
|
||||
Symbol.asyncIterator;
|
||||
JWKSMultipleMatchingKeys.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
|
||||
export class JWKSTimeout extends JOSEError {
|
||||
constructor(message = 'request timed out', options) {
|
||||
super(message, options);
|
||||
this.code = 'ERR_JWKS_TIMEOUT';
|
||||
}
|
||||
}
|
||||
JWKSTimeout.code = 'ERR_JWKS_TIMEOUT';
|
||||
export class JWSSignatureVerificationFailed extends JOSEError {
|
||||
constructor(message = 'signature verification failed', options) {
|
||||
super(message, options);
|
||||
this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
|
||||
}
|
||||
}
|
||||
JWSSignatureVerificationFailed.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
|
||||
2
node_modules/jose/dist/browser/util/runtime.js
generated
vendored
Normal file
2
node_modules/jose/dist/browser/util/runtime.js
generated
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import value from '../runtime/runtime.js';
|
||||
export default value;
|
||||
69
node_modules/jose/dist/node/cjs/index.js
generated
vendored
Normal file
69
node_modules/jose/dist/node/cjs/index.js
generated
vendored
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.cryptoRuntime = exports.base64url = exports.generateSecret = exports.generateKeyPair = exports.errors = exports.decodeJwt = exports.decodeProtectedHeader = exports.importJWK = exports.importX509 = exports.importPKCS8 = exports.importSPKI = exports.exportJWK = exports.exportSPKI = exports.exportPKCS8 = exports.UnsecuredJWT = exports.experimental_jwksCache = exports.jwksCache = exports.createRemoteJWKSet = exports.createLocalJWKSet = exports.EmbeddedJWK = exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = exports.EncryptJWT = exports.SignJWT = exports.GeneralSign = exports.FlattenedSign = exports.CompactSign = exports.FlattenedEncrypt = exports.CompactEncrypt = exports.jwtDecrypt = exports.jwtVerify = exports.generalVerify = exports.flattenedVerify = exports.compactVerify = exports.GeneralEncrypt = exports.generalDecrypt = exports.flattenedDecrypt = exports.compactDecrypt = void 0;
|
||||
var decrypt_js_1 = require("./jwe/compact/decrypt.js");
|
||||
Object.defineProperty(exports, "compactDecrypt", { enumerable: true, get: function () { return decrypt_js_1.compactDecrypt; } });
|
||||
var decrypt_js_2 = require("./jwe/flattened/decrypt.js");
|
||||
Object.defineProperty(exports, "flattenedDecrypt", { enumerable: true, get: function () { return decrypt_js_2.flattenedDecrypt; } });
|
||||
var decrypt_js_3 = require("./jwe/general/decrypt.js");
|
||||
Object.defineProperty(exports, "generalDecrypt", { enumerable: true, get: function () { return decrypt_js_3.generalDecrypt; } });
|
||||
var encrypt_js_1 = require("./jwe/general/encrypt.js");
|
||||
Object.defineProperty(exports, "GeneralEncrypt", { enumerable: true, get: function () { return encrypt_js_1.GeneralEncrypt; } });
|
||||
var verify_js_1 = require("./jws/compact/verify.js");
|
||||
Object.defineProperty(exports, "compactVerify", { enumerable: true, get: function () { return verify_js_1.compactVerify; } });
|
||||
var verify_js_2 = require("./jws/flattened/verify.js");
|
||||
Object.defineProperty(exports, "flattenedVerify", { enumerable: true, get: function () { return verify_js_2.flattenedVerify; } });
|
||||
var verify_js_3 = require("./jws/general/verify.js");
|
||||
Object.defineProperty(exports, "generalVerify", { enumerable: true, get: function () { return verify_js_3.generalVerify; } });
|
||||
var verify_js_4 = require("./jwt/verify.js");
|
||||
Object.defineProperty(exports, "jwtVerify", { enumerable: true, get: function () { return verify_js_4.jwtVerify; } });
|
||||
var decrypt_js_4 = require("./jwt/decrypt.js");
|
||||
Object.defineProperty(exports, "jwtDecrypt", { enumerable: true, get: function () { return decrypt_js_4.jwtDecrypt; } });
|
||||
var encrypt_js_2 = require("./jwe/compact/encrypt.js");
|
||||
Object.defineProperty(exports, "CompactEncrypt", { enumerable: true, get: function () { return encrypt_js_2.CompactEncrypt; } });
|
||||
var encrypt_js_3 = require("./jwe/flattened/encrypt.js");
|
||||
Object.defineProperty(exports, "FlattenedEncrypt", { enumerable: true, get: function () { return encrypt_js_3.FlattenedEncrypt; } });
|
||||
var sign_js_1 = require("./jws/compact/sign.js");
|
||||
Object.defineProperty(exports, "CompactSign", { enumerable: true, get: function () { return sign_js_1.CompactSign; } });
|
||||
var sign_js_2 = require("./jws/flattened/sign.js");
|
||||
Object.defineProperty(exports, "FlattenedSign", { enumerable: true, get: function () { return sign_js_2.FlattenedSign; } });
|
||||
var sign_js_3 = require("./jws/general/sign.js");
|
||||
Object.defineProperty(exports, "GeneralSign", { enumerable: true, get: function () { return sign_js_3.GeneralSign; } });
|
||||
var sign_js_4 = require("./jwt/sign.js");
|
||||
Object.defineProperty(exports, "SignJWT", { enumerable: true, get: function () { return sign_js_4.SignJWT; } });
|
||||
var encrypt_js_4 = require("./jwt/encrypt.js");
|
||||
Object.defineProperty(exports, "EncryptJWT", { enumerable: true, get: function () { return encrypt_js_4.EncryptJWT; } });
|
||||
var thumbprint_js_1 = require("./jwk/thumbprint.js");
|
||||
Object.defineProperty(exports, "calculateJwkThumbprint", { enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprint; } });
|
||||
Object.defineProperty(exports, "calculateJwkThumbprintUri", { enumerable: true, get: function () { return thumbprint_js_1.calculateJwkThumbprintUri; } });
|
||||
var embedded_js_1 = require("./jwk/embedded.js");
|
||||
Object.defineProperty(exports, "EmbeddedJWK", { enumerable: true, get: function () { return embedded_js_1.EmbeddedJWK; } });
|
||||
var local_js_1 = require("./jwks/local.js");
|
||||
Object.defineProperty(exports, "createLocalJWKSet", { enumerable: true, get: function () { return local_js_1.createLocalJWKSet; } });
|
||||
var remote_js_1 = require("./jwks/remote.js");
|
||||
Object.defineProperty(exports, "createRemoteJWKSet", { enumerable: true, get: function () { return remote_js_1.createRemoteJWKSet; } });
|
||||
Object.defineProperty(exports, "jwksCache", { enumerable: true, get: function () { return remote_js_1.jwksCache; } });
|
||||
Object.defineProperty(exports, "experimental_jwksCache", { enumerable: true, get: function () { return remote_js_1.experimental_jwksCache; } });
|
||||
var unsecured_js_1 = require("./jwt/unsecured.js");
|
||||
Object.defineProperty(exports, "UnsecuredJWT", { enumerable: true, get: function () { return unsecured_js_1.UnsecuredJWT; } });
|
||||
var export_js_1 = require("./key/export.js");
|
||||
Object.defineProperty(exports, "exportPKCS8", { enumerable: true, get: function () { return export_js_1.exportPKCS8; } });
|
||||
Object.defineProperty(exports, "exportSPKI", { enumerable: true, get: function () { return export_js_1.exportSPKI; } });
|
||||
Object.defineProperty(exports, "exportJWK", { enumerable: true, get: function () { return export_js_1.exportJWK; } });
|
||||
var import_js_1 = require("./key/import.js");
|
||||
Object.defineProperty(exports, "importSPKI", { enumerable: true, get: function () { return import_js_1.importSPKI; } });
|
||||
Object.defineProperty(exports, "importPKCS8", { enumerable: true, get: function () { return import_js_1.importPKCS8; } });
|
||||
Object.defineProperty(exports, "importX509", { enumerable: true, get: function () { return import_js_1.importX509; } });
|
||||
Object.defineProperty(exports, "importJWK", { enumerable: true, get: function () { return import_js_1.importJWK; } });
|
||||
var decode_protected_header_js_1 = require("./util/decode_protected_header.js");
|
||||
Object.defineProperty(exports, "decodeProtectedHeader", { enumerable: true, get: function () { return decode_protected_header_js_1.decodeProtectedHeader; } });
|
||||
var decode_jwt_js_1 = require("./util/decode_jwt.js");
|
||||
Object.defineProperty(exports, "decodeJwt", { enumerable: true, get: function () { return decode_jwt_js_1.decodeJwt; } });
|
||||
exports.errors = require("./util/errors.js");
|
||||
var generate_key_pair_js_1 = require("./key/generate_key_pair.js");
|
||||
Object.defineProperty(exports, "generateKeyPair", { enumerable: true, get: function () { return generate_key_pair_js_1.generateKeyPair; } });
|
||||
var generate_secret_js_1 = require("./key/generate_secret.js");
|
||||
Object.defineProperty(exports, "generateSecret", { enumerable: true, get: function () { return generate_secret_js_1.generateSecret; } });
|
||||
exports.base64url = require("./util/base64url.js");
|
||||
var runtime_js_1 = require("./util/runtime.js");
|
||||
Object.defineProperty(exports, "cryptoRuntime", { enumerable: true, get: function () { return runtime_js_1.default; } });
|
||||
30
node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js
generated
vendored
Normal file
30
node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.compactDecrypt = compactDecrypt;
|
||||
const decrypt_js_1 = require("../flattened/decrypt.js");
|
||||
const errors_js_1 = require("../../util/errors.js");
|
||||
const buffer_utils_js_1 = require("../../lib/buffer_utils.js");
|
||||
async function compactDecrypt(jwe, key, options) {
|
||||
if (jwe instanceof Uint8Array) {
|
||||
jwe = buffer_utils_js_1.decoder.decode(jwe);
|
||||
}
|
||||
if (typeof jwe !== 'string') {
|
||||
throw new errors_js_1.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 errors_js_1.JWEInvalid('Invalid Compact JWE');
|
||||
}
|
||||
const decrypted = await (0, decrypt_js_1.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;
|
||||
}
|
||||
31
node_modules/jose/dist/node/cjs/jwe/compact/encrypt.js
generated
vendored
Normal file
31
node_modules/jose/dist/node/cjs/jwe/compact/encrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.CompactEncrypt = void 0;
|
||||
const encrypt_js_1 = require("../flattened/encrypt.js");
|
||||
class CompactEncrypt {
|
||||
_flattened;
|
||||
constructor(plaintext) {
|
||||
this._flattened = new encrypt_js_1.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('.');
|
||||
}
|
||||
}
|
||||
exports.CompactEncrypt = CompactEncrypt;
|
||||
164
node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js
generated
vendored
Normal file
164
node_modules/jose/dist/node/cjs/jwe/flattened/decrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.flattenedDecrypt = flattenedDecrypt;
|
||||
const base64url_js_1 = require("../../runtime/base64url.js");
|
||||
const decrypt_js_1 = require("../../runtime/decrypt.js");
|
||||
const errors_js_1 = require("../../util/errors.js");
|
||||
const is_disjoint_js_1 = require("../../lib/is_disjoint.js");
|
||||
const is_object_js_1 = require("../../lib/is_object.js");
|
||||
const decrypt_key_management_js_1 = require("../../lib/decrypt_key_management.js");
|
||||
const buffer_utils_js_1 = require("../../lib/buffer_utils.js");
|
||||
const cek_js_1 = require("../../lib/cek.js");
|
||||
const validate_crit_js_1 = require("../../lib/validate_crit.js");
|
||||
const validate_algorithms_js_1 = require("../../lib/validate_algorithms.js");
|
||||
async function flattenedDecrypt(jwe, key, options) {
|
||||
if (!(0, is_object_js_1.default)(jwe)) {
|
||||
throw new errors_js_1.JWEInvalid('Flattened JWE must be an object');
|
||||
}
|
||||
if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {
|
||||
throw new errors_js_1.JWEInvalid('JOSE Header missing');
|
||||
}
|
||||
if (jwe.iv !== undefined && typeof jwe.iv !== 'string') {
|
||||
throw new errors_js_1.JWEInvalid('JWE Initialization Vector incorrect type');
|
||||
}
|
||||
if (typeof jwe.ciphertext !== 'string') {
|
||||
throw new errors_js_1.JWEInvalid('JWE Ciphertext missing or incorrect type');
|
||||
}
|
||||
if (jwe.tag !== undefined && typeof jwe.tag !== 'string') {
|
||||
throw new errors_js_1.JWEInvalid('JWE Authentication Tag incorrect type');
|
||||
}
|
||||
if (jwe.protected !== undefined && typeof jwe.protected !== 'string') {
|
||||
throw new errors_js_1.JWEInvalid('JWE Protected Header incorrect type');
|
||||
}
|
||||
if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') {
|
||||
throw new errors_js_1.JWEInvalid('JWE Encrypted Key incorrect type');
|
||||
}
|
||||
if (jwe.aad !== undefined && typeof jwe.aad !== 'string') {
|
||||
throw new errors_js_1.JWEInvalid('JWE AAD incorrect type');
|
||||
}
|
||||
if (jwe.header !== undefined && !(0, is_object_js_1.default)(jwe.header)) {
|
||||
throw new errors_js_1.JWEInvalid('JWE Shared Unprotected Header incorrect type');
|
||||
}
|
||||
if (jwe.unprotected !== undefined && !(0, is_object_js_1.default)(jwe.unprotected)) {
|
||||
throw new errors_js_1.JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type');
|
||||
}
|
||||
let parsedProt;
|
||||
if (jwe.protected) {
|
||||
try {
|
||||
const protectedHeader = (0, base64url_js_1.decode)(jwe.protected);
|
||||
parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader));
|
||||
}
|
||||
catch {
|
||||
throw new errors_js_1.JWEInvalid('JWE Protected Header is invalid');
|
||||
}
|
||||
}
|
||||
if (!(0, is_disjoint_js_1.default)(parsedProt, jwe.header, jwe.unprotected)) {
|
||||
throw new errors_js_1.JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint');
|
||||
}
|
||||
const joseHeader = {
|
||||
...parsedProt,
|
||||
...jwe.header,
|
||||
...jwe.unprotected,
|
||||
};
|
||||
(0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader);
|
||||
if (joseHeader.zip !== undefined) {
|
||||
throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
|
||||
}
|
||||
const { alg, enc } = joseHeader;
|
||||
if (typeof alg !== 'string' || !alg) {
|
||||
throw new errors_js_1.JWEInvalid('missing JWE Algorithm (alg) in JWE Header');
|
||||
}
|
||||
if (typeof enc !== 'string' || !enc) {
|
||||
throw new errors_js_1.JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header');
|
||||
}
|
||||
const keyManagementAlgorithms = options && (0, validate_algorithms_js_1.default)('keyManagementAlgorithms', options.keyManagementAlgorithms);
|
||||
const contentEncryptionAlgorithms = options &&
|
||||
(0, validate_algorithms_js_1.default)('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);
|
||||
if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||
|
||||
(!keyManagementAlgorithms && alg.startsWith('PBES2'))) {
|
||||
throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
|
||||
}
|
||||
if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
|
||||
throw new errors_js_1.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
|
||||
}
|
||||
let encryptedKey;
|
||||
if (jwe.encrypted_key !== undefined) {
|
||||
try {
|
||||
encryptedKey = (0, base64url_js_1.decode)(jwe.encrypted_key);
|
||||
}
|
||||
catch {
|
||||
throw new errors_js_1.JWEInvalid('Failed to base64url decode the encrypted_key');
|
||||
}
|
||||
}
|
||||
let resolvedKey = false;
|
||||
if (typeof key === 'function') {
|
||||
key = await key(parsedProt, jwe);
|
||||
resolvedKey = true;
|
||||
}
|
||||
let cek;
|
||||
try {
|
||||
cek = await (0, decrypt_key_management_js_1.default)(alg, key, encryptedKey, joseHeader, options);
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof TypeError || err instanceof errors_js_1.JWEInvalid || err instanceof errors_js_1.JOSENotSupported) {
|
||||
throw err;
|
||||
}
|
||||
cek = (0, cek_js_1.default)(enc);
|
||||
}
|
||||
let iv;
|
||||
let tag;
|
||||
if (jwe.iv !== undefined) {
|
||||
try {
|
||||
iv = (0, base64url_js_1.decode)(jwe.iv);
|
||||
}
|
||||
catch {
|
||||
throw new errors_js_1.JWEInvalid('Failed to base64url decode the iv');
|
||||
}
|
||||
}
|
||||
if (jwe.tag !== undefined) {
|
||||
try {
|
||||
tag = (0, base64url_js_1.decode)(jwe.tag);
|
||||
}
|
||||
catch {
|
||||
throw new errors_js_1.JWEInvalid('Failed to base64url decode the tag');
|
||||
}
|
||||
}
|
||||
const protectedHeader = buffer_utils_js_1.encoder.encode(jwe.protected ?? '');
|
||||
let additionalData;
|
||||
if (jwe.aad !== undefined) {
|
||||
additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(jwe.aad));
|
||||
}
|
||||
else {
|
||||
additionalData = protectedHeader;
|
||||
}
|
||||
let ciphertext;
|
||||
try {
|
||||
ciphertext = (0, base64url_js_1.decode)(jwe.ciphertext);
|
||||
}
|
||||
catch {
|
||||
throw new errors_js_1.JWEInvalid('Failed to base64url decode the ciphertext');
|
||||
}
|
||||
const plaintext = await (0, decrypt_js_1.default)(enc, cek, ciphertext, iv, tag, additionalData);
|
||||
const result = { plaintext };
|
||||
if (jwe.protected !== undefined) {
|
||||
result.protectedHeader = parsedProt;
|
||||
}
|
||||
if (jwe.aad !== undefined) {
|
||||
try {
|
||||
result.additionalAuthenticatedData = (0, base64url_js_1.decode)(jwe.aad);
|
||||
}
|
||||
catch {
|
||||
throw new errors_js_1.JWEInvalid('Failed to base64url decode the aad');
|
||||
}
|
||||
}
|
||||
if (jwe.unprotected !== undefined) {
|
||||
result.sharedUnprotectedHeader = jwe.unprotected;
|
||||
}
|
||||
if (jwe.header !== undefined) {
|
||||
result.unprotectedHeader = jwe.header;
|
||||
}
|
||||
if (resolvedKey) {
|
||||
return { ...result, key };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
165
node_modules/jose/dist/node/cjs/jwe/flattened/encrypt.js
generated
vendored
Normal file
165
node_modules/jose/dist/node/cjs/jwe/flattened/encrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.FlattenedEncrypt = void 0;
|
||||
const base64url_js_1 = require("../../runtime/base64url.js");
|
||||
const private_symbols_js_1 = require("../../lib/private_symbols.js");
|
||||
const encrypt_js_1 = require("../../runtime/encrypt.js");
|
||||
const encrypt_key_management_js_1 = require("../../lib/encrypt_key_management.js");
|
||||
const errors_js_1 = require("../../util/errors.js");
|
||||
const is_disjoint_js_1 = require("../../lib/is_disjoint.js");
|
||||
const buffer_utils_js_1 = require("../../lib/buffer_utils.js");
|
||||
const validate_crit_js_1 = require("../../lib/validate_crit.js");
|
||||
class FlattenedEncrypt {
|
||||
_plaintext;
|
||||
_protectedHeader;
|
||||
_sharedUnprotectedHeader;
|
||||
_unprotectedHeader;
|
||||
_aad;
|
||||
_cek;
|
||||
_iv;
|
||||
_keyManagementParameters;
|
||||
constructor(plaintext) {
|
||||
if (!(plaintext instanceof Uint8Array)) {
|
||||
throw new TypeError('plaintext must be an instance of Uint8Array');
|
||||
}
|
||||
this._plaintext = plaintext;
|
||||
}
|
||||
setKeyManagementParameters(parameters) {
|
||||
if (this._keyManagementParameters) {
|
||||
throw new TypeError('setKeyManagementParameters can only be called once');
|
||||
}
|
||||
this._keyManagementParameters = parameters;
|
||||
return this;
|
||||
}
|
||||
setProtectedHeader(protectedHeader) {
|
||||
if (this._protectedHeader) {
|
||||
throw new TypeError('setProtectedHeader can only be called once');
|
||||
}
|
||||
this._protectedHeader = protectedHeader;
|
||||
return this;
|
||||
}
|
||||
setSharedUnprotectedHeader(sharedUnprotectedHeader) {
|
||||
if (this._sharedUnprotectedHeader) {
|
||||
throw new TypeError('setSharedUnprotectedHeader can only be called once');
|
||||
}
|
||||
this._sharedUnprotectedHeader = sharedUnprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
setUnprotectedHeader(unprotectedHeader) {
|
||||
if (this._unprotectedHeader) {
|
||||
throw new TypeError('setUnprotectedHeader can only be called once');
|
||||
}
|
||||
this._unprotectedHeader = unprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
setAdditionalAuthenticatedData(aad) {
|
||||
this._aad = aad;
|
||||
return this;
|
||||
}
|
||||
setContentEncryptionKey(cek) {
|
||||
if (this._cek) {
|
||||
throw new TypeError('setContentEncryptionKey can only be called once');
|
||||
}
|
||||
this._cek = cek;
|
||||
return this;
|
||||
}
|
||||
setInitializationVector(iv) {
|
||||
if (this._iv) {
|
||||
throw new TypeError('setInitializationVector can only be called once');
|
||||
}
|
||||
this._iv = iv;
|
||||
return this;
|
||||
}
|
||||
async encrypt(key, options) {
|
||||
if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {
|
||||
throw new errors_js_1.JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');
|
||||
}
|
||||
if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) {
|
||||
throw new errors_js_1.JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
|
||||
}
|
||||
const joseHeader = {
|
||||
...this._protectedHeader,
|
||||
...this._unprotectedHeader,
|
||||
...this._sharedUnprotectedHeader,
|
||||
};
|
||||
(0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader);
|
||||
if (joseHeader.zip !== undefined) {
|
||||
throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
|
||||
}
|
||||
const { alg, enc } = joseHeader;
|
||||
if (typeof alg !== 'string' || !alg) {
|
||||
throw new errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
|
||||
}
|
||||
if (typeof enc !== 'string' || !enc) {
|
||||
throw new errors_js_1.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}`);
|
||||
}
|
||||
let cek;
|
||||
{
|
||||
let parameters;
|
||||
({ cek, encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(alg, enc, key, this._cek, this._keyManagementParameters));
|
||||
if (parameters) {
|
||||
if (options && private_symbols_js_1.unprotected in options) {
|
||||
if (!this._unprotectedHeader) {
|
||||
this.setUnprotectedHeader(parameters);
|
||||
}
|
||||
else {
|
||||
this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters };
|
||||
}
|
||||
}
|
||||
else if (!this._protectedHeader) {
|
||||
this.setProtectedHeader(parameters);
|
||||
}
|
||||
else {
|
||||
this._protectedHeader = { ...this._protectedHeader, ...parameters };
|
||||
}
|
||||
}
|
||||
}
|
||||
let additionalData;
|
||||
let protectedHeader;
|
||||
let aadMember;
|
||||
if (this._protectedHeader) {
|
||||
protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader)));
|
||||
}
|
||||
else {
|
||||
protectedHeader = buffer_utils_js_1.encoder.encode('');
|
||||
}
|
||||
if (this._aad) {
|
||||
aadMember = (0, base64url_js_1.encode)(this._aad);
|
||||
additionalData = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), buffer_utils_js_1.encoder.encode(aadMember));
|
||||
}
|
||||
else {
|
||||
additionalData = protectedHeader;
|
||||
}
|
||||
const { ciphertext, tag, iv } = await (0, encrypt_js_1.default)(enc, this._plaintext, cek, this._iv, additionalData);
|
||||
const jwe = {
|
||||
ciphertext: (0, base64url_js_1.encode)(ciphertext),
|
||||
};
|
||||
if (iv) {
|
||||
jwe.iv = (0, base64url_js_1.encode)(iv);
|
||||
}
|
||||
if (tag) {
|
||||
jwe.tag = (0, base64url_js_1.encode)(tag);
|
||||
}
|
||||
if (encryptedKey) {
|
||||
jwe.encrypted_key = (0, base64url_js_1.encode)(encryptedKey);
|
||||
}
|
||||
if (aadMember) {
|
||||
jwe.aad = aadMember;
|
||||
}
|
||||
if (this._protectedHeader) {
|
||||
jwe.protected = buffer_utils_js_1.decoder.decode(protectedHeader);
|
||||
}
|
||||
if (this._sharedUnprotectedHeader) {
|
||||
jwe.unprotected = this._sharedUnprotectedHeader;
|
||||
}
|
||||
if (this._unprotectedHeader) {
|
||||
jwe.header = this._unprotectedHeader;
|
||||
}
|
||||
return jwe;
|
||||
}
|
||||
}
|
||||
exports.FlattenedEncrypt = FlattenedEncrypt;
|
||||
34
node_modules/jose/dist/node/cjs/jwe/general/decrypt.js
generated
vendored
Normal file
34
node_modules/jose/dist/node/cjs/jwe/general/decrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.generalDecrypt = generalDecrypt;
|
||||
const decrypt_js_1 = require("../flattened/decrypt.js");
|
||||
const errors_js_1 = require("../../util/errors.js");
|
||||
const is_object_js_1 = require("../../lib/is_object.js");
|
||||
async function generalDecrypt(jwe, key, options) {
|
||||
if (!(0, is_object_js_1.default)(jwe)) {
|
||||
throw new errors_js_1.JWEInvalid('General JWE must be an object');
|
||||
}
|
||||
if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(is_object_js_1.default)) {
|
||||
throw new errors_js_1.JWEInvalid('JWE Recipients missing or incorrect type');
|
||||
}
|
||||
if (!jwe.recipients.length) {
|
||||
throw new errors_js_1.JWEInvalid('JWE Recipients has no members');
|
||||
}
|
||||
for (const recipient of jwe.recipients) {
|
||||
try {
|
||||
return await (0, decrypt_js_1.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 errors_js_1.JWEDecryptionFailed();
|
||||
}
|
||||
186
node_modules/jose/dist/node/cjs/jwe/general/encrypt.js
generated
vendored
Normal file
186
node_modules/jose/dist/node/cjs/jwe/general/encrypt.js
generated
vendored
Normal file
|
|
@ -0,0 +1,186 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.GeneralEncrypt = void 0;
|
||||
const encrypt_js_1 = require("../flattened/encrypt.js");
|
||||
const private_symbols_js_1 = require("../../lib/private_symbols.js");
|
||||
const errors_js_1 = require("../../util/errors.js");
|
||||
const cek_js_1 = require("../../lib/cek.js");
|
||||
const is_disjoint_js_1 = require("../../lib/is_disjoint.js");
|
||||
const encrypt_key_management_js_1 = require("../../lib/encrypt_key_management.js");
|
||||
const base64url_js_1 = require("../../runtime/base64url.js");
|
||||
const validate_crit_js_1 = require("../../lib/validate_crit.js");
|
||||
class IndividualRecipient {
|
||||
parent;
|
||||
unprotectedHeader;
|
||||
key;
|
||||
options;
|
||||
constructor(enc, key, options) {
|
||||
this.parent = enc;
|
||||
this.key = key;
|
||||
this.options = options;
|
||||
}
|
||||
setUnprotectedHeader(unprotectedHeader) {
|
||||
if (this.unprotectedHeader) {
|
||||
throw new TypeError('setUnprotectedHeader can only be called once');
|
||||
}
|
||||
this.unprotectedHeader = unprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
addRecipient(...args) {
|
||||
return this.parent.addRecipient(...args);
|
||||
}
|
||||
encrypt(...args) {
|
||||
return this.parent.encrypt(...args);
|
||||
}
|
||||
done() {
|
||||
return this.parent;
|
||||
}
|
||||
}
|
||||
class GeneralEncrypt {
|
||||
_plaintext;
|
||||
_recipients = [];
|
||||
_protectedHeader;
|
||||
_unprotectedHeader;
|
||||
_aad;
|
||||
constructor(plaintext) {
|
||||
this._plaintext = plaintext;
|
||||
}
|
||||
addRecipient(key, options) {
|
||||
const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
|
||||
this._recipients.push(recipient);
|
||||
return recipient;
|
||||
}
|
||||
setProtectedHeader(protectedHeader) {
|
||||
if (this._protectedHeader) {
|
||||
throw new TypeError('setProtectedHeader can only be called once');
|
||||
}
|
||||
this._protectedHeader = protectedHeader;
|
||||
return this;
|
||||
}
|
||||
setSharedUnprotectedHeader(sharedUnprotectedHeader) {
|
||||
if (this._unprotectedHeader) {
|
||||
throw new TypeError('setSharedUnprotectedHeader can only be called once');
|
||||
}
|
||||
this._unprotectedHeader = sharedUnprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
setAdditionalAuthenticatedData(aad) {
|
||||
this._aad = aad;
|
||||
return this;
|
||||
}
|
||||
async encrypt() {
|
||||
if (!this._recipients.length) {
|
||||
throw new errors_js_1.JWEInvalid('at least one recipient must be added');
|
||||
}
|
||||
if (this._recipients.length === 1) {
|
||||
const [recipient] = this._recipients;
|
||||
const flattened = await new encrypt_js_1.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 (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) {
|
||||
throw new errors_js_1.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 errors_js_1.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
|
||||
}
|
||||
if (alg === 'dir' || alg === 'ECDH-ES') {
|
||||
throw new errors_js_1.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');
|
||||
}
|
||||
if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) {
|
||||
throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
|
||||
}
|
||||
if (!enc) {
|
||||
enc = joseHeader.enc;
|
||||
}
|
||||
else if (enc !== joseHeader.enc) {
|
||||
throw new errors_js_1.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');
|
||||
}
|
||||
(0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader);
|
||||
if (joseHeader.zip !== undefined) {
|
||||
throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
|
||||
}
|
||||
}
|
||||
const cek = (0, cek_js_1.default)(enc);
|
||||
const jwe = {
|
||||
ciphertext: '',
|
||||
iv: '',
|
||||
recipients: [],
|
||||
tag: '',
|
||||
};
|
||||
for (let i = 0; i < this._recipients.length; i++) {
|
||||
const recipient = this._recipients[i];
|
||||
const target = {};
|
||||
jwe.recipients.push(target);
|
||||
const joseHeader = {
|
||||
...this._protectedHeader,
|
||||
...this._unprotectedHeader,
|
||||
...recipient.unprotectedHeader,
|
||||
};
|
||||
const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined;
|
||||
if (i === 0) {
|
||||
const flattened = await new encrypt_js_1.FlattenedEncrypt(this._plaintext)
|
||||
.setAdditionalAuthenticatedData(this._aad)
|
||||
.setContentEncryptionKey(cek)
|
||||
.setProtectedHeader(this._protectedHeader)
|
||||
.setSharedUnprotectedHeader(this._unprotectedHeader)
|
||||
.setUnprotectedHeader(recipient.unprotectedHeader)
|
||||
.setKeyManagementParameters({ p2c })
|
||||
.encrypt(recipient.key, {
|
||||
...recipient.options,
|
||||
[private_symbols_js_1.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 { encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(recipient.unprotectedHeader?.alg ||
|
||||
this._protectedHeader?.alg ||
|
||||
this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c });
|
||||
target.encrypted_key = (0, base64url_js_1.encode)(encryptedKey);
|
||||
if (recipient.unprotectedHeader || parameters)
|
||||
target.header = { ...recipient.unprotectedHeader, ...parameters };
|
||||
}
|
||||
return jwe;
|
||||
}
|
||||
}
|
||||
exports.GeneralEncrypt = GeneralEncrypt;
|
||||
20
node_modules/jose/dist/node/cjs/jwk/embedded.js
generated
vendored
Normal file
20
node_modules/jose/dist/node/cjs/jwk/embedded.js
generated
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.EmbeddedJWK = EmbeddedJWK;
|
||||
const import_js_1 = require("../key/import.js");
|
||||
const is_object_js_1 = require("../lib/is_object.js");
|
||||
const errors_js_1 = require("../util/errors.js");
|
||||
async function EmbeddedJWK(protectedHeader, token) {
|
||||
const joseHeader = {
|
||||
...protectedHeader,
|
||||
...token?.header,
|
||||
};
|
||||
if (!(0, is_object_js_1.default)(joseHeader.jwk)) {
|
||||
throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');
|
||||
}
|
||||
const key = await (0, import_js_1.importJWK)({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
|
||||
if (key instanceof Uint8Array || key.type !== 'public') {
|
||||
throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');
|
||||
}
|
||||
return key;
|
||||
}
|
||||
57
node_modules/jose/dist/node/cjs/jwk/thumbprint.js
generated
vendored
Normal file
57
node_modules/jose/dist/node/cjs/jwk/thumbprint.js
generated
vendored
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.calculateJwkThumbprint = calculateJwkThumbprint;
|
||||
exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri;
|
||||
const digest_js_1 = require("../runtime/digest.js");
|
||||
const base64url_js_1 = require("../runtime/base64url.js");
|
||||
const errors_js_1 = require("../util/errors.js");
|
||||
const buffer_utils_js_1 = require("../lib/buffer_utils.js");
|
||||
const is_object_js_1 = require("../lib/is_object.js");
|
||||
const check = (value, description) => {
|
||||
if (typeof value !== 'string' || !value) {
|
||||
throw new errors_js_1.JWKInvalid(`${description} missing or invalid`);
|
||||
}
|
||||
};
|
||||
async function calculateJwkThumbprint(jwk, digestAlgorithm) {
|
||||
if (!(0, is_object_js_1.default)(jwk)) {
|
||||
throw new TypeError('JWK must be an object');
|
||||
}
|
||||
digestAlgorithm ??= 'sha256';
|
||||
if (digestAlgorithm !== 'sha256' &&
|
||||
digestAlgorithm !== 'sha384' &&
|
||||
digestAlgorithm !== 'sha512') {
|
||||
throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
|
||||
}
|
||||
let components;
|
||||
switch (jwk.kty) {
|
||||
case 'EC':
|
||||
check(jwk.crv, '"crv" (Curve) Parameter');
|
||||
check(jwk.x, '"x" (X Coordinate) Parameter');
|
||||
check(jwk.y, '"y" (Y Coordinate) Parameter');
|
||||
components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
|
||||
break;
|
||||
case 'OKP':
|
||||
check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
|
||||
check(jwk.x, '"x" (Public Key) Parameter');
|
||||
components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
|
||||
break;
|
||||
case 'RSA':
|
||||
check(jwk.e, '"e" (Exponent) Parameter');
|
||||
check(jwk.n, '"n" (Modulus) Parameter');
|
||||
components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
|
||||
break;
|
||||
case 'oct':
|
||||
check(jwk.k, '"k" (Key Value) Parameter');
|
||||
components = { k: jwk.k, kty: jwk.kty };
|
||||
break;
|
||||
default:
|
||||
throw new errors_js_1.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
|
||||
}
|
||||
const data = buffer_utils_js_1.encoder.encode(JSON.stringify(components));
|
||||
return (0, base64url_js_1.encode)(await (0, digest_js_1.default)(digestAlgorithm, data));
|
||||
}
|
||||
async function calculateJwkThumbprintUri(jwk, digestAlgorithm) {
|
||||
digestAlgorithm ??= 'sha256';
|
||||
const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);
|
||||
return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
|
||||
}
|
||||
125
node_modules/jose/dist/node/cjs/jwks/local.js
generated
vendored
Normal file
125
node_modules/jose/dist/node/cjs/jwks/local.js
generated
vendored
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createLocalJWKSet = createLocalJWKSet;
|
||||
const import_js_1 = require("../key/import.js");
|
||||
const errors_js_1 = require("../util/errors.js");
|
||||
const is_object_js_1 = require("../lib/is_object.js");
|
||||
function getKtyFromAlg(alg) {
|
||||
switch (typeof alg === 'string' && alg.slice(0, 2)) {
|
||||
case 'RS':
|
||||
case 'PS':
|
||||
return 'RSA';
|
||||
case 'ES':
|
||||
return 'EC';
|
||||
case 'Ed':
|
||||
return 'OKP';
|
||||
default:
|
||||
throw new errors_js_1.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 (0, is_object_js_1.default)(key);
|
||||
}
|
||||
function clone(obj) {
|
||||
if (typeof structuredClone === 'function') {
|
||||
return structuredClone(obj);
|
||||
}
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
}
|
||||
class LocalJWKSet {
|
||||
_jwks;
|
||||
_cached = new WeakMap();
|
||||
constructor(jwks) {
|
||||
if (!isJWKSLike(jwks)) {
|
||||
throw new errors_js_1.JWKSInvalid('JSON Web Key Set malformed');
|
||||
}
|
||||
this._jwks = clone(jwks);
|
||||
}
|
||||
async getKey(protectedHeader, token) {
|
||||
const { alg, kid } = { ...protectedHeader, ...token?.header };
|
||||
const kty = getKtyFromAlg(alg);
|
||||
const candidates = this._jwks.keys.filter((jwk) => {
|
||||
let candidate = kty === jwk.kty;
|
||||
if (candidate && typeof kid === 'string') {
|
||||
candidate = kid === jwk.kid;
|
||||
}
|
||||
if (candidate && typeof jwk.alg === 'string') {
|
||||
candidate = alg === jwk.alg;
|
||||
}
|
||||
if (candidate && typeof jwk.use === 'string') {
|
||||
candidate = jwk.use === 'sig';
|
||||
}
|
||||
if (candidate && Array.isArray(jwk.key_ops)) {
|
||||
candidate = jwk.key_ops.includes('verify');
|
||||
}
|
||||
if (candidate && alg === 'EdDSA') {
|
||||
candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448';
|
||||
}
|
||||
if (candidate) {
|
||||
switch (alg) {
|
||||
case 'ES256':
|
||||
candidate = jwk.crv === 'P-256';
|
||||
break;
|
||||
case 'ES256K':
|
||||
candidate = jwk.crv === 'secp256k1';
|
||||
break;
|
||||
case 'ES384':
|
||||
candidate = jwk.crv === 'P-384';
|
||||
break;
|
||||
case 'ES512':
|
||||
candidate = jwk.crv === 'P-521';
|
||||
break;
|
||||
}
|
||||
}
|
||||
return candidate;
|
||||
});
|
||||
const { 0: jwk, length } = candidates;
|
||||
if (length === 0) {
|
||||
throw new errors_js_1.JWKSNoMatchingKey();
|
||||
}
|
||||
if (length !== 1) {
|
||||
const error = new errors_js_1.JWKSMultipleMatchingKeys();
|
||||
const { _cached } = this;
|
||||
error[Symbol.asyncIterator] = async function* () {
|
||||
for (const jwk of candidates) {
|
||||
try {
|
||||
yield await importWithAlgCache(_cached, jwk, alg);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
};
|
||||
throw error;
|
||||
}
|
||||
return importWithAlgCache(this._cached, jwk, alg);
|
||||
}
|
||||
}
|
||||
async function importWithAlgCache(cache, jwk, alg) {
|
||||
const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);
|
||||
if (cached[alg] === undefined) {
|
||||
const key = await (0, import_js_1.importJWK)({ ...jwk, ext: true }, alg);
|
||||
if (key instanceof Uint8Array || key.type !== 'public') {
|
||||
throw new errors_js_1.JWKSInvalid('JSON Web Key Set members must be public keys');
|
||||
}
|
||||
cached[alg] = key;
|
||||
}
|
||||
return cached[alg];
|
||||
}
|
||||
function createLocalJWKSet(jwks) {
|
||||
const set = new LocalJWKSet(jwks);
|
||||
const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
|
||||
Object.defineProperties(localJWKSet, {
|
||||
jwks: {
|
||||
value: () => clone(set._jwks),
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
writable: false,
|
||||
},
|
||||
});
|
||||
return localJWKSet;
|
||||
}
|
||||
152
node_modules/jose/dist/node/cjs/jwks/remote.js
generated
vendored
Normal file
152
node_modules/jose/dist/node/cjs/jwks/remote.js
generated
vendored
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.experimental_jwksCache = exports.jwksCache = void 0;
|
||||
exports.createRemoteJWKSet = createRemoteJWKSet;
|
||||
const fetch_jwks_js_1 = require("../runtime/fetch_jwks.js");
|
||||
const errors_js_1 = require("../util/errors.js");
|
||||
const local_js_1 = require("./local.js");
|
||||
const is_object_js_1 = require("../lib/is_object.js");
|
||||
function isCloudflareWorkers() {
|
||||
return (typeof WebSocketPair !== 'undefined' ||
|
||||
(typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
|
||||
(typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
|
||||
}
|
||||
let USER_AGENT;
|
||||
if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
|
||||
const NAME = 'jose';
|
||||
const VERSION = 'v5.9.6';
|
||||
USER_AGENT = `${NAME}/${VERSION}`;
|
||||
}
|
||||
exports.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) ||
|
||||
!(0, is_object_js_1.default)(input.jwks) ||
|
||||
!Array.isArray(input.jwks.keys) ||
|
||||
!Array.prototype.every.call(input.jwks.keys, is_object_js_1.default)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
class RemoteJWKSet {
|
||||
_url;
|
||||
_timeoutDuration;
|
||||
_cooldownDuration;
|
||||
_cacheMaxAge;
|
||||
_jwksTimestamp;
|
||||
_pendingFetch;
|
||||
_options;
|
||||
_local;
|
||||
_cache;
|
||||
constructor(url, options) {
|
||||
if (!(url instanceof URL)) {
|
||||
throw new TypeError('url must be an instance of URL');
|
||||
}
|
||||
this._url = new URL(url.href);
|
||||
this._options = { agent: options?.agent, headers: options?.headers };
|
||||
this._timeoutDuration =
|
||||
typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;
|
||||
this._cooldownDuration =
|
||||
typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;
|
||||
this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;
|
||||
if (options?.[exports.jwksCache] !== undefined) {
|
||||
this._cache = options?.[exports.jwksCache];
|
||||
if (isFreshJwksCache(options?.[exports.jwksCache], this._cacheMaxAge)) {
|
||||
this._jwksTimestamp = this._cache.uat;
|
||||
this._local = (0, local_js_1.createLocalJWKSet)(this._cache.jwks);
|
||||
}
|
||||
}
|
||||
}
|
||||
coolingDown() {
|
||||
return typeof this._jwksTimestamp === 'number'
|
||||
? Date.now() < this._jwksTimestamp + this._cooldownDuration
|
||||
: false;
|
||||
}
|
||||
fresh() {
|
||||
return typeof this._jwksTimestamp === 'number'
|
||||
? Date.now() < this._jwksTimestamp + this._cacheMaxAge
|
||||
: false;
|
||||
}
|
||||
async getKey(protectedHeader, token) {
|
||||
if (!this._local || !this.fresh()) {
|
||||
await this.reload();
|
||||
}
|
||||
try {
|
||||
return await this._local(protectedHeader, token);
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof errors_js_1.JWKSNoMatchingKey) {
|
||||
if (this.coolingDown() === false) {
|
||||
await this.reload();
|
||||
return this._local(protectedHeader, token);
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
async reload() {
|
||||
if (this._pendingFetch && isCloudflareWorkers()) {
|
||||
this._pendingFetch = undefined;
|
||||
}
|
||||
const headers = new Headers(this._options.headers);
|
||||
if (USER_AGENT && !headers.has('User-Agent')) {
|
||||
headers.set('User-Agent', USER_AGENT);
|
||||
this._options.headers = Object.fromEntries(headers.entries());
|
||||
}
|
||||
this._pendingFetch ||= (0, fetch_jwks_js_1.default)(this._url, this._timeoutDuration, this._options)
|
||||
.then((json) => {
|
||||
this._local = (0, local_js_1.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;
|
||||
}
|
||||
}
|
||||
function createRemoteJWKSet(url, options) {
|
||||
const set = new RemoteJWKSet(url, options);
|
||||
const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
|
||||
Object.defineProperties(remoteJWKSet, {
|
||||
coolingDown: {
|
||||
get: () => set.coolingDown(),
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
},
|
||||
fresh: {
|
||||
get: () => set.fresh(),
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
},
|
||||
reload: {
|
||||
value: () => set.reload(),
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
writable: false,
|
||||
},
|
||||
reloading: {
|
||||
get: () => !!set._pendingFetch,
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
},
|
||||
jwks: {
|
||||
value: () => set._local?.jwks(),
|
||||
enumerable: true,
|
||||
configurable: false,
|
||||
writable: false,
|
||||
},
|
||||
});
|
||||
return remoteJWKSet;
|
||||
}
|
||||
exports.experimental_jwksCache = exports.jwksCache;
|
||||
22
node_modules/jose/dist/node/cjs/jws/compact/sign.js
generated
vendored
Normal file
22
node_modules/jose/dist/node/cjs/jws/compact/sign.js
generated
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.CompactSign = void 0;
|
||||
const sign_js_1 = require("../flattened/sign.js");
|
||||
class CompactSign {
|
||||
_flattened;
|
||||
constructor(payload) {
|
||||
this._flattened = new sign_js_1.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}`;
|
||||
}
|
||||
}
|
||||
exports.CompactSign = CompactSign;
|
||||
24
node_modules/jose/dist/node/cjs/jws/compact/verify.js
generated
vendored
Normal file
24
node_modules/jose/dist/node/cjs/jws/compact/verify.js
generated
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.compactVerify = compactVerify;
|
||||
const verify_js_1 = require("../flattened/verify.js");
|
||||
const errors_js_1 = require("../../util/errors.js");
|
||||
const buffer_utils_js_1 = require("../../lib/buffer_utils.js");
|
||||
async function compactVerify(jws, key, options) {
|
||||
if (jws instanceof Uint8Array) {
|
||||
jws = buffer_utils_js_1.decoder.decode(jws);
|
||||
}
|
||||
if (typeof jws !== 'string') {
|
||||
throw new errors_js_1.JWSInvalid('Compact JWS must be a string or Uint8Array');
|
||||
}
|
||||
const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');
|
||||
if (length !== 3) {
|
||||
throw new errors_js_1.JWSInvalid('Invalid Compact JWS');
|
||||
}
|
||||
const verified = await (0, verify_js_1.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;
|
||||
}
|
||||
88
node_modules/jose/dist/node/cjs/jws/flattened/sign.js
generated
vendored
Normal file
88
node_modules/jose/dist/node/cjs/jws/flattened/sign.js
generated
vendored
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.FlattenedSign = void 0;
|
||||
const base64url_js_1 = require("../../runtime/base64url.js");
|
||||
const sign_js_1 = require("../../runtime/sign.js");
|
||||
const is_disjoint_js_1 = require("../../lib/is_disjoint.js");
|
||||
const errors_js_1 = require("../../util/errors.js");
|
||||
const buffer_utils_js_1 = require("../../lib/buffer_utils.js");
|
||||
const check_key_type_js_1 = require("../../lib/check_key_type.js");
|
||||
const validate_crit_js_1 = require("../../lib/validate_crit.js");
|
||||
class FlattenedSign {
|
||||
_payload;
|
||||
_protectedHeader;
|
||||
_unprotectedHeader;
|
||||
constructor(payload) {
|
||||
if (!(payload instanceof Uint8Array)) {
|
||||
throw new TypeError('payload must be an instance of Uint8Array');
|
||||
}
|
||||
this._payload = payload;
|
||||
}
|
||||
setProtectedHeader(protectedHeader) {
|
||||
if (this._protectedHeader) {
|
||||
throw new TypeError('setProtectedHeader can only be called once');
|
||||
}
|
||||
this._protectedHeader = protectedHeader;
|
||||
return this;
|
||||
}
|
||||
setUnprotectedHeader(unprotectedHeader) {
|
||||
if (this._unprotectedHeader) {
|
||||
throw new TypeError('setUnprotectedHeader can only be called once');
|
||||
}
|
||||
this._unprotectedHeader = unprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
async sign(key, options) {
|
||||
if (!this._protectedHeader && !this._unprotectedHeader) {
|
||||
throw new errors_js_1.JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');
|
||||
}
|
||||
if (!(0, is_disjoint_js_1.default)(this._protectedHeader, this._unprotectedHeader)) {
|
||||
throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
|
||||
}
|
||||
const joseHeader = {
|
||||
...this._protectedHeader,
|
||||
...this._unprotectedHeader,
|
||||
};
|
||||
const extensions = (0, validate_crit_js_1.default)(errors_js_1.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 errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
|
||||
}
|
||||
}
|
||||
const { alg } = joseHeader;
|
||||
if (typeof alg !== 'string' || !alg) {
|
||||
throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
||||
}
|
||||
(0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'sign');
|
||||
let payload = this._payload;
|
||||
if (b64) {
|
||||
payload = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(payload));
|
||||
}
|
||||
let protectedHeader;
|
||||
if (this._protectedHeader) {
|
||||
protectedHeader = buffer_utils_js_1.encoder.encode((0, base64url_js_1.encode)(JSON.stringify(this._protectedHeader)));
|
||||
}
|
||||
else {
|
||||
protectedHeader = buffer_utils_js_1.encoder.encode('');
|
||||
}
|
||||
const data = (0, buffer_utils_js_1.concat)(protectedHeader, buffer_utils_js_1.encoder.encode('.'), payload);
|
||||
const signature = await (0, sign_js_1.default)(alg, key, data);
|
||||
const jws = {
|
||||
signature: (0, base64url_js_1.encode)(signature),
|
||||
payload: '',
|
||||
};
|
||||
if (b64) {
|
||||
jws.payload = buffer_utils_js_1.decoder.decode(payload);
|
||||
}
|
||||
if (this._unprotectedHeader) {
|
||||
jws.header = this._unprotectedHeader;
|
||||
}
|
||||
if (this._protectedHeader) {
|
||||
jws.protected = buffer_utils_js_1.decoder.decode(protectedHeader);
|
||||
}
|
||||
return jws;
|
||||
}
|
||||
}
|
||||
exports.FlattenedSign = FlattenedSign;
|
||||
125
node_modules/jose/dist/node/cjs/jws/flattened/verify.js
generated
vendored
Normal file
125
node_modules/jose/dist/node/cjs/jws/flattened/verify.js
generated
vendored
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.flattenedVerify = flattenedVerify;
|
||||
const base64url_js_1 = require("../../runtime/base64url.js");
|
||||
const verify_js_1 = require("../../runtime/verify.js");
|
||||
const errors_js_1 = require("../../util/errors.js");
|
||||
const buffer_utils_js_1 = require("../../lib/buffer_utils.js");
|
||||
const is_disjoint_js_1 = require("../../lib/is_disjoint.js");
|
||||
const is_object_js_1 = require("../../lib/is_object.js");
|
||||
const check_key_type_js_1 = require("../../lib/check_key_type.js");
|
||||
const validate_crit_js_1 = require("../../lib/validate_crit.js");
|
||||
const validate_algorithms_js_1 = require("../../lib/validate_algorithms.js");
|
||||
const is_jwk_js_1 = require("../../lib/is_jwk.js");
|
||||
const import_js_1 = require("../../key/import.js");
|
||||
async function flattenedVerify(jws, key, options) {
|
||||
if (!(0, is_object_js_1.default)(jws)) {
|
||||
throw new errors_js_1.JWSInvalid('Flattened JWS must be an object');
|
||||
}
|
||||
if (jws.protected === undefined && jws.header === undefined) {
|
||||
throw new errors_js_1.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
|
||||
}
|
||||
if (jws.protected !== undefined && typeof jws.protected !== 'string') {
|
||||
throw new errors_js_1.JWSInvalid('JWS Protected Header incorrect type');
|
||||
}
|
||||
if (jws.payload === undefined) {
|
||||
throw new errors_js_1.JWSInvalid('JWS Payload missing');
|
||||
}
|
||||
if (typeof jws.signature !== 'string') {
|
||||
throw new errors_js_1.JWSInvalid('JWS Signature missing or incorrect type');
|
||||
}
|
||||
if (jws.header !== undefined && !(0, is_object_js_1.default)(jws.header)) {
|
||||
throw new errors_js_1.JWSInvalid('JWS Unprotected Header incorrect type');
|
||||
}
|
||||
let parsedProt = {};
|
||||
if (jws.protected) {
|
||||
try {
|
||||
const protectedHeader = (0, base64url_js_1.decode)(jws.protected);
|
||||
parsedProt = JSON.parse(buffer_utils_js_1.decoder.decode(protectedHeader));
|
||||
}
|
||||
catch {
|
||||
throw new errors_js_1.JWSInvalid('JWS Protected Header is invalid');
|
||||
}
|
||||
}
|
||||
if (!(0, is_disjoint_js_1.default)(parsedProt, jws.header)) {
|
||||
throw new errors_js_1.JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
|
||||
}
|
||||
const joseHeader = {
|
||||
...parsedProt,
|
||||
...jws.header,
|
||||
};
|
||||
const extensions = (0, validate_crit_js_1.default)(errors_js_1.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 errors_js_1.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
|
||||
}
|
||||
}
|
||||
const { alg } = joseHeader;
|
||||
if (typeof alg !== 'string' || !alg) {
|
||||
throw new errors_js_1.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
||||
}
|
||||
const algorithms = options && (0, validate_algorithms_js_1.default)('algorithms', options.algorithms);
|
||||
if (algorithms && !algorithms.has(alg)) {
|
||||
throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
|
||||
}
|
||||
if (b64) {
|
||||
if (typeof jws.payload !== 'string') {
|
||||
throw new errors_js_1.JWSInvalid('JWS Payload must be a string');
|
||||
}
|
||||
}
|
||||
else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {
|
||||
throw new errors_js_1.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;
|
||||
(0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify');
|
||||
if ((0, is_jwk_js_1.isJWK)(key)) {
|
||||
key = await (0, import_js_1.importJWK)(key, alg);
|
||||
}
|
||||
}
|
||||
else {
|
||||
(0, check_key_type_js_1.checkKeyTypeWithJwk)(alg, key, 'verify');
|
||||
}
|
||||
const data = (0, buffer_utils_js_1.concat)(buffer_utils_js_1.encoder.encode(jws.protected ?? ''), buffer_utils_js_1.encoder.encode('.'), typeof jws.payload === 'string' ? buffer_utils_js_1.encoder.encode(jws.payload) : jws.payload);
|
||||
let signature;
|
||||
try {
|
||||
signature = (0, base64url_js_1.decode)(jws.signature);
|
||||
}
|
||||
catch {
|
||||
throw new errors_js_1.JWSInvalid('Failed to base64url decode the signature');
|
||||
}
|
||||
const verified = await (0, verify_js_1.default)(alg, key, signature, data);
|
||||
if (!verified) {
|
||||
throw new errors_js_1.JWSSignatureVerificationFailed();
|
||||
}
|
||||
let payload;
|
||||
if (b64) {
|
||||
try {
|
||||
payload = (0, base64url_js_1.decode)(jws.payload);
|
||||
}
|
||||
catch {
|
||||
throw new errors_js_1.JWSInvalid('Failed to base64url decode the payload');
|
||||
}
|
||||
}
|
||||
else if (typeof jws.payload === 'string') {
|
||||
payload = buffer_utils_js_1.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 };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
77
node_modules/jose/dist/node/cjs/jws/general/sign.js
generated
vendored
Normal file
77
node_modules/jose/dist/node/cjs/jws/general/sign.js
generated
vendored
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.GeneralSign = void 0;
|
||||
const sign_js_1 = require("../flattened/sign.js");
|
||||
const errors_js_1 = require("../../util/errors.js");
|
||||
class IndividualSignature {
|
||||
parent;
|
||||
protectedHeader;
|
||||
unprotectedHeader;
|
||||
options;
|
||||
key;
|
||||
constructor(sig, key, options) {
|
||||
this.parent = sig;
|
||||
this.key = key;
|
||||
this.options = options;
|
||||
}
|
||||
setProtectedHeader(protectedHeader) {
|
||||
if (this.protectedHeader) {
|
||||
throw new TypeError('setProtectedHeader can only be called once');
|
||||
}
|
||||
this.protectedHeader = protectedHeader;
|
||||
return this;
|
||||
}
|
||||
setUnprotectedHeader(unprotectedHeader) {
|
||||
if (this.unprotectedHeader) {
|
||||
throw new TypeError('setUnprotectedHeader can only be called once');
|
||||
}
|
||||
this.unprotectedHeader = unprotectedHeader;
|
||||
return this;
|
||||
}
|
||||
addSignature(...args) {
|
||||
return this.parent.addSignature(...args);
|
||||
}
|
||||
sign(...args) {
|
||||
return this.parent.sign(...args);
|
||||
}
|
||||
done() {
|
||||
return this.parent;
|
||||
}
|
||||
}
|
||||
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 errors_js_1.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 sign_js_1.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 errors_js_1.JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)');
|
||||
}
|
||||
jws.signatures.push(rest);
|
||||
}
|
||||
return jws;
|
||||
}
|
||||
}
|
||||
exports.GeneralSign = GeneralSign;
|
||||
27
node_modules/jose/dist/node/cjs/jws/general/verify.js
generated
vendored
Normal file
27
node_modules/jose/dist/node/cjs/jws/general/verify.js
generated
vendored
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.generalVerify = generalVerify;
|
||||
const verify_js_1 = require("../flattened/verify.js");
|
||||
const errors_js_1 = require("../../util/errors.js");
|
||||
const is_object_js_1 = require("../../lib/is_object.js");
|
||||
async function generalVerify(jws, key, options) {
|
||||
if (!(0, is_object_js_1.default)(jws)) {
|
||||
throw new errors_js_1.JWSInvalid('General JWS must be an object');
|
||||
}
|
||||
if (!Array.isArray(jws.signatures) || !jws.signatures.every(is_object_js_1.default)) {
|
||||
throw new errors_js_1.JWSInvalid('JWS Signatures missing or incorrect type');
|
||||
}
|
||||
for (const signature of jws.signatures) {
|
||||
try {
|
||||
return await (0, verify_js_1.flattenedVerify)({
|
||||
header: signature.header,
|
||||
payload: jws.payload,
|
||||
protected: signature.protected,
|
||||
signature: signature.signature,
|
||||
}, key, options);
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
throw new errors_js_1.JWSSignatureVerificationFailed();
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue