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

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

@@ -0,0 +1,32 @@
export { compactDecrypt } from './jwe/compact/decrypt.js';
export { flattenedDecrypt } from './jwe/flattened/decrypt.js';
export { generalDecrypt } from './jwe/general/decrypt.js';
export { GeneralEncrypt } from './jwe/general/encrypt.js';
export { compactVerify } from './jws/compact/verify.js';
export { flattenedVerify } from './jws/flattened/verify.js';
export { generalVerify } from './jws/general/verify.js';
export { jwtVerify } from './jwt/verify.js';
export { jwtDecrypt } from './jwt/decrypt.js';
export { CompactEncrypt } from './jwe/compact/encrypt.js';
export { FlattenedEncrypt } from './jwe/flattened/encrypt.js';
export { CompactSign } from './jws/compact/sign.js';
export { FlattenedSign } from './jws/flattened/sign.js';
export { GeneralSign } from './jws/general/sign.js';
export { SignJWT } from './jwt/sign.js';
export { EncryptJWT } from './jwt/encrypt.js';
export { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js';
export { EmbeddedJWK } from './jwk/embedded.js';
export { createLocalJWKSet } from './jwks/local.js';
export { createRemoteJWKSet } from './jwks/remote.js';
export { UnsecuredJWT } from './jwt/unsecured.js';
export { exportPKCS8, exportSPKI, exportJWK } from './key/export.js';
export { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js';
export { decodeProtectedHeader } from './util/decode_protected_header.js';
export { decodeJwt } from './util/decode_jwt.js';
import * as errors_1 from './util/errors.js';
export { errors_1 as errors };
export { generateKeyPair } from './key/generate_key_pair.js';
export { generateSecret } from './key/generate_secret.js';
import * as base64url_1 from './util/base64url.js';
export { base64url_1 as base64url };
export { default as cryptoRuntime } from './util/runtime.js';

27
node_modules/jose/dist/browser/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/browser/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('.');
}
}

166
node_modules/jose/dist/browser/jwe/flattened/decrypt.js generated vendored Normal file
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 (_b) {
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 (_c) {
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 (_d) {
throw new JWEInvalid('Failed to base64url decode the iv');
}
try {
tag = base64url(jwe.tag);
}
catch (_e) {
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 (_f) {
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 (_g) {
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;
}

175
node_modules/jose/dist/browser/jwe/flattened/encrypt.js generated vendored Normal file
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/browser/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 (_a) {
}
}
throw new JWEDecryptionFailed();
}

178
node_modules/jose/dist/browser/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/browser/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/browser/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/browser/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 (_a) {
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/browser/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/browser/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/browser/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/browser/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/browser/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 (_b) {
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 (_c) {
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 (_d) {
throw new JWSInvalid('Failed to base64url decode the payload');
}
}
else if (typeof jws.payload === 'string') {
payload = encoder.encode(jws.payload);
}
else {
payload = jws.payload;
}
const result = { payload };
if (jws.protected !== undefined) {
result.protectedHeader = parsedProt;
}
if (jws.header !== undefined) {
result.unprotectedHeader = jws.header;
}
if (resolvedKey) {
return { ...result, key };
}
return result;
}

67
node_modules/jose/dist/browser/jws/general/sign.js generated vendored Normal file
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/browser/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 (_a) {
}
}
throw new JWSSignatureVerificationFailed();
}

23
node_modules/jose/dist/browser/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/browser/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/browser/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/browser/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/browser/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 (_a) {
throw new JWTInvalid('Invalid Unsecured JWT');
}
const payload = jwtPayload(header, base64url.decode(encodedPayload), options);
return { payload, header };
}
}

16
node_modules/jose/dist/browser/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/browser/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/browser/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/browser/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/browser/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/browser/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/browser/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/browser/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/browser/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 (_a) {
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 (_b) {
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 (_c) {
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 (_d) {
throw new JWEInvalid('Failed to base64url decode the iv');
}
let tag;
try {
tag = base64url(joseHeader.tag);
}
catch (_e) {
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/browser/lib/epoch.js generated vendored Normal file
View File

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

4
node_modules/jose/dist/browser/lib/format_pem.js generated vendored Normal file
View File

@@ -0,0 +1,4 @@
export default (b64, descriptor) => {
const newlined = (b64.match(/.{1,64}/g) || []).join('\n');
return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`;
};

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/browser/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/browser/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/browser/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/browser/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 (_a) {
}
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/browser/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/browser/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/browser/package.json generated vendored Normal file
View File

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

32
node_modules/jose/dist/browser/runtime/aeskw.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
import bogusWebCrypto from './bogus.js';
import crypto, { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
function checkKeySize(key, alg) {
if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {
throw new TypeError(`Invalid key size for alg: ${alg}`);
}
}
function getCryptoKey(key, alg, usage) {
if (isCryptoKey(key)) {
checkEncCryptoKey(key, alg, usage);
return key;
}
if (key instanceof Uint8Array) {
return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]);
}
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
}
export const wrap = async (alg, key, cek) => {
const cryptoKey = await getCryptoKey(key, alg, 'wrapKey');
checkKeySize(cryptoKey, alg);
const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto);
return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW'));
};
export const unwrap = async (alg, key, encryptedKey) => {
const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey');
checkKeySize(cryptoKey, alg);
const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', ...bogusWebCrypto);
return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));
};

202
node_modules/jose/dist/browser/runtime/asn1.js generated vendored Normal file
View File

@@ -0,0 +1,202 @@
import crypto, { isCryptoKey } from './webcrypto.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { encodeBase64, decodeBase64 } from './base64url.js';
import formatPEM from '../lib/format_pem.js';
import { JOSENotSupported } from '../util/errors.js';
import { types } from './is_key_like.js';
const genericExport = async (keyType, keyFormat, key) => {
if (!isCryptoKey(key)) {
throw new TypeError(invalidKeyInput(key, ...types));
}
if (!key.extractable) {
throw new TypeError('CryptoKey is not extractable');
}
if (key.type !== keyType) {
throw new TypeError(`key is not a ${keyType} key`);
}
return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
};
export const toSPKI = (key) => {
return genericExport('public', 'spki', key);
};
export const toPKCS8 = (key) => {
return genericExport('private', 'pkcs8', key);
};
const findOid = (keyData, oid, from = 0) => {
if (from === 0) {
oid.unshift(oid.length);
oid.unshift(0x06);
}
let i = keyData.indexOf(oid[0], from);
if (i === -1)
return false;
const sub = keyData.subarray(i, i + oid.length);
if (sub.length !== oid.length)
return false;
return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1);
};
const getNamedCurve = (keyData) => {
switch (true) {
case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]):
return 'P-256';
case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]):
return 'P-384';
case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]):
return 'P-521';
case findOid(keyData, [0x2b, 0x65, 0x6e]):
return 'X25519';
case findOid(keyData, [0x2b, 0x65, 0x6f]):
return 'X448';
case findOid(keyData, [0x2b, 0x65, 0x70]):
return 'Ed25519';
case findOid(keyData, [0x2b, 0x65, 0x71]):
return 'Ed448';
default:
throw new JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type');
}
};
const genericImport = async (replace, keyFormat, pem, alg, options) => {
var _a;
let algorithm;
let keyUsages;
const keyData = new Uint8Array(atob(pem.replace(replace, ''))
.split('')
.map((c) => c.charCodeAt(0)));
const isPublic = keyFormat === 'spki';
switch (alg) {
case 'PS256':
case 'PS384':
case 'PS512':
algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };
keyUsages = isPublic ? ['verify'] : ['sign'];
break;
case 'RS256':
case 'RS384':
case 'RS512':
algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };
keyUsages = isPublic ? ['verify'] : ['sign'];
break;
case 'RSA-OAEP':
case 'RSA-OAEP-256':
case 'RSA-OAEP-384':
case 'RSA-OAEP-512':
algorithm = {
name: 'RSA-OAEP',
hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
};
keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'];
break;
case 'ES256':
algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
keyUsages = isPublic ? ['verify'] : ['sign'];
break;
case 'ES384':
algorithm = { name: 'ECDSA', namedCurve: 'P-384' };
keyUsages = isPublic ? ['verify'] : ['sign'];
break;
case 'ES512':
algorithm = { name: 'ECDSA', namedCurve: 'P-521' };
keyUsages = isPublic ? ['verify'] : ['sign'];
break;
case 'ECDH-ES':
case 'ECDH-ES+A128KW':
case 'ECDH-ES+A192KW':
case 'ECDH-ES+A256KW': {
const namedCurve = getNamedCurve(keyData);
algorithm = namedCurve.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: namedCurve };
keyUsages = isPublic ? [] : ['deriveBits'];
break;
}
case 'EdDSA':
algorithm = { name: getNamedCurve(keyData) };
keyUsages = isPublic ? ['verify'] : ['sign'];
break;
default:
throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
}
return crypto.subtle.importKey(keyFormat, keyData, algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages);
};
export const fromPKCS8 = (pem, alg, options) => {
return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, 'pkcs8', pem, alg, options);
};
export const fromSPKI = (pem, alg, options) => {
return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, 'spki', pem, alg, options);
};
function getElement(seq) {
let result = [];
let next = 0;
while (next < seq.length) {
let nextPart = parseElement(seq.subarray(next));
result.push(nextPart);
next += nextPart.byteLength;
}
return result;
}
function parseElement(bytes) {
let position = 0;
let tag = bytes[0] & 0x1f;
position++;
if (tag === 0x1f) {
tag = 0;
while (bytes[position] >= 0x80) {
tag = tag * 128 + bytes[position] - 0x80;
position++;
}
tag = tag * 128 + bytes[position] - 0x80;
position++;
}
let length = 0;
if (bytes[position] < 0x80) {
length = bytes[position];
position++;
}
else if (length === 0x80) {
length = 0;
while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) {
if (length > bytes.byteLength) {
throw new TypeError('invalid indefinite form length');
}
length++;
}
const byteLength = position + length + 2;
return {
byteLength,
contents: bytes.subarray(position, position + length),
raw: bytes.subarray(0, byteLength),
};
}
else {
let numberOfDigits = bytes[position] & 0x7f;
position++;
length = 0;
for (let i = 0; i < numberOfDigits; i++) {
length = length * 256 + bytes[position];
position++;
}
}
const byteLength = position + length;
return {
byteLength,
contents: bytes.subarray(position, byteLength),
raw: bytes.subarray(0, byteLength),
};
}
function spkiFromX509(buf) {
const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents);
return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw);
}
function getSPKI(x509) {
const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g, '');
const raw = decodeBase64(pem);
return formatPEM(spkiFromX509(raw), 'PUBLIC KEY');
}
export const fromX509 = (pem, alg, options) => {
let spki;
try {
spki = getSPKI(pem);
}
catch (cause) {
throw new TypeError('Failed to parse the X.509 certificate', { cause });
}
return fromSPKI(spki, alg, options);
};

37
node_modules/jose/dist/browser/runtime/base64url.js generated vendored Normal file
View File

@@ -0,0 +1,37 @@
import { encoder, decoder } from '../lib/buffer_utils.js';
export const encodeBase64 = (input) => {
let unencoded = input;
if (typeof unencoded === 'string') {
unencoded = encoder.encode(unencoded);
}
const CHUNK_SIZE = 0x8000;
const arr = [];
for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {
arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));
}
return btoa(arr.join(''));
};
export const encode = (input) => {
return encodeBase64(input).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
};
export const decodeBase64 = (encoded) => {
const binary = atob(encoded);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
};
export const decode = (input) => {
let encoded = input;
if (encoded instanceof Uint8Array) {
encoded = decoder.decode(encoded);
}
encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
try {
return decodeBase64(encoded);
}
catch (_a) {
throw new TypeError('The input to be decoded is not correctly encoded.');
}
};

6
node_modules/jose/dist/browser/runtime/bogus.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
const bogusWebCrypto = [
{ hash: 'SHA-256', name: 'HMAC' },
true,
['sign'],
];
export default bogusWebCrypto;

View File

@@ -0,0 +1,8 @@
import { JWEInvalid } from '../util/errors.js';
const checkCekLength = (cek, expected) => {
const actual = cek.byteLength << 3;
if (actual !== expected) {
throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
}
};
export default checkCekLength;

View File

@@ -0,0 +1,8 @@
export default (alg, key) => {
if (alg.startsWith('RS') || alg.startsWith('PS')) {
const { modulusLength } = key.algorithm;
if (typeof modulusLength !== 'number' || modulusLength < 2048) {
throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
}
}
};

85
node_modules/jose/dist/browser/runtime/decrypt.js generated vendored Normal file
View File

@@ -0,0 +1,85 @@
import { concat, uint64be } from '../lib/buffer_utils.js';
import checkIvLength from '../lib/check_iv_length.js';
import checkCekLength from './check_cek_length.js';
import timingSafeEqual from './timing_safe_equal.js';
import { JOSENotSupported, JWEDecryptionFailed } from '../util/errors.js';
import crypto, { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
if (!(cek instanceof Uint8Array)) {
throw new TypeError(invalidKeyInput(cek, 'Uint8Array'));
}
const keySize = parseInt(enc.slice(1, 4), 10);
const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['decrypt']);
const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {
hash: `SHA-${keySize << 1}`,
name: 'HMAC',
}, false, ['sign']);
const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
const expectedTag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));
let macCheckPassed;
try {
macCheckPassed = timingSafeEqual(tag, expectedTag);
}
catch (_a) {
}
if (!macCheckPassed) {
throw new JWEDecryptionFailed();
}
let plaintext;
try {
plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext));
}
catch (_b) {
}
if (!plaintext) {
throw new JWEDecryptionFailed();
}
return plaintext;
}
async function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {
let encKey;
if (cek instanceof Uint8Array) {
encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']);
}
else {
checkEncCryptoKey(cek, enc, 'decrypt');
encKey = cek;
}
try {
return new Uint8Array(await crypto.subtle.decrypt({
additionalData: aad,
iv,
name: 'AES-GCM',
tagLength: 128,
}, encKey, concat(ciphertext, tag)));
}
catch (_a) {
throw new JWEDecryptionFailed();
}
}
const decrypt = async (enc, cek, ciphertext, iv, tag, aad) => {
if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array'));
}
checkIvLength(enc, iv);
switch (enc) {
case 'A128CBC-HS256':
case 'A192CBC-HS384':
case 'A256CBC-HS512':
if (cek instanceof Uint8Array)
checkCekLength(cek, parseInt(enc.slice(-3), 10));
return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad);
case 'A128GCM':
case 'A192GCM':
case 'A256GCM':
if (cek instanceof Uint8Array)
checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad);
default:
throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
}
};
export default decrypt;

6
node_modules/jose/dist/browser/runtime/digest.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import crypto from './webcrypto.js';
const digest = async (algorithm, data) => {
const subtleDigest = `SHA-${algorithm.slice(-3)}`;
return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
};
export default digest;

46
node_modules/jose/dist/browser/runtime/ecdhes.js generated vendored Normal file
View File

@@ -0,0 +1,46 @@
import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js';
import crypto, { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
export async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
if (!isCryptoKey(publicKey)) {
throw new TypeError(invalidKeyInput(publicKey, ...types));
}
checkEncCryptoKey(publicKey, 'ECDH');
if (!isCryptoKey(privateKey)) {
throw new TypeError(invalidKeyInput(privateKey, ...types));
}
checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits');
const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength));
let length;
if (publicKey.algorithm.name === 'X25519') {
length = 256;
}
else if (publicKey.algorithm.name === 'X448') {
length = 448;
}
else {
length =
Math.ceil(parseInt(publicKey.algorithm.namedCurve.substr(-3), 10) / 8) << 3;
}
const sharedSecret = new Uint8Array(await crypto.subtle.deriveBits({
name: publicKey.algorithm.name,
public: publicKey,
}, privateKey, length));
return concatKdf(sharedSecret, keyLength, value);
}
export async function generateEpk(key) {
if (!isCryptoKey(key)) {
throw new TypeError(invalidKeyInput(key, ...types));
}
return crypto.subtle.generateKey(key.algorithm, true, ['deriveBits']);
}
export function ecdhAllowed(key) {
if (!isCryptoKey(key)) {
throw new TypeError(invalidKeyInput(key, ...types));
}
return (['P-256', 'P-384', 'P-521'].includes(key.algorithm.namedCurve) ||
key.algorithm.name === 'X25519' ||
key.algorithm.name === 'X448');
}

68
node_modules/jose/dist/browser/runtime/encrypt.js generated vendored Normal file
View File

@@ -0,0 +1,68 @@
import { concat, uint64be } from '../lib/buffer_utils.js';
import checkIvLength from '../lib/check_iv_length.js';
import checkCekLength from './check_cek_length.js';
import crypto, { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { JOSENotSupported } from '../util/errors.js';
import { types } from './is_key_like.js';
async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
if (!(cek instanceof Uint8Array)) {
throw new TypeError(invalidKeyInput(cek, 'Uint8Array'));
}
const keySize = parseInt(enc.slice(1, 4), 10);
const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['encrypt']);
const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {
hash: `SHA-${keySize << 1}`,
name: 'HMAC',
}, false, ['sign']);
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
iv,
name: 'AES-CBC',
}, encKey, plaintext));
const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
const tag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));
return { ciphertext, tag };
}
async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
let encKey;
if (cek instanceof Uint8Array) {
encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);
}
else {
checkEncCryptoKey(cek, enc, 'encrypt');
encKey = cek;
}
const encrypted = new Uint8Array(await crypto.subtle.encrypt({
additionalData: aad,
iv,
name: 'AES-GCM',
tagLength: 128,
}, encKey, plaintext));
const tag = encrypted.slice(-16);
const ciphertext = encrypted.slice(0, -16);
return { ciphertext, tag };
}
const encrypt = async (enc, plaintext, cek, iv, aad) => {
if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array'));
}
checkIvLength(enc, iv);
switch (enc) {
case 'A128CBC-HS256':
case 'A192CBC-HS384':
case 'A256CBC-HS512':
if (cek instanceof Uint8Array)
checkCekLength(cek, parseInt(enc.slice(-3), 10));
return cbcEncrypt(enc, plaintext, cek, iv, aad);
case 'A128GCM':
case 'A192GCM':
case 'A256GCM':
if (cek instanceof Uint8Array)
checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
return gcmEncrypt(enc, plaintext, cek, iv, aad);
default:
throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
}
};
export default encrypt;

34
node_modules/jose/dist/browser/runtime/fetch_jwks.js generated vendored Normal file
View File

@@ -0,0 +1,34 @@
import { JOSEError, JWKSTimeout } from '../util/errors.js';
const fetchJwks = async (url, timeout, options) => {
let controller;
let id;
let timedOut = false;
if (typeof AbortController === 'function') {
controller = new AbortController();
id = setTimeout(() => {
timedOut = true;
controller.abort();
}, timeout);
}
const response = await fetch(url.href, {
signal: controller ? controller.signal : undefined,
redirect: 'manual',
headers: options.headers,
}).catch((err) => {
if (timedOut)
throw new JWKSTimeout();
throw err;
});
if (id !== undefined)
clearTimeout(id);
if (response.status !== 200) {
throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');
}
try {
return await response.json();
}
catch (_a) {
throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');
}
};
export default fetchJwks;

141
node_modules/jose/dist/browser/runtime/generate.js generated vendored Normal file
View File

@@ -0,0 +1,141 @@
import crypto from './webcrypto.js';
import { JOSENotSupported } from '../util/errors.js';
import random from './random.js';
export async function generateSecret(alg, options) {
var _a;
let length;
let algorithm;
let keyUsages;
switch (alg) {
case 'HS256':
case 'HS384':
case 'HS512':
length = parseInt(alg.slice(-3), 10);
algorithm = { name: 'HMAC', hash: `SHA-${length}`, length };
keyUsages = ['sign', 'verify'];
break;
case 'A128CBC-HS256':
case 'A192CBC-HS384':
case 'A256CBC-HS512':
length = parseInt(alg.slice(-3), 10);
return random(new Uint8Array(length >> 3));
case 'A128KW':
case 'A192KW':
case 'A256KW':
length = parseInt(alg.slice(1, 4), 10);
algorithm = { name: 'AES-KW', length };
keyUsages = ['wrapKey', 'unwrapKey'];
break;
case 'A128GCMKW':
case 'A192GCMKW':
case 'A256GCMKW':
case 'A128GCM':
case 'A192GCM':
case 'A256GCM':
length = parseInt(alg.slice(1, 4), 10);
algorithm = { name: 'AES-GCM', length };
keyUsages = ['encrypt', 'decrypt'];
break;
default:
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
}
return crypto.subtle.generateKey(algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages);
}
function getModulusLengthOption(options) {
var _a;
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');
}
return modulusLength;
}
export async function generateKeyPair(alg, options) {
var _a, _b, _c;
let algorithm;
let keyUsages;
switch (alg) {
case 'PS256':
case 'PS384':
case 'PS512':
algorithm = {
name: 'RSA-PSS',
hash: `SHA-${alg.slice(-3)}`,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
modulusLength: getModulusLengthOption(options),
};
keyUsages = ['sign', 'verify'];
break;
case 'RS256':
case 'RS384':
case 'RS512':
algorithm = {
name: 'RSASSA-PKCS1-v1_5',
hash: `SHA-${alg.slice(-3)}`,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
modulusLength: getModulusLengthOption(options),
};
keyUsages = ['sign', 'verify'];
break;
case 'RSA-OAEP':
case 'RSA-OAEP-256':
case 'RSA-OAEP-384':
case 'RSA-OAEP-512':
algorithm = {
name: 'RSA-OAEP',
hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
modulusLength: getModulusLengthOption(options),
};
keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey'];
break;
case 'ES256':
algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
keyUsages = ['sign', 'verify'];
break;
case 'ES384':
algorithm = { name: 'ECDSA', namedCurve: 'P-384' };
keyUsages = ['sign', 'verify'];
break;
case 'ES512':
algorithm = { name: 'ECDSA', namedCurve: 'P-521' };
keyUsages = ['sign', 'verify'];
break;
case 'EdDSA':
keyUsages = ['sign', 'verify'];
const crv = (_a = options === null || options === void 0 ? void 0 : options.crv) !== null && _a !== void 0 ? _a : 'Ed25519';
switch (crv) {
case 'Ed25519':
case 'Ed448':
algorithm = { name: crv };
break;
default:
throw new JOSENotSupported('Invalid or unsupported crv option provided');
}
break;
case 'ECDH-ES':
case 'ECDH-ES+A128KW':
case 'ECDH-ES+A192KW':
case 'ECDH-ES+A256KW': {
keyUsages = ['deriveKey', 'deriveBits'];
const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : 'P-256';
switch (crv) {
case 'P-256':
case 'P-384':
case 'P-521': {
algorithm = { name: 'ECDH', namedCurve: crv };
break;
}
case 'X25519':
case 'X448':
algorithm = { name: crv };
break;
default:
throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448');
}
break;
}
default:
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
}
return (crypto.subtle.generateKey(algorithm, (_c = options === null || options === void 0 ? void 0 : options.extractable) !== null && _c !== void 0 ? _c : false, keyUsages));
}

View File

@@ -0,0 +1,17 @@
import crypto, { isCryptoKey } from './webcrypto.js';
import { checkSigCryptoKey } from '../lib/crypto_key.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
export default function getCryptoKey(alg, key, usage) {
if (isCryptoKey(key)) {
checkSigCryptoKey(key, alg, usage);
return key;
}
if (key instanceof Uint8Array) {
if (!alg.startsWith('HS')) {
throw new TypeError(invalidKeyInput(key, ...types));
}
return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);
}
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
}

View File

@@ -0,0 +1,5 @@
import { isCryptoKey } from './webcrypto.js';
export default (key) => {
return isCryptoKey(key);
};
export const types = ['CryptoKey'];

143
node_modules/jose/dist/browser/runtime/jwk_to_key.js generated vendored Normal file
View File

@@ -0,0 +1,143 @@
import crypto from './webcrypto.js';
import { JOSENotSupported } from '../util/errors.js';
import { decode as base64url } from './base64url.js';
function subtleMapping(jwk) {
let algorithm;
let keyUsages;
switch (jwk.kty) {
case 'oct': {
switch (jwk.alg) {
case 'HS256':
case 'HS384':
case 'HS512':
algorithm = { name: 'HMAC', hash: `SHA-${jwk.alg.slice(-3)}` };
keyUsages = ['sign', 'verify'];
break;
case 'A128CBC-HS256':
case 'A192CBC-HS384':
case 'A256CBC-HS512':
throw new JOSENotSupported(`${jwk.alg} keys cannot be imported as CryptoKey instances`);
case 'A128GCM':
case 'A192GCM':
case 'A256GCM':
case 'A128GCMKW':
case 'A192GCMKW':
case 'A256GCMKW':
algorithm = { name: 'AES-GCM' };
keyUsages = ['encrypt', 'decrypt'];
break;
case 'A128KW':
case 'A192KW':
case 'A256KW':
algorithm = { name: 'AES-KW' };
keyUsages = ['wrapKey', 'unwrapKey'];
break;
case 'PBES2-HS256+A128KW':
case 'PBES2-HS384+A192KW':
case 'PBES2-HS512+A256KW':
algorithm = { name: 'PBKDF2' };
keyUsages = ['deriveBits'];
break;
default:
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
}
break;
}
case 'RSA': {
switch (jwk.alg) {
case 'PS256':
case 'PS384':
case 'PS512':
algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };
keyUsages = jwk.d ? ['sign'] : ['verify'];
break;
case 'RS256':
case 'RS384':
case 'RS512':
algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };
keyUsages = jwk.d ? ['sign'] : ['verify'];
break;
case 'RSA-OAEP':
case 'RSA-OAEP-256':
case 'RSA-OAEP-384':
case 'RSA-OAEP-512':
algorithm = {
name: 'RSA-OAEP',
hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,
};
keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];
break;
default:
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
}
break;
}
case 'EC': {
switch (jwk.alg) {
case 'ES256':
algorithm = { name: 'ECDSA', namedCurve: 'P-256' };
keyUsages = jwk.d ? ['sign'] : ['verify'];
break;
case 'ES384':
algorithm = { name: 'ECDSA', namedCurve: 'P-384' };
keyUsages = jwk.d ? ['sign'] : ['verify'];
break;
case 'ES512':
algorithm = { name: 'ECDSA', namedCurve: 'P-521' };
keyUsages = jwk.d ? ['sign'] : ['verify'];
break;
case 'ECDH-ES':
case 'ECDH-ES+A128KW':
case 'ECDH-ES+A192KW':
case 'ECDH-ES+A256KW':
algorithm = { name: 'ECDH', namedCurve: jwk.crv };
keyUsages = jwk.d ? ['deriveBits'] : [];
break;
default:
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
}
break;
}
case 'OKP': {
switch (jwk.alg) {
case 'EdDSA':
algorithm = { name: jwk.crv };
keyUsages = jwk.d ? ['sign'] : ['verify'];
break;
case 'ECDH-ES':
case 'ECDH-ES+A128KW':
case 'ECDH-ES+A192KW':
case 'ECDH-ES+A256KW':
algorithm = { name: jwk.crv };
keyUsages = jwk.d ? ['deriveBits'] : [];
break;
default:
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
}
break;
}
default:
throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
}
return { algorithm, keyUsages };
}
const parse = async (jwk) => {
var _a, _b;
if (!jwk.alg) {
throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
}
const { algorithm, keyUsages } = subtleMapping(jwk);
const rest = [
algorithm,
(_a = jwk.ext) !== null && _a !== void 0 ? _a : false,
(_b = jwk.key_ops) !== null && _b !== void 0 ? _b : keyUsages,
];
if (algorithm.name === 'PBKDF2') {
return crypto.subtle.importKey('raw', base64url(jwk.k), ...rest);
}
const keyData = { ...jwk };
delete keyData.alg;
delete keyData.use;
return crypto.subtle.importKey('jwk', keyData, ...rest);
};
export default parse;

21
node_modules/jose/dist/browser/runtime/key_to_jwk.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
import crypto, { isCryptoKey } from './webcrypto.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { encode as base64url } from './base64url.js';
import { types } from './is_key_like.js';
const keyToJWK = async (key) => {
if (key instanceof Uint8Array) {
return {
kty: 'oct',
k: base64url(key),
};
}
if (!isCryptoKey(key)) {
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
}
if (!key.extractable) {
throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK');
}
const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key);
return jwk;
};
export default keyToJWK;

51
node_modules/jose/dist/browser/runtime/pbes2kw.js generated vendored Normal file
View File

@@ -0,0 +1,51 @@
import random from './random.js';
import { p2s as concatSalt } from '../lib/buffer_utils.js';
import { encode as base64url } from './base64url.js';
import { wrap, unwrap } from './aeskw.js';
import checkP2s from '../lib/check_p2s.js';
import crypto, { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
function getCryptoKey(key, alg) {
if (key instanceof Uint8Array) {
return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']);
}
if (isCryptoKey(key)) {
checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey');
return key;
}
throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
}
async function deriveKey(p2s, alg, p2c, key) {
checkP2s(p2s);
const salt = concatSalt(alg, p2s);
const keylen = parseInt(alg.slice(13, 16), 10);
const subtleAlg = {
hash: `SHA-${alg.slice(8, 11)}`,
iterations: p2c,
name: 'PBKDF2',
salt,
};
const wrapAlg = {
length: keylen,
name: 'AES-KW',
};
const cryptoKey = await getCryptoKey(key, alg);
if (cryptoKey.usages.includes('deriveBits')) {
return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
}
if (cryptoKey.usages.includes('deriveKey')) {
return crypto.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ['wrapKey', 'unwrapKey']);
}
throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"');
}
export const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => {
const derived = await deriveKey(p2s, alg, p2c, key);
const encryptedKey = await wrap(alg.slice(-6), derived, cek);
return { encryptedKey, p2c, p2s: base64url(p2s) };
};
export const decrypt = async (alg, key, encryptedKey, p2c, p2s) => {
const derived = await deriveKey(p2s, alg, p2c, key);
return unwrap(alg.slice(-6), derived, encryptedKey);
};

2
node_modules/jose/dist/browser/runtime/random.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import crypto from './webcrypto.js';
export default crypto.getRandomValues.bind(crypto);

37
node_modules/jose/dist/browser/runtime/rsaes.js generated vendored Normal file
View File

@@ -0,0 +1,37 @@
import subtleAlgorithm from './subtle_rsaes.js';
import bogusWebCrypto from './bogus.js';
import crypto, { isCryptoKey } from './webcrypto.js';
import { checkEncCryptoKey } from '../lib/crypto_key.js';
import checkKeyLength from './check_key_length.js';
import invalidKeyInput from '../lib/invalid_key_input.js';
import { types } from './is_key_like.js';
export const encrypt = async (alg, key, cek) => {
if (!isCryptoKey(key)) {
throw new TypeError(invalidKeyInput(key, ...types));
}
checkEncCryptoKey(key, alg, 'encrypt', 'wrapKey');
checkKeyLength(alg, key);
if (key.usages.includes('encrypt')) {
return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));
}
if (key.usages.includes('wrapKey')) {
const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto);
return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, key, subtleAlgorithm(alg)));
}
throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation');
};
export const decrypt = async (alg, key, encryptedKey) => {
if (!isCryptoKey(key)) {
throw new TypeError(invalidKeyInput(key, ...types));
}
checkEncCryptoKey(key, alg, 'decrypt', 'unwrapKey');
checkKeyLength(alg, key);
if (key.usages.includes('decrypt')) {
return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));
}
if (key.usages.includes('unwrapKey')) {
const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, key, subtleAlgorithm(alg), ...bogusWebCrypto);
return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));
}
throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation');
};

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

@@ -0,0 +1 @@
export default 'WebCryptoAPI';

11
node_modules/jose/dist/browser/runtime/sign.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
import subtleAlgorithm from './subtle_dsa.js';
import crypto from './webcrypto.js';
import checkKeyLength from './check_key_length.js';
import getSignKey from './get_sign_verify_key.js';
const sign = async (alg, key, data) => {
const cryptoKey = await getSignKey(alg, key, 'sign');
checkKeyLength(alg, cryptoKey);
const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
return new Uint8Array(signature);
};
export default sign;

26
node_modules/jose/dist/browser/runtime/subtle_dsa.js generated vendored Normal file
View File

@@ -0,0 +1,26 @@
import { JOSENotSupported } from '../util/errors.js';
export default function subtleDsa(alg, algorithm) {
const hash = `SHA-${alg.slice(-3)}`;
switch (alg) {
case 'HS256':
case 'HS384':
case 'HS512':
return { hash, name: 'HMAC' };
case 'PS256':
case 'PS384':
case 'PS512':
return { hash, name: 'RSA-PSS', saltLength: alg.slice(-3) >> 3 };
case 'RS256':
case 'RS384':
case 'RS512':
return { hash, name: 'RSASSA-PKCS1-v1_5' };
case 'ES256':
case 'ES384':
case 'ES512':
return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };
case 'EdDSA':
return { name: algorithm.name };
default:
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
}
}

12
node_modules/jose/dist/browser/runtime/subtle_rsaes.js generated vendored Normal file
View File

@@ -0,0 +1,12 @@
import { JOSENotSupported } from '../util/errors.js';
export default function subtleRsaEs(alg) {
switch (alg) {
case 'RSA-OAEP':
case 'RSA-OAEP-256':
case 'RSA-OAEP-384':
case 'RSA-OAEP-512':
return 'RSA-OAEP';
default:
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
}
}

View File

@@ -0,0 +1,19 @@
const timingSafeEqual = (a, b) => {
if (!(a instanceof Uint8Array)) {
throw new TypeError('First argument must be a buffer');
}
if (!(b instanceof Uint8Array)) {
throw new TypeError('Second argument must be a buffer');
}
if (a.length !== b.length) {
throw new TypeError('Input buffers must have the same length');
}
const len = a.length;
let out = 0;
let i = -1;
while (++i < len) {
out |= a[i] ^ b[i];
}
return out === 0;
};
export default timingSafeEqual;

16
node_modules/jose/dist/browser/runtime/verify.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
import subtleAlgorithm from './subtle_dsa.js';
import crypto from './webcrypto.js';
import checkKeyLength from './check_key_length.js';
import getVerifyKey from './get_sign_verify_key.js';
const verify = async (alg, key, signature, data) => {
const cryptoKey = await getVerifyKey(alg, key, 'verify');
checkKeyLength(alg, cryptoKey);
const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
try {
return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
}
catch (_a) {
return false;
}
};
export default verify;

2
node_modules/jose/dist/browser/runtime/webcrypto.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export default crypto;
export const isCryptoKey = (key) => key instanceof CryptoKey;

7
node_modules/jose/dist/browser/runtime/zlib.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import { JOSENotSupported } from '../util/errors.js';
export const inflate = async () => {
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.');
};
export const deflate = async () => {
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.');
};

3
node_modules/jose/dist/browser/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/browser/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 (_a) {
throw new JWTInvalid('Failed to base64url decode the payload');
}
let result;
try {
result = JSON.parse(decoder.decode(decoded));
}
catch (_b) {
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 (_a) {
throw new TypeError('Invalid Token or Protected Header formatting');
}
}

158
node_modules/jose/dist/browser/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/browser/util/runtime.js generated vendored Normal file
View File

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