Socket
Socket
Sign inDemoInstall

jose

Package Overview
Dependencies
0
Maintainers
1
Versions
201
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 4.15.4 to 5.0.0

dist/node/cjs/runtime/check_key_length.js

6

dist/browser/index.js

@@ -26,8 +26,6 @@ export { compactDecrypt } from './jwe/compact/decrypt.js';

export { decodeJwt } from './util/decode_jwt.js';
import * as errors_1 from './util/errors.js';
export { errors_1 as errors };
export * as errors from './util/errors.js';
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 * as base64url from './util/base64url.js';
export { default as cryptoRuntime } from './util/runtime.js';
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';

@@ -13,3 +12,2 @@ import isDisjoint from '../../lib/is_disjoint.js';

export async function flattenedDecrypt(jwe, key, options) {
var _a;
if (!isObject(jwe)) {

@@ -51,3 +49,3 @@ throw new JWEInvalid('Flattened JWE must be an object');

}
catch (_b) {
catch {
throw new JWEInvalid('JWE Protected Header is invalid');

@@ -64,10 +62,5 @@ }

};
validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader);
validateCrit(JWEInvalid, new Map(), 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');
}
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
}

@@ -84,7 +77,8 @@ const { alg, enc } = joseHeader;

validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);
if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) {
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');
if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||
(!keyManagementAlgorithms && alg.startsWith('PBES2'))) {
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
}
if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed');
throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
}

@@ -96,3 +90,3 @@ let encryptedKey;

}
catch (_c) {
catch {
throw new JWEInvalid('Failed to base64url decode the encrypted_key');

@@ -121,3 +115,3 @@ }

}
catch (_d) {
catch {
throw new JWEInvalid('Failed to base64url decode the iv');

@@ -128,6 +122,6 @@ }

}
catch (_e) {
catch {
throw new JWEInvalid('Failed to base64url decode the tag');
}
const protectedHeader = encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : '');
const protectedHeader = encoder.encode(jwe.protected ?? '');
let additionalData;

@@ -144,9 +138,6 @@ if (jwe.aad !== undefined) {

}
catch (_f) {
catch {
throw new JWEInvalid('Failed to base64url decode the ciphertext');
}
let plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData);
if (joseHeader.zip === 'DEF') {
plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || inflate)(plaintext);
}
const result = { plaintext };

@@ -160,3 +151,3 @@ if (jwe.protected !== undefined) {

}
catch (_g) {
catch {
throw new JWEInvalid('Failed to base64url decode the aad');

@@ -163,0 +154,0 @@ }

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

@@ -76,10 +75,5 @@ import encryptKeyManagement from '../../lib/encrypt_key_management.js';

};
validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);
validateCrit(JWEInvalid, new Map(), 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');
}
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
}

@@ -144,12 +138,3 @@ const { alg, enc } = joseHeader;

}
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 { ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData);
const jwe = {

@@ -156,0 +141,0 @@ ciphertext: base64url(ciphertext),

@@ -27,3 +27,3 @@ import { flattenedDecrypt } from '../flattened/decrypt.js';

}
catch (_a) {
catch {
}

@@ -30,0 +30,0 @@ }

import { FlattenedEncrypt, unprotected } from '../flattened/encrypt.js';
import { JWEInvalid } from '../../util/errors.js';
import { JOSENotSupported, JWEInvalid } from '../../util/errors.js';
import generateCek from '../../lib/cek.js';

@@ -37,3 +37,3 @@ import isDisjoint from '../../lib/is_disjoint.js';

addRecipient(key, options) {
const recipient = new IndividualRecipient(this, key, { crit: options === null || options === void 0 ? void 0 : options.crit });
const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
this._recipients.push(recipient);

@@ -60,8 +60,6 @@ return recipient;

}
async encrypt(options) {
var _a, _b, _c;
async encrypt() {
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) {

@@ -74,3 +72,3 @@ const [recipient] = this._recipients;

.setUnprotectedHeader(recipient.unprotectedHeader)
.encrypt(recipient.key, { ...recipient.options, ...options });
.encrypt(recipient.key, { ...recipient.options });
let jwe = {

@@ -123,5 +121,3 @@ ciphertext: flattened.ciphertext,

if (joseHeader.zip !== undefined) {
if (!this._protectedHeader || !this._protectedHeader.zip) {
throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');
}
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
}

@@ -156,3 +152,2 @@ }

...recipient.options,
...options,
[unprotected]: true,

@@ -174,5 +169,5 @@ });

}
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 });
const { encryptedKey, parameters } = await encryptKeyManagement(recipient.unprotectedHeader?.alg ||
this._protectedHeader?.alg ||
this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c });
target.encrypted_key = base64url(encryptedKey);

@@ -179,0 +174,0 @@ if (recipient.unprotectedHeader || parameters)

@@ -7,3 +7,3 @@ import { importJWK } from '../key/import.js';

...protectedHeader,
...token === null || token === void 0 ? void 0 : token.header,
...token?.header,
};

@@ -13,3 +13,3 @@ if (!isObject(joseHeader.jwk)) {

}
const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg, true);
const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
if (key instanceof Uint8Array || key.type !== 'public') {

@@ -16,0 +16,0 @@ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');

@@ -15,3 +15,3 @@ import digest from '../runtime/digest.js';

}
digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256');
digestAlgorithm ?? (digestAlgorithm = 'sha256');
if (digestAlgorithm !== 'sha256' &&

@@ -51,5 +51,5 @@ digestAlgorithm !== 'sha384' &&

export async function calculateJwkThumbprintUri(jwk, digestAlgorithm) {
digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256');
digestAlgorithm ?? (digestAlgorithm = 'sha256');
const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);
return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
}

@@ -41,3 +41,3 @@ import { importJWK } from '../key/import.js';

async getKey(protectedHeader, token) {
const { alg, kid } = { ...protectedHeader, ...token === null || token === void 0 ? void 0 : token.header };
const { alg, kid } = { ...protectedHeader, ...token?.header };
const kty = getKtyFromAlg(alg);

@@ -91,3 +91,3 @@ const candidates = this._jwks.keys.filter((jwk) => {

}
catch (_a) {
catch {
continue;

@@ -94,0 +94,0 @@ }

@@ -17,8 +17,8 @@ import fetchJwks from '../runtime/fetch_jwks.js';

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._options = { agent: options?.agent, headers: 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;
typeof options?.timeoutDuration === 'number' ? 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;
typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;
this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;
}

@@ -25,0 +25,0 @@ coolingDown() {

@@ -40,3 +40,3 @@ import { encode as base64url } from '../../runtime/base64url.js';

};
const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);
const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader);
let b64 = true;

@@ -43,0 +43,0 @@ if (extensions.has('b64')) {

@@ -11,3 +11,2 @@ import { decode as base64url } from '../../runtime/base64url.js';

export async function flattenedVerify(jws, key, options) {
var _a;
if (!isObject(jws)) {

@@ -37,3 +36,3 @@ throw new JWSInvalid('Flattened JWS must be an object');

}
catch (_b) {
catch {
throw new JWSInvalid('JWS Protected Header is invalid');

@@ -49,3 +48,3 @@ }

};
const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader);
const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);
let b64 = true;

@@ -64,3 +63,3 @@ if (extensions.has('b64')) {

if (algorithms && !algorithms.has(alg)) {
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
}

@@ -81,3 +80,3 @@ if (b64) {

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);
const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload);
let signature;

@@ -87,3 +86,3 @@ try {

}
catch (_c) {
catch {
throw new JWSInvalid('Failed to base64url decode the signature');

@@ -100,3 +99,3 @@ }

}
catch (_d) {
catch {
throw new JWSInvalid('Failed to base64url decode the payload');

@@ -103,0 +102,0 @@ }

@@ -20,3 +20,3 @@ import { flattenedVerify } from '../flattened/verify.js';

}
catch (_a) {
catch {
}

@@ -23,0 +23,0 @@ }

import epoch from '../lib/epoch.js';
import isObject from '../lib/is_object.js';
import secs from '../lib/secs.js';
function validateInput(label, input) {
if (!Number.isFinite(input)) {
throw new TypeError(`Invalid ${label} input`);
}
return input;
}
export class ProduceJWT {
constructor(payload) {
constructor(payload = {}) {
if (!isObject(payload)) {

@@ -29,4 +35,7 @@ throw new TypeError('JWT Claims Set MUST be an object');

if (typeof input === 'number') {
this._payload = { ...this._payload, nbf: input };
this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) };
}
else if (input instanceof Date) {
this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) };
}
else {

@@ -39,4 +48,7 @@ this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) };

if (typeof input === 'number') {
this._payload = { ...this._payload, exp: input };
this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) };
}
else if (input instanceof Date) {
this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) };
}
else {

@@ -51,4 +63,7 @@ this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) };

}
else if (input instanceof Date) {
this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) };
}
else {
this._payload = { ...this._payload, iat: input };
this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) };
}

@@ -55,0 +70,0 @@ return this;

@@ -11,6 +11,5 @@ import { CompactSign } from '../jws/compact/sign.js';

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) &&
if (Array.isArray(this._protectedHeader?.crit) &&
this._protectedHeader.crit.includes('b64') &&

@@ -17,0 +16,0 @@ this._protectedHeader.b64 === false) {

@@ -26,3 +26,3 @@ import * as base64url from '../runtime/base64url.js';

}
catch (_a) {
catch {
throw new JWTInvalid('Invalid Unsecured JWT');

@@ -29,0 +29,0 @@ }

@@ -5,5 +5,4 @@ import { compactVerify } from '../jws/compact/verify.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) {
if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
throw new JWTInvalid('JWTs MUST NOT use unencoded payload');

@@ -10,0 +9,0 @@ }

@@ -24,4 +24,3 @@ import { decode as decodeBase64URL } from '../runtime/base64url.js';

}
export async function importJWK(jwk, alg, octAsKeyObject) {
var _a;
export async function importJWK(jwk, alg) {
if (!isObject(jwk)) {

@@ -36,6 +35,2 @@ throw new TypeError('JWK must be an object');

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

@@ -42,0 +37,0 @@ case 'RSA':

@@ -39,3 +39,3 @@ import { unwrap as aesKw } from '../runtime/aeskw.js';

}
catch (_a) {
catch {
throw new JWEInvalid('Failed to base64url decode the apu');

@@ -50,3 +50,3 @@ }

}
catch (_b) {
catch {
throw new JWEInvalid('Failed to base64url decode the apv');

@@ -78,3 +78,3 @@ }

throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 10000;
const p2cLimit = options?.maxPBES2Count || 10000;
if (joseHeader.p2c > p2cLimit)

@@ -88,3 +88,3 @@ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);

}
catch (_c) {
catch {
throw new JWEInvalid('Failed to base64url decode the p2s');

@@ -114,3 +114,3 @@ }

}
catch (_d) {
catch {
throw new JWEInvalid('Failed to base64url decode the iv');

@@ -122,3 +122,3 @@ }

}
catch (_e) {
catch {
throw new JWEInvalid('Failed to base64url decode the tag');

@@ -125,0 +125,0 @@ }

@@ -27,3 +27,3 @@ import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';

}
catch (_a) {
catch {
}

@@ -30,0 +30,0 @@ if (!isObject(payload)) {

@@ -59,3 +59,2 @@ import crypto, { isCryptoKey } from './webcrypto.js';

const genericImport = async (replace, keyFormat, pem, alg, options) => {
var _a;
let algorithm;

@@ -118,3 +117,3 @@ let keyUsages;

}
return crypto.subtle.importKey(keyFormat, keyData, algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages);
return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? false, keyUsages);
};

@@ -121,0 +120,0 @@ export const fromPKCS8 = (pem, alg, options) => {

@@ -34,5 +34,5 @@ import { encoder, decoder } from '../lib/buffer_utils.js';

}
catch (_a) {
catch {
throw new TypeError('The input to be decoded is not correctly encoded.');
}
};

@@ -26,3 +26,3 @@ import { concat, uint64be } from '../lib/buffer_utils.js';

}
catch (_a) {
catch {
}

@@ -36,3 +36,3 @@ if (!macCheckPassed) {

}
catch (_b) {
catch {
}

@@ -61,3 +61,3 @@ if (!plaintext) {

}
catch (_a) {
catch {
throw new JWEDecryptionFailed();

@@ -64,0 +64,0 @@ }

@@ -30,3 +30,3 @@ import { JOSEError, JWKSTimeout } from '../util/errors.js';

}
catch (_a) {
catch {
throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');

@@ -33,0 +33,0 @@ }

@@ -5,3 +5,2 @@ import crypto from './webcrypto.js';

export async function generateSecret(alg, options) {
var _a;
let length;

@@ -43,7 +42,6 @@ let algorithm;

}
return crypto.subtle.generateKey(algorithm, (_a = options === null || options === void 0 ? void 0 : options.extractable) !== null && _a !== void 0 ? _a : false, keyUsages);
return crypto.subtle.generateKey(algorithm, options?.extractable ?? 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;
const modulusLength = options?.modulusLength ?? 2048;
if (typeof modulusLength !== 'number' || modulusLength < 2048) {

@@ -55,3 +53,2 @@ throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');

export async function generateKeyPair(alg, options) {
var _a, _b, _c;
let algorithm;

@@ -108,3 +105,3 @@ let keyUsages;

keyUsages = ['sign', 'verify'];
const crv = (_a = options === null || options === void 0 ? void 0 : options.crv) !== null && _a !== void 0 ? _a : 'Ed25519';
const crv = options?.crv ?? 'Ed25519';
switch (crv) {

@@ -124,3 +121,3 @@ case 'Ed25519':

keyUsages = ['deriveKey', 'deriveBits'];
const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : 'P-256';
const crv = options?.crv ?? 'P-256';
switch (crv) {

@@ -145,3 +142,3 @@ case 'P-256':

}
return (crypto.subtle.generateKey(algorithm, (_c = options === null || options === void 0 ? void 0 : options.extractable) !== null && _c !== void 0 ? _c : false, keyUsages));
return (crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages));
}
import crypto from './webcrypto.js';
import { JOSENotSupported } from '../util/errors.js';
import { decode as base64url } from './base64url.js';
function subtleMapping(jwk) {

@@ -8,40 +7,2 @@ let algorithm;

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': {

@@ -126,3 +87,2 @@ switch (jwk.alg) {

const parse = async (jwk) => {
var _a, _b;
if (!jwk.alg) {

@@ -134,8 +94,5 @@ throw new TypeError('"alg" argument is required when "jwk.alg" is not present');

algorithm,
(_a = jwk.ext) !== null && _a !== void 0 ? _a : false,
(_b = jwk.key_ops) !== null && _b !== void 0 ? _b : keyUsages,
jwk.ext ?? false,
jwk.key_ops ?? keyUsages,
];
if (algorithm.name === 'PBKDF2') {
return crypto.subtle.importKey('raw', base64url(jwk.k), ...rest);
}
const keyData = { ...jwk };

@@ -142,0 +99,0 @@ delete keyData.alg;

@@ -12,3 +12,3 @@ import subtleAlgorithm from './subtle_dsa.js';

}
catch (_a) {
catch {
return false;

@@ -15,0 +15,0 @@ }

@@ -19,3 +19,3 @@ import { decode as base64url } from './base64url.js';

}
catch (_a) {
catch {
throw new JWTInvalid('Failed to base64url decode the payload');

@@ -27,3 +27,3 @@ }

}
catch (_b) {
catch {
throw new JWTInvalid('Failed to parse the decoded payload as JSON');

@@ -30,0 +30,0 @@ }

@@ -31,5 +31,5 @@ import { decode as base64url } from './base64url.js';

}
catch (_a) {
catch {
throw new TypeError('Invalid Token or Protected Header formatting');
}
}

@@ -6,7 +6,6 @@ export class JOSEError extends Error {

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);
Error.captureStackTrace?.(this, this.constructor);
}

@@ -13,0 +12,0 @@ }

@@ -6,2 +6,3 @@ "use strict";

class CompactEncrypt {
_flattened;
constructor(plaintext) {

@@ -8,0 +9,0 @@ this._flattened = new encrypt_js_1.FlattenedEncrypt(plaintext);

@@ -6,3 +6,2 @@ "use strict";

const decrypt_js_1 = require("../../runtime/decrypt.js");
const zlib_js_1 = require("../../runtime/zlib.js");
const errors_js_1 = require("../../util/errors.js");

@@ -17,3 +16,2 @@ const is_disjoint_js_1 = require("../../lib/is_disjoint.js");

async function flattenedDecrypt(jwe, key, options) {
var _a;
if (!(0, is_object_js_1.default)(jwe)) {

@@ -67,10 +65,5 @@ throw new errors_js_1.JWEInvalid('Flattened JWE must be an object');

};
(0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader);
(0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader);
if (joseHeader.zip !== undefined) {
if (!parsedProt || !parsedProt.zip) {
throw new errors_js_1.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');
}
if (joseHeader.zip !== 'DEF') {
throw new errors_js_1.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value');
}
throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
}

@@ -87,7 +80,8 @@ const { alg, enc } = joseHeader;

(0, validate_algorithms_js_1.default)('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);
if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) {
throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');
if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||
(!keyManagementAlgorithms && alg.startsWith('PBES2'))) {
throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
}
if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
throw new errors_js_1.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed');
throw new errors_js_1.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
}

@@ -132,3 +126,3 @@ let encryptedKey;

}
const protectedHeader = buffer_utils_js_1.encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : '');
const protectedHeader = buffer_utils_js_1.encoder.encode(jwe.protected ?? '');
let additionalData;

@@ -149,5 +143,2 @@ if (jwe.aad !== undefined) {

let plaintext = await (0, decrypt_js_1.default)(enc, cek, ciphertext, iv, tag, additionalData);
if (joseHeader.zip === 'DEF') {
plaintext = await ((options === null || options === void 0 ? void 0 : options.inflateRaw) || zlib_js_1.inflate)(plaintext);
}
const result = { plaintext };

@@ -154,0 +145,0 @@ if (jwe.protected !== undefined) {

@@ -6,3 +6,2 @@ "use strict";

const encrypt_js_1 = require("../../runtime/encrypt.js");
const zlib_js_1 = require("../../runtime/zlib.js");
const iv_js_1 = require("../../lib/iv.js");

@@ -16,2 +15,10 @@ const encrypt_key_management_js_1 = require("../../lib/encrypt_key_management.js");

class FlattenedEncrypt {
_plaintext;
_protectedHeader;
_sharedUnprotectedHeader;
_unprotectedHeader;
_aad;
_cek;
_iv;
_keyManagementParameters;
constructor(plaintext) {

@@ -81,10 +88,5 @@ if (!(plaintext instanceof Uint8Array)) {

};
(0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);
(0, validate_crit_js_1.default)(errors_js_1.JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader);
if (joseHeader.zip !== undefined) {
if (!this._protectedHeader || !this._protectedHeader.zip) {
throw new errors_js_1.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');
}
if (joseHeader.zip !== 'DEF') {
throw new errors_js_1.JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value');
}
throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
}

@@ -132,3 +134,3 @@ const { alg, enc } = joseHeader;

}
this._iv || (this._iv = (0, iv_js_1.default)(enc));
this._iv ||= (0, iv_js_1.default)(enc);
let additionalData;

@@ -150,12 +152,3 @@ let protectedHeader;

}
let ciphertext;
let tag;
if (joseHeader.zip === 'DEF') {
const deflated = await ((options === null || options === void 0 ? void 0 : options.deflateRaw) || zlib_js_1.deflate)(this._plaintext);
({ ciphertext, tag } = await (0, encrypt_js_1.default)(enc, deflated, cek, this._iv, additionalData));
}
else {
;
({ ciphertext, tag } = await (0, encrypt_js_1.default)(enc, this._plaintext, cek, this._iv, additionalData));
}
const { ciphertext, tag } = await (0, encrypt_js_1.default)(enc, this._plaintext, cek, this._iv, additionalData);
const jwe = {

@@ -162,0 +155,0 @@ ciphertext: (0, base64url_js_1.encode)(ciphertext),

@@ -12,2 +12,6 @@ "use strict";

class IndividualRecipient {
parent;
unprotectedHeader;
key;
options;
constructor(enc, key, options) {

@@ -36,8 +40,12 @@ this.parent = enc;

class GeneralEncrypt {
_plaintext;
_recipients = [];
_protectedHeader;
_unprotectedHeader;
_aad;
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 });
const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
this._recipients.push(recipient);

@@ -64,8 +72,6 @@ return recipient;

}
async encrypt(options) {
var _a, _b, _c;
async encrypt() {
if (!this._recipients.length) {
throw new errors_js_1.JWEInvalid('at least one recipient must be added');
}
options = { deflateRaw: options === null || options === void 0 ? void 0 : options.deflateRaw };
if (this._recipients.length === 1) {

@@ -78,3 +84,3 @@ const [recipient] = this._recipients;

.setUnprotectedHeader(recipient.unprotectedHeader)
.encrypt(recipient.key, { ...recipient.options, ...options });
.encrypt(recipient.key, { ...recipient.options });
let jwe = {

@@ -127,5 +133,3 @@ ciphertext: flattened.ciphertext,

if (joseHeader.zip !== undefined) {
if (!this._protectedHeader || !this._protectedHeader.zip) {
throw new errors_js_1.JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');
}
throw new errors_js_1.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
}

@@ -160,3 +164,2 @@ }

...recipient.options,
...options,
[encrypt_js_1.unprotected]: true,

@@ -178,5 +181,5 @@ });

}
const { encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(((_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 });
const { encryptedKey, parameters } = await (0, encrypt_key_management_js_1.default)(recipient.unprotectedHeader?.alg ||
this._protectedHeader?.alg ||
this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c });
target.encrypted_key = (0, base64url_js_1.encode)(encryptedKey);

@@ -183,0 +186,0 @@ if (recipient.unprotectedHeader || parameters)

@@ -10,3 +10,3 @@ "use strict";

...protectedHeader,
...token === null || token === void 0 ? void 0 : token.header,
...token?.header,
};

@@ -16,3 +16,3 @@ if (!(0, is_object_js_1.default)(joseHeader.jwk)) {

}
const key = await (0, import_js_1.importJWK)({ ...joseHeader.jwk, ext: true }, joseHeader.alg, true);
const key = await (0, import_js_1.importJWK)({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
if (key instanceof Uint8Array || key.type !== 'public') {

@@ -19,0 +19,0 @@ throw new errors_js_1.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');

@@ -18,3 +18,3 @@ "use strict";

}
digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256');
digestAlgorithm ??= 'sha256';
if (digestAlgorithm !== 'sha256' &&

@@ -55,3 +55,3 @@ digestAlgorithm !== 'sha384' &&

async function calculateJwkThumbprintUri(jwk, digestAlgorithm) {
digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256');
digestAlgorithm ??= 'sha256';
const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);

@@ -58,0 +58,0 @@ return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;

@@ -37,4 +37,5 @@ "use strict";

class LocalJWKSet {
_jwks;
_cached = new WeakMap();
constructor(jwks) {
this._cached = new WeakMap();
if (!isJWKSLike(jwks)) {

@@ -46,3 +47,3 @@ throw new errors_js_1.JWKSInvalid('JSON Web Key Set malformed');

async getKey(protectedHeader, token) {
const { alg, kid } = { ...protectedHeader, ...token === null || token === void 0 ? void 0 : token.header };
const { alg, kid } = { ...protectedHeader, ...token?.header };
const kty = getKtyFromAlg(alg);

@@ -49,0 +50,0 @@ const candidates = this._jwks.keys.filter((jwk) => {

@@ -13,2 +13,9 @@ "use strict";

class RemoteJWKSet extends local_js_1.LocalJWKSet {
_url;
_timeoutDuration;
_cooldownDuration;
_cacheMaxAge;
_jwksTimestamp;
_pendingFetch;
_options;
constructor(url, options) {

@@ -21,8 +28,8 @@ super({ keys: [] });

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._options = { agent: options?.agent, headers: 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;
typeof options?.timeoutDuration === 'number' ? 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;
typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;
this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;
}

@@ -60,3 +67,3 @@ coolingDown() {

}
this._pendingFetch || (this._pendingFetch = (0, fetch_jwks_js_1.default)(this._url, this._timeoutDuration, this._options)
this._pendingFetch ||= (0, fetch_jwks_js_1.default)(this._url, this._timeoutDuration, this._options)
.then((json) => {

@@ -73,3 +80,3 @@ if (!(0, local_js_1.isJWKSLike)(json)) {

throw err;
}));
});
await this._pendingFetch;

@@ -76,0 +83,0 @@ }

@@ -6,2 +6,3 @@ "use strict";

class CompactSign {
_flattened;
constructor(payload) {

@@ -8,0 +9,0 @@ this._flattened = new sign_js_1.FlattenedSign(payload);

@@ -12,2 +12,5 @@ "use strict";

class FlattenedSign {
_payload;
_protectedHeader;
_unprotectedHeader;
constructor(payload) {

@@ -44,3 +47,3 @@ if (!(payload instanceof Uint8Array)) {

};
const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);
const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader);
let b64 = true;

@@ -47,0 +50,0 @@ if (extensions.has('b64')) {

@@ -14,3 +14,2 @@ "use strict";

async function flattenedVerify(jws, key, options) {
var _a;
if (!(0, is_object_js_1.default)(jws)) {

@@ -51,3 +50,3 @@ throw new errors_js_1.JWSInvalid('Flattened JWS must be an object');

};
const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader);
const extensions = (0, validate_crit_js_1.default)(errors_js_1.JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);
let b64 = true;

@@ -66,3 +65,3 @@ if (extensions.has('b64')) {

if (algorithms && !algorithms.has(alg)) {
throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');
throw new errors_js_1.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
}

@@ -83,3 +82,3 @@ if (b64) {

(0, check_key_type_js_1.default)(alg, key, 'verify');
const data = (0, buffer_utils_js_1.concat)(buffer_utils_js_1.encoder.encode((_a = jws.protected) !== null && _a !== void 0 ? _a : ''), buffer_utils_js_1.encoder.encode('.'), typeof jws.payload === 'string' ? buffer_utils_js_1.encoder.encode(jws.payload) : jws.payload);
const data = (0, buffer_utils_js_1.concat)(buffer_utils_js_1.encoder.encode(jws.protected ?? ''), buffer_utils_js_1.encoder.encode('.'), typeof jws.payload === 'string' ? buffer_utils_js_1.encoder.encode(jws.payload) : jws.payload);
let signature;

@@ -86,0 +85,0 @@ try {

@@ -7,2 +7,7 @@ "use strict";

class IndividualSignature {
parent;
protectedHeader;
unprotectedHeader;
options;
key;
constructor(sig, key, options) {

@@ -38,4 +43,5 @@ this.parent = sig;

class GeneralSign {
_payload;
_signatures = [];
constructor(payload) {
this._signatures = [];
this._payload = payload;

@@ -42,0 +48,0 @@ }

@@ -8,2 +8,9 @@ "use strict";

class EncryptJWT extends produce_js_1.ProduceJWT {
_cek;
_iv;
_keyManagementParameters;
_protectedHeader;
_replicateIssuerAsHeader;
_replicateSubjectAsHeader;
_replicateAudienceAsHeader;
setProtectedHeader(protectedHeader) {

@@ -10,0 +17,0 @@ if (this._protectedHeader) {

@@ -7,4 +7,11 @@ "use strict";

const secs_js_1 = require("../lib/secs.js");
function validateInput(label, input) {
if (!Number.isFinite(input)) {
throw new TypeError(`Invalid ${label} input`);
}
return input;
}
class ProduceJWT {
constructor(payload) {
_payload;
constructor(payload = {}) {
if (!(0, is_object_js_1.default)(payload)) {

@@ -33,4 +40,7 @@ throw new TypeError('JWT Claims Set MUST be an object');

if (typeof input === 'number') {
this._payload = { ...this._payload, nbf: input };
this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) };
}
else if (input instanceof Date) {
this._payload = { ...this._payload, nbf: validateInput('setNotBefore', (0, epoch_js_1.default)(input)) };
}
else {

@@ -43,4 +53,7 @@ this._payload = { ...this._payload, nbf: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) };

if (typeof input === 'number') {
this._payload = { ...this._payload, exp: input };
this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) };
}
else if (input instanceof Date) {
this._payload = { ...this._payload, exp: validateInput('setExpirationTime', (0, epoch_js_1.default)(input)) };
}
else {

@@ -55,4 +68,7 @@ this._payload = { ...this._payload, exp: (0, epoch_js_1.default)(new Date()) + (0, secs_js_1.default)(input) };

}
else if (input instanceof Date) {
this._payload = { ...this._payload, iat: validateInput('setIssuedAt', (0, epoch_js_1.default)(input)) };
}
else {
this._payload = { ...this._payload, iat: input };
this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) };
}

@@ -59,0 +75,0 @@ return this;

@@ -9,2 +9,3 @@ "use strict";

class SignJWT extends produce_js_1.ProduceJWT {
_protectedHeader;
setProtectedHeader(protectedHeader) {

@@ -15,6 +16,5 @@ this._protectedHeader = protectedHeader;

async sign(key, options) {
var _a;
const sig = new sign_js_1.CompactSign(buffer_utils_js_1.encoder.encode(JSON.stringify(this._payload)));
sig.setProtectedHeader(this._protectedHeader);
if (Array.isArray((_a = this._protectedHeader) === null || _a === void 0 ? void 0 : _a.crit) &&
if (Array.isArray(this._protectedHeader?.crit) &&
this._protectedHeader.crit.includes('b64') &&

@@ -21,0 +21,0 @@ this._protectedHeader.b64 === false) {

@@ -8,5 +8,4 @@ "use strict";

async function jwtVerify(jwt, key, options) {
var _a;
const verified = await (0, verify_js_1.compactVerify)(jwt, key, options);
if (((_a = verified.protectedHeader.crit) === null || _a === void 0 ? void 0 : _a.includes('b64')) && verified.protectedHeader.b64 === false) {
if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
throw new errors_js_1.JWTInvalid('JWTs MUST NOT use unencoded payload');

@@ -13,0 +12,0 @@ }

@@ -30,8 +30,7 @@ "use strict";

exports.importPKCS8 = importPKCS8;
async function importJWK(jwk, alg, octAsKeyObject) {
var _a;
async function importJWK(jwk, alg) {
if (!(0, is_object_js_1.default)(jwk)) {
throw new TypeError('JWK must be an object');
}
alg || (alg = jwk.alg);
alg ||= jwk.alg;
switch (jwk.kty) {

@@ -42,6 +41,2 @@ case 'oct':

}
octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : (octAsKeyObject = jwk.ext !== true);
if (octAsKeyObject) {
return (0, jwk_to_key_js_1.default)({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false });
}
return (0, base64url_js_1.decode)(jwk.k);

@@ -48,0 +43,0 @@ case 'RSA':

@@ -10,3 +10,3 @@ "use strict";

const jweAlgorithm = alg.slice(0, 7);
iv || (iv = (0, iv_js_1.default)(jweAlgorithm));
iv ||= (0, iv_js_1.default)(jweAlgorithm);
const { ciphertext: encryptedKey, tag } = await (0, encrypt_js_1.default)(jweAlgorithm, cek, key, iv, new Uint8Array(0));

@@ -13,0 +13,0 @@ return { encryptedKey, iv: (0, base64url_js_1.encode)(iv), tag: (0, base64url_js_1.encode)(tag) };

@@ -78,3 +78,3 @@ "use strict";

throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 10000;
const p2cLimit = options?.maxPBES2Count || 10000;
if (joseHeader.p2c > p2cLimit)

@@ -81,0 +81,0 @@ throw new errors_js_1.JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);

@@ -32,3 +32,3 @@ "use strict";

let { epk: ephemeralKey } = providedParameters;
ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey);
ephemeralKey ||= (await ECDH.generateEpk(key)).privateKey;
const { x, y, crv, kty } = await (0, export_js_1.exportJWK)(ephemeralKey);

@@ -35,0 +35,0 @@ const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? (0, cek_js_1.bitLength)(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unwrap = exports.wrap = void 0;
const buffer_1 = require("buffer");
const crypto_1 = require("crypto");
const node_buffer_1 = require("node:buffer");
const node_crypto_1 = require("node:crypto");
const errors_js_1 = require("../util/errors.js");

@@ -24,7 +24,7 @@ const buffer_utils_js_1 = require("../lib/buffer_utils.js");

if (key instanceof Uint8Array) {
return (0, crypto_1.createSecretKey)(key);
return (0, node_crypto_1.createSecretKey)(key);
}
if ((0, webcrypto_js_1.isCryptoKey)(key)) {
(0, crypto_key_js_1.checkEncCryptoKey)(key, alg, usage);
return crypto_1.KeyObject.from(key);
return node_crypto_1.KeyObject.from(key);
}

@@ -41,3 +41,3 @@ throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array'));

checkKeySize(keyObject, alg);
const cipher = (0, crypto_1.createCipheriv)(algorithm, keyObject, buffer_1.Buffer.alloc(8, 0xa6));
const cipher = (0, node_crypto_1.createCipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6));
return (0, buffer_utils_js_1.concat)(cipher.update(cek), cipher.final());

@@ -54,5 +54,5 @@ };

checkKeySize(keyObject, alg);
const cipher = (0, crypto_1.createDecipheriv)(algorithm, keyObject, buffer_1.Buffer.alloc(8, 0xa6));
const cipher = (0, node_crypto_1.createDecipheriv)(algorithm, keyObject, node_buffer_1.Buffer.alloc(8, 0xa6));
return (0, buffer_utils_js_1.concat)(cipher.update(encryptedKey), cipher.final());
};
exports.unwrap = unwrap;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromX509 = exports.fromSPKI = exports.fromPKCS8 = exports.toPKCS8 = exports.toSPKI = void 0;
const crypto_1 = require("crypto");
const buffer_1 = require("buffer");
const node_crypto_1 = require("node:crypto");
const node_buffer_1 = require("node:buffer");
const webcrypto_js_1 = require("./webcrypto.js");

@@ -16,3 +16,3 @@ const is_key_object_js_1 = require("./is_key_object.js");

}
keyObject = crypto_1.KeyObject.from(key);
keyObject = node_crypto_1.KeyObject.from(key);
}

@@ -38,4 +38,4 @@ else if ((0, is_key_object_js_1.default)(key)) {

exports.toPKCS8 = toPKCS8;
const fromPKCS8 = (pem) => (0, crypto_1.createPrivateKey)({
key: buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'),
const fromPKCS8 = (pem) => (0, node_crypto_1.createPrivateKey)({
key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, ''), 'base64'),
type: 'pkcs8',

@@ -45,4 +45,4 @@ format: 'der',

exports.fromPKCS8 = fromPKCS8;
const fromSPKI = (pem) => (0, crypto_1.createPublicKey)({
key: buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'),
const fromSPKI = (pem) => (0, node_crypto_1.createPublicKey)({
key: node_buffer_1.Buffer.from(pem.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g, ''), 'base64'),
type: 'spki',

@@ -52,3 +52,3 @@ format: 'der',

exports.fromSPKI = fromSPKI;
const fromX509 = (pem) => (0, crypto_1.createPublicKey)({
const fromX509 = (pem) => (0, node_crypto_1.createPublicKey)({
key: pem,

@@ -55,0 +55,0 @@ type: 'spki',

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decode = exports.encode = exports.encodeBase64 = exports.decodeBase64 = void 0;
const buffer_1 = require("buffer");
const node_buffer_1 = require("node:buffer");
const buffer_utils_js_1 = require("../lib/buffer_utils.js");
let encode;
function normalize(input) {

@@ -14,13 +13,9 @@ let encoded = input;

}
if (buffer_1.Buffer.isEncoding('base64url')) {
exports.encode = encode = (input) => buffer_1.Buffer.from(input).toString('base64url');
}
else {
exports.encode = encode = (input) => buffer_1.Buffer.from(input).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
const decodeBase64 = (input) => buffer_1.Buffer.from(input, 'base64');
const encode = (input) => node_buffer_1.Buffer.from(input).toString('base64url');
exports.encode = encode;
const decodeBase64 = (input) => new Uint8Array(node_buffer_1.Buffer.from(input, 'base64'));
exports.decodeBase64 = decodeBase64;
const encodeBase64 = (input) => buffer_1.Buffer.from(input).toString('base64');
const encodeBase64 = (input) => node_buffer_1.Buffer.from(input).toString('base64');
exports.encodeBase64 = encodeBase64;
const decode = (input) => buffer_1.Buffer.from(normalize(input), 'base64');
const decode = (input) => new Uint8Array(node_buffer_1.Buffer.from(normalize(input), 'base64'));
exports.decode = decode;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const node_crypto_1 = require("node:crypto");
const buffer_utils_js_1 = require("../lib/buffer_utils.js");
function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) {
const macData = (0, buffer_utils_js_1.concat)(aad, iv, ciphertext, (0, buffer_utils_js_1.uint64be)(aad.length << 3));
const hmac = (0, crypto_1.createHmac)(`sha${macSize}`, macKey);
const hmac = (0, node_crypto_1.createHmac)(`sha${macSize}`, macKey);
hmac.update(macData);

@@ -9,0 +9,0 @@ return hmac.digest().slice(0, keySize >> 3);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const node_crypto_1 = require("node:crypto");
let ciphers;
exports.default = (algorithm) => {
ciphers || (ciphers = new Set((0, crypto_1.getCiphers)()));
ciphers ||= new Set((0, node_crypto_1.getCiphers)());
return ciphers.has(algorithm);
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const node_crypto_1 = require("node:crypto");
const check_iv_length_js_1 = require("../lib/check_iv_length.js");

@@ -40,3 +40,3 @@ const check_cek_length_js_1 = require("./check_cek_length.js");

try {
const decipher = (0, crypto_1.createDecipheriv)(algorithm, encKey, iv);
const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, encKey, iv);
plaintext = (0, buffer_utils_js_1.concat)(decipher.update(ciphertext), decipher.final());

@@ -58,3 +58,3 @@ }

try {
const decipher = (0, crypto_1.createDecipheriv)(algorithm, cek, iv, { authTagLength: 16 });
const decipher = (0, node_crypto_1.createDecipheriv)(algorithm, cek, iv, { authTagLength: 16 });
decipher.setAuthTag(tag);

@@ -76,3 +76,3 @@ if (aad.byteLength) {

(0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'decrypt');
key = crypto_1.KeyObject.from(cek);
key = node_crypto_1.KeyObject.from(cek);
}

@@ -79,0 +79,0 @@ else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const digest = (algorithm, data) => (0, crypto_1.createHash)(algorithm).update(data).digest();
const node_crypto_1 = require("node:crypto");
const digest = (algorithm, data) => (0, node_crypto_1.createHash)(algorithm).update(data).digest();
exports.default = digest;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ecdhAllowed = exports.generateEpk = exports.deriveKey = void 0;
const crypto_1 = require("crypto");
const util_1 = require("util");
const node_crypto_1 = require("node:crypto");
const node_util_1 = require("node:util");
const get_named_curve_js_1 = require("./get_named_curve.js");

@@ -14,3 +14,3 @@ const buffer_utils_js_1 = require("../lib/buffer_utils.js");

const is_key_like_js_1 = require("./is_key_like.js");
const generateKeyPair = (0, util_1.promisify)(crypto_1.generateKeyPair);
const generateKeyPair = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair);
async function deriveKey(publicKee, privateKee, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {

@@ -20,3 +20,3 @@ let publicKey;

(0, crypto_key_js_1.checkEncCryptoKey)(publicKee, 'ECDH');
publicKey = crypto_1.KeyObject.from(publicKee);
publicKey = node_crypto_1.KeyObject.from(publicKee);
}

@@ -32,3 +32,3 @@ else if ((0, is_key_object_js_1.default)(publicKee)) {

(0, crypto_key_js_1.checkEncCryptoKey)(privateKee, 'ECDH', 'deriveBits');
privateKey = crypto_1.KeyObject.from(privateKee);
privateKey = node_crypto_1.KeyObject.from(privateKee);
}

@@ -42,3 +42,3 @@ else if ((0, is_key_object_js_1.default)(privateKee)) {

const value = (0, buffer_utils_js_1.concat)((0, buffer_utils_js_1.lengthAndInput)(buffer_utils_js_1.encoder.encode(algorithm)), (0, buffer_utils_js_1.lengthAndInput)(apu), (0, buffer_utils_js_1.lengthAndInput)(apv), (0, buffer_utils_js_1.uint32be)(keyLength));
const sharedSecret = (0, crypto_1.diffieHellman)({ privateKey, publicKey });
const sharedSecret = (0, node_crypto_1.diffieHellman)({ privateKey, publicKey });
return (0, buffer_utils_js_1.concatKdf)(sharedSecret, keyLength, value);

@@ -50,3 +50,3 @@ }

if ((0, webcrypto_js_1.isCryptoKey)(kee)) {
key = crypto_1.KeyObject.from(kee);
key = node_crypto_1.KeyObject.from(kee);
}

@@ -53,0 +53,0 @@ else if ((0, is_key_object_js_1.default)(kee)) {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const node_crypto_1 = require("node:crypto");
const check_iv_length_js_1 = require("../lib/check_iv_length.js");

@@ -26,3 +26,3 @@ const check_cek_length_js_1 = require("./check_cek_length.js");

}
const cipher = (0, crypto_1.createCipheriv)(algorithm, encKey, iv);
const cipher = (0, node_crypto_1.createCipheriv)(algorithm, encKey, iv);
const ciphertext = (0, buffer_utils_js_1.concat)(cipher.update(plaintext), cipher.final());

@@ -39,3 +39,3 @@ const macSize = parseInt(enc.slice(-3), 10);

}
const cipher = (0, crypto_1.createCipheriv)(algorithm, cek, iv, { authTagLength: 16 });
const cipher = (0, node_crypto_1.createCipheriv)(algorithm, cek, iv, { authTagLength: 16 });
if (aad.byteLength) {

@@ -53,3 +53,3 @@ cipher.setAAD(aad, { plaintextLength: plaintext.length });

(0, crypto_key_js_1.checkEncCryptoKey)(cek, enc, 'encrypt');
key = crypto_1.KeyObject.from(cek);
key = node_crypto_1.KeyObject.from(cek);
}

@@ -56,0 +56,0 @@ else if (cek instanceof Uint8Array || (0, is_key_object_js_1.default)(cek)) {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const http = require("http");
const https = require("https");
const events_1 = require("events");
const http = require("node:http");
const https = require("node:https");
const node_events_1 = require("node:events");
const errors_js_1 = require("../util/errors.js");

@@ -26,3 +26,3 @@ const buffer_utils_js_1 = require("../lib/buffer_utils.js");

});
const [response] = (await Promise.race([(0, events_1.once)(req, 'response'), (0, events_1.once)(req, 'timeout')]));
const [response] = (await Promise.race([(0, node_events_1.once)(req, 'response'), (0, node_events_1.once)(req, 'timeout')]));
if (!response) {

@@ -29,0 +29,0 @@ req.destroy();

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateKeyPair = exports.generateSecret = void 0;
const crypto_1 = require("crypto");
const util_1 = require("util");
const node_crypto_1 = require("node:crypto");
const node_util_1 = require("node:util");
const random_js_1 = require("./random.js");
const check_modulus_length_js_1 = require("./check_modulus_length.js");
const errors_js_1 = require("../util/errors.js");
const generate = (0, util_1.promisify)(crypto_1.generateKeyPair);
const generate = (0, node_util_1.promisify)(node_crypto_1.generateKeyPair);
async function generateSecret(alg, options) {

@@ -35,7 +34,6 @@ let length;

}
return (0, crypto_1.createSecretKey)((0, random_js_1.default)(new Uint8Array(length >> 3)));
return (0, node_crypto_1.createSecretKey)((0, random_js_1.default)(new Uint8Array(length >> 3)));
}
exports.generateSecret = generateSecret;
async function generateKeyPair(alg, options) {
var _a, _b;
switch (alg) {

@@ -53,3 +51,3 @@ case 'RS256':

case 'RSA1_5': {
const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048;
const modulusLength = options?.modulusLength ?? 2048;
if (typeof modulusLength !== 'number' || modulusLength < 2048) {

@@ -62,4 +60,2 @@ throw new errors_js_1.JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');

});
(0, check_modulus_length_js_1.setModulusLength)(keypair.privateKey, modulusLength);
(0, check_modulus_length_js_1.setModulusLength)(keypair.publicKey, modulusLength);
return keypair;

@@ -76,3 +72,3 @@ }

case 'EdDSA': {
switch (options === null || options === void 0 ? void 0 : options.crv) {
switch (options?.crv) {
case undefined:

@@ -91,3 +87,3 @@ case 'Ed25519':

case 'ECDH-ES+A256KW':
const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : 'P-256';
const crv = options?.crv ?? 'P-256';
switch (crv) {

@@ -94,0 +90,0 @@ case undefined:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setCurve = exports.weakMap = void 0;
const buffer_1 = require("buffer");
const crypto_1 = require("crypto");
exports.weakMap = void 0;
const node_crypto_1 = require("node:crypto");
const errors_js_1 = require("../util/errors.js");

@@ -11,6 +10,2 @@ const webcrypto_js_1 = require("./webcrypto.js");

const is_key_like_js_1 = require("./is_key_like.js");
const p256 = buffer_1.Buffer.from([42, 134, 72, 206, 61, 3, 1, 7]);
const p384 = buffer_1.Buffer.from([43, 129, 4, 0, 34]);
const p521 = buffer_1.Buffer.from([43, 129, 4, 0, 35]);
const secp256k1 = buffer_1.Buffer.from([43, 129, 4, 0, 10]);
exports.weakMap = new WeakMap();

@@ -32,6 +27,5 @@ const namedCurveToJOSE = (namedCurve) => {

const getNamedCurve = (kee, raw) => {
var _a;
let key;
if ((0, webcrypto_js_1.isCryptoKey)(kee)) {
key = crypto_1.KeyObject.from(kee);
key = node_crypto_1.KeyObject.from(kee);
}

@@ -55,35 +49,7 @@ else if ((0, is_key_object_js_1.default)(kee)) {

case 'ec': {
if (exports.weakMap.has(key)) {
return exports.weakMap.get(key);
let namedCurve = key.asymmetricKeyDetails.namedCurve;
if (raw) {
return namedCurve;
}
let namedCurve = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.namedCurve;
if (!namedCurve && key.type === 'private') {
namedCurve = getNamedCurve((0, crypto_1.createPublicKey)(key), true);
}
else if (!namedCurve) {
const buf = key.export({ format: 'der', type: 'spki' });
const i = buf[1] < 128 ? 14 : 15;
const len = buf[i];
const curveOid = buf.slice(i + 1, i + 1 + len);
if (curveOid.equals(p256)) {
namedCurve = 'prime256v1';
}
else if (curveOid.equals(p384)) {
namedCurve = 'secp384r1';
}
else if (curveOid.equals(p521)) {
namedCurve = 'secp521r1';
}
else if (curveOid.equals(secp256k1)) {
namedCurve = 'secp256k1';
}
else {
throw new errors_js_1.JOSENotSupported('Unsupported key curve for this operation');
}
}
if (raw)
return namedCurve;
const curve = namedCurveToJOSE(namedCurve);
exports.weakMap.set(key, curve);
return curve;
return namedCurveToJOSE(namedCurve);
}

@@ -94,6 +60,2 @@ default:

};
function setCurve(keyObject, curve) {
exports.weakMap.set(keyObject, curve);
}
exports.setCurve = setCurve;
exports.default = getNamedCurve;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const node_crypto_1 = require("node:crypto");
const webcrypto_js_1 = require("./webcrypto.js");

@@ -13,5 +13,5 @@ const crypto_key_js_1 = require("../lib/crypto_key.js");

}
return (0, crypto_1.createSecretKey)(key);
return (0, node_crypto_1.createSecretKey)(key);
}
if (key instanceof crypto_1.KeyObject) {
if (key instanceof node_crypto_1.KeyObject) {
return key;

@@ -21,3 +21,3 @@ }

(0, crypto_key_js_1.checkSigCryptoKey)(key, alg, usage);
return crypto_1.KeyObject.from(key);
return node_crypto_1.KeyObject.from(key);
}

@@ -24,0 +24,0 @@ throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array'));

@@ -9,4 +9,4 @@ "use strict";

exports.types = types;
if (globalThis.CryptoKey || (webcrypto_js_1.default === null || webcrypto_js_1.default === void 0 ? void 0 : webcrypto_js_1.default.CryptoKey)) {
if (globalThis.CryptoKey || webcrypto_js_1.default?.CryptoKey) {
types.push('CryptoKey');
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const util = require("util");
exports.default = util.types.isKeyObject
? (obj) => util.types.isKeyObject(obj)
: (obj) => obj != null && obj instanceof crypto_1.KeyObject;
const util = require("node:util");
exports.default = (obj) => util.types.isKeyObject(obj);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const buffer_1 = require("buffer");
const crypto_1 = require("crypto");
const base64url_js_1 = require("./base64url.js");
const errors_js_1 = require("../util/errors.js");
const get_named_curve_js_1 = require("./get_named_curve.js");
const check_modulus_length_js_1 = require("./check_modulus_length.js");
const asn1_sequence_encoder_js_1 = require("./asn1_sequence_encoder.js");
const flags_js_1 = require("./flags.js");
const node_crypto_1 = require("node:crypto");
const parse = (jwk) => {
if (flags_js_1.jwkImport && jwk.kty !== 'oct') {
return jwk.d
? (0, crypto_1.createPrivateKey)({ format: 'jwk', key: jwk })
: (0, crypto_1.createPublicKey)({ format: 'jwk', key: jwk });
}
switch (jwk.kty) {
case 'oct': {
return (0, crypto_1.createSecretKey)((0, base64url_js_1.decode)(jwk.k));
}
case 'RSA': {
const enc = new asn1_sequence_encoder_js_1.default();
const isPrivate = jwk.d !== undefined;
const modulus = buffer_1.Buffer.from(jwk.n, 'base64');
const exponent = buffer_1.Buffer.from(jwk.e, 'base64');
if (isPrivate) {
enc.zero();
enc.unsignedInteger(modulus);
enc.unsignedInteger(exponent);
enc.unsignedInteger(buffer_1.Buffer.from(jwk.d, 'base64'));
enc.unsignedInteger(buffer_1.Buffer.from(jwk.p, 'base64'));
enc.unsignedInteger(buffer_1.Buffer.from(jwk.q, 'base64'));
enc.unsignedInteger(buffer_1.Buffer.from(jwk.dp, 'base64'));
enc.unsignedInteger(buffer_1.Buffer.from(jwk.dq, 'base64'));
enc.unsignedInteger(buffer_1.Buffer.from(jwk.qi, 'base64'));
}
else {
enc.unsignedInteger(modulus);
enc.unsignedInteger(exponent);
}
const der = enc.end();
const createInput = {
key: der,
format: 'der',
type: 'pkcs1',
};
const keyObject = isPrivate ? (0, crypto_1.createPrivateKey)(createInput) : (0, crypto_1.createPublicKey)(createInput);
(0, check_modulus_length_js_1.setModulusLength)(keyObject, modulus.length << 3);
return keyObject;
}
case 'EC': {
const enc = new asn1_sequence_encoder_js_1.default();
const isPrivate = jwk.d !== undefined;
const pub = buffer_1.Buffer.concat([
buffer_1.Buffer.alloc(1, 4),
buffer_1.Buffer.from(jwk.x, 'base64'),
buffer_1.Buffer.from(jwk.y, 'base64'),
]);
if (isPrivate) {
enc.zero();
const enc$1 = new asn1_sequence_encoder_js_1.default();
enc$1.oidFor('ecPublicKey');
enc$1.oidFor(jwk.crv);
enc.add(enc$1.end());
const enc$2 = new asn1_sequence_encoder_js_1.default();
enc$2.one();
enc$2.octStr(buffer_1.Buffer.from(jwk.d, 'base64'));
const enc$3 = new asn1_sequence_encoder_js_1.default();
enc$3.bitStr(pub);
const f2 = enc$3.end(buffer_1.Buffer.from([0xa1]));
enc$2.add(f2);
const f = enc$2.end();
const enc$4 = new asn1_sequence_encoder_js_1.default();
enc$4.add(f);
const f3 = enc$4.end(buffer_1.Buffer.from([0x04]));
enc.add(f3);
const der = enc.end();
const keyObject = (0, crypto_1.createPrivateKey)({ key: der, format: 'der', type: 'pkcs8' });
(0, get_named_curve_js_1.setCurve)(keyObject, jwk.crv);
return keyObject;
}
const enc$1 = new asn1_sequence_encoder_js_1.default();
enc$1.oidFor('ecPublicKey');
enc$1.oidFor(jwk.crv);
enc.add(enc$1.end());
enc.bitStr(pub);
const der = enc.end();
const keyObject = (0, crypto_1.createPublicKey)({ key: der, format: 'der', type: 'spki' });
(0, get_named_curve_js_1.setCurve)(keyObject, jwk.crv);
return keyObject;
}
case 'OKP': {
const enc = new asn1_sequence_encoder_js_1.default();
const isPrivate = jwk.d !== undefined;
if (isPrivate) {
enc.zero();
const enc$1 = new asn1_sequence_encoder_js_1.default();
enc$1.oidFor(jwk.crv);
enc.add(enc$1.end());
const enc$2 = new asn1_sequence_encoder_js_1.default();
enc$2.octStr(buffer_1.Buffer.from(jwk.d, 'base64'));
const f = enc$2.end(buffer_1.Buffer.from([0x04]));
enc.add(f);
const der = enc.end();
return (0, crypto_1.createPrivateKey)({ key: der, format: 'der', type: 'pkcs8' });
}
const enc$1 = new asn1_sequence_encoder_js_1.default();
enc$1.oidFor(jwk.crv);
enc.add(enc$1.end());
enc.bitStr(buffer_1.Buffer.from(jwk.x, 'base64'));
const der = enc.end();
return (0, crypto_1.createPublicKey)({ key: der, format: 'der', type: 'spki' });
}
default:
throw new errors_js_1.JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
}
return (jwk.d ? node_crypto_1.createPrivateKey : node_crypto_1.createPublicKey)({ format: 'jwk', key: jwk });
};
exports.default = parse;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const node_crypto_1 = require("node:crypto");
const base64url_js_1 = require("./base64url.js");
const asn1_sequence_decoder_js_1 = require("./asn1_sequence_decoder.js");
const errors_js_1 = require("../util/errors.js");
const get_named_curve_js_1 = require("./get_named_curve.js");
const webcrypto_js_1 = require("./webcrypto.js");

@@ -12,3 +10,2 @@ const is_key_object_js_1 = require("./is_key_object.js");

const is_key_like_js_1 = require("./is_key_like.js");
const flags_js_1 = require("./flags.js");
const keyToJWK = (key) => {

@@ -20,3 +17,3 @@ let keyObject;

}
keyObject = crypto_1.KeyObject.from(key);
keyObject = node_crypto_1.KeyObject.from(key);
}

@@ -35,129 +32,8 @@ else if ((0, is_key_object_js_1.default)(key)) {

}
if (flags_js_1.jwkExport) {
if (keyObject.type !== 'secret' &&
!['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) {
throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType');
}
return keyObject.export({ format: 'jwk' });
if (keyObject.type !== 'secret' &&
!['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) {
throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType');
}
switch (keyObject.type) {
case 'secret':
return {
kty: 'oct',
k: (0, base64url_js_1.encode)(keyObject.export()),
};
case 'private':
case 'public': {
switch (keyObject.asymmetricKeyType) {
case 'rsa': {
const der = keyObject.export({ format: 'der', type: 'pkcs1' });
const dec = new asn1_sequence_decoder_js_1.default(der);
if (keyObject.type === 'private') {
dec.unsignedInteger();
}
const n = (0, base64url_js_1.encode)(dec.unsignedInteger());
const e = (0, base64url_js_1.encode)(dec.unsignedInteger());
let jwk;
if (keyObject.type === 'private') {
jwk = {
d: (0, base64url_js_1.encode)(dec.unsignedInteger()),
p: (0, base64url_js_1.encode)(dec.unsignedInteger()),
q: (0, base64url_js_1.encode)(dec.unsignedInteger()),
dp: (0, base64url_js_1.encode)(dec.unsignedInteger()),
dq: (0, base64url_js_1.encode)(dec.unsignedInteger()),
qi: (0, base64url_js_1.encode)(dec.unsignedInteger()),
};
}
dec.end();
return { kty: 'RSA', n, e, ...jwk };
}
case 'ec': {
const crv = (0, get_named_curve_js_1.default)(keyObject);
let len;
let offset;
let correction;
switch (crv) {
case 'secp256k1':
len = 64;
offset = 31 + 2;
correction = -1;
break;
case 'P-256':
len = 64;
offset = 34 + 2;
correction = -1;
break;
case 'P-384':
len = 96;
offset = 33 + 2;
correction = -3;
break;
case 'P-521':
len = 132;
offset = 33 + 2;
correction = -3;
break;
default:
throw new errors_js_1.JOSENotSupported('Unsupported curve');
}
if (keyObject.type === 'public') {
const der = keyObject.export({ type: 'spki', format: 'der' });
return {
kty: 'EC',
crv,
x: (0, base64url_js_1.encode)(der.subarray(-len, -len / 2)),
y: (0, base64url_js_1.encode)(der.subarray(-len / 2)),
};
}
const der = keyObject.export({ type: 'pkcs8', format: 'der' });
if (der.length < 100) {
offset += correction;
}
return {
...keyToJWK((0, crypto_1.createPublicKey)(keyObject)),
d: (0, base64url_js_1.encode)(der.subarray(offset, offset + len / 2)),
};
}
case 'ed25519':
case 'x25519': {
const crv = (0, get_named_curve_js_1.default)(keyObject);
if (keyObject.type === 'public') {
const der = keyObject.export({ type: 'spki', format: 'der' });
return {
kty: 'OKP',
crv,
x: (0, base64url_js_1.encode)(der.subarray(-32)),
};
}
const der = keyObject.export({ type: 'pkcs8', format: 'der' });
return {
...keyToJWK((0, crypto_1.createPublicKey)(keyObject)),
d: (0, base64url_js_1.encode)(der.subarray(-32)),
};
}
case 'ed448':
case 'x448': {
const crv = (0, get_named_curve_js_1.default)(keyObject);
if (keyObject.type === 'public') {
const der = keyObject.export({ type: 'spki', format: 'der' });
return {
kty: 'OKP',
crv,
x: (0, base64url_js_1.encode)(der.subarray(crv === 'Ed448' ? -57 : -56)),
};
}
const der = keyObject.export({ type: 'pkcs8', format: 'der' });
return {
...keyToJWK((0, crypto_1.createPublicKey)(keyObject)),
d: (0, base64url_js_1.encode)(der.subarray(crv === 'Ed448' ? -57 : -56)),
};
}
default:
throw new errors_js_1.JOSENotSupported('Unsupported key asymmetricKeyType');
}
}
default:
throw new errors_js_1.JOSENotSupported('Unsupported key type');
}
return keyObject.export({ format: 'jwk' });
};
exports.default = keyToJWK;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const node_crypto_1 = require("node:crypto");
const get_named_curve_js_1 = require("./get_named_curve.js");
const errors_js_1 = require("../util/errors.js");
const check_modulus_length_js_1 = require("./check_modulus_length.js");
const flags_js_1 = require("./flags.js");
const check_key_length_js_1 = require("./check_key_length.js");
const PSS = {
padding: crypto_1.constants.RSA_PKCS1_PSS_PADDING,
saltLength: crypto_1.constants.RSA_PSS_SALTLEN_DIGEST,
padding: node_crypto_1.constants.RSA_PKCS1_PSS_PADDING,
saltLength: node_crypto_1.constants.RSA_PSS_SALTLEN_DIGEST,
};

@@ -31,7 +30,7 @@ const ecCurveAlgMap = new Map([

}
(0, check_modulus_length_js_1.default)(key, alg);
(0, check_key_length_js_1.default)(key, alg);
return key;
case flags_js_1.rsaPssParams && 'PS256':
case flags_js_1.rsaPssParams && 'PS384':
case flags_js_1.rsaPssParams && 'PS512':
case 'PS256':
case 'PS384':
case 'PS512':
if (key.asymmetricKeyType === 'rsa-pss') {

@@ -51,12 +50,4 @@ const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails;

}
(0, check_modulus_length_js_1.default)(key, alg);
(0, check_key_length_js_1.default)(key, alg);
return { key, ...PSS };
case !flags_js_1.rsaPssParams && 'PS256':
case !flags_js_1.rsaPssParams && 'PS384':
case !flags_js_1.rsaPssParams && 'PS512':
if (key.asymmetricKeyType !== 'rsa') {
throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');
}
(0, check_modulus_length_js_1.default)(key, alg);
return { key, ...PSS };
case 'ES256':

@@ -63,0 +54,0 @@ case 'ES256K':

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decrypt = exports.encrypt = void 0;
const util_1 = require("util");
const crypto_1 = require("crypto");
const node_util_1 = require("node:util");
const node_crypto_1 = require("node:crypto");
const random_js_1 = require("./random.js");

@@ -16,3 +16,3 @@ const buffer_utils_js_1 = require("../lib/buffer_utils.js");

const is_key_like_js_1 = require("./is_key_like.js");
const pbkdf2 = (0, util_1.promisify)(crypto_1.pbkdf2);
const pbkdf2 = (0, node_util_1.promisify)(node_crypto_1.pbkdf2);
function getPassword(key, alg) {

@@ -27,3 +27,3 @@ if ((0, is_key_object_js_1.default)(key)) {

(0, crypto_key_js_1.checkEncCryptoKey)(key, alg, 'deriveBits', 'deriveKey');
return crypto_1.KeyObject.from(key).export();
return node_crypto_1.KeyObject.from(key).export();
}

@@ -30,0 +30,0 @@ throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types, 'Uint8Array'));

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = void 0;
var crypto_1 = require("crypto");
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return crypto_1.randomFillSync; } });
var node_crypto_1 = require("node:crypto");
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return node_crypto_1.randomFillSync; } });
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.decrypt = exports.encrypt = void 0;
const crypto_1 = require("crypto");
const check_modulus_length_js_1 = require("./check_modulus_length.js");
const node_crypto_1 = require("node:crypto");
const check_key_length_js_1 = require("./check_key_length.js");
const webcrypto_js_1 = require("./webcrypto.js");

@@ -15,3 +15,3 @@ const crypto_key_js_1 = require("../lib/crypto_key.js");

}
(0, check_modulus_length_js_1.default)(key, alg);
(0, check_key_length_js_1.default)(key, alg);
};

@@ -24,5 +24,5 @@ const resolvePadding = (alg) => {

case 'RSA-OAEP-512':
return crypto_1.constants.RSA_PKCS1_OAEP_PADDING;
return node_crypto_1.constants.RSA_PKCS1_OAEP_PADDING;
case 'RSA1_5':
return crypto_1.constants.RSA_PKCS1_PADDING;
return node_crypto_1.constants.RSA_PKCS1_PADDING;
default:

@@ -52,3 +52,3 @@ return undefined;

(0, crypto_key_js_1.checkEncCryptoKey)(key, alg, ...usages);
return crypto_1.KeyObject.from(key);
return node_crypto_1.KeyObject.from(key);
}

@@ -62,3 +62,3 @@ throw new TypeError((0, invalid_key_input_js_1.default)(key, ...is_key_like_js_1.types));

checkKey(keyObject, alg);
return (0, crypto_1.publicEncrypt)({ key: keyObject, oaepHash, padding }, cek);
return (0, node_crypto_1.publicEncrypt)({ key: keyObject, oaepHash, padding }, cek);
};

@@ -71,4 +71,4 @@ exports.encrypt = encrypt;

checkKey(keyObject, alg);
return (0, crypto_1.privateDecrypt)({ key: keyObject, oaepHash, padding }, encryptedKey);
return (0, node_crypto_1.privateDecrypt)({ key: keyObject, oaepHash, padding }, encryptedKey);
};
exports.decrypt = decrypt;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto = require("crypto");
const util_1 = require("util");
const crypto = require("node:crypto");
const node_util_1 = require("node:util");
const dsa_digest_js_1 = require("./dsa_digest.js");

@@ -9,9 +9,3 @@ const hmac_digest_js_1 = require("./hmac_digest.js");

const get_sign_verify_key_js_1 = require("./get_sign_verify_key.js");
let oneShotSign;
if (crypto.sign.length > 3) {
oneShotSign = (0, util_1.promisify)(crypto.sign);
}
else {
oneShotSign = crypto.sign;
}
const oneShotSign = (0, node_util_1.promisify)(crypto.sign);
const sign = async (alg, key, data) => {

@@ -18,0 +12,0 @@ const keyObject = (0, get_sign_verify_key_js_1.default)(alg, key, 'sign');

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const timingSafeEqual = crypto_1.timingSafeEqual;
const node_crypto_1 = require("node:crypto");
const timingSafeEqual = node_crypto_1.timingSafeEqual;
exports.default = timingSafeEqual;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto = require("crypto");
const util_1 = require("util");
const crypto = require("node:crypto");
const node_util_1 = require("node:util");
const dsa_digest_js_1 = require("./dsa_digest.js");

@@ -9,10 +9,3 @@ const node_key_js_1 = require("./node_key.js");

const get_sign_verify_key_js_1 = require("./get_sign_verify_key.js");
const flags_js_1 = require("./flags.js");
let oneShotVerify;
if (crypto.verify.length > 4 && flags_js_1.oneShotCallback) {
oneShotVerify = (0, util_1.promisify)(crypto.verify);
}
else {
oneShotVerify = crypto.verify;
}
const oneShotVerify = (0, node_util_1.promisify)(crypto.verify);
const verify = async (alg, key, signature, data) => {

@@ -19,0 +12,0 @@ const keyObject = (0, get_sign_verify_key_js_1.default)(alg, key, 'verify');

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCryptoKey = void 0;
const crypto = require("crypto");
const util = require("util");
const crypto = require("node:crypto");
const util = require("node:util");
const webcrypto = crypto.webcrypto;
exports.default = webcrypto;
exports.isCryptoKey = util.types.isCryptoKey
? (key) => util.types.isCryptoKey(key)
:
(key) => false;
const isCryptoKey = (key) => util.types.isCryptoKey(key);
exports.isCryptoKey = isCryptoKey;

@@ -8,8 +8,7 @@ "use strict";

}
code = '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);
Error.captureStackTrace?.(this, this.constructor);
}

@@ -22,5 +21,7 @@ }

}
code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
claim;
reason;
constructor(message, claim = 'unspecified', reason = 'unspecified') {
super(message);
this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
this.claim = claim;

@@ -35,5 +36,7 @@ this.reason = reason;

}
code = 'ERR_JWT_EXPIRED';
claim;
reason;
constructor(message, claim = 'unspecified', reason = 'unspecified') {
super(message);
this.code = 'ERR_JWT_EXPIRED';
this.claim = claim;

@@ -45,126 +48,90 @@ this.reason = reason;

class JOSEAlgNotAllowed extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JOSE_ALG_NOT_ALLOWED';
}
static get code() {
return 'ERR_JOSE_ALG_NOT_ALLOWED';
}
code = 'ERR_JOSE_ALG_NOT_ALLOWED';
}
exports.JOSEAlgNotAllowed = JOSEAlgNotAllowed;
class JOSENotSupported extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JOSE_NOT_SUPPORTED';
}
static get code() {
return 'ERR_JOSE_NOT_SUPPORTED';
}
code = 'ERR_JOSE_NOT_SUPPORTED';
}
exports.JOSENotSupported = JOSENotSupported;
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';
}
code = 'ERR_JWE_DECRYPTION_FAILED';
message = 'decryption operation failed';
}
exports.JWEDecryptionFailed = JWEDecryptionFailed;
class JWEInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWE_INVALID';
}
static get code() {
return 'ERR_JWE_INVALID';
}
code = 'ERR_JWE_INVALID';
}
exports.JWEInvalid = JWEInvalid;
class JWSInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWS_INVALID';
}
static get code() {
return 'ERR_JWS_INVALID';
}
code = 'ERR_JWS_INVALID';
}
exports.JWSInvalid = JWSInvalid;
class JWTInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWT_INVALID';
}
static get code() {
return 'ERR_JWT_INVALID';
}
code = 'ERR_JWT_INVALID';
}
exports.JWTInvalid = JWTInvalid;
class JWKInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWK_INVALID';
}
static get code() {
return 'ERR_JWK_INVALID';
}
code = 'ERR_JWK_INVALID';
}
exports.JWKInvalid = JWKInvalid;
class JWKSInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWKS_INVALID';
}
static get code() {
return 'ERR_JWKS_INVALID';
}
code = 'ERR_JWKS_INVALID';
}
exports.JWKSInvalid = JWKSInvalid;
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';
}
code = 'ERR_JWKS_NO_MATCHING_KEY';
message = 'no applicable key found in the JSON Web Key Set';
}
exports.JWKSNoMatchingKey = JWKSNoMatchingKey;
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';
}
[Symbol.asyncIterator];
static get code() {
return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
}
code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
message = 'multiple matching keys found in the JSON Web Key Set';
}
exports.JWKSMultipleMatchingKeys = JWKSMultipleMatchingKeys;
Symbol.asyncIterator;
class JWKSTimeout extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWKS_TIMEOUT';
this.message = 'request timed out';
}
static get code() {
return 'ERR_JWKS_TIMEOUT';
}
code = 'ERR_JWKS_TIMEOUT';
message = 'request timed out';
}
exports.JWKSTimeout = JWKSTimeout;
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';
}
code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
message = 'signature verification failed';
}
exports.JWSSignatureVerificationFailed = JWSSignatureVerificationFailed;
import { FlattenedEncrypt } from '../flattened/encrypt.js';
export class CompactEncrypt {
_flattened;
constructor(plaintext) {

@@ -4,0 +5,0 @@ this._flattened = new FlattenedEncrypt(plaintext);

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

@@ -13,3 +12,2 @@ import isDisjoint from '../../lib/is_disjoint.js';

export async function flattenedDecrypt(jwe, key, options) {
var _a;
if (!isObject(jwe)) {

@@ -63,10 +61,5 @@ throw new JWEInvalid('Flattened JWE must be an object');

};
validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader);
validateCrit(JWEInvalid, new Map(), 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');
}
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
}

@@ -83,7 +76,8 @@ const { alg, enc } = joseHeader;

validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);
if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) {
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');
if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||
(!keyManagementAlgorithms && alg.startsWith('PBES2'))) {
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
}
if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter not allowed');
throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
}

@@ -128,3 +122,3 @@ let encryptedKey;

}
const protectedHeader = encoder.encode((_a = jwe.protected) !== null && _a !== void 0 ? _a : '');
const protectedHeader = encoder.encode(jwe.protected ?? '');
let additionalData;

@@ -145,5 +139,2 @@ if (jwe.aad !== undefined) {

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

@@ -150,0 +141,0 @@ if (jwe.protected !== undefined) {

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

@@ -12,2 +11,10 @@ import encryptKeyManagement from '../../lib/encrypt_key_management.js';

export class FlattenedEncrypt {
_plaintext;
_protectedHeader;
_sharedUnprotectedHeader;
_unprotectedHeader;
_aad;
_cek;
_iv;
_keyManagementParameters;
constructor(plaintext) {

@@ -77,10 +84,5 @@ if (!(plaintext instanceof Uint8Array)) {

};
validateCrit(JWEInvalid, new Map(), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);
validateCrit(JWEInvalid, new Map(), 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');
}
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
}

@@ -128,3 +130,3 @@ const { alg, enc } = joseHeader;

}
this._iv || (this._iv = generateIv(enc));
this._iv ||= generateIv(enc);
let additionalData;

@@ -146,12 +148,3 @@ let 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 { ciphertext, tag } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData);
const jwe = {

@@ -158,0 +151,0 @@ ciphertext: base64url(ciphertext),

import { FlattenedEncrypt, unprotected } from '../flattened/encrypt.js';
import { JWEInvalid } from '../../util/errors.js';
import { JOSENotSupported, JWEInvalid } from '../../util/errors.js';
import generateCek from '../../lib/cek.js';

@@ -9,2 +9,6 @@ import isDisjoint from '../../lib/is_disjoint.js';

class IndividualRecipient {
parent;
unprotectedHeader;
key;
options;
constructor(enc, key, options) {

@@ -33,8 +37,12 @@ this.parent = enc;

export class GeneralEncrypt {
_plaintext;
_recipients = [];
_protectedHeader;
_unprotectedHeader;
_aad;
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 });
const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
this._recipients.push(recipient);

@@ -61,8 +69,6 @@ return recipient;

}
async encrypt(options) {
var _a, _b, _c;
async encrypt() {
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) {

@@ -75,3 +81,3 @@ const [recipient] = this._recipients;

.setUnprotectedHeader(recipient.unprotectedHeader)
.encrypt(recipient.key, { ...recipient.options, ...options });
.encrypt(recipient.key, { ...recipient.options });
let jwe = {

@@ -124,5 +130,3 @@ ciphertext: flattened.ciphertext,

if (joseHeader.zip !== undefined) {
if (!this._protectedHeader || !this._protectedHeader.zip) {
throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');
}
throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
}

@@ -157,3 +161,2 @@ }

...recipient.options,
...options,
[unprotected]: true,

@@ -175,5 +178,5 @@ });

}
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 });
const { encryptedKey, parameters } = await encryptKeyManagement(recipient.unprotectedHeader?.alg ||
this._protectedHeader?.alg ||
this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c });
target.encrypted_key = base64url(encryptedKey);

@@ -180,0 +183,0 @@ if (recipient.unprotectedHeader || parameters)

@@ -7,3 +7,3 @@ import { importJWK } from '../key/import.js';

...protectedHeader,
...token === null || token === void 0 ? void 0 : token.header,
...token?.header,
};

@@ -13,3 +13,3 @@ if (!isObject(joseHeader.jwk)) {

}
const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg, true);
const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg);
if (key instanceof Uint8Array || key.type !== 'public') {

@@ -16,0 +16,0 @@ throw new JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');

@@ -15,3 +15,3 @@ import digest from '../runtime/digest.js';

}
digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256');
digestAlgorithm ??= 'sha256';
if (digestAlgorithm !== 'sha256' &&

@@ -51,5 +51,5 @@ digestAlgorithm !== 'sha384' &&

export async function calculateJwkThumbprintUri(jwk, digestAlgorithm) {
digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256');
digestAlgorithm ??= 'sha256';
const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);
return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
}

@@ -33,4 +33,5 @@ import { importJWK } from '../key/import.js';

export class LocalJWKSet {
_jwks;
_cached = new WeakMap();
constructor(jwks) {
this._cached = new WeakMap();
if (!isJWKSLike(jwks)) {

@@ -42,3 +43,3 @@ throw new JWKSInvalid('JSON Web Key Set malformed');

async getKey(protectedHeader, token) {
const { alg, kid } = { ...protectedHeader, ...token === null || token === void 0 ? void 0 : token.header };
const { alg, kid } = { ...protectedHeader, ...token?.header };
const kty = getKtyFromAlg(alg);

@@ -45,0 +46,0 @@ const candidates = this._jwks.keys.filter((jwk) => {

@@ -10,2 +10,9 @@ import fetchJwks from '../runtime/fetch_jwks.js';

class RemoteJWKSet extends LocalJWKSet {
_url;
_timeoutDuration;
_cooldownDuration;
_cacheMaxAge;
_jwksTimestamp;
_pendingFetch;
_options;
constructor(url, options) {

@@ -18,8 +25,8 @@ super({ keys: [] });

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._options = { agent: options?.agent, headers: 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;
typeof options?.timeoutDuration === 'number' ? 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;
typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;
this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;
}

@@ -57,3 +64,3 @@ coolingDown() {

}
this._pendingFetch || (this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options)
this._pendingFetch ||= fetchJwks(this._url, this._timeoutDuration, this._options)
.then((json) => {

@@ -70,3 +77,3 @@ if (!isJWKSLike(json)) {

throw err;
}));
});
await this._pendingFetch;

@@ -73,0 +80,0 @@ }

import { FlattenedSign } from '../flattened/sign.js';
export class CompactSign {
_flattened;
constructor(payload) {

@@ -4,0 +5,0 @@ this._flattened = new FlattenedSign(payload);

@@ -9,2 +9,5 @@ import { encode as base64url } from '../../runtime/base64url.js';

export class FlattenedSign {
_payload;
_protectedHeader;
_unprotectedHeader;
constructor(payload) {

@@ -41,3 +44,3 @@ if (!(payload instanceof Uint8Array)) {

};
const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, this._protectedHeader, joseHeader);
const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader);
let b64 = true;

@@ -44,0 +47,0 @@ if (extensions.has('b64')) {

@@ -11,3 +11,2 @@ import { decode as base64url } from '../../runtime/base64url.js';

export async function flattenedVerify(jws, key, options) {
var _a;
if (!isObject(jws)) {

@@ -48,3 +47,3 @@ throw new JWSInvalid('Flattened JWS must be an object');

};
const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options === null || options === void 0 ? void 0 : options.crit, parsedProt, joseHeader);
const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);
let b64 = true;

@@ -63,3 +62,3 @@ if (extensions.has('b64')) {

if (algorithms && !algorithms.has(alg)) {
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter not allowed');
throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
}

@@ -80,3 +79,3 @@ if (b64) {

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);
const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload);
let signature;

@@ -83,0 +82,0 @@ try {

import { FlattenedSign } from '../flattened/sign.js';
import { JWSInvalid } from '../../util/errors.js';
class IndividualSignature {
parent;
protectedHeader;
unprotectedHeader;
options;
key;
constructor(sig, key, options) {

@@ -34,4 +39,5 @@ this.parent = sig;

export class GeneralSign {
_payload;
_signatures = [];
constructor(payload) {
this._signatures = [];
this._payload = payload;

@@ -38,0 +44,0 @@ }

@@ -5,2 +5,9 @@ import { CompactEncrypt } from '../jwe/compact/encrypt.js';

export class EncryptJWT extends ProduceJWT {
_cek;
_iv;
_keyManagementParameters;
_protectedHeader;
_replicateIssuerAsHeader;
_replicateSubjectAsHeader;
_replicateAudienceAsHeader;
setProtectedHeader(protectedHeader) {

@@ -7,0 +14,0 @@ if (this._protectedHeader) {

import epoch from '../lib/epoch.js';
import isObject from '../lib/is_object.js';
import secs from '../lib/secs.js';
function validateInput(label, input) {
if (!Number.isFinite(input)) {
throw new TypeError(`Invalid ${label} input`);
}
return input;
}
export class ProduceJWT {
constructor(payload) {
_payload;
constructor(payload = {}) {
if (!isObject(payload)) {

@@ -29,4 +36,7 @@ throw new TypeError('JWT Claims Set MUST be an object');

if (typeof input === 'number') {
this._payload = { ...this._payload, nbf: input };
this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) };
}
else if (input instanceof Date) {
this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) };
}
else {

@@ -39,4 +49,7 @@ this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) };

if (typeof input === 'number') {
this._payload = { ...this._payload, exp: input };
this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) };
}
else if (input instanceof Date) {
this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) };
}
else {

@@ -51,4 +64,7 @@ this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) };

}
else if (input instanceof Date) {
this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) };
}
else {
this._payload = { ...this._payload, iat: input };
this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) };
}

@@ -55,0 +71,0 @@ return this;

@@ -6,2 +6,3 @@ import { CompactSign } from '../jws/compact/sign.js';

export class SignJWT extends ProduceJWT {
_protectedHeader;
setProtectedHeader(protectedHeader) {

@@ -12,6 +13,5 @@ this._protectedHeader = protectedHeader;

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) &&
if (Array.isArray(this._protectedHeader?.crit) &&
this._protectedHeader.crit.includes('b64') &&

@@ -18,0 +18,0 @@ this._protectedHeader.b64 === false) {

@@ -5,5 +5,4 @@ import { compactVerify } from '../jws/compact/verify.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) {
if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
throw new JWTInvalid('JWTs MUST NOT use unencoded payload');

@@ -10,0 +9,0 @@ }

@@ -24,8 +24,7 @@ import { decode as decodeBase64URL } from '../runtime/base64url.js';

}
export async function importJWK(jwk, alg, octAsKeyObject) {
var _a;
export async function importJWK(jwk, alg) {
if (!isObject(jwk)) {
throw new TypeError('JWK must be an object');
}
alg || (alg = jwk.alg);
alg ||= jwk.alg;
switch (jwk.kty) {

@@ -36,6 +35,2 @@ case 'oct':

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

@@ -42,0 +37,0 @@ case 'RSA':

@@ -7,3 +7,3 @@ import encrypt from '../runtime/encrypt.js';

const jweAlgorithm = alg.slice(0, 7);
iv || (iv = generateIv(jweAlgorithm));
iv ||= generateIv(jweAlgorithm);
const { ciphertext: encryptedKey, tag } = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0));

@@ -10,0 +10,0 @@ return { encryptedKey, iv: base64url(iv), tag: base64url(tag) };

@@ -76,3 +76,3 @@ import { unwrap as aesKw } from '../runtime/aeskw.js';

throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
const p2cLimit = (options === null || options === void 0 ? void 0 : options.maxPBES2Count) || 10000;
const p2cLimit = options?.maxPBES2Count || 10000;
if (joseHeader.p2c > p2cLimit)

@@ -79,0 +79,0 @@ throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);

@@ -30,3 +30,3 @@ import { wrap as aesKw } from '../runtime/aeskw.js';

let { epk: ephemeralKey } = providedParameters;
ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey);
ephemeralKey ||= (await ECDH.generateEpk(key)).privateKey;
const { x, y, crv, kty } = await exportJWK(ephemeralKey);

@@ -33,0 +33,0 @@ 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);

@@ -1,3 +0,3 @@

import { Buffer } from 'buffer';
import { KeyObject, createDecipheriv, createCipheriv, createSecretKey } from 'crypto';
import { Buffer } from 'node:buffer';
import { KeyObject, createDecipheriv, createCipheriv, createSecretKey } from 'node:crypto';
import { JOSENotSupported } from '../util/errors.js';

@@ -4,0 +4,0 @@ import { concat } from '../lib/buffer_utils.js';

@@ -1,3 +0,3 @@

import { createPrivateKey, createPublicKey, KeyObject } from 'crypto';
import { Buffer } from 'buffer';
import { createPrivateKey, createPublicKey, KeyObject } from 'node:crypto';
import { Buffer } from 'node:buffer';
import { isCryptoKey } from './webcrypto.js';

@@ -4,0 +4,0 @@ import isKeyObject from './is_key_object.js';

@@ -1,4 +0,3 @@

import { Buffer } from 'buffer';
import { Buffer } from 'node:buffer';
import { decoder } from '../lib/buffer_utils.js';
let encode;
function normalize(input) {

@@ -11,11 +10,6 @@ let encoded = input;

}
if (Buffer.isEncoding('base64url')) {
encode = (input) => Buffer.from(input).toString('base64url');
}
else {
encode = (input) => Buffer.from(input).toString('base64').replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
export const decodeBase64 = (input) => Buffer.from(input, 'base64');
const encode = (input) => Buffer.from(input).toString('base64url');
export const decodeBase64 = (input) => new Uint8Array(Buffer.from(input, 'base64'));
export const encodeBase64 = (input) => Buffer.from(input).toString('base64');
export { encode };
export const decode = (input) => Buffer.from(normalize(input), 'base64');
export const decode = (input) => new Uint8Array(Buffer.from(normalize(input), 'base64'));

@@ -1,2 +0,2 @@

import { createHmac } from 'crypto';
import { createHmac } from 'node:crypto';
import { concat, uint64be } from '../lib/buffer_utils.js';

@@ -3,0 +3,0 @@ export default function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) {

@@ -1,6 +0,6 @@

import { getCiphers } from 'crypto';
import { getCiphers } from 'node:crypto';
let ciphers;
export default (algorithm) => {
ciphers || (ciphers = new Set(getCiphers()));
ciphers ||= new Set(getCiphers());
return ciphers.has(algorithm);
};

@@ -1,2 +0,2 @@

import { createDecipheriv, KeyObject } from 'crypto';
import { createDecipheriv, KeyObject } from 'node:crypto';
import checkIvLength from '../lib/check_iv_length.js';

@@ -3,0 +3,0 @@ import checkCekLength from './check_cek_length.js';

@@ -1,3 +0,3 @@

import { createHash } from 'crypto';
import { createHash } from 'node:crypto';
const digest = (algorithm, data) => createHash(algorithm).update(data).digest();
export default digest;

@@ -1,3 +0,3 @@

import { diffieHellman, generateKeyPair as generateKeyPairCb, KeyObject } from 'crypto';
import { promisify } from 'util';
import { diffieHellman, generateKeyPair as generateKeyPairCb, KeyObject } from 'node:crypto';
import { promisify } from 'node:util';
import getNamedCurve from './get_named_curve.js';

@@ -4,0 +4,0 @@ import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js';

@@ -1,2 +0,2 @@

import { createCipheriv, KeyObject } from 'crypto';
import { createCipheriv, KeyObject } from 'node:crypto';
import checkIvLength from '../lib/check_iv_length.js';

@@ -3,0 +3,0 @@ import checkCekLength from './check_cek_length.js';

@@ -1,4 +0,4 @@

import * as http from 'http';
import * as https from 'https';
import { once } from 'events';
import * as http from 'node:http';
import * as https from 'node:https';
import { once } from 'node:events';
import { JOSEError, JWKSTimeout } from '../util/errors.js';

@@ -5,0 +5,0 @@ import { concat, decoder } from '../lib/buffer_utils.js';

@@ -1,5 +0,4 @@

import { createSecretKey, generateKeyPair as generateKeyPairCb } from 'crypto';
import { promisify } from 'util';
import { createSecretKey, generateKeyPair as generateKeyPairCb } from 'node:crypto';
import { promisify } from 'node:util';
import random from './random.js';
import { setModulusLength } from './check_modulus_length.js';
import { JOSENotSupported } from '../util/errors.js';

@@ -35,3 +34,2 @@ const generate = promisify(generateKeyPairCb);

export async function generateKeyPair(alg, options) {
var _a, _b;
switch (alg) {

@@ -49,3 +47,3 @@ case 'RS256':

case 'RSA1_5': {
const modulusLength = (_a = options === null || options === void 0 ? void 0 : options.modulusLength) !== null && _a !== void 0 ? _a : 2048;
const modulusLength = options?.modulusLength ?? 2048;
if (typeof modulusLength !== 'number' || modulusLength < 2048) {

@@ -58,4 +56,2 @@ throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');

});
setModulusLength(keypair.privateKey, modulusLength);
setModulusLength(keypair.publicKey, modulusLength);
return keypair;

@@ -72,3 +68,3 @@ }

case 'EdDSA': {
switch (options === null || options === void 0 ? void 0 : options.crv) {
switch (options?.crv) {
case undefined:

@@ -87,3 +83,3 @@ case 'Ed25519':

case 'ECDH-ES+A256KW':
const crv = (_b = options === null || options === void 0 ? void 0 : options.crv) !== null && _b !== void 0 ? _b : 'P-256';
const crv = options?.crv ?? 'P-256';
switch (crv) {

@@ -90,0 +86,0 @@ case undefined:

@@ -1,3 +0,2 @@

import { Buffer } from 'buffer';
import { createPublicKey, KeyObject } from 'crypto';
import { KeyObject } from 'node:crypto';
import { JOSENotSupported } from '../util/errors.js';

@@ -8,6 +7,2 @@ import { isCryptoKey } from './webcrypto.js';

import { types } from './is_key_like.js';
const p256 = Buffer.from([42, 134, 72, 206, 61, 3, 1, 7]);
const p384 = Buffer.from([43, 129, 4, 0, 34]);
const p521 = Buffer.from([43, 129, 4, 0, 35]);
const secp256k1 = Buffer.from([43, 129, 4, 0, 10]);
export const weakMap = new WeakMap();

@@ -29,3 +24,2 @@ const namedCurveToJOSE = (namedCurve) => {

const getNamedCurve = (kee, raw) => {
var _a;
let key;

@@ -52,35 +46,7 @@ if (isCryptoKey(kee)) {

case 'ec': {
if (weakMap.has(key)) {
return weakMap.get(key);
let namedCurve = key.asymmetricKeyDetails.namedCurve;
if (raw) {
return namedCurve;
}
let namedCurve = (_a = key.asymmetricKeyDetails) === null || _a === void 0 ? void 0 : _a.namedCurve;
if (!namedCurve && key.type === 'private') {
namedCurve = getNamedCurve(createPublicKey(key), true);
}
else if (!namedCurve) {
const buf = key.export({ format: 'der', type: 'spki' });
const i = buf[1] < 128 ? 14 : 15;
const len = buf[i];
const curveOid = buf.slice(i + 1, i + 1 + len);
if (curveOid.equals(p256)) {
namedCurve = 'prime256v1';
}
else if (curveOid.equals(p384)) {
namedCurve = 'secp384r1';
}
else if (curveOid.equals(p521)) {
namedCurve = 'secp521r1';
}
else if (curveOid.equals(secp256k1)) {
namedCurve = 'secp256k1';
}
else {
throw new JOSENotSupported('Unsupported key curve for this operation');
}
}
if (raw)
return namedCurve;
const curve = namedCurveToJOSE(namedCurve);
weakMap.set(key, curve);
return curve;
return namedCurveToJOSE(namedCurve);
}

@@ -91,5 +57,2 @@ default:

};
export function setCurve(keyObject, curve) {
weakMap.set(keyObject, curve);
}
export default getNamedCurve;

@@ -1,2 +0,2 @@

import { KeyObject, createSecretKey } from 'crypto';
import { KeyObject, createSecretKey } from 'node:crypto';
import { isCryptoKey } from './webcrypto.js';

@@ -3,0 +3,0 @@ import { checkSigCryptoKey } from '../lib/crypto_key.js';

@@ -5,5 +5,5 @@ import webcrypto, { isCryptoKey } from './webcrypto.js';

const types = ['KeyObject'];
if (globalThis.CryptoKey || (webcrypto === null || webcrypto === void 0 ? void 0 : webcrypto.CryptoKey)) {
if (globalThis.CryptoKey || webcrypto?.CryptoKey) {
types.push('CryptoKey');
}
export { types };

@@ -1,5 +0,2 @@

import { KeyObject } from 'crypto';
import * as util from 'util';
export default util.types.isKeyObject
? (obj) => util.types.isKeyObject(obj)
: (obj) => obj != null && obj instanceof KeyObject;
import * as util from 'node:util';
export default (obj) => util.types.isKeyObject(obj);

@@ -1,116 +0,5 @@

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

@@ -1,6 +0,4 @@

import { KeyObject, createPublicKey } from 'crypto';
import { KeyObject } from 'node:crypto';
import { encode as base64url } from './base64url.js';
import Asn1SequenceDecoder from './asn1_sequence_decoder.js';
import { JOSENotSupported } from '../util/errors.js';
import getNamedCurve from './get_named_curve.js';
import { isCryptoKey } from './webcrypto.js';

@@ -10,3 +8,2 @@ import isKeyObject from './is_key_object.js';

import { types } from './is_key_like.js';
import { jwkExport } from './flags.js';
const keyToJWK = (key) => {

@@ -32,129 +29,8 @@ let keyObject;

}
if (jwkExport) {
if (keyObject.type !== 'secret' &&
!['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) {
throw new JOSENotSupported('Unsupported key asymmetricKeyType');
}
return keyObject.export({ format: 'jwk' });
if (keyObject.type !== 'secret' &&
!['rsa', 'ec', 'ed25519', 'x25519', 'ed448', 'x448'].includes(keyObject.asymmetricKeyType)) {
throw new JOSENotSupported('Unsupported key asymmetricKeyType');
}
switch (keyObject.type) {
case 'secret':
return {
kty: 'oct',
k: base64url(keyObject.export()),
};
case 'private':
case 'public': {
switch (keyObject.asymmetricKeyType) {
case 'rsa': {
const der = keyObject.export({ format: 'der', type: 'pkcs1' });
const dec = new Asn1SequenceDecoder(der);
if (keyObject.type === 'private') {
dec.unsignedInteger();
}
const n = base64url(dec.unsignedInteger());
const e = base64url(dec.unsignedInteger());
let jwk;
if (keyObject.type === 'private') {
jwk = {
d: base64url(dec.unsignedInteger()),
p: base64url(dec.unsignedInteger()),
q: base64url(dec.unsignedInteger()),
dp: base64url(dec.unsignedInteger()),
dq: base64url(dec.unsignedInteger()),
qi: base64url(dec.unsignedInteger()),
};
}
dec.end();
return { kty: 'RSA', n, e, ...jwk };
}
case 'ec': {
const crv = getNamedCurve(keyObject);
let len;
let offset;
let correction;
switch (crv) {
case 'secp256k1':
len = 64;
offset = 31 + 2;
correction = -1;
break;
case 'P-256':
len = 64;
offset = 34 + 2;
correction = -1;
break;
case 'P-384':
len = 96;
offset = 33 + 2;
correction = -3;
break;
case 'P-521':
len = 132;
offset = 33 + 2;
correction = -3;
break;
default:
throw new JOSENotSupported('Unsupported curve');
}
if (keyObject.type === 'public') {
const der = keyObject.export({ type: 'spki', format: 'der' });
return {
kty: 'EC',
crv,
x: base64url(der.subarray(-len, -len / 2)),
y: base64url(der.subarray(-len / 2)),
};
}
const der = keyObject.export({ type: 'pkcs8', format: 'der' });
if (der.length < 100) {
offset += correction;
}
return {
...keyToJWK(createPublicKey(keyObject)),
d: base64url(der.subarray(offset, offset + len / 2)),
};
}
case 'ed25519':
case 'x25519': {
const crv = getNamedCurve(keyObject);
if (keyObject.type === 'public') {
const der = keyObject.export({ type: 'spki', format: 'der' });
return {
kty: 'OKP',
crv,
x: base64url(der.subarray(-32)),
};
}
const der = keyObject.export({ type: 'pkcs8', format: 'der' });
return {
...keyToJWK(createPublicKey(keyObject)),
d: base64url(der.subarray(-32)),
};
}
case 'ed448':
case 'x448': {
const crv = getNamedCurve(keyObject);
if (keyObject.type === 'public') {
const der = keyObject.export({ type: 'spki', format: 'der' });
return {
kty: 'OKP',
crv,
x: base64url(der.subarray(crv === 'Ed448' ? -57 : -56)),
};
}
const der = keyObject.export({ type: 'pkcs8', format: 'der' });
return {
...keyToJWK(createPublicKey(keyObject)),
d: base64url(der.subarray(crv === 'Ed448' ? -57 : -56)),
};
}
default:
throw new JOSENotSupported('Unsupported key asymmetricKeyType');
}
}
default:
throw new JOSENotSupported('Unsupported key type');
}
return keyObject.export({ format: 'jwk' });
};
export default keyToJWK;

@@ -1,6 +0,5 @@

import { constants } from 'crypto';
import { constants } from 'node:crypto';
import getNamedCurve from './get_named_curve.js';
import { JOSENotSupported } from '../util/errors.js';
import checkModulusLength from './check_modulus_length.js';
import { rsaPssParams } from './flags.js';
import checkKeyLength from './check_key_length.js';
const PSS = {

@@ -29,7 +28,7 @@ padding: constants.RSA_PKCS1_PSS_PADDING,

}
checkModulusLength(key, alg);
checkKeyLength(key, alg);
return key;
case rsaPssParams && 'PS256':
case rsaPssParams && 'PS384':
case rsaPssParams && 'PS512':
case 'PS256':
case 'PS384':
case 'PS512':
if (key.asymmetricKeyType === 'rsa-pss') {

@@ -49,12 +48,4 @@ const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = key.asymmetricKeyDetails;

}
checkModulusLength(key, alg);
checkKeyLength(key, alg);
return { key, ...PSS };
case !rsaPssParams && 'PS256':
case !rsaPssParams && 'PS384':
case !rsaPssParams && 'PS512':
if (key.asymmetricKeyType !== 'rsa') {
throw new TypeError('Invalid key for this operation, its asymmetricKeyType must be rsa');
}
checkModulusLength(key, alg);
return { key, ...PSS };
case 'ES256':

@@ -61,0 +52,0 @@ case 'ES256K':

@@ -1,3 +0,3 @@

import { promisify } from 'util';
import { KeyObject, pbkdf2 as pbkdf2cb } from 'crypto';
import { promisify } from 'node:util';
import { KeyObject, pbkdf2 as pbkdf2cb } from 'node:crypto';
import random from './random.js';

@@ -4,0 +4,0 @@ import { p2s as concatSalt } from '../lib/buffer_utils.js';

@@ -1,1 +0,1 @@

export { randomFillSync as default } from 'crypto';
export { randomFillSync as default } from 'node:crypto';

@@ -1,3 +0,3 @@

import { KeyObject, publicEncrypt, constants, privateDecrypt } from 'crypto';
import checkModulusLength from './check_modulus_length.js';
import { KeyObject, publicEncrypt, constants, privateDecrypt } from 'node:crypto';
import checkKeyLength from './check_key_length.js';
import { isCryptoKey } from './webcrypto.js';

@@ -12,3 +12,3 @@ import { checkEncCryptoKey } from '../lib/crypto_key.js';

}
checkModulusLength(key, alg);
checkKeyLength(key, alg);
};

@@ -15,0 +15,0 @@ const resolvePadding = (alg) => {

@@ -1,3 +0,3 @@

import * as crypto from 'crypto';
import { promisify } from 'util';
import * as crypto from 'node:crypto';
import { promisify } from 'node:util';
import nodeDigest from './dsa_digest.js';

@@ -7,9 +7,3 @@ import hmacDigest from './hmac_digest.js';

import getSignKey from './get_sign_verify_key.js';
let oneShotSign;
if (crypto.sign.length > 3) {
oneShotSign = promisify(crypto.sign);
}
else {
oneShotSign = crypto.sign;
}
const oneShotSign = promisify(crypto.sign);
const sign = async (alg, key, data) => {

@@ -16,0 +10,0 @@ const keyObject = getSignKey(alg, key, 'sign');

@@ -1,3 +0,3 @@

import { timingSafeEqual as impl } from 'crypto';
import { timingSafeEqual as impl } from 'node:crypto';
const timingSafeEqual = impl;
export default timingSafeEqual;

@@ -1,3 +0,3 @@

import * as crypto from 'crypto';
import { promisify } from 'util';
import * as crypto from 'node:crypto';
import { promisify } from 'node:util';
import nodeDigest from './dsa_digest.js';

@@ -7,10 +7,3 @@ import nodeKey from './node_key.js';

import getVerifyKey from './get_sign_verify_key.js';
import { oneShotCallback } from './flags.js';
let oneShotVerify;
if (crypto.verify.length > 4 && oneShotCallback) {
oneShotVerify = promisify(crypto.verify);
}
else {
oneShotVerify = crypto.verify;
}
const oneShotVerify = promisify(crypto.verify);
const verify = async (alg, key, signature, data) => {

@@ -17,0 +10,0 @@ const keyObject = getVerifyKey(alg, key, 'verify');

@@ -1,8 +0,5 @@

import * as crypto from 'crypto';
import * as util from 'util';
import * as crypto from 'node:crypto';
import * as util from 'node:util';
const webcrypto = crypto.webcrypto;
export default webcrypto;
export const isCryptoKey = util.types.isCryptoKey
? (key) => util.types.isCryptoKey(key)
:
(key) => false;
export const isCryptoKey = (key) => util.types.isCryptoKey(key);

@@ -5,8 +5,7 @@ export class JOSEError extends Error {

}
code = '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);
Error.captureStackTrace?.(this, this.constructor);
}

@@ -18,5 +17,7 @@ }

}
code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
claim;
reason;
constructor(message, claim = 'unspecified', reason = 'unspecified') {
super(message);
this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
this.claim = claim;

@@ -30,5 +31,7 @@ this.reason = reason;

}
code = 'ERR_JWT_EXPIRED';
claim;
reason;
constructor(message, claim = 'unspecified', reason = 'unspecified') {
super(message);
this.code = 'ERR_JWT_EXPIRED';
this.claim = claim;

@@ -39,114 +42,78 @@ 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';
}
code = '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';
}
code = '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';
}
code = 'ERR_JWE_DECRYPTION_FAILED';
message = 'decryption operation failed';
}
export class JWEInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWE_INVALID';
}
static get code() {
return 'ERR_JWE_INVALID';
}
code = 'ERR_JWE_INVALID';
}
export class JWSInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWS_INVALID';
}
static get code() {
return 'ERR_JWS_INVALID';
}
code = 'ERR_JWS_INVALID';
}
export class JWTInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWT_INVALID';
}
static get code() {
return 'ERR_JWT_INVALID';
}
code = 'ERR_JWT_INVALID';
}
export class JWKInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWK_INVALID';
}
static get code() {
return 'ERR_JWK_INVALID';
}
code = 'ERR_JWK_INVALID';
}
export class JWKSInvalid extends JOSEError {
constructor() {
super(...arguments);
this.code = 'ERR_JWKS_INVALID';
}
static get code() {
return 'ERR_JWKS_INVALID';
}
code = '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';
}
code = 'ERR_JWKS_NO_MATCHING_KEY';
message = 'no applicable key found in the JSON Web Key Set';
}
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';
}
[Symbol.asyncIterator];
static get code() {
return 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
}
code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
message = 'multiple matching keys found in the JSON Web Key Set';
}
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';
}
code = 'ERR_JWKS_TIMEOUT';
message = 'request timed out';
}
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';
}
code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
message = 'signature verification failed';
}

@@ -47,3 +47,3 @@ export { compactDecrypt } from './jwe/compact/decrypt';

export * as base64url from './util/base64url';
export type { KeyLike, JWK, FlattenedJWSInput, GeneralJWSInput, FlattenedJWS, GeneralJWS, JoseHeaderParameters, JWSHeaderParameters, JWEKeyManagementHeaderParameters, FlattenedJWE, GeneralJWE, JWEHeaderParameters, CritOption, DeflateOption, DecryptOptions, EncryptOptions, JWTClaimVerificationOptions, VerifyOptions, SignOptions, JWTPayload, DeflateFunction, InflateFunction, FlattenedDecryptResult, GeneralDecryptResult, CompactDecryptResult, FlattenedVerifyResult, GeneralVerifyResult, CompactVerifyResult, JWTVerifyResult, JWTDecryptResult, ResolvedKey, CompactJWEHeaderParameters, CompactJWSHeaderParameters, JWTHeaderParameters, JSONWebKeySet, CryptoRuntime, GetKeyFunction, } from './types';
export type { KeyLike, JWK, FlattenedJWSInput, GeneralJWSInput, FlattenedJWS, GeneralJWS, JoseHeaderParameters, JWSHeaderParameters, JWEKeyManagementHeaderParameters, FlattenedJWE, GeneralJWE, JWEHeaderParameters, CritOption, DecryptOptions, EncryptOptions, JWTClaimVerificationOptions, VerifyOptions, SignOptions, JWTPayload, FlattenedDecryptResult, GeneralDecryptResult, CompactDecryptResult, FlattenedVerifyResult, GeneralVerifyResult, CompactVerifyResult, JWTVerifyResult, JWTDecryptResult, ResolvedKey, CompactJWEHeaderParameters, CompactJWSHeaderParameters, JWTHeaderParameters, JSONWebKeySet, CryptoRuntime, GetKeyFunction, } from './types';
export { default as cryptoRuntime } from './util/runtime';

@@ -23,2 +23,2 @@ import type { KeyLike, DecryptOptions, CompactJWEHeaderParameters, GetKeyFunction, FlattenedJWE, CompactDecryptResult, ResolvedKey } from '../../types';

*/
export declare function compactDecrypt<T extends KeyLike = KeyLike>(jwe: string | Uint8Array, getKey: CompactDecryptGetKey, options?: DecryptOptions): Promise<CompactDecryptResult & ResolvedKey<T>>;
export declare function compactDecrypt<KeyLikeType extends KeyLike = KeyLike>(jwe: string | Uint8Array, getKey: CompactDecryptGetKey, options?: DecryptOptions): Promise<CompactDecryptResult & ResolvedKey<KeyLikeType>>;

@@ -23,2 +23,2 @@ import type { FlattenedDecryptResult, KeyLike, FlattenedJWE, JWEHeaderParameters, DecryptOptions, GetKeyFunction, ResolvedKey } from '../../types';

*/
export declare function flattenedDecrypt<T extends KeyLike = KeyLike>(jwe: FlattenedJWE, getKey: FlattenedDecryptGetKey, options?: DecryptOptions): Promise<FlattenedDecryptResult & ResolvedKey<T>>;
export declare function flattenedDecrypt<KeyLikeType extends KeyLike = KeyLike>(jwe: FlattenedJWE, getKey: FlattenedDecryptGetKey, options?: DecryptOptions): Promise<FlattenedDecryptResult & ResolvedKey<KeyLikeType>>;

@@ -23,2 +23,2 @@ import type { KeyLike, DecryptOptions, JWEHeaderParameters, GetKeyFunction, FlattenedJWE, GeneralJWE, GeneralDecryptResult, ResolvedKey } from '../../types';

*/
export declare function generalDecrypt<T extends KeyLike = KeyLike>(jwe: GeneralJWE, getKey: GeneralDecryptGetKey, options?: DecryptOptions): Promise<GeneralDecryptResult & ResolvedKey<T>>;
export declare function generalDecrypt<KeyLikeType extends KeyLike = KeyLike>(jwe: GeneralJWE, getKey: GeneralDecryptGetKey, options?: DecryptOptions): Promise<GeneralDecryptResult & ResolvedKey<KeyLikeType>>;

@@ -1,2 +0,2 @@

import type { KeyLike, GeneralJWE, JWEHeaderParameters, CritOption, DeflateOption } from '../../types';
import type { KeyLike, GeneralJWE, JWEHeaderParameters, CritOption } from '../../types';
export interface Recipient {

@@ -54,8 +54,4 @@ /**

setAdditionalAuthenticatedData(aad: Uint8Array): this;
/**
* Encrypts and resolves the value of the General JWE object.
*
* @param options JWE Encryption options.
*/
encrypt(options?: DeflateOption): Promise<GeneralJWE>;
/** Encrypts and resolves the value of the General JWE object. */
encrypt(): Promise<GeneralJWE>;
}

