Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

jose-node-esm-runtime

Package Overview
Dependencies
Maintainers
1
Versions
132
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jose-node-esm-runtime - npm Package Compare versions

Comparing version 4.15.4 to 5.0.0

dist/node/esm/runtime/check_key_length.js

1

dist/node/esm/jwe/compact/encrypt.js
import { FlattenedEncrypt } from '../flattened/encrypt.js';
export class CompactEncrypt {
_flattened;
constructor(plaintext) {

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

23

dist/node/esm/jwe/flattened/decrypt.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)) {

@@ -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-node-esm-runtime",
"version": "4.15.4",
"version": "5.0.0",
"homepage": "https://github.com/panva/jose",

@@ -5,0 +5,0 @@ "repository": "panva/jose",

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc