main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

30
node_modules/jose/dist/node/esm/index.js generated vendored Normal file
View 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 } 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/node/esm/jwe/compact/decrypt.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import { flattenedDecrypt } from '../flattened/decrypt.js';
import { JWEInvalid } from '../../util/errors.js';
import { decoder } from '../../lib/buffer_utils.js';
export async function compactDecrypt(jwe, key, options) {
if (jwe instanceof Uint8Array) {
jwe = decoder.decode(jwe);
}
if (typeof jwe !== 'string') {
throw new JWEInvalid('Compact JWE must be a string or Uint8Array');
}
const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.');
if (length !== 5) {
throw new JWEInvalid('Invalid Compact JWE');
}
const decrypted = await flattenedDecrypt({
ciphertext,
iv: (iv || undefined),
protected: protectedHeader || undefined,
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/node/esm/jwe/compact/encrypt.js generated vendored Normal file
View 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('.');
}
}

View File

@@ -0,0 +1,166 @@
import { decode as base64url } from '../../runtime/base64url.js';
import decrypt from '../../runtime/decrypt.js';
import { inflate } from '../../runtime/zlib.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) {
var _a;
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 (typeof jwe.iv !== 'string') {
throw new JWEInvalid('JWE Initialization Vector missing or incorrect type');
}
if (typeof jwe.ciphertext !== 'string') {
throw new JWEInvalid('JWE Ciphertext missing or incorrect type');
}
if (typeof jwe.tag !== 'string') {
throw new JWEInvalid('JWE Authentication Tag missing or 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 === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader);
if (joseHeader.zip !== undefined) {
if (!parsedProt || !parsedProt.zip) {
throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');
}
if (joseHeader.zip !== 'DEF') {
throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value');
}
}
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)) {
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');
}
if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter 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;
try {
iv = base64url(jwe.iv);
}
catch {
throw new JWEInvalid('Failed to base64url decode the iv');
}
try {
tag = base64url(jwe.tag);
}
catch {
throw new JWEInvalid('Failed to base64url decode the tag');
}
const protectedHeader = encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : '');
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');
}
let plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData);
if (joseHeader.zip === 'DEF') {
plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || inflate)(plaintext);
}
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;
}

View File

@@ -0,0 +1,175 @@
import { encode as base64url } from '../../runtime/base64url.js';
import encrypt from '../../runtime/encrypt.js';
import { deflate } from '../../runtime/zlib.js';
import generateIv from '../../lib/iv.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 const unprotected = Symbol();
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 === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);
if (joseHeader.zip !== undefined) {
if (!this._protectedHeader || !this._protectedHeader.zip) {
throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');
}
if (joseHeader.zip !== 'DEF') {
throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value');
}
}
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 (alg === 'dir') {
if (this._cek) {
throw new TypeError('setContentEncryptionKey cannot be called when using Direct Encryption');
}
}
else if (alg === 'ECDH-ES') {
if (this._cek) {
throw new TypeError('setContentEncryptionKey cannot be called when using Direct Key Agreement');
}
}
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 };
}
}
}
}
this._iv || (this._iv = generateIv(enc));
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;
}
let ciphertext;
let tag;
if (joseHeader.zip === 'DEF') {
const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || deflate)(this._plaintext);
({ ciphertext, tag } = await encrypt(enc, deflated, cek, this._iv, additionalData));
}
else {
;
({ ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData));
}
const jwe = {
ciphertext: base64url(ciphertext),
iv: base64url(this._iv),
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/node/esm/jwe/general/decrypt.js generated vendored Normal file
View File

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

178
node_modules/jose/dist/node/esm/jwe/general/encrypt.js generated vendored Normal file
View File

@@ -0,0 +1,178 @@
import { FlattenedEncrypt, unprotected } from '../flattened/encrypt.js';
import { 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 === null || options === void 0 ? void 0 : 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(options) {
var _a, _b, _c;
if (!this._recipients.length) {
throw new JWEInvalid('at least one recipient must be added');
}
options = { deflateRaw: options === null || options === void 0 ? void 0 : options.deflateRaw };
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, ...options });
let 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) {
if (!this._protectedHeader || !this._protectedHeader.zip) {
throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');
}
}
}
const cek = generateCek(enc);
let 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,
...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(((_a = recipient.unprotectedHeader) === null || _a === void 0 ? void 0 : _a.alg) ||
((_b = this._protectedHeader) === null || _b === void 0 ? void 0 : _b.alg) ||
((_c = this._unprotectedHeader) === null || _c === void 0 ? void 0 : _c.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/node/esm/jwk/embedded.js generated vendored Normal file
View 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 === null || token === void 0 ? void 0 : 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, true);
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/node/esm/jwk/thumbprint.js generated vendored Normal file
View 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 !== null && digestAlgorithm !== void 0 ? 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 !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256');
const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);
return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
}

116
node_modules/jose/dist/node/esm/jwks/local.js generated vendored Normal file
View File

@@ -0,0 +1,116 @@
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');
}
}
export 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));
}
export 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 === null || token === void 0 ? void 0 : 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();
}
else 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 {
continue;
}
}
};
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);
return async function (protectedHeader, token) {
return set.getKey(protectedHeader, token);
};
}

76
node_modules/jose/dist/node/esm/jwks/remote.js generated vendored Normal file
View File

@@ -0,0 +1,76 @@
import fetchJwks from '../runtime/fetch_jwks.js';
import { JWKSInvalid, JWKSNoMatchingKey } from '../util/errors.js';
import { isJWKSLike, LocalJWKSet } from './local.js';
function isCloudflareWorkers() {
return (typeof WebSocketPair !== 'undefined' ||
(typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
(typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
}
class RemoteJWKSet extends LocalJWKSet {
constructor(url, options) {
super({ keys: [] });
this._jwks = undefined;
if (!(url instanceof URL)) {
throw new TypeError('url must be an instance of URL');
}
this._url = new URL(url.href);
this._options = { agent: options === null || options === void 0 ? void 0 : options.agent, headers: options === null || options === void 0 ? void 0 : options.headers };
this._timeoutDuration =
typeof (options === null || options === void 0 ? void 0 : options.timeoutDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.timeoutDuration : 5000;
this._cooldownDuration =
typeof (options === null || options === void 0 ? void 0 : options.cooldownDuration) === 'number' ? options === null || options === void 0 ? void 0 : options.cooldownDuration : 30000;
this._cacheMaxAge = typeof (options === null || options === void 0 ? void 0 : options.cacheMaxAge) === 'number' ? options === null || options === void 0 ? void 0 : options.cacheMaxAge : 600000;
}
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._jwks || !this.fresh()) {
await this.reload();
}
try {
return await super.getKey(protectedHeader, token);
}
catch (err) {
if (err instanceof JWKSNoMatchingKey) {
if (this.coolingDown() === false) {
await this.reload();
return super.getKey(protectedHeader, token);
}
}
throw err;
}
}
async reload() {
if (this._pendingFetch && isCloudflareWorkers()) {
this._pendingFetch = undefined;
}
this._pendingFetch || (this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options)
.then((json) => {
if (!isJWKSLike(json)) {
throw new JWKSInvalid('JSON Web Key Set malformed');
}
this._jwks = { keys: json.keys };
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);
return async function (protectedHeader, token) {
return set.getKey(protectedHeader, token);
};
}

17
node_modules/jose/dist/node/esm/jws/compact/sign.js generated vendored Normal file
View 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/node/esm/jws/compact/verify.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
import { flattenedVerify } from '../flattened/verify.js';
import { JWSInvalid } from '../../util/errors.js';
import { decoder } from '../../lib/buffer_utils.js';
export async function compactVerify(jws, key, options) {
if (jws instanceof Uint8Array) {
jws = decoder.decode(jws);
}
if (typeof jws !== 'string') {
throw new JWSInvalid('Compact JWS must be a string or Uint8Array');
}
const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');
if (length !== 3) {
throw new JWSInvalid('Invalid Compact JWS');
}
const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
if (typeof key === 'function') {
return { ...result, key: verified.key };
}
return result;
}

81
node_modules/jose/dist/node/esm/jws/flattened/sign.js generated vendored Normal file
View 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 checkKeyType 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 === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);
let b64 = true;
if (extensions.has('b64')) {
b64 = this._protectedHeader.b64;
if (typeof b64 !== 'boolean') {
throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
}
}
const { alg } = joseHeader;
if (typeof alg !== 'string' || !alg) {
throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
}
checkKeyType(alg, key, 'sign');
let payload = this._payload;
if (b64) {
payload = encoder.encode(base64url(payload));
}
let protectedHeader;
if (this._protectedHeader) {
protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));
}
else {
protectedHeader = encoder.encode('');
}
const data = concat(protectedHeader, encoder.encode('.'), payload);
const 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;
}
}

115
node_modules/jose/dist/node/esm/jws/flattened/verify.js generated vendored Normal file
View File

@@ -0,0 +1,115 @@
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 checkKeyType from '../../lib/check_key_type.js';
import validateCrit from '../../lib/validate_crit.js';
import validateAlgorithms from '../../lib/validate_algorithms.js';
export async function flattenedVerify(jws, key, options) {
var _a;
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 === null || options === void 0 ? void 0 : 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 not allowed');
}
if (b64) {
if (typeof jws.payload !== 'string') {
throw new JWSInvalid('JWS Payload must be a string');
}
}
else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {
throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');
}
let resolvedKey = false;
if (typeof key === 'function') {
key = await key(parsedProt, jws);
resolvedKey = true;
}
checkKeyType(alg, key, 'verify');
const data = concat(encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ''), 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/node/esm/jws/general/sign.js generated vendored Normal file
View 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/node/esm/jws/general/verify.js generated vendored Normal file
View File

@@ -0,0 +1,24 @@
import { flattenedVerify } from '../flattened/verify.js';
import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';
import isObject from '../../lib/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/node/esm/jwt/decrypt.js generated vendored Normal file
View 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', 'iss', 'mismatch');
}
if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) {
throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', 'sub', 'mismatch');
}
if (protectedHeader.aud !== undefined &&
JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', 'aud', 'mismatch');
}
const result = { payload, protectedHeader };
if (typeof key === 'function') {
return { ...result, key: decrypted.key };
}
return result;
}

68
node_modules/jose/dist/node/esm/jwt/encrypt.js generated vendored Normal file
View 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);
}
}

54
node_modules/jose/dist/node/esm/jwt/produce.js generated vendored Normal file
View File

@@ -0,0 +1,54 @@
import epoch from '../lib/epoch.js';
import isObject from '../lib/is_object.js';
import secs from '../lib/secs.js';
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: 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: 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 {
this._payload = { ...this._payload, iat: input };
}
return this;
}
}

21
node_modules/jose/dist/node/esm/jwt/sign.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
import { CompactSign } from '../jws/compact/sign.js';
import { JWTInvalid } from '../util/errors.js';
import { encoder } from '../lib/buffer_utils.js';
import { ProduceJWT } from './produce.js';
export class SignJWT extends ProduceJWT {
setProtectedHeader(protectedHeader) {
this._protectedHeader = protectedHeader;
return this;
}
async sign(key, options) {
var _a;
const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)));
sig.setProtectedHeader(this._protectedHeader);
if (Array.isArray((_a = this._protectedHeader) === null || _a === void 0 ? void 0 : _a.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/node/esm/jwt/unsecured.js generated vendored Normal file
View 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 };
}
}

16
node_modules/jose/dist/node/esm/jwt/verify.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
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) {
var _a;
const verified = await compactVerify(jwt, key, options);
if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.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/node/esm/key/export.js generated vendored Normal file
View 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);
}

View File

@@ -0,0 +1,4 @@
import { generateKeyPair as generate } from '../runtime/generate.js';
export async function generateKeyPair(alg, options) {
return generate(alg, options);
}

View File

@@ -0,0 +1,4 @@
import { generateSecret as generate } from '../runtime/generate.js';
export async function generateSecret(alg, options) {
return generate(alg, options);
}

50
node_modules/jose/dist/node/esm/key/import.js generated vendored Normal file
View File

@@ -0,0 +1,50 @@
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, octAsKeyObject) {
var _a;
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');
}
octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : (octAsKeyObject = jwk.ext !== true);
if (octAsKeyObject) {
return asKeyObject({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false });
}
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');
}
}

14
node_modules/jose/dist/node/esm/lib/aesgcmkw.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import encrypt from '../runtime/encrypt.js';
import decrypt from '../runtime/decrypt.js';
import generateIv from './iv.js';
import { encode as base64url } from '../runtime/base64url.js';
export async function wrap(alg, key, cek, iv) {
const jweAlgorithm = alg.slice(0, 7);
iv || (iv = generateIv(jweAlgorithm));
const { ciphertext: encryptedKey, tag } = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0));
return { encryptedKey, iv: base64url(iv), tag: base64url(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/node/esm/lib/buffer_utils.js generated vendored Normal file
View 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;
buffers.forEach((buffer) => {
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/node/esm/lib/cek.js generated vendored Normal file
View 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));

View 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;

45
node_modules/jose/dist/node/esm/lib/check_key_type.js generated vendored Normal file
View File

@@ -0,0 +1,45 @@
import { withAlg as invalidKeyInput } from './invalid_key_input.js';
import isKeyLike, { types } from '../runtime/is_key_like.js';
const symmetricTypeCheck = (alg, key) => {
if (key instanceof Uint8Array)
return;
if (!isKeyLike(key)) {
throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array'));
}
if (key.type !== 'secret') {
throw new TypeError(`${types.join(' or ')} instances for symmetric algorithms must be of type "secret"`);
}
};
const asymmetricTypeCheck = (alg, key, usage) => {
if (!isKeyLike(key)) {
throw new TypeError(invalidKeyInput(alg, key, ...types));
}
if (key.type === 'secret') {
throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithms must not be of type "secret"`);
}
if (usage === 'sign' && key.type === 'public') {
throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm signing must be of type "private"`);
}
if (usage === 'decrypt' && key.type === 'public') {
throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm decryption must be of type "private"`);
}
if (key.algorithm && usage === 'verify' && key.type === 'private') {
throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm verifying must be of type "public"`);
}
if (key.algorithm && usage === 'encrypt' && key.type === 'private') {
throw new TypeError(`${types.join(' or ')} instances for asymmetric algorithm encryption must be of type "public"`);
}
};
const checkKeyType = (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);
}
else {
asymmetricTypeCheck(alg, key, usage);
}
};
export default checkKeyType;

6
node_modules/jose/dist/node/esm/lib/check_p2s.js generated vendored Normal file
View 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/node/esm/lib/crypto_key.js generated vendored Normal file
View 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);
}

View File

@@ -0,0 +1,127 @@
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 { 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');
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 === null || options === void 0 ? void 0 : 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;

View File

@@ -0,0 +1,87 @@
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 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');
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/node/esm/lib/epoch.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export default (date) => Math.floor(date.getTime() / 1000);

View File

@@ -0,0 +1,30 @@
function message(msg, actual, ...types) {
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 && 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/node/esm/lib/is_disjoint.js generated vendored Normal file
View 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;

16
node_modules/jose/dist/node/esm/lib/is_object.js generated vendored Normal file
View 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/node/esm/lib/iv.js generated vendored Normal file
View 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));

102
node_modules/jose/dist/node/esm/lib/jwt_claims_set.js generated vendored Normal file
View File

@@ -0,0 +1,102 @@
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 = {}) => {
const { typ } = options;
if (typ &&
(typeof protectedHeader.typ !== 'string' ||
normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', 'typ', 'check_failed');
}
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 { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
if (maxTokenAge !== undefined)
requiredClaims.push('iat');
if (audience !== undefined)
requiredClaims.push('aud');
if (subject !== undefined)
requiredClaims.push('sub');
if (issuer !== undefined)
requiredClaims.push('iss');
for (const claim of new Set(requiredClaims.reverse())) {
if (!(claim in payload)) {
throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, claim, 'missing');
}
}
if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
throw new JWTClaimValidationFailed('unexpected "iss" claim value', 'iss', 'check_failed');
}
if (subject && payload.sub !== subject) {
throw new JWTClaimValidationFailed('unexpected "sub" claim value', 'sub', 'check_failed');
}
if (audience &&
!checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {
throw new JWTClaimValidationFailed('unexpected "aud" claim value', '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', 'iat', 'invalid');
}
if (payload.nbf !== undefined) {
if (typeof payload.nbf !== 'number') {
throw new JWTClaimValidationFailed('"nbf" claim must be a number', 'nbf', 'invalid');
}
if (payload.nbf > now + tolerance) {
throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', 'nbf', 'check_failed');
}
}
if (payload.exp !== undefined) {
if (typeof payload.exp !== 'number') {
throw new JWTClaimValidationFailed('"exp" claim must be a number', 'exp', 'invalid');
}
if (payload.exp <= now - tolerance) {
throw new JWTExpired('"exp" claim timestamp check failed', '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)', 'iat', 'check_failed');
}
if (age < 0 - tolerance) {
throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', 'iat', 'check_failed');
}
}
return payload;
};

44
node_modules/jose/dist/node/esm/lib/secs.js generated vendored Normal file
View File

@@ -0,0 +1,44 @@
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)$/i;
export default (str) => {
const matched = REGEX.exec(str);
if (!matched) {
throw new TypeError('Invalid time period format');
}
const value = parseFloat(matched[1]);
const unit = matched[2].toLowerCase();
switch (unit) {
case 'sec':
case 'secs':
case 'second':
case 'seconds':
case 's':
return Math.round(value);
case 'minute':
case 'minutes':
case 'min':
case 'mins':
case 'm':
return Math.round(value * minute);
case 'hour':
case 'hours':
case 'hr':
case 'hrs':
case 'h':
return Math.round(value * hour);
case 'day':
case 'days':
case 'd':
return Math.round(value * day);
case 'week':
case 'weeks':
case 'w':
return Math.round(value * week);
default:
return Math.round(value * year);
}
};

View 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/node/esm/lib/validate_crit.js generated vendored Normal file
View 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`);
}
else 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/node/esm/package.json generated vendored Normal file
View File

@@ -0,0 +1 @@
{"type":"module","sideEffects":false}

50
node_modules/jose/dist/node/esm/runtime/aeskw.js generated vendored Normal file
View File

@@ -0,0 +1,50 @@
import { Buffer } from 'buffer';
import { KeyObject, createDecipheriv, createCipheriv, createSecretKey } from 'crypto';
import { JOSENotSupported } from '../util/errors.js';
import { concat } from '../lib/buffer_utils.js';
import { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import isKeyObject from './is_key_object.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import supported from './ciphers.js';
import { types } from './is_key_like.js';
function checkKeySize(key, alg) {
if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) {
throw new TypeError(`Invalid key size for alg: ${alg}`);
}
}
function ensureKeyObject(key, alg, usage) {
if (isKeyObject(key)) {
return key;
}
if (key instanceof Uint8Array) {
return createSecretKey(key);
}
if (isCryptoKey(key)) {
checkEncCryptoKey(key, alg, usage);
return KeyObject.from(key);
}
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
}
export const wrap = (alg, key, cek) => {
const size = parseInt(alg.slice(1, 4), 10);
const algorithm = `aes${size}-wrap`;
if (!supported(algorithm)) {
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
}
const keyObject = ensureKeyObject(key, alg, 'wrapKey');
checkKeySize(keyObject, alg);
const cipher = createCipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6));
return concat(cipher.update(cek), cipher.final());
};
export const unwrap = (alg, key, encryptedKey) => {
const size = parseInt(alg.slice(1, 4), 10);
const algorithm = `aes${size}-wrap`;
if (!supported(algorithm)) {
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
}
const keyObject = ensureKeyObject(key, alg, 'unwrapKey');
checkKeySize(keyObject, alg);
const cipher = createDecipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6));
return concat(cipher.update(encryptedKey), cipher.final());
};

46
node_modules/jose/dist/node/esm/runtime/asn1.js generated vendored Normal file
View File

@@ -0,0 +1,46 @@
import { createPrivateKey, createPublicKey, KeyObject } from 'crypto';
import { Buffer } from 'buffer';
import { isCryptoKey } from './webcrypto.js';
import isKeyObject from './is_key_object.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
const genericExport = (keyType, keyFormat, key) => {
let keyObject;
if (isCryptoKey(key)) {
if (!key.extractable) {
throw new TypeError('CryptoKey is not extractable');
}
keyObject = KeyObject.from(key);
}
else if (isKeyObject(key)) {
keyObject = key;
}
else {
throw new TypeError(invalidKeyInput(key, ...types));
}
if (keyObject.type !== keyType) {
throw new TypeError(`key is not a ${keyType} key`);
}
return keyObject.export({ format: 'pem', type: keyFormat });
};
export const toSPKI = (key) => {
return genericExport('public', 'spki', key);
};
export const toPKCS8 = (key) => {
return genericExport('private', 'pkcs8', key);
};
export const fromPKCS8 = (pem) => createPrivateKey({
key: Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'),
type: 'pkcs8',
format: 'der',
});
export const fromSPKI = (pem) => createPublicKey({
key: Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'),
type: 'spki',
format: 'der',
});
export const fromX509 = (pem) => createPublicKey({
key: pem,
type: 'spki',
format: 'pem',
});

View File

@@ -0,0 +1,44 @@
const tagInteger = 0x02;
const tagSequence = 0x30;
export default class Asn1SequenceDecoder {
constructor(buffer) {
if (buffer[0] !== tagSequence) {
throw new TypeError();
}
this.buffer = buffer;
this.offset = 1;
const len = this.decodeLength();
if (len !== buffer.length - this.offset) {
throw new TypeError();
}
}
decodeLength() {
let length = this.buffer[this.offset++];
if (length & 0x80) {
const nBytes = length & ~0x80;
length = 0;
for (let i = 0; i < nBytes; i++)
length = (length << 8) | this.buffer[this.offset + i];
this.offset += nBytes;
}
return length;
}
unsignedInteger() {
if (this.buffer[this.offset++] !== tagInteger) {
throw new TypeError();
}
let length = this.decodeLength();
if (this.buffer[this.offset] === 0) {
this.offset++;
length--;
}
const result = this.buffer.slice(this.offset, this.offset + length);
this.offset += length;
return result;
}
end() {
if (this.offset !== this.buffer.length) {
throw new TypeError();
}
}
}

View File

@@ -0,0 +1,88 @@
import { Buffer } from 'buffer';
import { JOSENotSupported } from '../util/errors.js';
const tagInteger = 0x02;
const tagBitStr = 0x03;
const tagOctStr = 0x04;
const tagSequence = 0x30;
const bZero = Buffer.from([0x00]);
const bTagInteger = Buffer.from([tagInteger]);
const bTagBitStr = Buffer.from([tagBitStr]);
const bTagSequence = Buffer.from([tagSequence]);
const bTagOctStr = Buffer.from([tagOctStr]);
const encodeLength = (len) => {
if (len < 128)
return Buffer.from([len]);
const buffer = Buffer.alloc(5);
buffer.writeUInt32BE(len, 1);
let offset = 1;
while (buffer[offset] === 0)
offset++;
buffer[offset - 1] = 0x80 | (5 - offset);
return buffer.slice(offset - 1);
};
const oids = new Map([
['P-256', Buffer.from('06 08 2A 86 48 CE 3D 03 01 07'.replace(/ /g, ''), 'hex')],
['secp256k1', Buffer.from('06 05 2B 81 04 00 0A'.replace(/ /g, ''), 'hex')],
['P-384', Buffer.from('06 05 2B 81 04 00 22'.replace(/ /g, ''), 'hex')],
['P-521', Buffer.from('06 05 2B 81 04 00 23'.replace(/ /g, ''), 'hex')],
['ecPublicKey', Buffer.from('06 07 2A 86 48 CE 3D 02 01'.replace(/ /g, ''), 'hex')],
['X25519', Buffer.from('06 03 2B 65 6E'.replace(/ /g, ''), 'hex')],
['X448', Buffer.from('06 03 2B 65 6F'.replace(/ /g, ''), 'hex')],
['Ed25519', Buffer.from('06 03 2B 65 70'.replace(/ /g, ''), 'hex')],
['Ed448', Buffer.from('06 03 2B 65 71'.replace(/ /g, ''), 'hex')],
]);
export default class DumbAsn1Encoder {
constructor() {
this.length = 0;
this.elements = [];
}
oidFor(oid) {
const bOid = oids.get(oid);
if (!bOid) {
throw new JOSENotSupported('Invalid or unsupported OID');
}
this.elements.push(bOid);
this.length += bOid.length;
}
zero() {
this.elements.push(bTagInteger, Buffer.from([0x01]), bZero);
this.length += 3;
}
one() {
this.elements.push(bTagInteger, Buffer.from([0x01]), Buffer.from([0x01]));
this.length += 3;
}
unsignedInteger(integer) {
if (integer[0] & 0x80) {
const len = encodeLength(integer.length + 1);
this.elements.push(bTagInteger, len, bZero, integer);
this.length += 2 + len.length + integer.length;
}
else {
let i = 0;
while (integer[i] === 0 && (integer[i + 1] & 0x80) === 0)
i++;
const len = encodeLength(integer.length - i);
this.elements.push(bTagInteger, encodeLength(integer.length - i), integer.slice(i));
this.length += 1 + len.length + integer.length - i;
}
}
octStr(octStr) {
const len = encodeLength(octStr.length);
this.elements.push(bTagOctStr, encodeLength(octStr.length), octStr);
this.length += 1 + len.length + octStr.length;
}
bitStr(bitS) {
const len = encodeLength(bitS.length + 1);
this.elements.push(bTagBitStr, encodeLength(bitS.length + 1), bZero, bitS);
this.length += 1 + len.length + bitS.length + 1;
}
add(seq) {
this.elements.push(seq);
this.length += seq.length;
}
end(tag = bTagSequence) {
const len = encodeLength(this.length);
return Buffer.concat([tag, len, ...this.elements], 1 + len.length + this.length);
}
}

20
node_modules/jose/dist/node/esm/runtime/base64url.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
import { Buffer } from 'buffer';
import { decoder } from '../lib/buffer_utils.js';
let encode;
function normalize(input) {
let encoded = input;
if (encoded instanceof Uint8Array) {
encoded = decoder.decode(encoded);
}
return encoded;
}
if (Buffer.isEncoding('base64url')) {
encode = (input) => Buffer.from(input).toString('base64url');
}
else {
encode = (input) => Buffer.from(input).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
export const decodeBase64 = (input) => Buffer.from(input, 'base64');
export const encodeBase64 = (input) => Buffer.from(input).toString('base64');
export { encode };
export const decode = (input) => Buffer.from(normalize(input), 'base64');

8
node_modules/jose/dist/node/esm/runtime/cbc_tag.js generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import { createHmac } from 'crypto';
import { concat, uint64be } from '../lib/buffer_utils.js';
export default function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) {
const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
const hmac = createHmac(`sha${macSize}`, macKey);
hmac.update(macData);
return hmac.digest().slice(0, keySize >> 3);
}

View File

@@ -0,0 +1,35 @@
import { JWEInvalid, JOSENotSupported } from '../util/errors.js';
import isKeyObject from './is_key_object.js';
const checkCekLength = (enc, cek) => {
let expected;
switch (enc) {
case 'A128CBC-HS256':
case 'A192CBC-HS384':
case 'A256CBC-HS512':
expected = parseInt(enc.slice(-3), 10);
break;
case 'A128GCM':
case 'A192GCM':
case 'A256GCM':
expected = parseInt(enc.slice(1, 4), 10);
break;
default:
throw new JOSENotSupported(`Content Encryption Algorithm ${enc} is not supported either by JOSE or your javascript runtime`);
}
if (cek instanceof Uint8Array) {
const actual = cek.byteLength << 3;
if (actual !== expected) {
throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
}
return;
}
if (isKeyObject(cek) && cek.type === 'secret') {
const actual = cek.symmetricKeySize << 3;
if (actual !== expected) {
throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
}
return;
}
throw new TypeError('Invalid Content Encryption Key type');
};
export default checkCekLength;

View File

@@ -0,0 +1,48 @@
export const weakMap = new WeakMap();
const getLength = (buf, index) => {
let len = buf.readUInt8(1);
if ((len & 0x80) === 0) {
if (index === 0) {
return len;
}
return getLength(buf.subarray(2 + len), index - 1);
}
const num = len & 0x7f;
len = 0;
for (let i = 0; i < num; i++) {
len <<= 8;
const j = buf.readUInt8(2 + i);
len |= j;
}
if (index === 0) {
return len;
}
return getLength(buf.subarray(2 + len), index - 1);
};
const getLengthOfSeqIndex = (sequence, index) => {
const len = sequence.readUInt8(1);
if ((len & 0x80) === 0) {
return getLength(sequence.subarray(2), index);
}
const num = len & 0x7f;
return getLength(sequence.subarray(2 + num), index);
};
const getModulusLength = (key) => {
var _a, _b;
if (weakMap.has(key)) {
return weakMap.get(key);
}
const modulusLength = (_b = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.modulusLength) !== null && _b !== void 0 ? _b : (getLengthOfSeqIndex(key.export({ format: 'der', type: 'pkcs1' }), key.type === 'private' ? 1 : 0) -
1) <<
3;
weakMap.set(key, modulusLength);
return modulusLength;
};
export const setModulusLength = (keyObject, modulusLength) => {
weakMap.set(keyObject, modulusLength);
};
export default (key, alg) => {
if (getModulusLength(key) < 2048) {
throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
}
};

6
node_modules/jose/dist/node/esm/runtime/ciphers.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { getCiphers } from 'crypto';
let ciphers;
export default (algorithm) => {
ciphers || (ciphers = new Set(getCiphers()));
return ciphers.has(algorithm);
};

95
node_modules/jose/dist/node/esm/runtime/decrypt.js generated vendored Normal file
View File

@@ -0,0 +1,95 @@
import { createDecipheriv, KeyObject } from 'crypto';
import checkIvLength from '../lib/check_iv_length.js';
import checkCekLength from './check_cek_length.js';
import { concat } from '../lib/buffer_utils.js';
import { JOSENotSupported, JWEDecryptionFailed } from '../util/errors.js';
import timingSafeEqual from './timing_safe_equal.js';
import cbcTag from './cbc_tag.js';
import { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import isKeyObject from './is_key_object.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import supported from './ciphers.js';
import { types } from './is_key_like.js';
function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
const keySize = parseInt(enc.slice(1, 4), 10);
if (isKeyObject(cek)) {
cek = cek.export();
}
const encKey = cek.subarray(keySize >> 3);
const macKey = cek.subarray(0, keySize >> 3);
const macSize = parseInt(enc.slice(-3), 10);
const algorithm = `aes-${keySize}-cbc`;
if (!supported(algorithm)) {
throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
}
const expectedTag = cbcTag(aad, iv, ciphertext, macSize, macKey, keySize);
let macCheckPassed;
try {
macCheckPassed = timingSafeEqual(tag, expectedTag);
}
catch {
}
if (!macCheckPassed) {
throw new JWEDecryptionFailed();
}
let plaintext;
try {
const decipher = createDecipheriv(algorithm, encKey, iv);
plaintext = concat(decipher.update(ciphertext), decipher.final());
}
catch {
}
if (!plaintext) {
throw new JWEDecryptionFailed();
}
return plaintext;
}
function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {
const keySize = parseInt(enc.slice(1, 4), 10);
const algorithm = `aes-${keySize}-gcm`;
if (!supported(algorithm)) {
throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
}
try {
const decipher = createDecipheriv(algorithm, cek, iv, { authTagLength: 16 });
decipher.setAuthTag(tag);
if (aad.byteLength) {
decipher.setAAD(aad, { plaintextLength: ciphertext.length });
}
const plaintext = decipher.update(ciphertext);
decipher.final();
return plaintext;
}
catch {
throw new JWEDecryptionFailed();
}
}
const decrypt = (enc, cek, ciphertext, iv, tag, aad) => {
let key;
if (isCryptoKey(cek)) {
checkEncCryptoKey(cek, enc, 'decrypt');
key = KeyObject.from(cek);
}
else if (cek instanceof Uint8Array || isKeyObject(cek)) {
key = cek;
}
else {
throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array'));
}
checkCekLength(enc, key);
checkIvLength(enc, iv);
switch (enc) {
case 'A128CBC-HS256':
case 'A192CBC-HS384':
case 'A256CBC-HS512':
return cbcDecrypt(enc, key, ciphertext, iv, tag, aad);
case 'A128GCM':
case 'A192GCM':
case 'A256GCM':
return gcmDecrypt(enc, key, ciphertext, iv, tag, aad);
default:
throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
}
};
export default decrypt;

3
node_modules/jose/dist/node/esm/runtime/digest.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import { createHash } from 'crypto';
const digest = (algorithm, data) => createHash(algorithm).update(data).digest();
export default digest;

22
node_modules/jose/dist/node/esm/runtime/dsa_digest.js generated vendored Normal file
View File

@@ -0,0 +1,22 @@
import { JOSENotSupported } from '../util/errors.js';
export default function dsaDigest(alg) {
switch (alg) {
case 'PS256':
case 'RS256':
case 'ES256':
case 'ES256K':
return 'sha256';
case 'PS384':
case 'RS384':
case 'ES384':
return 'sha384';
case 'PS512':
case 'RS512':
case 'ES512':
return 'sha512';
case 'EdDSA':
return undefined;
default:
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
}
}

64
node_modules/jose/dist/node/esm/runtime/ecdhes.js generated vendored Normal file
View File

@@ -0,0 +1,64 @@
import { diffieHellman, generateKeyPair as generateKeyPairCb, KeyObject } from 'crypto';
import { promisify } from 'util';
import getNamedCurve from './get_named_curve.js';
import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js';
import { JOSENotSupported } from '../util/errors.js';
import { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import isKeyObject from './is_key_object.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
const generateKeyPair = promisify(generateKeyPairCb);
export async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
let publicKey;
if (isCryptoKey(publicKee)) {
checkEncCryptoKey(publicKee, 'ECDH');
publicKey = KeyObject.from(publicKee);
}
else if (isKeyObject(publicKee)) {
publicKey = publicKee;
}
else {
throw new TypeError(invalidKeyInput(publicKee, ...types));
}
let privateKey;
if (isCryptoKey(privateKee)) {
checkEncCryptoKey(privateKee, 'ECDH', 'deriveBits');
privateKey = KeyObject.from(privateKee);
}
else if (isKeyObject(privateKee)) {
privateKey = privateKee;
}
else {
throw new TypeError(invalidKeyInput(privateKee, ...types));
}
const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength));
const sharedSecret = diffieHellman({ privateKey, publicKey });
return concatKdf(sharedSecret, keyLength, value);
}
export async function generateEpk(kee) {
let key;
if (isCryptoKey(kee)) {
key = KeyObject.from(kee);
}
else if (isKeyObject(kee)) {
key = kee;
}
else {
throw new TypeError(invalidKeyInput(kee, ...types));
}
switch (key.asymmetricKeyType) {
case 'x25519':
return generateKeyPair('x25519');
case 'x448': {
return generateKeyPair('x448');
}
case 'ec': {
const namedCurve = getNamedCurve(key);
return generateKeyPair('ec', { namedCurve });
}
default:
throw new JOSENotSupported('Invalid or unsupported EPK');
}
}
export const ecdhAllowed = (key) => ['P-256', 'P-384', 'P-521', 'X25519', 'X448'].includes(getNamedCurve(key));

72
node_modules/jose/dist/node/esm/runtime/encrypt.js generated vendored Normal file
View File

@@ -0,0 +1,72 @@
import { createCipheriv, KeyObject } from 'crypto';
import checkIvLength from '../lib/check_iv_length.js';
import checkCekLength from './check_cek_length.js';
import { concat } from '../lib/buffer_utils.js';
import cbcTag from './cbc_tag.js';
import { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import isKeyObject from './is_key_object.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { JOSENotSupported } from '../util/errors.js';
import supported from './ciphers.js';
import { types } from './is_key_like.js';
function cbcEncrypt(enc, plaintext, cek, iv, aad) {
const keySize = parseInt(enc.slice(1, 4), 10);
if (isKeyObject(cek)) {
cek = cek.export();
}
const encKey = cek.subarray(keySize >> 3);
const macKey = cek.subarray(0, keySize >> 3);
const algorithm = `aes-${keySize}-cbc`;
if (!supported(algorithm)) {
throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
}
const cipher = createCipheriv(algorithm, encKey, iv);
const ciphertext = concat(cipher.update(plaintext), cipher.final());
const macSize = parseInt(enc.slice(-3), 10);
const tag = cbcTag(aad, iv, ciphertext, macSize, macKey, keySize);
return { ciphertext, tag };
}
function gcmEncrypt(enc, plaintext, cek, iv, aad) {
const keySize = parseInt(enc.slice(1, 4), 10);
const algorithm = `aes-${keySize}-gcm`;
if (!supported(algorithm)) {
throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`);
}
const cipher = createCipheriv(algorithm, cek, iv, { authTagLength: 16 });
if (aad.byteLength) {
cipher.setAAD(aad, { plaintextLength: plaintext.length });
}
const ciphertext = cipher.update(plaintext);
cipher.final();
const tag = cipher.getAuthTag();
return { ciphertext, tag };
}
const encrypt = (enc, plaintext, cek, iv, aad) => {
let key;
if (isCryptoKey(cek)) {
checkEncCryptoKey(cek, enc, 'encrypt');
key = KeyObject.from(cek);
}
else if (cek instanceof Uint8Array || isKeyObject(cek)) {
key = cek;
}
else {
throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array'));
}
checkCekLength(enc, key);
checkIvLength(enc, iv);
switch (enc) {
case 'A128CBC-HS256':
case 'A192CBC-HS384':
case 'A256CBC-HS512':
return cbcEncrypt(enc, plaintext, key, iv, aad);
case 'A128GCM':
case 'A192GCM':
case 'A256GCM':
return gcmEncrypt(enc, plaintext, key, iv, aad);
default:
throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
}
};
export default encrypt;

43
node_modules/jose/dist/node/esm/runtime/fetch_jwks.js generated vendored Normal file
View File

@@ -0,0 +1,43 @@
import * as http from 'http';
import * as https from 'https';
import { once } from 'events';
import { JOSEError, JWKSTimeout } from '../util/errors.js';
import { concat, decoder } from '../lib/buffer_utils.js';
const fetchJwks = async (url, timeout, options) => {
let get;
switch (url.protocol) {
case 'https:':
get = https.get;
break;
case 'http:':
get = http.get;
break;
default:
throw new TypeError('Unsupported URL protocol.');
}
const { agent, headers } = options;
const req = get(url.href, {
agent,
timeout,
headers,
});
const [response] = (await Promise.race([once(req, 'response'), once(req, 'timeout')]));
if (!response) {
req.destroy();
throw new JWKSTimeout();
}
if (response.statusCode !== 200) {
throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');
}
const parts = [];
for await (const part of response) {
parts.push(part);
}
try {
return JSON.parse(decoder.decode(concat(...parts)));
}
catch {
throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');
}
};
export default fetchJwks;

5
node_modules/jose/dist/node/esm/runtime/flags.js generated vendored Normal file
View File

@@ -0,0 +1,5 @@
const [major, minor] = process.versions.node.split('.').map((str) => parseInt(str, 10));
export const oneShotCallback = major >= 16 || (major === 15 && minor >= 13);
export const rsaPssParams = !('electron' in process.versions) && (major >= 17 || (major === 16 && minor >= 9));
export const jwkExport = major >= 16 || (major === 15 && minor >= 9);
export const jwkImport = major >= 16 || (major === 15 && minor >= 12);

100
node_modules/jose/dist/node/esm/runtime/generate.js generated vendored Normal file
View File

@@ -0,0 +1,100 @@
import { createSecretKey, generateKeyPair as generateKeyPairCb } from 'crypto';
import { promisify } from 'util';
import random from './random.js';
import { setModulusLength } from './check_modulus_length.js';
import { JOSENotSupported } from '../util/errors.js';
const generate = promisify(generateKeyPairCb);
export async function generateSecret(alg, options) {
let length;
switch (alg) {
case 'HS256':
case 'HS384':
case 'HS512':
case 'A128CBC-HS256':
case 'A192CBC-HS384':
case 'A256CBC-HS512':
length = parseInt(alg.slice(-3), 10);
break;
case 'A128KW':
case 'A192KW':
case 'A256KW':
case 'A128GCMKW':
case 'A192GCMKW':
case 'A256GCMKW':
case 'A128GCM':
case 'A192GCM':
case 'A256GCM':
length = parseInt(alg.slice(1, 4), 10);
break;
default:
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
}
return createSecretKey(random(new Uint8Array(length >> 3)));
}
export async function generateKeyPair(alg, options) {
var _a, _b;
switch (alg) {
case 'RS256':
case 'RS384':
case 'RS512':
case 'PS256':
case 'PS384':
case 'PS512':
case 'RSA-OAEP':
case 'RSA-OAEP-256':
case 'RSA-OAEP-384':
case 'RSA-OAEP-512':
case 'RSA1_5': {
const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048;
if (typeof modulusLength !== 'number' || modulusLength < 2048) {
throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');
}
const keypair = await generate('rsa', {
modulusLength,
publicExponent: 0x10001,
});
setModulusLength(keypair.privateKey, modulusLength);
setModulusLength(keypair.publicKey, modulusLength);
return keypair;
}
case 'ES256':
return generate('ec', { namedCurve: 'P-256' });
case 'ES256K':
return generate('ec', { namedCurve: 'secp256k1' });
case 'ES384':
return generate('ec', { namedCurve: 'P-384' });
case 'ES512':
return generate('ec', { namedCurve: 'P-521' });
case 'EdDSA': {
switch (options === null || options === void 0 ? void 0 : options.crv) {
case undefined:
case 'Ed25519':
return generate('ed25519');
case 'Ed448':
return generate('ed448');
default:
throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448');
}
}
case 'ECDH-ES':
case 'ECDH-ES+A128KW':
case 'ECDH-ES+A192KW':
case 'ECDH-ES+A256KW':
const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : 'P-256';
switch (crv) {
case undefined:
case 'P-256':
case 'P-384':
case 'P-521':
return generate('ec', { namedCurve: crv });
case 'X25519':
return generate('x25519');
case 'X448':
return generate('x448');
default:
throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448');
}
default:
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
}
}

View File

@@ -0,0 +1,91 @@
import { Buffer } from 'buffer';
import { createPublicKey, KeyObject } from 'crypto';
import { JOSENotSupported } from '../util/errors.js';
import { isCryptoKey } from './webcrypto.js';
import isKeyObject from './is_key_object.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
const p256 = Buffer.from([42, 134, 72, 206, 61, 3, 1, 7]);
const p384 = Buffer.from([43, 129, 4, 0, 34]);
const p521 = Buffer.from([43, 129, 4, 0, 35]);
const secp256k1 = Buffer.from([43, 129, 4, 0, 10]);
export const weakMap = new WeakMap();
const namedCurveToJOSE = (namedCurve) => {
switch (namedCurve) {
case 'prime256v1':
return 'P-256';
case 'secp384r1':
return 'P-384';
case 'secp521r1':
return 'P-521';
case 'secp256k1':
return 'secp256k1';
default:
throw new JOSENotSupported('Unsupported key curve for this operation');
}
};
const getNamedCurve = (kee, raw) => {
var _a;
let key;
if (isCryptoKey(kee)) {
key = KeyObject.from(kee);
}
else if (isKeyObject(kee)) {
key = kee;
}
else {
throw new TypeError(invalidKeyInput(kee, ...types));
}
if (key.type === 'secret') {
throw new TypeError('only "private" or "public" type keys can be used for this operation');
}
switch (key.asymmetricKeyType) {
case 'ed25519':
case 'ed448':
return `Ed${key.asymmetricKeyType.slice(2)}`;
case 'x25519':
case 'x448':
return `X${key.asymmetricKeyType.slice(1)}`;
case 'ec': {
if (weakMap.has(key)) {
return weakMap.get(key);
}
let namedCurve = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.namedCurve;
if (!namedCurve && key.type === 'private') {
namedCurve = getNamedCurve(createPublicKey(key), true);
}
else if (!namedCurve) {
const buf = key.export({ format: 'der', type: 'spki' });
const i = buf[1] < 128 ? 14 : 15;
const len = buf[i];
const curveOid = buf.slice(i + 1, i + 1 + len);
if (curveOid.equals(p256)) {
namedCurve = 'prime256v1';
}
else if (curveOid.equals(p384)) {
namedCurve = 'secp384r1';
}
else if (curveOid.equals(p521)) {
namedCurve = 'secp521r1';
}
else if (curveOid.equals(secp256k1)) {
namedCurve = 'secp256k1';
}
else {
throw new JOSENotSupported('Unsupported key curve for this operation');
}
}
if (raw)
return namedCurve;
const curve = namedCurveToJOSE(namedCurve);
weakMap.set(key, curve);
return curve;
}
default:
throw new TypeError('Invalid asymmetric key type for this operation');
}
};
export function setCurve(keyObject, curve) {
weakMap.set(keyObject, curve);
}
export default getNamedCurve;

View File

@@ -0,0 +1,21 @@
import { KeyObject, createSecretKey } from 'crypto';
import { 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';
export default function getSignVerifyKey(alg, key, usage) {
if (key instanceof Uint8Array) {
if (!alg.startsWith('HS')) {
throw new TypeError(invalidKeyInput(key, ...types));
}
return createSecretKey(key);
}
if (key instanceof KeyObject) {
return key;
}
if (isCryptoKey(key)) {
checkSigCryptoKey(key, alg, usage);
return KeyObject.from(key);
}
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
}

13
node_modules/jose/dist/node/esm/runtime/hmac_digest.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { JOSENotSupported } from '../util/errors.js';
export default function hmacDigest(alg) {
switch (alg) {
case 'HS256':
return 'sha256';
case 'HS384':
return 'sha384';
case 'HS512':
return 'sha512';
default:
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
}
}

View File

@@ -0,0 +1,8 @@
import webcrypto, { isCryptoKey } from './webcrypto.js';
import isKeyObject from './is_key_object.js';
export default (key) => isKeyObject(key) || isCryptoKey(key);
const types = ['KeyObject'];
if (globalThis.CryptoKey || (webcrypto === null || webcrypto === void 0 ? void 0 : webcrypto.CryptoKey)) {
types.push('CryptoKey');
}
export { types };

View File

@@ -0,0 +1,5 @@
import { KeyObject } from 'crypto';
import * as util from 'util';
export default util.types.isKeyObject
? (obj) => util.types.isKeyObject(obj)
: (obj) => obj != null && obj instanceof KeyObject;

116
node_modules/jose/dist/node/esm/runtime/jwk_to_key.js generated vendored Normal file
View File

@@ -0,0 +1,116 @@
import { Buffer } from 'buffer';
import { createPrivateKey, createPublicKey, createSecretKey } from 'crypto';
import { decode as base64url } from './base64url.js';
import { JOSENotSupported } from '../util/errors.js';
import { setCurve } from './get_named_curve.js';
import { setModulusLength } from './check_modulus_length.js';
import Asn1SequenceEncoder from './asn1_sequence_encoder.js';
import { jwkImport } from './flags.js';
const parse = (jwk) => {
if (jwkImport && jwk.kty !== 'oct') {
return jwk.d
? createPrivateKey({ format: 'jwk', key: jwk })
: createPublicKey({ format: 'jwk', key: jwk });
}
switch (jwk.kty) {
case 'oct': {
return createSecretKey(base64url(jwk.k));
}
case 'RSA': {
const enc = new Asn1SequenceEncoder();
const isPrivate = jwk.d !== undefined;
const modulus = Buffer.from(jwk.n, 'base64');
const exponent = Buffer.from(jwk.e, 'base64');
if (isPrivate) {
enc.zero();
enc.unsignedInteger(modulus);
enc.unsignedInteger(exponent);
enc.unsignedInteger(Buffer.from(jwk.d, 'base64'));
enc.unsignedInteger(Buffer.from(jwk.p, 'base64'));
enc.unsignedInteger(Buffer.from(jwk.q, 'base64'));
enc.unsignedInteger(Buffer.from(jwk.dp, 'base64'));
enc.unsignedInteger(Buffer.from(jwk.dq, 'base64'));
enc.unsignedInteger(Buffer.from(jwk.qi, 'base64'));
}
else {
enc.unsignedInteger(modulus);
enc.unsignedInteger(exponent);
}
const der = enc.end();
const createInput = {
key: der,
format: 'der',
type: 'pkcs1',
};
const keyObject = isPrivate ? createPrivateKey(createInput) : createPublicKey(createInput);
setModulusLength(keyObject, modulus.length << 3);
return keyObject;
}
case 'EC': {
const enc = new Asn1SequenceEncoder();
const isPrivate = jwk.d !== undefined;
const pub = Buffer.concat([
Buffer.alloc(1, 4),
Buffer.from(jwk.x, 'base64'),
Buffer.from(jwk.y, 'base64'),
]);
if (isPrivate) {
enc.zero();
const enc$1 = new Asn1SequenceEncoder();
enc$1.oidFor('ecPublicKey');
enc$1.oidFor(jwk.crv);
enc.add(enc$1.end());
const enc$2 = new Asn1SequenceEncoder();
enc$2.one();
enc$2.octStr(Buffer.from(jwk.d, 'base64'));
const enc$3 = new Asn1SequenceEncoder();
enc$3.bitStr(pub);
const f2 = enc$3.end(Buffer.from([0xa1]));
enc$2.add(f2);
const f = enc$2.end();
const enc$4 = new Asn1SequenceEncoder();
enc$4.add(f);
const f3 = enc$4.end(Buffer.from([0x04]));
enc.add(f3);
const der = enc.end();
const keyObject = createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });
setCurve(keyObject, jwk.crv);
return keyObject;
}
const enc$1 = new Asn1SequenceEncoder();
enc$1.oidFor('ecPublicKey');
enc$1.oidFor(jwk.crv);
enc.add(enc$1.end());
enc.bitStr(pub);
const der = enc.end();
const keyObject = createPublicKey({ key: der, format: 'der', type: 'spki' });
setCurve(keyObject, jwk.crv);
return keyObject;
}
case 'OKP': {
const enc = new Asn1SequenceEncoder();
const isPrivate = jwk.d !== undefined;
if (isPrivate) {
enc.zero();
const enc$1 = new Asn1SequenceEncoder();
enc$1.oidFor(jwk.crv);
enc.add(enc$1.end());
const enc$2 = new Asn1SequenceEncoder();
enc$2.octStr(Buffer.from(jwk.d, 'base64'));
const f = enc$2.end(Buffer.from([0x04]));
enc.add(f);
const der = enc.end();
return createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });
}
const enc$1 = new Asn1SequenceEncoder();
enc$1.oidFor(jwk.crv);
enc.add(enc$1.end());
enc.bitStr(Buffer.from(jwk.x, 'base64'));
const der = enc.end();
return createPublicKey({ key: der, format: 'der', type: 'spki' });
}
default:
throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
}
};
export default parse;

158
node_modules/jose/dist/node/esm/runtime/key_to_jwk.js generated vendored Normal file
View File

@@ -0,0 +1,158 @@
import { KeyObject, createPublicKey } from 'crypto';
import { encode as base64url } from './base64url.js';
import Asn1SequenceDecoder from './asn1_sequence_decoder.js';
import { JOSENotSupported } from '../util/errors.js';
import getNamedCurve from './get_named_curve.js';
import { isCryptoKey } from './webcrypto.js';
import isKeyObject from './is_key_object.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
import { jwkExport } from './flags.js';
const keyToJWK = (key) => {
let keyObject;
if (isCryptoKey(key)) {
if (!key.extractable) {
throw new TypeError('CryptoKey is not extractable');
}
keyObject = KeyObject.from(key);
}
else if (isKeyObject(key)) {
keyObject = key;
}
else if (key instanceof Uint8Array) {
return {
kty: 'oct',
k: base64url(key),
};
}
else {
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
}
if (jwkExport) {
if (keyObject.type !== 'secret' &&
!['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) {
throw new JOSENotSupported('Unsupported key asymmetricKeyType');
}
return keyObject.export({ format: 'jwk' });
}
switch (keyObject.type) {
case 'secret':
return {
kty: 'oct',
k: base64url(keyObject.export()),
};
case 'private':
case 'public': {
switch (keyObject.asymmetricKeyType) {
case 'rsa': {
const der = keyObject.export({ format: 'der', type: 'pkcs1' });
const dec = new Asn1SequenceDecoder(der);
if (keyObject.type === 'private') {
dec.unsignedInteger();
}
const n = base64url(dec.unsignedInteger());
const e = base64url(dec.unsignedInteger());
let jwk;
if (keyObject.type === 'private') {
jwk = {
d: base64url(dec.unsignedInteger()),
p: base64url(dec.unsignedInteger()),
q: base64url(dec.unsignedInteger()),
dp: base64url(dec.unsignedInteger()),
dq: base64url(dec.unsignedInteger()),
qi: base64url(dec.unsignedInteger()),
};
}
dec.end();
return { kty: 'RSA', n, e, ...jwk };
}
case 'ec': {
const crv = getNamedCurve(keyObject);
let len;
let offset;
let correction;
switch (crv) {
case 'secp256k1':
len = 64;
offset = 31 + 2;
correction = -1;
break;
case 'P-256':
len = 64;
offset = 34 + 2;
correction = -1;
break;
case 'P-384':
len = 96;
offset = 33 + 2;
correction = -3;
break;
case 'P-521':
len = 132;
offset = 33 + 2;
correction = -3;
break;
default:
throw new JOSENotSupported('Unsupported curve');
}
if (keyObject.type === 'public') {
const der = keyObject.export({ type: 'spki', format: 'der' });
return {
kty: 'EC',
crv,
x: base64url(der.subarray(-len, -len / 2)),
y: base64url(der.subarray(-len / 2)),
};
}
const der = keyObject.export({ type: 'pkcs8', format: 'der' });
if (der.length < 100) {
offset += correction;
}
return {
...keyToJWK(createPublicKey(keyObject)),
d: base64url(der.subarray(offset, offset + len / 2)),
};
}
case 'ed25519':
case 'x25519': {
const crv = getNamedCurve(keyObject);
if (keyObject.type === 'public') {
const der = keyObject.export({ type: 'spki', format: 'der' });
return {
kty: 'OKP',
crv,
x: base64url(der.subarray(-32)),
};
}
const der = keyObject.export({ type: 'pkcs8', format: 'der' });
return {
...keyToJWK(createPublicKey(keyObject)),
d: base64url(der.subarray(-32)),
};
}
case 'ed448':
case 'x448': {
const crv = getNamedCurve(keyObject);
if (keyObject.type === 'public') {
const der = keyObject.export({ type: 'spki', format: 'der' });
return {
kty: 'OKP',
crv,
x: base64url(der.subarray(crv === 'Ed448' ? -57 : -56)),
};
}
const der = keyObject.export({ type: 'pkcs8', format: 'der' });
return {
...keyToJWK(createPublicKey(keyObject)),
d: base64url(der.subarray(crv === 'Ed448' ? -57 : -56)),
};
}
default:
throw new JOSENotSupported('Unsupported key asymmetricKeyType');
}
}
default:
throw new JOSENotSupported('Unsupported key type');
}
};
export default keyToJWK;

75
node_modules/jose/dist/node/esm/runtime/node_key.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
import { constants } from 'crypto';
import getNamedCurve from './get_named_curve.js';
import { JOSENotSupported } from '../util/errors.js';
import checkModulusLength from './check_modulus_length.js';
import { rsaPssParams } from './flags.js';
const PSS = {
padding: constants.RSA_PKCS1_PSS_PADDING,
saltLength: constants.RSA_PSS_SALTLEN_DIGEST,
};
const ecCurveAlgMap = new Map([
['ES256', 'P-256'],
['ES256K', 'secp256k1'],
['ES384', 'P-384'],
['ES512', 'P-521'],
]);
export default function keyForCrypto(alg, key) {
switch (alg) {
case 'EdDSA':
if (!['ed25519', 'ed448'].includes(key.asymmetricKeyType)) {
throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448');
}
return key;
case 'RS256':
case 'RS384':
case 'RS512':
if (key.asymmetricKeyType !== 'rsa') {
throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');
}
checkModulusLength(key, alg);
return key;
case rsaPssParams && 'PS256':
case rsaPssParams && 'PS384':
case rsaPssParams && 'PS512':
if (key.asymmetricKeyType === 'rsa-pss') {
const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails;
const length = parseInt(alg.slice(-3), 10);
if (hashAlgorithm !== undefined &&
(hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) {
throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`);
}
if (saltLength !== undefined && saltLength > length >> 3) {
throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`);
}
}
else if (key.asymmetricKeyType !== 'rsa') {
throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss');
}
checkModulusLength(key, alg);
return { key, ...PSS };
case !rsaPssParams && 'PS256':
case !rsaPssParams && 'PS384':
case !rsaPssParams && 'PS512':
if (key.asymmetricKeyType !== 'rsa') {
throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');
}
checkModulusLength(key, alg);
return { key, ...PSS };
case 'ES256':
case 'ES256K':
case 'ES384':
case 'ES512': {
if (key.asymmetricKeyType !== 'ec') {
throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be ec');
}
const actual = getNamedCurve(key);
const expected = ecCurveAlgMap.get(alg);
if (actual !== expected) {
throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`);
}
return { dsaEncoding: 'ieee-p1363', key };
}
default:
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
}
}

43
node_modules/jose/dist/node/esm/runtime/pbes2kw.js generated vendored Normal file
View File

@@ -0,0 +1,43 @@
import { promisify } from 'util';
import { KeyObject, pbkdf2 as pbkdf2cb } from 'crypto';
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 { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import isKeyObject from './is_key_object.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
const pbkdf2 = promisify(pbkdf2cb);
function getPassword(key, alg) {
if (isKeyObject(key)) {
return key.export();
}
if (key instanceof Uint8Array) {
return key;
}
if (isCryptoKey(key)) {
checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey');
return KeyObject.from(key).export();
}
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
}
export const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => {
checkP2s(p2s);
const salt = concatSalt(alg, p2s);
const keylen = parseInt(alg.slice(13, 16), 10) >> 3;
const password = getPassword(key, alg);
const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`);
const encryptedKey = await wrap(alg.slice(-6), derivedKey, cek);
return { encryptedKey, p2c, p2s: base64url(p2s) };
};
export const decrypt = async (alg, key, encryptedKey, p2c, p2s) => {
checkP2s(p2s);
const salt = concatSalt(alg, p2s);
const keylen = parseInt(alg.slice(13, 16), 10) >> 3;
const password = getPassword(key, alg);
const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`);
return unwrap(alg.slice(-6), derivedKey, encryptedKey);
};

1
node_modules/jose/dist/node/esm/runtime/random.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export { randomFillSync as default } from 'crypto';

64
node_modules/jose/dist/node/esm/runtime/rsaes.js generated vendored Normal file
View File

@@ -0,0 +1,64 @@
import { KeyObject, publicEncrypt, constants, privateDecrypt } from 'crypto';
import checkModulusLength from './check_modulus_length.js';
import { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import isKeyObject from './is_key_object.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
const checkKey = (key, alg) => {
if (key.asymmetricKeyType !== 'rsa') {
throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');
}
checkModulusLength(key, alg);
};
const resolvePadding = (alg) => {
switch (alg) {
case 'RSA-OAEP':
case 'RSA-OAEP-256':
case 'RSA-OAEP-384':
case 'RSA-OAEP-512':
return constants.RSA_PKCS1_OAEP_PADDING;
case 'RSA1_5':
return constants.RSA_PKCS1_PADDING;
default:
return undefined;
}
};
const resolveOaepHash = (alg) => {
switch (alg) {
case 'RSA-OAEP':
return 'sha1';
case 'RSA-OAEP-256':
return 'sha256';
case 'RSA-OAEP-384':
return 'sha384';
case 'RSA-OAEP-512':
return 'sha512';
default:
return undefined;
}
};
function ensureKeyObject(key, alg, ...usages) {
if (isKeyObject(key)) {
return key;
}
if (isCryptoKey(key)) {
checkEncCryptoKey(key, alg, ...usages);
return KeyObject.from(key);
}
throw new TypeError(invalidKeyInput(key, ...types));
}
export const encrypt = (alg, key, cek) => {
const padding = resolvePadding(alg);
const oaepHash = resolveOaepHash(alg);
const keyObject = ensureKeyObject(key, alg, 'wrapKey', 'encrypt');
checkKey(keyObject, alg);
return publicEncrypt({ key: keyObject, oaepHash, padding }, cek);
};
export const decrypt = (alg, key, encryptedKey) => {
const padding = resolvePadding(alg);
const oaepHash = resolveOaepHash(alg);
const keyObject = ensureKeyObject(key, alg, 'unwrapKey', 'decrypt');
checkKey(keyObject, alg);
return privateDecrypt({ key: keyObject, oaepHash, padding }, encryptedKey);
};

1
node_modules/jose/dist/node/esm/runtime/runtime.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export default 'node:crypto';

23
node_modules/jose/dist/node/esm/runtime/sign.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import * as crypto from 'crypto';
import { promisify } from 'util';
import nodeDigest from './dsa_digest.js';
import hmacDigest from './hmac_digest.js';
import nodeKey from './node_key.js';
import getSignKey from './get_sign_verify_key.js';
let oneShotSign;
if (crypto.sign.length > 3) {
oneShotSign = promisify(crypto.sign);
}
else {
oneShotSign = crypto.sign;
}
const sign = async (alg, key, data) => {
const keyObject = getSignKey(alg, key, 'sign');
if (alg.startsWith('HS')) {
const hmac = crypto.createHmac(hmacDigest(alg), keyObject);
hmac.update(data);
return hmac.digest();
}
return oneShotSign(nodeDigest(alg), data, nodeKey(alg, keyObject));
};
export default sign;

View File

@@ -0,0 +1,3 @@
import { timingSafeEqual as impl } from 'crypto';
const timingSafeEqual = impl;
export default timingSafeEqual;

36
node_modules/jose/dist/node/esm/runtime/verify.js generated vendored Normal file
View File

@@ -0,0 +1,36 @@
import * as crypto from 'crypto';
import { promisify } from 'util';
import nodeDigest from './dsa_digest.js';
import nodeKey from './node_key.js';
import sign from './sign.js';
import getVerifyKey from './get_sign_verify_key.js';
import { oneShotCallback } from './flags.js';
let oneShotVerify;
if (crypto.verify.length > 4 && oneShotCallback) {
oneShotVerify = promisify(crypto.verify);
}
else {
oneShotVerify = crypto.verify;
}
const verify = async (alg, key, signature, data) => {
const keyObject = getVerifyKey(alg, key, 'verify');
if (alg.startsWith('HS')) {
const expected = await sign(alg, keyObject, data);
const actual = signature;
try {
return crypto.timingSafeEqual(actual, expected);
}
catch {
return false;
}
}
const algorithm = nodeDigest(alg);
const keyInput = nodeKey(alg, keyObject);
try {
return await oneShotVerify(algorithm, data, keyInput, signature);
}
catch {
return false;
}
};
export default verify;

8
node_modules/jose/dist/node/esm/runtime/webcrypto.js generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import * as crypto from 'crypto';
import * as util from 'util';
const webcrypto = crypto.webcrypto;
export default webcrypto;
export const isCryptoKey = util.types.isCryptoKey
? (key) => util.types.isCryptoKey(key)
:
(key) => false;

9
node_modules/jose/dist/node/esm/runtime/zlib.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import { promisify } from 'util';
import { inflateRaw as inflateRawCb, deflateRaw as deflateRawCb } from 'zlib';
import { JWEDecompressionFailed } from '../util/errors.js';
const inflateRaw = promisify(inflateRawCb);
const deflateRaw = promisify(deflateRawCb);
export const inflate = (input) => inflateRaw(input, { maxOutputLength: 250000 }).catch(() => {
throw new JWEDecompressionFailed();
});
export const deflate = (input) => deflateRaw(input);

3
node_modules/jose/dist/node/esm/util/base64url.js generated vendored Normal file
View 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/node/esm/util/decode_jwt.js generated vendored Normal file
View 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;
}

View 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');
}
}

158
node_modules/jose/dist/node/esm/util/errors.js generated vendored Normal file
View File

@@ -0,0 +1,158 @@
export class JOSEError extends Error {
static get code() {
return 'ERR_JOSE_GENERIC';
}
constructor(message) {
var _a;
super(message);
this.code = 'ERR_JOSE_GENERIC';
this.name = this.constructor.name;
(_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, this.constructor);
}
}
export class JWTClaimValidationFailed extends JOSEError {
static get code() {
return 'ERR_JWT_CLAIM_VALIDATION_FAILED';
}
constructor(message, claim = 'unspecified', reason = 'unspecified') {
super(message);
this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
this.claim = claim;
this.reason = reason;
}
}
export class JWTExpired extends JOSEError {
static get code() {
return 'ERR_JWT_EXPIRED';
}
constructor(message, claim = 'unspecified', reason = 'unspecified') {
super(message);
this.code = 'ERR_JWT_EXPIRED';
this.claim = claim;
this.reason = reason;
}
}
export class JOSEAlgNotAllowed extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JOSE_ALG_NOT_ALLOWED';
}
static get code() {
return 'ERR_JOSE_ALG_NOT_ALLOWED';
}
}
export class JOSENotSupported extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JOSE_NOT_SUPPORTED';
}
static get code() {
return 'ERR_JOSE_NOT_SUPPORTED';
}
}
export class JWEDecryptionFailed extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWE_DECRYPTION_FAILED';
this.message = 'decryption operation failed';
}
static get code() {
return 'ERR_JWE_DECRYPTION_FAILED';
}
}
export class JWEDecompressionFailed extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWE_DECOMPRESSION_FAILED';
this.message = 'decompression operation failed';
}
static get code() {
return 'ERR_JWE_DECOMPRESSION_FAILED';
}
}
export class JWEInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWE_INVALID';
}
static get code() {
return 'ERR_JWE_INVALID';
}
}
export class JWSInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWS_INVALID';
}
static get code() {
return 'ERR_JWS_INVALID';
}
}
export class JWTInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWT_INVALID';
}
static get code() {
return 'ERR_JWT_INVALID';
}
}
export class JWKInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWK_INVALID';
}
static get code() {
return 'ERR_JWK_INVALID';
}
}
export class JWKSInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWKS_INVALID';
}
static get code() {
return 'ERR_JWKS_INVALID';
}
}
export class JWKSNoMatchingKey extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWKS_NO_MATCHING_KEY';
this.message = 'no applicable key found in the JSON Web Key Set';
}
static get code() {
return 'ERR_JWKS_NO_MATCHING_KEY';
}
}
export class JWKSMultipleMatchingKeys extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
this.message = 'multiple matching keys found in the JSON Web Key Set';
}
static get code() {
return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
}
}
Symbol.asyncIterator;
export class JWKSTimeout extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWKS_TIMEOUT';
this.message = 'request timed out';
}
static get code() {
return 'ERR_JWKS_TIMEOUT';
}
}
export class JWSSignatureVerificationFailed extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
this.message = 'signature verification failed';
}
static get code() {
return 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
}
}

2
node_modules/jose/dist/node/esm/util/runtime.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import value from '../runtime/runtime.js';
export default value;