@@ -9,2 +9,2 @@ import type { KeyLike, FlattenedJWSInput, JWSHeaderParameters } from '../types';

*/
export declare function EmbeddedJWK<T extends KeyLike = KeyLike>(protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput): Promise<T>;
export declare function EmbeddedJWK<KeyLikeType extends KeyLike = KeyLike>(protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput): Promise<KeyLikeType>;

@@ -5,7 +5,7 @@ import type { KeyLike, JWSHeaderParameters, JSONWebKeySet, FlattenedJWSInput } from '../types';

/** @private */
export declare class LocalJWKSet<T extends KeyLike = KeyLike> {
export declare class LocalJWKSet<KeyLikeType extends KeyLike = KeyLike> {
protected _jwks?: JSONWebKeySet;
private _cached;
constructor(jwks: unknown);
getKey(protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput): Promise<T>;
getKey(protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput): Promise<KeyLikeType>;
}

@@ -27,2 +27,2 @@ /**

*/
export declare function createLocalJWKSet<T extends KeyLike = KeyLike>(jwks: JSONWebKeySet): (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput) => Promise<T>;
export declare function createLocalJWKSet<KeyLikeType extends KeyLike = KeyLike>(jwks: JSONWebKeySet): (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput) => Promise<KeyLikeType>;

@@ -49,2 +49,2 @@ import type { KeyLike, JWSHeaderParameters, FlattenedJWSInput } from '../types';

*/
export declare function createRemoteJWKSet<T extends KeyLike = KeyLike>(url: URL, options?: RemoteJWKSetOptions): (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput) => Promise<T>;
export declare function createRemoteJWKSet<KeyLikeType extends KeyLike = KeyLike>(url: URL, options?: RemoteJWKSetOptions): (protectedHeader?: JWSHeaderParameters, token?: FlattenedJWSInput) => Promise<KeyLikeType>;

@@ -25,2 +25,2 @@ import type { CompactVerifyResult, FlattenedJWSInput, GetKeyFunction, CompactJWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey } from '../../types';

*/
export declare function compactVerify<T extends KeyLike = KeyLike>(jws: string | Uint8Array, getKey: CompactVerifyGetKey, options?: VerifyOptions): Promise<CompactVerifyResult & ResolvedKey<T>>;
export declare function compactVerify<KeyLikeType extends KeyLike = KeyLike>(jws: string | Uint8Array, getKey: CompactVerifyGetKey, options?: VerifyOptions): Promise<CompactVerifyResult & ResolvedKey<KeyLikeType>>;

@@ -25,2 +25,2 @@ import type { FlattenedVerifyResult, KeyLike, FlattenedJWSInput, JWSHeaderParameters, VerifyOptions, GetKeyFunction, ResolvedKey } from '../../types';

*/
export declare function flattenedVerify<T extends KeyLike = KeyLike>(jws: FlattenedJWSInput, getKey: FlattenedVerifyGetKey, options?: VerifyOptions): Promise<FlattenedVerifyResult & ResolvedKey<T>>;
export declare function flattenedVerify<KeyLikeType extends KeyLike = KeyLike>(jws: FlattenedJWSInput, getKey: FlattenedVerifyGetKey, options?: VerifyOptions): Promise<FlattenedVerifyResult & ResolvedKey<KeyLikeType>>;

@@ -25,2 +25,2 @@ import type { GeneralJWSInput, GeneralVerifyResult, FlattenedJWSInput, GetKeyFunction, JWSHeaderParameters, KeyLike, VerifyOptions, ResolvedKey } from '../../types';

*/
export declare function generalVerify<T extends KeyLike = KeyLike>(jws: GeneralJWSInput, getKey: GeneralVerifyGetKey, options?: VerifyOptions): Promise<GeneralVerifyResult & ResolvedKey<T>>;
export declare function generalVerify<KeyLikeType extends KeyLike = KeyLike>(jws: GeneralJWSInput, getKey: GeneralVerifyGetKey, options?: VerifyOptions): Promise<GeneralVerifyResult & ResolvedKey<KeyLikeType>>;

@@ -1,2 +0,2 @@

import type { KeyLike, DecryptOptions, JWTClaimVerificationOptions, GetKeyFunction, CompactJWEHeaderParameters, FlattenedJWE, JWTDecryptResult, ResolvedKey } from '../types';
import type { JWTPayload, KeyLike, DecryptOptions, JWTClaimVerificationOptions, GetKeyFunction, CompactJWEHeaderParameters, FlattenedJWE, JWTDecryptResult, ResolvedKey } from '../types';
/** Combination of JWE Decryption options and JWT Claims Set verification options. */

@@ -20,3 +20,3 @@ export interface JWTDecryptOptions extends DecryptOptions, JWTClaimVerificationOptions {

*/
export declare function jwtDecrypt(jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTDecryptOptions): Promise<JWTDecryptResult>;
export declare function jwtDecrypt<PayloadType = JWTPayload>(jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTDecryptOptions): Promise<JWTDecryptResult<PayloadType>>;
/**

@@ -28,2 +28,2 @@ * @param jwt JSON Web Token value (encoded as JWE).

*/
export declare function jwtDecrypt<T extends KeyLike = KeyLike>(jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions): Promise<JWTDecryptResult & ResolvedKey<T>>;
export declare function jwtDecrypt<PayloadType = JWTPayload, KeyLikeType extends KeyLike = KeyLike>(jwt: string | Uint8Array, getKey: JWTDecryptGetKey, options?: JWTDecryptOptions): Promise<JWTDecryptResult<PayloadType> & ResolvedKey<KeyLikeType>>;

@@ -5,6 +5,6 @@ import type { JWTPayload } from '../types';

protected _payload: JWTPayload;
/** @param payload The JWT Claims Set object. */
constructor(payload: JWTPayload);
/** @param payload The JWT Claims Set object. Defaults to an empty object. */
constructor(payload?: JWTPayload);
/**
* Set "iss" (Issuer) Claim.
* Set the "iss" (Issuer) Claim.
*

@@ -15,3 +15,3 @@ * @param issuer "Issuer" Claim value to set on the JWT Claims Set.

/**
* Set "sub" (Subject) Claim.
* Set the "sub" (Subject) Claim.
*

@@ -22,3 +22,3 @@ * @param subject "sub" (Subject) Claim value to set on the JWT Claims Set.

/**
* Set "aud" (Audience) Claim.
* Set the "aud" (Audience) Claim.
*

@@ -29,3 +29,3 @@ * @param audience "aud" (Audience) Claim value to set on the JWT Claims Set.

/**
* Set "jti" (JWT ID) Claim.
* Set the "jti" (JWT ID) Claim.
*

@@ -36,3 +36,3 @@ * @param jwtId "jti" (JWT ID) Claim value to set on the JWT Claims Set.

/**
* Set "nbf" (Not Before) Claim.
* Set the "nbf" (Not Before) Claim.
*

@@ -43,5 +43,5 @@ * @param input "nbf" (Not Before) Claim value to set on the JWT Claims Set. When number is passed

*/
setNotBefore(input: number | string): this;
setNotBefore(input: number | string | Date): this;
/**
* Set "exp" (Expiration Time) Claim.
* Set the "exp" (Expiration Time) Claim.
*

@@ -52,5 +52,5 @@ * @param input "exp" (Expiration Time) Claim value to set on the JWT Claims Set. When number is

*/
setExpirationTime(input: number | string): this;
setExpirationTime(input: number | string | Date): this;
/**
* Set "iat" (Issued At) Claim.
* Set the "iat" (Issued At) Claim.
*

@@ -60,3 +60,3 @@ * @param input "iat" (Issued At) Claim value to set on the JWT Claims Set. Default is current

*/
setIssuedAt(input?: number): this;
setIssuedAt(input?: number | Date): this;
}
import type { JWSHeaderParameters, JWTClaimVerificationOptions, JWTPayload } from '../types';
import { ProduceJWT } from './produce';
export interface UnsecuredResult {
payload: JWTPayload;
export interface UnsecuredResult<PayloadType = JWTPayload> {
payload: PayloadType & JWTPayload;
header: JWSHeaderParameters;

@@ -20,3 +20,3 @@ }

*/
static decode(jwt: string, options?: JWTClaimVerificationOptions): UnsecuredResult;
static decode<PayloadType = JWTPayload>(jwt: string, options?: JWTClaimVerificationOptions): UnsecuredResult<PayloadType>;
}

@@ -1,2 +0,2 @@

import type { KeyLike, VerifyOptions, JWTClaimVerificationOptions, JWTHeaderParameters, GetKeyFunction, FlattenedJWSInput, JWTVerifyResult, ResolvedKey } from '../types';
import type { JWTPayload, KeyLike, VerifyOptions, JWTClaimVerificationOptions, JWTHeaderParameters, GetKeyFunction, FlattenedJWSInput, JWTVerifyResult, ResolvedKey } from '../types';
/** Combination of JWS Verification options and JWT Claims Set verification options. */

@@ -22,3 +22,3 @@ export interface JWTVerifyOptions extends VerifyOptions, JWTClaimVerificationOptions {

*/
export declare function jwtVerify(jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTVerifyOptions): Promise<JWTVerifyResult>;
export declare function jwtVerify<PayloadType = JWTPayload>(jwt: string | Uint8Array, key: KeyLike | Uint8Array, options?: JWTVerifyOptions): Promise<JWTVerifyResult<PayloadType>>;
/**

@@ -30,2 +30,2 @@ * @param jwt JSON Web Token value (encoded as JWS).

*/
export declare function jwtVerify<T extends KeyLike = KeyLike>(jwt: string | Uint8Array, getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): Promise<JWTVerifyResult & ResolvedKey<T>>;
export declare function jwtVerify<PayloadType = JWTPayload, KeyLikeType extends KeyLike = KeyLike>(jwt: string | Uint8Array, getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): Promise<JWTVerifyResult<PayloadType> & ResolvedKey<KeyLikeType>>;
import type { KeyLike } from '../types';
export interface GenerateKeyPairResult<T extends KeyLike = KeyLike> {
export interface GenerateKeyPairResult<KeyLikeType extends KeyLike = KeyLike> {
/** The generated Private Key. */
privateKey: T;
privateKey: KeyLikeType;
/** Public Key corresponding to the generated Private Key. */
publicKey: T;
publicKey: KeyLikeType;
}

@@ -23,2 +23,3 @@ export interface GenerateKeyPairOptions {

* `extractable` argument. Default is false.
*
*/

@@ -32,3 +33,4 @@ extractable?: boolean;

* Note: Under Web Crypto API runtime the `privateKey` is generated with `extractable` set to
* `false` by default.
* `false` by default. See {@link GenerateKeyPairOptions.extractable} to generate an extractable
* `privateKey`.
*

@@ -38,2 +40,2 @@ * @param alg JWA Algorithm Identifier to be used with the generated key pair.

*/
export declare function generateKeyPair<T extends KeyLike = KeyLike>(alg: string, options?: GenerateKeyPairOptions): Promise<GenerateKeyPairResult<T>>;
export declare function generateKeyPair<KeyLikeType extends KeyLike = KeyLike>(alg: string, options?: GenerateKeyPairOptions): Promise<GenerateKeyPairResult<KeyLikeType>>;

@@ -19,2 +19,2 @@ import type { KeyLike } from '../types';

*/
export declare function generateSecret<T extends KeyLike = KeyLike>(alg: string, options?: GenerateSecretOptions): Promise<T | Uint8Array>;
export declare function generateSecret<KeyLikeType extends KeyLike = KeyLike>(alg: string, options?: GenerateSecretOptions): Promise<KeyLikeType | Uint8Array>;

@@ -19,3 +19,3 @@ import type { JWK, KeyLike } from '../types';

*/
export declare function importSPKI<T extends KeyLike = KeyLike>(spki: string, alg: string, options?: PEMImportOptions): Promise<T>;
export declare function importSPKI<KeyLikeType extends KeyLike = KeyLike>(spki: string, alg: string, options?: PEMImportOptions): Promise<KeyLikeType>;
/**

@@ -30,3 +30,3 @@ * Imports the SPKI from an X.509 string certificate as a runtime-specific public key representation

*/
export declare function importX509<T extends KeyLike = KeyLike>(x509: string, alg: string, options?: PEMImportOptions): Promise<T>;
export declare function importX509<KeyLikeType extends KeyLike = KeyLike>(x509: string, alg: string, options?: PEMImportOptions): Promise<KeyLikeType>;
/**

@@ -41,3 +41,3 @@ * Imports a PEM-encoded PKCS#8 string as a runtime-specific private key representation (KeyObject

*/
export declare function importPKCS8<T extends KeyLike = KeyLike>(pkcs8: string, alg: string, options?: PEMImportOptions): Promise<T>;
export declare function importPKCS8<KeyLikeType extends KeyLike = KeyLike>(pkcs8: string, alg: string, options?: PEMImportOptions): Promise<KeyLikeType>;
/**

@@ -54,5 +54,3 @@ * Imports a JWK to a runtime-specific key representation (KeyLike). Either JWK "alg" (Algorithm)

* {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}.
* @param octAsKeyObject Forces a symmetric key to be imported to a KeyObject or CryptoKey. Default
* is true unless JWK "ext" (Extractable) is true.
*/
export declare function importJWK<T extends KeyLike = KeyLike>(jwk: JWK, alg?: string, octAsKeyObject?: boolean): Promise<T | Uint8Array>;
export declare function importJWK<KeyLikeType extends KeyLike = KeyLike>(jwk: JWK, alg?: string): Promise<KeyLikeType | Uint8Array>;

@@ -307,3 +307,3 @@ /**

/**
* JWE "zip" (Compression Algorithm) Header Parameter.
* JWE "zip" (Compression Algorithm) Header Parameter. This parameter is not supported anymore.
*

@@ -348,3 +348,7 @@ * @deprecated Compression of data SHOULD NOT be done before encryption, because such compressed

export interface DecryptOptions extends CritOption {
/** A list of accepted JWE "alg" (Algorithm) Header Parameter values. */
/**
* A list of accepted JWE "alg" (Algorithm) Header Parameter values. By default all "alg"
* (Algorithm) Header Parameter values applicable for the used key/secret are allowed except for
* all PBES2 Key Management Algorithms, these need to be explicitly allowed using this option.
*/
keyManagementAlgorithms?: string[]

@@ -359,8 +363,2 @@

/**
* In a browser runtime you have to provide an implementation for Inflate Raw when you expect JWEs
* with compressed plaintext.
*/
inflateRaw?: InflateFunction
/**
* (PBES2 Key Management Algorithms only) Maximum allowed "p2c" (PBES2 Count) Header Parameter

@@ -373,13 +371,4 @@ * value. The PBKDF2 iteration count defines the algorithm's computational expense. By default

/** JWE Deflate option. */
export interface DeflateOption {
/**
* In a browser runtime you have to provide an implementation for Deflate Raw when you will be
* producing JWEs with compressed plaintext.
*/
deflateRaw?: DeflateFunction
}
/** JWE Encryption options. */
export interface EncryptOptions extends CritOption, DeflateOption {}
export interface EncryptOptions extends CritOption {}

@@ -498,28 +487,2 @@ /** JWT Claims Set verification options. */

/**
* Deflate Raw implementation, e.g. promisified
* {@link https://nodejs.org/api/zlib.html#zlibdeflaterawbuffer-options-callback zlib.deflateRaw}.
*
* @deprecated Compression of data SHOULD NOT be done before encryption, because such compressed
* data often reveals information about the plaintext.
*
* @see {@link https://www.rfc-editor.org/rfc/rfc8725#name-avoid-compression-of-encryp Avoid Compression of Encryption Inputs}
*/
export interface DeflateFunction {
(input: Uint8Array): Promise<Uint8Array>
}
/**
* Inflate Raw implementation, e.g. promisified
* {@link https://nodejs.org/api/zlib.html#zlibinflaterawbuffer-options-callback zlib.inflateRaw}.
*
* @deprecated Compression of data SHOULD NOT be done before encryption, because such compressed
* data often reveals information about the plaintext.
*
* @see {@link https://www.rfc-editor.org/rfc/rfc8725#name-avoid-compression-of-encryp Avoid Compression of Encryption Inputs}
*/
export interface InflateFunction {
(input: Uint8Array): Promise<Uint8Array>
}
export interface FlattenedDecryptResult {

@@ -573,5 +536,5 @@ /** JWE AAD. */

export interface JWTVerifyResult {
export interface JWTVerifyResult<PayloadType = JWTPayload> {
/** JWT Claims Set. */
payload: JWTPayload
payload: PayloadType & JWTPayload

@@ -582,5 +545,5 @@ /** JWS Protected Header. */

export interface JWTDecryptResult {
export interface JWTDecryptResult<PayloadType = JWTPayload> {
/** JWT Claims Set. */
payload: JWTPayload
payload: PayloadType & JWTPayload

@@ -591,5 +554,5 @@ /** JWE Protected Header. */

export interface ResolvedKey<T extends KeyLike = KeyLike> {
export interface ResolvedKey<KeyLikeType extends KeyLike = KeyLike> {
/** Key resolved from the key resolver function. */
key: T | Uint8Array
key: KeyLikeType | Uint8Array
}

@@ -596,0 +559,0 @@

{
"name": "jose",
"version": "4.15.4",
"version": "5.0.0",
"description": "'JSON Web Almost Everything' - JWA, JWS, JWE, JWT, JWK, JWKS for Node.js, Browser, Cloudflare Workers, Deno, Bun, and other Web-interoperable runtimes",

@@ -5,0 +5,0 @@ "keywords": [

@@ -131,3 +131,4 @@ # jose

| ------- | --------- | -------- | -------- |
| [v4.x](https://github.com/panva/jose/tree/v4.x) | ✅ | ✅ | ✅ |
| [v5.x](https://github.com/panva/jose/tree/v5.x) | ✅ | ✅ | ✅ |
| [v4.x](https://github.com/panva/jose/tree/v4.x) | ✅ | ❌ | ❌ |
| [v2.x](https://github.com/panva/jose/tree/v2.x) | ✅ | ❌ | ❌ |
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc