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

did-jwt

Package Overview
Dependencies
Maintainers
8
Versions
146
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

did-jwt - npm Package Compare versions

Comparing version 5.0.0 to 5.0.1

7

CHANGELOG.md

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

## [5.0.1](https://github.com/decentralized-identity/did-jwt/compare/5.0.0...5.0.1) (2021-03-11)
### Bug Fixes
* add explicit support for EcdsaSecp256k1RecoveryMethod2020 ([#153](https://github.com/decentralized-identity/did-jwt/issues/153)) ([2b04c34](https://github.com/decentralized-identity/did-jwt/commit/2b04c347b1115e2de22c604093521a04d44c2629))
# [5.0.0](https://github.com/decentralized-identity/did-jwt/compare/4.9.0...5.0.0) (2021-03-09)

@@ -2,0 +9,0 @@

2

lib/index.d.ts

@@ -10,3 +10,3 @@ import SimpleSigner from './signers/SimpleSigner';

export { xc20pDirEncrypter, xc20pDirDecrypter, x25519Encrypter, x25519Decrypter, resolveX25519Encrypters } from './xc20pEncryption';
export { SimpleSigner, EllipticSigner, NaclSigner, ES256KSigner, EdDSASigner, verifyJWT, createJWT, decodeJWT, verifyJWS, createJWS, toEthereumAddress, Signer, JWTHeader, JWTPayload, JWTVerified, };
export { SimpleSigner, EllipticSigner, NaclSigner, ES256KSigner, EdDSASigner, verifyJWT, createJWT, decodeJWT, verifyJWS, createJWS, toEthereumAddress, Signer, JWTHeader, JWTPayload, JWTVerified };
//# sourceMappingURL=index.d.ts.map

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

import{toString as r,fromString as e,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as i}from"js-sha3";import{ec as o}from"elliptic";import{sign as a,verify as u}from"@stablelib/ed25519";import{XChaCha20Poly1305 as c}from"@stablelib/xchacha20poly1305";import{generateKeyPair as f,sharedKey as s}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function h(e){return r(e,"base64url")}function d(r){var t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e(t,"base64url")}function v(r){return e(r,"base58btc")}function p(r){var t=r.startsWith("0x")?r.substring(2):r;return e(t.toLowerCase(),"base16")}function y(r){return h(e(r))}function g(e){return r(d(e))}function m(e){return r(e,"base16")}function w(r){return e(r)}function b(r,t){var n=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(t?65:64);if(a.set(e(n,"base16"),0),a.set(e(i,"base16"),32),t){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return h(a)}function E(r){var e=d(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:m(e.slice(0,32)),s:m(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function P(r,e){return t([d(r),d(e)])}var k=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,K=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function x(r){if("string"==typeof r){if(k.test(r))return p(r);if(S.test(r))return v(r);if(K.test(r))return d(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function j(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function A(r){var t="string"==typeof r?e(r):r;return n(t)}function D(t){var n,o=e(t.slice(2),"base16");return"0x"+r((n=o,new Uint8Array(i.arrayBuffer(n))).slice(-20),"base16")}function J(r,t){void 0===t&&(t=new Uint8Array(4));var n=e(r.toString(),"base10");return t.set(n,4-n.length),t}var W=function(r){return t([J(r.length),r])};function T(r,i,o){if(256!==i)throw new Error("Unsupported key length: "+i);var a=t([W(e(o)),W(new Uint8Array(0)),W(new Uint8Array(0)),J(i)]);return n(t([J(1),r,a]))}var I=new o("secp256k1");function U(r,e){void 0===e&&(e=!1);var t=x(r);if(32!==t.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+t.length);var n=I.keyFromPrivate(t);return function(r){try{var t=n.sign(A(r)),i=t.s,o=t.recoveryParam;return Promise.resolve(b({r:j(t.r.toString("hex")),s:j(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function C(r){var e=U(r,!0);return function(r){try{return Promise.resolve(e(r)).then(E)}catch(r){return Promise.reject(r)}}}function O(r){return U(r)}function R(r){var e=x(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var t="string"==typeof r?w(r):r,n=a(e,t);return Promise.resolve(h(n))}catch(r){return Promise.reject(r)}}}function N(r){return R(r)}function B(){return(B=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var V=new o("secp256k1");function H(r,e){void 0===e&&(e=!1);var t=d(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");var n={r:m(t.slice(0,32)),s:m(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function M(r){return r.publicKeyBase58?v(r.publicKeyBase58):r.publicKeyBase64?d(r.publicKeyBase64):r.publicKeyHex?p(r.publicKeyHex):new Uint8Array}function X(r,e,t){var n;if(e.length>86)n=[H(e,!0)];else{var i=H(e,!1);n=[B({},i,{recoveryParam:0}),B({},i,{recoveryParam:1})]}var o=n.map(function(e){var n=A(r),i=V.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=D(o);return t.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function _(r,e,t){var n=w(r),i=d(e),o=t.find(function(r){return u(M(r),n,i)});if(!o)throw new Error("Signature invalid for JWT");return o}var z={ES256K:function(r,e,t){var n=A(r),i=H(e),o=t.filter(function(r){return void 0===r.ethereumAddress}),a=t.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=M(r);return V.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=X(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":X,Ed25519:_,EdDSA:_};function Z(r){var e=z[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function F(r){return"object"==typeof r&&"r"in r&&"s"in r}function L(r){return function(e,t){try{return Promise.resolve(t(e)).then(function(e){if(F(e))return b(e,r);if(r&&void 0===E(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function $(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(F(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}Z.toSignatureObject=H;var q={ES256K:L(),"ES256K-R":L(!0),Ed25519:$(),EdDSA:$()},G=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var t=ar(r),n=t.payload,i=t.header,o=t.signature,a=t.data;return Promise.resolve(function(r,e,t,n){try{var i=rr[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(t,{accept:tr})).then(function(r){var o,a,u;if(null!=(o=r.didResolutionMetadata)&&o.error){var c=r.didResolutionMetadata;throw new Error("Unable to resolve DID document for "+t+": "+c.error+", "+(c.message||""))}var f=function(r,e){var t=r.filter(function(r){return e===r.id});return t.length>0?t[0]:null},s=[];r.didDocument.verificationMethod&&(a=s).push.apply(a,r.didDocument.verificationMethod),r.didDocument.publicKey&&(u=s).push.apply(u,r.didDocument.publicKey),n&&(s=(r.didDocument.authentication||[]).map(function(r){return"string"==typeof r?f(s,r):"string"==typeof r.publicKey?f(s,r.publicKey):r}).filter(function(r){return null!=r}));var l=s.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(n&&(!l||0===l.length))throw new Error("DID document for "+t+" does not have public keys suitable for authenticating user");if(!l||0===l.length)throw new Error("DID document for "+t+" does not have public keys for "+e);return{authenticators:l,issuer:t,didResolutionResult:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,n.iss,e.auth)).then(function(t){var u=t.didResolutionResult,c=t.issuer;return Promise.resolve(ur({header:i,data:a,signature:o},t.authenticators)).then(function(t){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:ir;if(t){var a=i+o;if(n.nbf){if(n.nbf>a)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=i-o)throw new Error("JWT has expired: exp: "+n.exp+" < now: "+i);if(n.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,didResolutionResult:u,issuer:c,signer:t,jwt:r}}})})}catch(r){return Promise.reject(r)}},Q=function(r,e,t){var n=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===t&&(t={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!n)throw new Error("No issuing DID has been configured");t.typ||(t.typ="JWT"),t.alg||(t.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=B({},u,r,{iss:n});return Y(c,i,t)}catch(r){return Promise.reject(r)}},Y=function(r,e,t){void 0===t&&(t={});try{t.alg||(t.alg=er);var n="string"==typeof r?r:nr(r),i=[nr(t),n].join("."),o=function(r){var e=q[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(t.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},rr={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},er="ES256K",tr="application/did+json";function nr(r){return y(JSON.stringify(r))}var ir=300;function or(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(g(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function ar(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=or(r);return Object.assign(e,{payload:JSON.parse(g(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function ur(r,e){var t=r.header,n=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),Z(t.alg)(n,i,e)}function cr(r,e){return ur(or(r),e)}var fr=function(r,e){try{var t=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var n=JSON.parse(g(r.protected));if(n.enc!==e.enc)throw new Error("Decrypter does not support: '"+n.enc+"'");var i=P(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===n.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,d(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var t=0;return function(r,e,t){for(var n;;){var i=r();if(dr(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!dr(o)){n=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!dr(a)){n=2;break}}}var u=new hr,c=lr.bind(null,u,2);return(0===n?i.then(s):1===n?o.then(f):a.then(l)).then(void 0,c),u;function f(n){o=n;do{if(e&&(a=e())&&a.then&&!dr(a))return void a.then(l).then(void 0,c);if(!(i=r())||dr(i)&&!i.v)return void lr(u,1,o);if(i.then)return void i.then(s).then(void 0,c);dr(o=t())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=t())&&o.then?o.then(f).then(void 0,c):f(o):lr(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):lr(u,1,o)}}(function(){return!a&&t<r.recipients.length},function(){return t++},function(){var u=r.recipients[t];Object.assign(u.header,n);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,d(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(r){return Promise.reject(r)}},sr="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function lr(r,e,t){if(!r.s){if(t instanceof hr){if(!t.s)return void(t.o=lr.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(lr.bind(null,r,e),lr.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var hr=function(){function r(){}return r.prototype.then=function(e,t){var n=new r,i=this.s;if(i){var o=1&i?e:t;if(o){try{lr(n,1,o(this.v))}catch(r){lr(n,2,r)}return n}return this}return this.o=function(r){try{var i=r.v;1&r.s?lr(n,1,e?e(i):i):t?lr(n,1,t(i)):lr(n,2,i)}catch(r){lr(n,2,r)}},n},r}();function dr(r){return r instanceof hr&&1&r.s}function vr(r,e){var t=r.ciphertext,n=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:h(r.iv),ciphertext:h(t),tag:h(n)};return e&&(o.aad=h(e)),i&&(o.recipients=[i]),o}var pr=function(r,e,t,n){void 0===t&&(t={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,t,n)).then(function(r){return vr(r,n)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,t){if("function"==typeof r[sr]){var n,i,o,a=r[sr]();if(function r(t){try{for(;!(n=a.next()).done;)if((t=e(n.value))&&t.then){if(!dr(t))return void t.then(r,o||(o=lr.bind(null,i=new hr,2)));t=t.v}i?lr(i,1,t):i=t}catch(r){lr(i||(i=new hr),2,r)}}(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,i,o=-1;return function t(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!dr(a))return void a.then(t,i||(i=lr.bind(null,n=new hr,2)));a=a.v}n?lr(n,1,a):n=a}catch(r){lr(n||(n=new hr),2,r)}}(),n}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,t,n)).then(function(r){i=r.cek,o=vr(r,n)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}};function yr(r){var e=new c(r);return function(r,t){var n=l(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}var gr=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var t,n=e.didResolutionMetadata,i=e.didDocument;if(null!=n&&n.error)throw new Error("Could not find x25519 key for "+r+": "+n.error+", "+n.message);if(!i.keyAgreement)throw new Error("Could not find x25519 key for "+r);var o=(null==(t=i.keyAgreement)?void 0:t.map(function(r){return"string"==typeof r?[].concat(i.publicKey||[],i.verificationMethod||[]).find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!o)throw new Error("Could not find x25519 key for "+r);return br(v(o.publicKeyBase58),o.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}};function mr(r){var e=yr(r),t="XC20P";return{alg:"dir",enc:t,encrypt:function(r,n,i){void 0===n&&(n={});try{var o=y(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?o+"."+h(i):o));return Promise.resolve(B({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function wr(r){var e=new c(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,t,n){try{return Promise.resolve(e.open(t,r,n))}catch(r){return Promise.reject(r)}}}}function br(r,e){var t=function(t){try{var a=f(),u=yr(T(s(a.secretKey,r),i,n))(t),c={encrypted_key:h(u.ciphertext),header:{alg:n,iv:h(u.iv),tag:h(u.tag),epk:{kty:"OKP",crv:o,x:h(a.publicKey)}}};return e&&(c.header.kid=e),Promise.resolve(c)}catch(r){return Promise.reject(r)}},n="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:n,enc:"XC20P",encrypt:function(r,e,n){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=l(32);return Promise.resolve(mr(i).encrypt(r,e,n)).then(function(r){return Promise.resolve(t(i)).then(function(e){return B({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:t}}function Er(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(t,n,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var a=d(o.header.epk.x),u=T(s(r,a),256,e),c=P(o.encrypted_key,o.header.tag);return Promise.resolve(wr(u).decrypt(c,d(o.header.iv))).then(function(r){return null===r?null:wr(r).decrypt(t,n,i)})}catch(r){return Promise.reject(r)}}}}export{U as ES256KSigner,R as EdDSASigner,O as EllipticSigner,N as NaclSigner,C as SimpleSigner,pr as createJWE,Y as createJWS,Q as createJWT,ar as decodeJWT,fr as decryptJWE,gr as resolveX25519Encrypters,D as toEthereumAddress,cr as verifyJWS,G as verifyJWT,Er as x25519Decrypter,br as x25519Encrypter,wr as xc20pDirDecrypter,mr as xc20pDirEncrypter};
import{toString as r,fromString as e,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as i}from"js-sha3";import{ec as o}from"elliptic";import{sign as a,verify as u}from"@stablelib/ed25519";import{XChaCha20Poly1305 as c}from"@stablelib/xchacha20poly1305";import{generateKeyPair as f,sharedKey as s}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function h(e){return r(e,"base64url")}function d(r){var t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e(t,"base64url")}function v(r){return e(r,"base58btc")}function p(r){var t=r.startsWith("0x")?r.substring(2):r;return e(t.toLowerCase(),"base16")}function y(r){return h(e(r))}function g(e){return r(d(e))}function m(e){return r(e,"base16")}function w(r){return e(r)}function b(r,t){var n=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(t?65:64);if(a.set(e(n,"base16"),0),a.set(e(i,"base16"),32),t){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return h(a)}function E(r){var e=d(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:m(e.slice(0,32)),s:m(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function P(r,e){return t([d(r),d(e)])}var k=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,K=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function x(r){if("string"==typeof r){if(k.test(r))return p(r);if(S.test(r))return v(r);if(K.test(r))return d(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function j(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function A(r){var t="string"==typeof r?e(r):r;return n(t)}function D(t){var n,o=e(t.slice(2),"base16");return"0x"+r((n=o,new Uint8Array(i.arrayBuffer(n))).slice(-20),"base16")}function J(r,t){void 0===t&&(t=new Uint8Array(4));var n=e(r.toString(),"base10");return t.set(n,4-n.length),t}var W=function(r){return t([J(r.length),r])};function T(r,i,o){if(256!==i)throw new Error("Unsupported key length: "+i);var a=t([W(e(o)),W(new Uint8Array(0)),W(new Uint8Array(0)),J(i)]);return n(t([J(1),r,a]))}var I=new o("secp256k1");function U(r,e){void 0===e&&(e=!1);var t=x(r);if(32!==t.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+t.length);var n=I.keyFromPrivate(t);return function(r){try{var t=n.sign(A(r)),i=t.s,o=t.recoveryParam;return Promise.resolve(b({r:j(t.r.toString("hex")),s:j(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function C(r){var e=U(r,!0);return function(r){try{return Promise.resolve(e(r)).then(E)}catch(r){return Promise.reject(r)}}}function O(r){return U(r)}function R(r){var e=x(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var t="string"==typeof r?w(r):r,n=a(e,t);return Promise.resolve(h(n))}catch(r){return Promise.reject(r)}}}function M(r){return R(r)}function N(){return(N=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var B=new o("secp256k1");function V(r,e){void 0===e&&(e=!1);var t=d(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");var n={r:m(t.slice(0,32)),s:m(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function X(r){return r.publicKeyBase58?v(r.publicKeyBase58):r.publicKeyBase64?d(r.publicKeyBase64):r.publicKeyHex?p(r.publicKeyHex):new Uint8Array}function _(r,e,t){var n;if(e.length>86)n=[V(e,!0)];else{var i=V(e,!1);n=[N({},i,{recoveryParam:0}),N({},i,{recoveryParam:1})]}var o=n.map(function(e){var n=A(r),i=B.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=D(o);return t.find(function(r){var e=m(X(r));return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function z(r,e,t){var n=w(r),i=d(e),o=t.find(function(r){return u(X(r),n,i)});if(!o)throw new Error("Signature invalid for JWT");return o}var H={ES256K:function(r,e,t){var n=A(r),i=V(e),o=t.filter(function(r){return void 0===r.ethereumAddress}),a=t.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=X(r);return B.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=_(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":_,Ed25519:z,EdDSA:z};function Z(r){var e=H[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function F(r){return"object"==typeof r&&"r"in r&&"s"in r}function L(r){return function(e,t){try{return Promise.resolve(t(e)).then(function(e){if(F(e))return b(e,r);if(r&&void 0===E(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function $(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(F(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}Z.toSignatureObject=V;var q={ES256K:L(),"ES256K-R":L(!0),Ed25519:$(),EdDSA:$()},G=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var t=ar(r),n=t.payload,i=t.header,o=t.signature,a=t.data;return Promise.resolve(function(r,e,t,n){try{var i=rr[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(t,{accept:tr})).then(function(r){var o,a,u;if(null!=(o=r.didResolutionMetadata)&&o.error){var c=r.didResolutionMetadata;throw new Error("Unable to resolve DID document for "+t+": "+c.error+", "+(c.message||""))}var f=function(r,e){var t=r.filter(function(r){return e===r.id});return t.length>0?t[0]:null},s=[];r.didDocument.verificationMethod&&(a=s).push.apply(a,r.didDocument.verificationMethod),r.didDocument.publicKey&&(u=s).push.apply(u,r.didDocument.publicKey),n&&(s=(r.didDocument.authentication||[]).map(function(r){return"string"==typeof r?f(s,r):"string"==typeof r.publicKey?f(s,r.publicKey):r}).filter(function(r){return null!=r}));var l=s.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(n&&(!l||0===l.length))throw new Error("DID document for "+t+" does not have public keys suitable for authenticating user");if(!l||0===l.length)throw new Error("DID document for "+t+" does not have public keys for "+e);return{authenticators:l,issuer:t,didResolutionResult:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,n.iss,e.auth)).then(function(t){var u=t.didResolutionResult,c=t.issuer;return Promise.resolve(ur({header:i,data:a,signature:o},t.authenticators)).then(function(t){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:ir;if(t){var a=i+o;if(n.nbf){if(n.nbf>a)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=i-o)throw new Error("JWT has expired: exp: "+n.exp+" < now: "+i);if(n.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,didResolutionResult:u,issuer:c,signer:t,jwt:r}}})})}catch(r){return Promise.reject(r)}},Q=function(r,e,t){var n=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===t&&(t={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!n)throw new Error("No issuing DID has been configured");t.typ||(t.typ="JWT"),t.alg||(t.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=N({},u,r,{iss:n});return Y(c,i,t)}catch(r){return Promise.reject(r)}},Y=function(r,e,t){void 0===t&&(t={});try{t.alg||(t.alg=er);var n="string"==typeof r?r:nr(r),i=[nr(t),n].join("."),o=function(r){var e=q[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(t.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},rr={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},er="ES256K",tr="application/did+json";function nr(r){return y(JSON.stringify(r))}var ir=300;function or(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(g(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function ar(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=or(r);return Object.assign(e,{payload:JSON.parse(g(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function ur(r,e){var t=r.header,n=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),Z(t.alg)(n,i,e)}function cr(r,e){return ur(or(r),e)}var fr=function(r,e){try{var t=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var n=JSON.parse(g(r.protected));if(n.enc!==e.enc)throw new Error("Decrypter does not support: '"+n.enc+"'");var i=P(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===n.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,d(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var t=0;return function(r,e,t){for(var n;;){var i=r();if(dr(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!dr(o)){n=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!dr(a)){n=2;break}}}var u=new hr,c=lr.bind(null,u,2);return(0===n?i.then(s):1===n?o.then(f):a.then(l)).then(void 0,c),u;function f(n){o=n;do{if(e&&(a=e())&&a.then&&!dr(a))return void a.then(l).then(void 0,c);if(!(i=r())||dr(i)&&!i.v)return void lr(u,1,o);if(i.then)return void i.then(s).then(void 0,c);dr(o=t())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=t())&&o.then?o.then(f).then(void 0,c):f(o):lr(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):lr(u,1,o)}}(function(){return!a&&t<r.recipients.length},function(){return t++},function(){var u=r.recipients[t];Object.assign(u.header,n);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,d(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(r){return Promise.reject(r)}},sr="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function lr(r,e,t){if(!r.s){if(t instanceof hr){if(!t.s)return void(t.o=lr.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(lr.bind(null,r,e),lr.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var hr=function(){function r(){}return r.prototype.then=function(e,t){var n=new r,i=this.s;if(i){var o=1&i?e:t;if(o){try{lr(n,1,o(this.v))}catch(r){lr(n,2,r)}return n}return this}return this.o=function(r){try{var i=r.v;1&r.s?lr(n,1,e?e(i):i):t?lr(n,1,t(i)):lr(n,2,i)}catch(r){lr(n,2,r)}},n},r}();function dr(r){return r instanceof hr&&1&r.s}function vr(r,e){var t=r.ciphertext,n=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:h(r.iv),ciphertext:h(t),tag:h(n)};return e&&(o.aad=h(e)),i&&(o.recipients=[i]),o}var pr=function(r,e,t,n){void 0===t&&(t={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,t,n)).then(function(r){return vr(r,n)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,t){if("function"==typeof r[sr]){var n,i,o,a=r[sr]();if(function r(t){try{for(;!(n=a.next()).done;)if((t=e(n.value))&&t.then){if(!dr(t))return void t.then(r,o||(o=lr.bind(null,i=new hr,2)));t=t.v}i?lr(i,1,t):i=t}catch(r){lr(i||(i=new hr),2,r)}}(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,i,o=-1;return function t(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!dr(a))return void a.then(t,i||(i=lr.bind(null,n=new hr,2)));a=a.v}n?lr(n,1,a):n=a}catch(r){lr(n||(n=new hr),2,r)}}(),n}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,t,n)).then(function(r){i=r.cek,o=vr(r,n)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}};function yr(r){var e=new c(r);return function(r,t){var n=l(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}var gr=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var t,n=e.didResolutionMetadata,i=e.didDocument;if(null!=n&&n.error)throw new Error("Could not find x25519 key for "+r+": "+n.error+", "+n.message);if(!i.keyAgreement)throw new Error("Could not find x25519 key for "+r);var o=(null==(t=i.keyAgreement)?void 0:t.map(function(r){return"string"==typeof r?[].concat(i.publicKey||[],i.verificationMethod||[]).find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!o)throw new Error("Could not find x25519 key for "+r);return br(v(o.publicKeyBase58),o.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}};function mr(r){var e=yr(r),t="XC20P";return{alg:"dir",enc:t,encrypt:function(r,n,i){void 0===n&&(n={});try{var o=y(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?o+"."+h(i):o));return Promise.resolve(N({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function wr(r){var e=new c(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,t,n){try{return Promise.resolve(e.open(t,r,n))}catch(r){return Promise.reject(r)}}}}function br(r,e){var t=function(t){try{var a=f(),u=yr(T(s(a.secretKey,r),i,n))(t),c={encrypted_key:h(u.ciphertext),header:{alg:n,iv:h(u.iv),tag:h(u.tag),epk:{kty:"OKP",crv:o,x:h(a.publicKey)}}};return e&&(c.header.kid=e),Promise.resolve(c)}catch(r){return Promise.reject(r)}},n="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:n,enc:"XC20P",encrypt:function(r,e,n){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=l(32);return Promise.resolve(mr(i).encrypt(r,e,n)).then(function(r){return Promise.resolve(t(i)).then(function(e){return N({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:t}}function Er(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(t,n,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var a=d(o.header.epk.x),u=T(s(r,a),256,e),c=P(o.encrypted_key,o.header.tag);return Promise.resolve(wr(u).decrypt(c,d(o.header.iv))).then(function(r){return null===r?null:wr(r).decrypt(t,n,i)})}catch(r){return Promise.reject(r)}}}}export{U as ES256KSigner,R as EdDSASigner,O as EllipticSigner,M as NaclSigner,C as SimpleSigner,pr as createJWE,Y as createJWS,Q as createJWT,ar as decodeJWT,fr as decryptJWE,gr as resolveX25519Encrypters,D as toEthereumAddress,cr as verifyJWS,G as verifyJWT,Er as x25519Decrypter,br as x25519Encrypter,wr as xc20pDirDecrypter,mr as xc20pDirEncrypter};
//# sourceMappingURL=index.esm.js.map

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

var r=require("uint8arrays"),e=require("@stablelib/sha256"),t=require("js-sha3"),n=require("elliptic"),i=require("@stablelib/ed25519"),o=require("@stablelib/xchacha20poly1305"),a=require("@stablelib/x25519"),u=require("@stablelib/random");function c(e){return r.toString(e,"base64url")}function f(e){var t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r.fromString(t,"base64url")}function s(e){return r.fromString(e,"base58btc")}function l(e){var t=e.startsWith("0x")?e.substring(2):e;return r.fromString(t.toLowerCase(),"base16")}function h(e){return c(r.fromString(e))}function d(e){return r.toString(f(e))}function v(e){return r.toString(e,"base16")}function p(e){return r.fromString(e)}function y(e,t){var n=e.r,i=e.s,o=e.recoveryParam,a=new Uint8Array(t?65:64);if(a.set(r.fromString(n,"base16"),0),a.set(r.fromString(i,"base16"),32),t){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return c(a)}function g(r){var e=f(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:v(e.slice(0,32)),s:v(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function m(e,t){return r.concat([f(e),f(t)])}var w=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,b=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,E=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function P(r){if("string"==typeof r){if(w.test(r))return l(r);if(b.test(r))return s(r);if(E.test(r))return f(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function S(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function x(t){var n="string"==typeof t?r.fromString(t):t;return e.hash(n)}function k(e){var n,i=r.fromString(e.slice(2),"base16");return"0x"+r.toString((n=i,new Uint8Array(t.keccak_256.arrayBuffer(n))).slice(-20),"base16")}function K(e,t){void 0===t&&(t=new Uint8Array(4));var n=r.fromString(e.toString(),"base10");return t.set(n,4-n.length),t}var j=function(e){return r.concat([K(e.length),e])};function A(t,n,i){if(256!==n)throw new Error("Unsupported key length: "+n);var o=r.concat([j(r.fromString(i)),j(new Uint8Array(0)),j(new Uint8Array(0)),K(n)]);return e.hash(r.concat([K(1),t,o]))}var D=new n.ec("secp256k1");function J(r,e){void 0===e&&(e=!1);var t=P(r);if(32!==t.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+t.length);var n=D.keyFromPrivate(t);return function(r){try{var t=n.sign(x(r)),i=t.s,o=t.recoveryParam;return Promise.resolve(y({r:S(t.r.toString("hex")),s:S(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function W(r){var e=P(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var t="string"==typeof r?p(r):r,n=i.sign(e,t);return Promise.resolve(c(n))}catch(r){return Promise.reject(r)}}}function T(){return(T=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var C=new n.ec("secp256k1");function I(r,e){void 0===e&&(e=!1);var t=f(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");var n={r:v(t.slice(0,32)),s:v(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function U(r){return r.publicKeyBase58?s(r.publicKeyBase58):r.publicKeyBase64?f(r.publicKeyBase64):r.publicKeyHex?l(r.publicKeyHex):new Uint8Array}function O(r,e,t){var n;if(e.length>86)n=[I(e,!0)];else{var i=I(e,!1);n=[T({},i,{recoveryParam:0}),T({},i,{recoveryParam:1})]}var o=n.map(function(e){var n=x(r),i=C.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=k(o);return t.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function R(r,e,t){var n=p(r),o=f(e),a=t.find(function(r){return i.verify(U(r),n,o)});if(!a)throw new Error("Signature invalid for JWT");return a}var B={ES256K:function(r,e,t){var n=x(r),i=I(e),o=t.filter(function(r){return void 0===r.ethereumAddress}),a=t.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=U(r);return C.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=O(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":O,Ed25519:R,EdDSA:R};function N(r){var e=B[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function X(r){return"object"==typeof r&&"r"in r&&"s"in r}function V(r){return function(e,t){try{return Promise.resolve(t(e)).then(function(e){if(X(e))return y(e,r);if(r&&void 0===g(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function _(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(X(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}N.toSignatureObject=I;var q={ES256K:V(),"ES256K-R":V(!0),Ed25519:_(),EdDSA:_()},H=function(r,e,t){void 0===t&&(t={});try{t.alg||(t.alg=z);var n="string"==typeof r?r:Z(r),i=[Z(t),n].join("."),o=function(r){var e=q[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(t.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},M={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},z="ES256K";function Z(r){return h(JSON.stringify(r))}function F(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(d(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function L(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=F(r);return Object.assign(e,{payload:JSON.parse(d(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function $(r,e){var t=r.header,n=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),N(t.alg)(n,i,e)}var G="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Q(r,e,t){if(!r.s){if(t instanceof Y){if(!t.s)return void(t.o=Q.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(Q.bind(null,r,e),Q.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var Y=function(){function r(){}return r.prototype.then=function(e,t){var n=new r,i=this.s;if(i){var o=1&i?e:t;if(o){try{Q(n,1,o(this.v))}catch(r){Q(n,2,r)}return n}return this}return this.o=function(r){try{var i=r.v;1&r.s?Q(n,1,e?e(i):i):t?Q(n,1,t(i)):Q(n,2,i)}catch(r){Q(n,2,r)}},n},r}();function rr(r){return r instanceof Y&&1&r.s}function er(r,e){var t=r.ciphertext,n=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:c(r.iv),ciphertext:c(t),tag:c(n)};return e&&(o.aad=c(e)),i&&(o.recipients=[i]),o}function tr(r){var e=new o.XChaCha20Poly1305(r);return function(r,t){var n=u.randomBytes(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}function nr(r){var e=tr(r),t="XC20P";return{alg:"dir",enc:t,encrypt:function(r,n,i){void 0===n&&(n={});try{var o=h(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?o+"."+c(i):o));return Promise.resolve(T({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function ir(r){var e=new o.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,t,n){try{return Promise.resolve(e.open(t,r,n))}catch(r){return Promise.reject(r)}}}}function or(r,e){var t=function(t){try{var u=a.generateKeyPair(),f=tr(A(a.sharedKey(u.secretKey,r),i,n))(t),s={encrypted_key:c(f.ciphertext),header:{alg:n,iv:c(f.iv),tag:c(f.tag),epk:{kty:"OKP",crv:o,x:c(u.publicKey)}}};return e&&(s.header.kid=e),Promise.resolve(s)}catch(r){return Promise.reject(r)}},n="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:n,enc:"XC20P",encrypt:function(r,e,n){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=u.randomBytes(32);return Promise.resolve(nr(i).encrypt(r,e,n)).then(function(r){return Promise.resolve(t(i)).then(function(e){return T({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:t}}exports.ES256KSigner=J,exports.EdDSASigner=W,exports.EllipticSigner=function(r){return J(r)},exports.NaclSigner=function(r){return W(r)},exports.SimpleSigner=function(r){var e=J(r,!0);return function(r){try{return Promise.resolve(e(r)).then(g)}catch(r){return Promise.reject(r)}}},exports.createJWE=function(r,e,t,n){void 0===t&&(t={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,t,n)).then(function(r){return er(r,n)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,t){if("function"==typeof r[G]){var n,i,o,a=r[G]();if(function r(t){try{for(;!(n=a.next()).done;)if((t=e(n.value))&&t.then){if(!rr(t))return void t.then(r,o||(o=Q.bind(null,i=new Y,2)));t=t.v}i?Q(i,1,t):i=t}catch(r){Q(i||(i=new Y),2,r)}}(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,i,o=-1;return function t(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!rr(a))return void a.then(t,i||(i=Q.bind(null,n=new Y,2)));a=a.v}n?Q(n,1,a):n=a}catch(r){Q(n||(n=new Y),2,r)}}(),n}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,t,n)).then(function(r){i=r.cek,o=er(r,n)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},exports.createJWS=H,exports.createJWT=function(r,e,t){var n=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===t&&(t={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!n)throw new Error("No issuing DID has been configured");t.typ||(t.typ="JWT"),t.alg||(t.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=T({},u,r,{iss:n});return H(c,i,t)}catch(r){return Promise.reject(r)}},exports.decodeJWT=L,exports.decryptJWE=function(r,e){try{var t=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var n=JSON.parse(d(r.protected));if(n.enc!==e.enc)throw new Error("Decrypter does not support: '"+n.enc+"'");var i=m(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===n.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,f(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var t=0;return function(r,e,t){for(var n;;){var i=r();if(rr(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!rr(o)){n=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!rr(a)){n=2;break}}}var u=new Y,c=Q.bind(null,u,2);return(0===n?i.then(s):1===n?o.then(f):a.then(l)).then(void 0,c),u;function f(n){o=n;do{if(e&&(a=e())&&a.then&&!rr(a))return void a.then(l).then(void 0,c);if(!(i=r())||rr(i)&&!i.v)return void Q(u,1,o);if(i.then)return void i.then(s).then(void 0,c);rr(o=t())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=t())&&o.then?o.then(f).then(void 0,c):f(o):Q(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):Q(u,1,o)}}(function(){return!a&&t<r.recipients.length},function(){return t++},function(){var u=r.recipients[t];Object.assign(u.header,n);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,f(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(r){return Promise.reject(r)}},exports.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var t,n=e.didResolutionMetadata,i=e.didDocument;if(null!=n&&n.error)throw new Error("Could not find x25519 key for "+r+": "+n.error+", "+n.message);if(!i.keyAgreement)throw new Error("Could not find x25519 key for "+r);var o=(null==(t=i.keyAgreement)?void 0:t.map(function(r){return"string"==typeof r?[].concat(i.publicKey||[],i.verificationMethod||[]).find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!o)throw new Error("Could not find x25519 key for "+r);return or(s(o.publicKeyBase58),o.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},exports.toEthereumAddress=k,exports.verifyJWS=function(r,e){return $(F(r),e)},exports.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var t=L(r),n=t.payload,i=t.header,o=t.signature,a=t.data;return Promise.resolve(function(r,e,t,n){try{var i=M[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(t,{accept:"application/did+json"})).then(function(r){var o,a,u;if(null!=(o=r.didResolutionMetadata)&&o.error){var c=r.didResolutionMetadata;throw new Error("Unable to resolve DID document for "+t+": "+c.error+", "+(c.message||""))}var f=function(r,e){var t=r.filter(function(r){return e===r.id});return t.length>0?t[0]:null},s=[];r.didDocument.verificationMethod&&(a=s).push.apply(a,r.didDocument.verificationMethod),r.didDocument.publicKey&&(u=s).push.apply(u,r.didDocument.publicKey),n&&(s=(r.didDocument.authentication||[]).map(function(r){return"string"==typeof r?f(s,r):"string"==typeof r.publicKey?f(s,r.publicKey):r}).filter(function(r){return null!=r}));var l=s.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(n&&(!l||0===l.length))throw new Error("DID document for "+t+" does not have public keys suitable for authenticating user");if(!l||0===l.length)throw new Error("DID document for "+t+" does not have public keys for "+e);return{authenticators:l,issuer:t,didResolutionResult:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,n.iss,e.auth)).then(function(t){var u=t.didResolutionResult,c=t.issuer;return Promise.resolve($({header:i,data:a,signature:o},t.authenticators)).then(function(t){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(t){var a=i+o;if(n.nbf){if(n.nbf>a)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=i-o)throw new Error("JWT has expired: exp: "+n.exp+" < now: "+i);if(n.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,didResolutionResult:u,issuer:c,signer:t,jwt:r}}})})}catch(r){return Promise.reject(r)}},exports.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(t,n,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var u=f(o.header.epk.x),c=A(a.sharedKey(r,u),256,e),s=m(o.encrypted_key,o.header.tag);return Promise.resolve(ir(c).decrypt(s,f(o.header.iv))).then(function(r){return null===r?null:ir(r).decrypt(t,n,i)})}catch(r){return Promise.reject(r)}}}},exports.x25519Encrypter=or,exports.xc20pDirDecrypter=ir,exports.xc20pDirEncrypter=nr;
var r=require("uint8arrays"),e=require("@stablelib/sha256"),t=require("js-sha3"),n=require("elliptic"),i=require("@stablelib/ed25519"),o=require("@stablelib/xchacha20poly1305"),a=require("@stablelib/x25519"),u=require("@stablelib/random");function c(e){return r.toString(e,"base64url")}function f(e){var t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r.fromString(t,"base64url")}function s(e){return r.fromString(e,"base58btc")}function l(e){var t=e.startsWith("0x")?e.substring(2):e;return r.fromString(t.toLowerCase(),"base16")}function h(e){return c(r.fromString(e))}function d(e){return r.toString(f(e))}function v(e){return r.toString(e,"base16")}function p(e){return r.fromString(e)}function y(e,t){var n=e.r,i=e.s,o=e.recoveryParam,a=new Uint8Array(t?65:64);if(a.set(r.fromString(n,"base16"),0),a.set(r.fromString(i,"base16"),32),t){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return c(a)}function g(r){var e=f(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:v(e.slice(0,32)),s:v(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function m(e,t){return r.concat([f(e),f(t)])}var w=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,b=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,E=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function S(r){if("string"==typeof r){if(w.test(r))return l(r);if(b.test(r))return s(r);if(E.test(r))return f(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function P(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function x(t){var n="string"==typeof t?r.fromString(t):t;return e.hash(n)}function k(e){var n,i=r.fromString(e.slice(2),"base16");return"0x"+r.toString((n=i,new Uint8Array(t.keccak_256.arrayBuffer(n))).slice(-20),"base16")}function K(e,t){void 0===t&&(t=new Uint8Array(4));var n=r.fromString(e.toString(),"base10");return t.set(n,4-n.length),t}var j=function(e){return r.concat([K(e.length),e])};function A(t,n,i){if(256!==n)throw new Error("Unsupported key length: "+n);var o=r.concat([j(r.fromString(i)),j(new Uint8Array(0)),j(new Uint8Array(0)),K(n)]);return e.hash(r.concat([K(1),t,o]))}var D=new n.ec("secp256k1");function J(r,e){void 0===e&&(e=!1);var t=S(r);if(32!==t.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+t.length);var n=D.keyFromPrivate(t);return function(r){try{var t=n.sign(x(r)),i=t.s,o=t.recoveryParam;return Promise.resolve(y({r:P(t.r.toString("hex")),s:P(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function W(r){var e=S(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var t="string"==typeof r?p(r):r,n=i.sign(e,t);return Promise.resolve(c(n))}catch(r){return Promise.reject(r)}}}function T(){return(T=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var C=new n.ec("secp256k1");function I(r,e){void 0===e&&(e=!1);var t=f(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");var n={r:v(t.slice(0,32)),s:v(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function U(r){return r.publicKeyBase58?s(r.publicKeyBase58):r.publicKeyBase64?f(r.publicKeyBase64):r.publicKeyHex?l(r.publicKeyHex):new Uint8Array}function O(r,e,t){var n;if(e.length>86)n=[I(e,!0)];else{var i=I(e,!1);n=[T({},i,{recoveryParam:0}),T({},i,{recoveryParam:1})]}var o=n.map(function(e){var n=x(r),i=C.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=k(o);return t.find(function(r){var e=v(U(r));return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function R(r,e,t){var n=p(r),o=f(e),a=t.find(function(r){return i.verify(U(r),n,o)});if(!a)throw new Error("Signature invalid for JWT");return a}var B={ES256K:function(r,e,t){var n=x(r),i=I(e),o=t.filter(function(r){return void 0===r.ethereumAddress}),a=t.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=U(r);return C.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=O(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":O,Ed25519:R,EdDSA:R};function N(r){var e=B[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function X(r){return"object"==typeof r&&"r"in r&&"s"in r}function M(r){return function(e,t){try{return Promise.resolve(t(e)).then(function(e){if(X(e))return y(e,r);if(r&&void 0===g(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function V(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(X(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}N.toSignatureObject=I;var _={ES256K:M(),"ES256K-R":M(!0),Ed25519:V(),EdDSA:V()},q=function(r,e,t){void 0===t&&(t={});try{t.alg||(t.alg=H);var n="string"==typeof r?r:Z(r),i=[Z(t),n].join("."),o=function(r){var e=_[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(t.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},z={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},H="ES256K";function Z(r){return h(JSON.stringify(r))}function F(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(d(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function L(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=F(r);return Object.assign(e,{payload:JSON.parse(d(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function $(r,e){var t=r.header,n=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),N(t.alg)(n,i,e)}var G="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Q(r,e,t){if(!r.s){if(t instanceof Y){if(!t.s)return void(t.o=Q.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(Q.bind(null,r,e),Q.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var Y=function(){function r(){}return r.prototype.then=function(e,t){var n=new r,i=this.s;if(i){var o=1&i?e:t;if(o){try{Q(n,1,o(this.v))}catch(r){Q(n,2,r)}return n}return this}return this.o=function(r){try{var i=r.v;1&r.s?Q(n,1,e?e(i):i):t?Q(n,1,t(i)):Q(n,2,i)}catch(r){Q(n,2,r)}},n},r}();function rr(r){return r instanceof Y&&1&r.s}function er(r,e){var t=r.ciphertext,n=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:c(r.iv),ciphertext:c(t),tag:c(n)};return e&&(o.aad=c(e)),i&&(o.recipients=[i]),o}function tr(r){var e=new o.XChaCha20Poly1305(r);return function(r,t){var n=u.randomBytes(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}function nr(r){var e=tr(r),t="XC20P";return{alg:"dir",enc:t,encrypt:function(r,n,i){void 0===n&&(n={});try{var o=h(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?o+"."+c(i):o));return Promise.resolve(T({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function ir(r){var e=new o.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,t,n){try{return Promise.resolve(e.open(t,r,n))}catch(r){return Promise.reject(r)}}}}function or(r,e){var t=function(t){try{var u=a.generateKeyPair(),f=tr(A(a.sharedKey(u.secretKey,r),i,n))(t),s={encrypted_key:c(f.ciphertext),header:{alg:n,iv:c(f.iv),tag:c(f.tag),epk:{kty:"OKP",crv:o,x:c(u.publicKey)}}};return e&&(s.header.kid=e),Promise.resolve(s)}catch(r){return Promise.reject(r)}},n="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:n,enc:"XC20P",encrypt:function(r,e,n){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=u.randomBytes(32);return Promise.resolve(nr(i).encrypt(r,e,n)).then(function(r){return Promise.resolve(t(i)).then(function(e){return T({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:t}}exports.ES256KSigner=J,exports.EdDSASigner=W,exports.EllipticSigner=function(r){return J(r)},exports.NaclSigner=function(r){return W(r)},exports.SimpleSigner=function(r){var e=J(r,!0);return function(r){try{return Promise.resolve(e(r)).then(g)}catch(r){return Promise.reject(r)}}},exports.createJWE=function(r,e,t,n){void 0===t&&(t={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,t,n)).then(function(r){return er(r,n)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,t){if("function"==typeof r[G]){var n,i,o,a=r[G]();if(function r(t){try{for(;!(n=a.next()).done;)if((t=e(n.value))&&t.then){if(!rr(t))return void t.then(r,o||(o=Q.bind(null,i=new Y,2)));t=t.v}i?Q(i,1,t):i=t}catch(r){Q(i||(i=new Y),2,r)}}(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,i,o=-1;return function t(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!rr(a))return void a.then(t,i||(i=Q.bind(null,n=new Y,2)));a=a.v}n?Q(n,1,a):n=a}catch(r){Q(n||(n=new Y),2,r)}}(),n}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,t,n)).then(function(r){i=r.cek,o=er(r,n)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},exports.createJWS=q,exports.createJWT=function(r,e,t){var n=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===t&&(t={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!n)throw new Error("No issuing DID has been configured");t.typ||(t.typ="JWT"),t.alg||(t.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=T({},u,r,{iss:n});return q(c,i,t)}catch(r){return Promise.reject(r)}},exports.decodeJWT=L,exports.decryptJWE=function(r,e){try{var t=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var n=JSON.parse(d(r.protected));if(n.enc!==e.enc)throw new Error("Decrypter does not support: '"+n.enc+"'");var i=m(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===n.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,f(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var t=0;return function(r,e,t){for(var n;;){var i=r();if(rr(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!rr(o)){n=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!rr(a)){n=2;break}}}var u=new Y,c=Q.bind(null,u,2);return(0===n?i.then(s):1===n?o.then(f):a.then(l)).then(void 0,c),u;function f(n){o=n;do{if(e&&(a=e())&&a.then&&!rr(a))return void a.then(l).then(void 0,c);if(!(i=r())||rr(i)&&!i.v)return void Q(u,1,o);if(i.then)return void i.then(s).then(void 0,c);rr(o=t())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=t())&&o.then?o.then(f).then(void 0,c):f(o):Q(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):Q(u,1,o)}}(function(){return!a&&t<r.recipients.length},function(){return t++},function(){var u=r.recipients[t];Object.assign(u.header,n);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,f(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(r){return Promise.reject(r)}},exports.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var t,n=e.didResolutionMetadata,i=e.didDocument;if(null!=n&&n.error)throw new Error("Could not find x25519 key for "+r+": "+n.error+", "+n.message);if(!i.keyAgreement)throw new Error("Could not find x25519 key for "+r);var o=(null==(t=i.keyAgreement)?void 0:t.map(function(r){return"string"==typeof r?[].concat(i.publicKey||[],i.verificationMethod||[]).find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!o)throw new Error("Could not find x25519 key for "+r);return or(s(o.publicKeyBase58),o.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},exports.toEthereumAddress=k,exports.verifyJWS=function(r,e){return $(F(r),e)},exports.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var t=L(r),n=t.payload,i=t.header,o=t.signature,a=t.data;return Promise.resolve(function(r,e,t,n){try{var i=z[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(t,{accept:"application/did+json"})).then(function(r){var o,a,u;if(null!=(o=r.didResolutionMetadata)&&o.error){var c=r.didResolutionMetadata;throw new Error("Unable to resolve DID document for "+t+": "+c.error+", "+(c.message||""))}var f=function(r,e){var t=r.filter(function(r){return e===r.id});return t.length>0?t[0]:null},s=[];r.didDocument.verificationMethod&&(a=s).push.apply(a,r.didDocument.verificationMethod),r.didDocument.publicKey&&(u=s).push.apply(u,r.didDocument.publicKey),n&&(s=(r.didDocument.authentication||[]).map(function(r){return"string"==typeof r?f(s,r):"string"==typeof r.publicKey?f(s,r.publicKey):r}).filter(function(r){return null!=r}));var l=s.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(n&&(!l||0===l.length))throw new Error("DID document for "+t+" does not have public keys suitable for authenticating user");if(!l||0===l.length)throw new Error("DID document for "+t+" does not have public keys for "+e);return{authenticators:l,issuer:t,didResolutionResult:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,n.iss,e.auth)).then(function(t){var u=t.didResolutionResult,c=t.issuer;return Promise.resolve($({header:i,data:a,signature:o},t.authenticators)).then(function(t){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(t){var a=i+o;if(n.nbf){if(n.nbf>a)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=i-o)throw new Error("JWT has expired: exp: "+n.exp+" < now: "+i);if(n.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,didResolutionResult:u,issuer:c,signer:t,jwt:r}}})})}catch(r){return Promise.reject(r)}},exports.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(t,n,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var u=f(o.header.epk.x),c=A(a.sharedKey(r,u),256,e),s=m(o.encrypted_key,o.header.tag);return Promise.resolve(ir(c).decrypt(s,f(o.header.iv))).then(function(r){return null===r?null:ir(r).decrypt(t,n,i)})}catch(r){return Promise.reject(r)}}}},exports.x25519Encrypter=or,exports.xc20pDirDecrypter=ir,exports.xc20pDirEncrypter=nr;
//# sourceMappingURL=index.js.map

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

import{toString as e,fromString as r,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as i}from"js-sha3";import{ec as o}from"elliptic";import{sign as a,verify as c}from"@stablelib/ed25519";import{XChaCha20Poly1305 as s}from"@stablelib/xchacha20poly1305";import{generateKeyPair as u,sharedKey as f}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function d(r){return e(r,"base64url")}function p(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r(t,"base64url")}function y(e){return r(e,"base58btc")}function h(e){const t=e.startsWith("0x")?e.substring(2):e;return r(t.toLowerCase(),"base16")}function g(e){return d(r(e))}function w(r){return e(p(r))}function b(r){return e(r,"base16")}function E(e){return r(e)}function m({r:e,s:t,recoveryParam:n},i){const o=new Uint8Array(i?65:64);if(o.set(r(e,"base16"),0),o.set(r(t,"base16"),32),i){if(void 0===n)throw new Error("Signer did not return a recoveryParam");o[64]=n}return d(o)}function v(e){const r=p(e);if(r.length<64||r.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${r.length}`);return{r:b(r.slice(0,32)),s:b(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function k(e,r){return t([p(e),p(r)])}const K=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,x=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function $(e){if("string"==typeof e){if(K.test(e))return h(e);if(S.test(e))return y(e);if(x.test(e))return p(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function A(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function D(e){const t="string"==typeof e?r(e):e;return n(t)}function P(t){const n=r(t.slice(2),"base16");return`0x${e((o=n,new Uint8Array(i.arrayBuffer(o))).slice(-20),"base16")}`;var o}function J(e,t=new Uint8Array(4)){const n=r(e.toString(),"base10");return t.set(n,4-n.length),t}const W=e=>t([J(e.length),e]);function I(e,i,o){if(256!==i)throw new Error(`Unsupported key length: ${i}`);const a=t([W(r(o)),W(new Uint8Array(0)),W(new Uint8Array(0)),J(i)]);return n(t([J(1),e,a]))}const T=new o("secp256k1");function U(e,r=!1){const t=$(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=T.keyFromPrivate(t);return async e=>{const{r:t,s:i,recoveryParam:o}=n.sign(D(e));return m({r:A(t.toString("hex")),s:A(i.toString("hex")),recoveryParam:o},r)}}function C(e){const r=U(e,!0);return async e=>v(await r(e))}function j(e){return U(e)}function O(e){const r=$(e);if(64!==r.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${r.length}`);return async e=>{const t="string"==typeof e?E(e):e;return d(a(r,t))}}function R(e){return O(e)}function N(){return(N=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}const B=new o("secp256k1");function V(e,r=!1){const t=p(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:b(t.slice(0,32)),s:b(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function H(e){return e.publicKeyBase58?y(e.publicKeyBase58):e.publicKeyBase64?p(e.publicKeyBase64):e.publicKeyHex?h(e.publicKeyHex):new Uint8Array}function M(e,r,t){let n;if(r.length>86)n=[V(r,!0)];else{const e=V(r,!1);n=[N({},e,{recoveryParam:0}),N({},e,{recoveryParam:1})]}const i=n.map(r=>{const n=D(e),i=B.recoverPubKey(n,r,r.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),c=P(o);return t.find(({publicKeyHex:e,ethereumAddress:r})=>e===o||e===a||r===c)}).filter(e=>null!=e);if(0===i.length)throw new Error("Signature invalid for JWT");return i[0]}function X(e,r,t){const n=E(e),i=p(r),o=t.find(e=>c(H(e),n,i));if(!o)throw new Error("Signature invalid for JWT");return o}const _={ES256K:function(e,r,t){const n=D(e),i=V(r),o=t.filter(({ethereumAddress:e})=>void 0===e),a=t.filter(({ethereumAddress:e})=>void 0!==e);let c=o.find(e=>{try{const r=H(e);return B.keyFromPublic(r).verify(n,i)}catch(e){return!1}});if(!c&&a.length>0&&(c=M(e,r,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":M,Ed25519:X,EdDSA:X};function z(e){const r=_[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}function Z(e){return"object"==typeof e&&"r"in e&&"s"in e}function F(e){return async function(r,t){const n=await t(r);if(Z(n))return m(n,e);if(e&&void 0===v(n).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return n}}function L(){return async function(e,r){const t=await r(e);if(Z(t))throw new Error("expected a signer function that returns a string instead of signature object");return t}}z.toSignatureObject=V;const q={ES256K:F(),"ES256K-R":F(!0),Ed25519:L(),EdDSA:L()},G={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function Q(e){return g(JSON.stringify(e))}function Y(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(w(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function ee(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=Y(e);return Object.assign(r,{payload:JSON.parse(w(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}async function re(e,r,t={}){t.alg||(t.alg="ES256K");const n="string"==typeof e?e:Q(e),i=[Q(t),n].join("."),o=function(e){const r=q[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return[i,await o(i,r)].join(".")}async function te(e,{issuer:r,signer:t,alg:n,expiresIn:i},o={}){if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");o.typ||(o.typ="JWT"),o.alg||(o.alg=n);const a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(i){if("number"!=typeof i)throw new Error("JWT expiresIn is not a number");a.exp=(e.nbf||a.iat)+Math.floor(i)}return re(N({},a,e,{iss:r}),t,o)}function ne({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),z(e.alg)(r,t,n)}function ie(e,r){return ne(Y(e),r)}async function oe(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null}){if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:i,data:o}=ee(e),{didResolutionResult:a,authenticators:c,issuer:s}=await async function(e,r,t,n){var i;const o=G[r];if(!o||0===o.length)throw new Error(`No supported signature types for algorithm ${r}`);const a=await e.resolve(t,{accept:"application/did+json"});if(null!=(i=a.didResolutionMetadata)&&i.error){const{error:e,message:r}=a.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let s=[];a.didDocument.verificationMethod&&s.push(...a.didDocument.verificationMethod),a.didDocument.publicKey&&s.push(...a.didDocument.publicKey),n&&(s=(a.didDocument.authentication||[]).map(e=>"string"==typeof e?c(s,e):"string"==typeof e.publicKey?c(s,e.publicKey):e).filter(e=>null!=e));const u=s.filter(({type:e})=>o.find(r=>r===e));if(n&&(!u||0===u.length))throw new Error(`DID document for ${t} does not have public keys suitable for authenticating user`);if(!u||0===u.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:u,issuer:t,didResolutionResult:a}}(r.resolver,n.alg,t.iss,r.auth),u=await ne({header:n,data:o,signature:i},c),f=Math.floor(Date.now()/1e3),l=r.skewTime>=0?r.skewTime:300;if(u){const n=f+l;if(t.nbf){if(t.nbf>n)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>n)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=f-l)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${f}`);if(t.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,didResolutionResult:a,issuer:s,signer:u,jwt:e}}}function ae({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:i},o){const a={protected:n,iv:d(t),ciphertext:d(e),tag:d(r)};return o&&(a.aad=d(o)),i&&(a.recipients=[i]),a}async function ce(e,r,t={},n){if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return ae(await r[0].encrypt(e,t,n),n)}{const i=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===i,!0))throw new Error("Incompatible encrypters passed");let o,a;for(const i of r)if(o)a.recipients.push(await i.encryptCek(o));else{const r=await i.encrypt(e,t,n);o=r.cek,a=ae(r,n)}return a}}async function se(e,r){!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const t=JSON.parse(w(e.protected));if(t.enc!==r.enc)throw new Error(`Decrypter does not support: '${t.enc}'`);const n=k(e.ciphertext,e.tag),i=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let o=null;if("dir"===t.alg&&"dir"===r.alg)o=await r.decrypt(n,p(e.iv),i);else{if(!e.recipients||0===e.recipients.length)throw new Error("Invalid JWE");for(let a=0;!o&&a<e.recipients.length;a++){const c=e.recipients[a];Object.assign(c.header,t),c.header.alg===r.alg&&(o=await r.decrypt(n,p(e.iv),i,c))}}if(null===o)throw new Error("Failed to decrypt");return o}function ue(e){const r=new s(e);return(e,t)=>{const n=l(r.nonceLength),i=r.seal(n,e,t);return{ciphertext:i.subarray(0,i.length-r.tagLength),tag:i.subarray(i.length-r.tagLength),iv:n}}}function fe(e){const r=ue(e),t="XC20P";return{alg:"dir",enc:t,encrypt:async function(e,n={},i){const o=g(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?`${o}.${d(i)}`:o));return N({},r(e,a),{protectedHeader:o})}}}function le(e){const r=new s(e);return{alg:"dir",enc:"XC20P",decrypt:async function(e,t,n){return r.open(t,e,n)}}}function de(e,r){const t="ECDH-ES+XC20PKW";async function n(n){const i=u(),o=ue(I(f(i.secretKey,e),256,t))(n),a={encrypted_key:d(o.ciphertext),header:{alg:t,iv:d(o.iv),tag:d(o.tag),epk:{kty:"OKP",crv:"X25519",x:d(i.publicKey)}}};return r&&(a.header.kid=r),a}return{alg:t,enc:"XC20P",encrypt:async function(e,r={},t){Object.assign(r,{alg:void 0});const i=l(32);return N({},await fe(i).encrypt(e,r,t),{recipient:await n(i),cek:i})},encryptCek:n}}async function pe(e,r){return Promise.all(e.map(async e=>{var t;const{didResolutionMetadata:n,didDocument:i}=await r.resolve(e);if(null!=n&&n.error)throw new Error(`Could not find x25519 key for ${e}: ${n.error}, ${n.message}`);if(!i.keyAgreement)throw new Error(`Could not find x25519 key for ${e}`);const o=(null==(t=i.keyAgreement)?void 0:t.map(e=>"string"==typeof e?[...i.publicKey||[],...i.verificationMethod||[]].find(r=>r.id===e):e)).find(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!o)throw new Error(`Could not find x25519 key for ${e}`);return de(y(o.publicKeyBase58),o.id)}))}function ye(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:async function(t,n,i,o){if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return null;const a=p(o.header.epk.x),c=I(f(e,a),256,r),s=k(o.encrypted_key,o.header.tag),u=await le(c).decrypt(s,p(o.header.iv));return null===u?null:le(u).decrypt(t,n,i)}}}export{U as ES256KSigner,O as EdDSASigner,j as EllipticSigner,R as NaclSigner,C as SimpleSigner,ce as createJWE,re as createJWS,te as createJWT,ee as decodeJWT,se as decryptJWE,pe as resolveX25519Encrypters,P as toEthereumAddress,ie as verifyJWS,oe as verifyJWT,ye as x25519Decrypter,de as x25519Encrypter,le as xc20pDirDecrypter,fe as xc20pDirEncrypter};
import{toString as e,fromString as r,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as o}from"js-sha3";import{ec as i}from"elliptic";import{sign as a,verify as c}from"@stablelib/ed25519";import{XChaCha20Poly1305 as s}from"@stablelib/xchacha20poly1305";import{generateKeyPair as u,sharedKey as f}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function d(r){return e(r,"base64url")}function p(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r(t,"base64url")}function y(e){return r(e,"base58btc")}function h(e){const t=e.startsWith("0x")?e.substring(2):e;return r(t.toLowerCase(),"base16")}function g(e){return d(r(e))}function w(r){return e(p(r))}function b(r){return e(r,"base16")}function E(e){return r(e)}function m({r:e,s:t,recoveryParam:n},o){const i=new Uint8Array(o?65:64);if(i.set(r(e,"base16"),0),i.set(r(t,"base16"),32),o){if(void 0===n)throw new Error("Signer did not return a recoveryParam");i[64]=n}return d(i)}function v(e){const r=p(e);if(r.length<64||r.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${r.length}`);return{r:b(r.slice(0,32)),s:b(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function k(e,r){return t([p(e),p(r)])}const S=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,K=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,x=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function $(e){if("string"==typeof e){if(S.test(e))return h(e);if(K.test(e))return y(e);if(x.test(e))return p(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function A(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function D(e){const t="string"==typeof e?r(e):e;return n(t)}function P(t){const n=r(t.slice(2),"base16");return`0x${e((i=n,new Uint8Array(o.arrayBuffer(i))).slice(-20),"base16")}`;var i}function J(e,t=new Uint8Array(4)){const n=r(e.toString(),"base10");return t.set(n,4-n.length),t}const W=e=>t([J(e.length),e]);function I(e,o,i){if(256!==o)throw new Error(`Unsupported key length: ${o}`);const a=t([W(r(i)),W(new Uint8Array(0)),W(new Uint8Array(0)),J(o)]);return n(t([J(1),e,a]))}const T=new i("secp256k1");function U(e,r=!1){const t=$(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=T.keyFromPrivate(t);return async e=>{const{r:t,s:o,recoveryParam:i}=n.sign(D(e));return m({r:A(t.toString("hex")),s:A(o.toString("hex")),recoveryParam:i},r)}}function C(e){const r=U(e,!0);return async e=>v(await r(e))}function R(e){return U(e)}function j(e){const r=$(e);if(64!==r.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${r.length}`);return async e=>{const t="string"==typeof e?E(e):e;return d(a(r,t))}}function O(e){return j(e)}function M(){return(M=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}const N=new i("secp256k1");function B(e,r=!1){const t=p(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:b(t.slice(0,32)),s:b(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function V(e){return e.publicKeyBase58?y(e.publicKeyBase58):e.publicKeyBase64?p(e.publicKeyBase64):e.publicKeyHex?h(e.publicKeyHex):new Uint8Array}function X(e,r,t){let n;if(r.length>86)n=[B(r,!0)];else{const e=B(r,!1);n=[M({},e,{recoveryParam:0}),M({},e,{recoveryParam:1})]}const o=n.map(r=>{const n=D(e),o=N.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),a=o.encode("hex",!0),c=P(i);return t.find(e=>{const r=b(V(e));return r===i||r===a||e.ethereumAddress===c})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function _(e,r,t){const n=E(e),o=p(r),i=t.find(e=>c(V(e),n,o));if(!i)throw new Error("Signature invalid for JWT");return i}const z={ES256K:function(e,r,t){const n=D(e),o=B(r),i=t.filter(({ethereumAddress:e})=>void 0===e),a=t.filter(({ethereumAddress:e})=>void 0!==e);let c=i.find(e=>{try{const r=V(e);return N.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!c&&a.length>0&&(c=X(e,r,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":X,Ed25519:_,EdDSA:_};function H(e){const r=z[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}function Z(e){return"object"==typeof e&&"r"in e&&"s"in e}function F(e){return async function(r,t){const n=await t(r);if(Z(n))return m(n,e);if(e&&void 0===v(n).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return n}}function L(){return async function(e,r){const t=await r(e);if(Z(t))throw new Error("expected a signer function that returns a string instead of signature object");return t}}H.toSignatureObject=B;const q={ES256K:F(),"ES256K-R":F(!0),Ed25519:L(),EdDSA:L()},G={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function Q(e){return g(JSON.stringify(e))}function Y(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(w(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function ee(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=Y(e);return Object.assign(r,{payload:JSON.parse(w(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}async function re(e,r,t={}){t.alg||(t.alg="ES256K");const n="string"==typeof e?e:Q(e),o=[Q(t),n].join("."),i=function(e){const r=q[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return[o,await i(o,r)].join(".")}async function te(e,{issuer:r,signer:t,alg:n,expiresIn:o},i={}){if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");i.typ||(i.typ="JWT"),i.alg||(i.alg=n);const a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(o){if("number"!=typeof o)throw new Error("JWT expiresIn is not a number");a.exp=(e.nbf||a.iat)+Math.floor(o)}return re(M({},a,e,{iss:r}),t,i)}function ne({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),H(e.alg)(r,t,n)}function oe(e,r){return ne(Y(e),r)}async function ie(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null}){if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:o,data:i}=ee(e),{didResolutionResult:a,authenticators:c,issuer:s}=await async function(e,r,t,n){var o;const i=G[r];if(!i||0===i.length)throw new Error(`No supported signature types for algorithm ${r}`);const a=await e.resolve(t,{accept:"application/did+json"});if(null!=(o=a.didResolutionMetadata)&&o.error){const{error:e,message:r}=a.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let s=[];a.didDocument.verificationMethod&&s.push(...a.didDocument.verificationMethod),a.didDocument.publicKey&&s.push(...a.didDocument.publicKey),n&&(s=(a.didDocument.authentication||[]).map(e=>"string"==typeof e?c(s,e):"string"==typeof e.publicKey?c(s,e.publicKey):e).filter(e=>null!=e));const u=s.filter(({type:e})=>i.find(r=>r===e));if(n&&(!u||0===u.length))throw new Error(`DID document for ${t} does not have public keys suitable for authenticating user`);if(!u||0===u.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:u,issuer:t,didResolutionResult:a}}(r.resolver,n.alg,t.iss,r.auth),u=await ne({header:n,data:i,signature:o},c),f=Math.floor(Date.now()/1e3),l=r.skewTime>=0?r.skewTime:300;if(u){const n=f+l;if(t.nbf){if(t.nbf>n)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>n)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=f-l)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${f}`);if(t.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,didResolutionResult:a,issuer:s,signer:u,jwt:e}}}function ae({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const a={protected:n,iv:d(t),ciphertext:d(e),tag:d(r)};return i&&(a.aad=d(i)),o&&(a.recipients=[o]),a}async function ce(e,r,t={},n){if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return ae(await r[0].encrypt(e,t,n),n)}{const o=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===o,!0))throw new Error("Incompatible encrypters passed");let i,a;for(const o of r)if(i)a.recipients.push(await o.encryptCek(i));else{const r=await o.encrypt(e,t,n);i=r.cek,a=ae(r,n)}return a}}async function se(e,r){!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const t=JSON.parse(w(e.protected));if(t.enc!==r.enc)throw new Error(`Decrypter does not support: '${t.enc}'`);const n=k(e.ciphertext,e.tag),o=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let i=null;if("dir"===t.alg&&"dir"===r.alg)i=await r.decrypt(n,p(e.iv),o);else{if(!e.recipients||0===e.recipients.length)throw new Error("Invalid JWE");for(let a=0;!i&&a<e.recipients.length;a++){const c=e.recipients[a];Object.assign(c.header,t),c.header.alg===r.alg&&(i=await r.decrypt(n,p(e.iv),o,c))}}if(null===i)throw new Error("Failed to decrypt");return i}function ue(e){const r=new s(e);return(e,t)=>{const n=l(r.nonceLength),o=r.seal(n,e,t);return{ciphertext:o.subarray(0,o.length-r.tagLength),tag:o.subarray(o.length-r.tagLength),iv:n}}}function fe(e){const r=ue(e),t="XC20P";return{alg:"dir",enc:t,encrypt:async function(e,n={},o){const i=g(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(o?`${i}.${d(o)}`:i));return M({},r(e,a),{protectedHeader:i})}}}function le(e){const r=new s(e);return{alg:"dir",enc:"XC20P",decrypt:async function(e,t,n){return r.open(t,e,n)}}}function de(e,r){const t="ECDH-ES+XC20PKW";async function n(n){const o=u(),i=ue(I(f(o.secretKey,e),256,t))(n),a={encrypted_key:d(i.ciphertext),header:{alg:t,iv:d(i.iv),tag:d(i.tag),epk:{kty:"OKP",crv:"X25519",x:d(o.publicKey)}}};return r&&(a.header.kid=r),a}return{alg:t,enc:"XC20P",encrypt:async function(e,r={},t){Object.assign(r,{alg:void 0});const o=l(32);return M({},await fe(o).encrypt(e,r,t),{recipient:await n(o),cek:o})},encryptCek:n}}async function pe(e,r){return Promise.all(e.map(async e=>{var t;const{didResolutionMetadata:n,didDocument:o}=await r.resolve(e);if(null!=n&&n.error)throw new Error(`Could not find x25519 key for ${e}: ${n.error}, ${n.message}`);if(!o.keyAgreement)throw new Error(`Could not find x25519 key for ${e}`);const i=(null==(t=o.keyAgreement)?void 0:t.map(e=>"string"==typeof e?[...o.publicKey||[],...o.verificationMethod||[]].find(r=>r.id===e):e)).find(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!i)throw new Error(`Could not find x25519 key for ${e}`);return de(y(i.publicKeyBase58),i.id)}))}function ye(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:async function(t,n,o,i){if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(i.header),"X25519"!==i.header.epk.crv)return null;const a=p(i.header.epk.x),c=I(f(e,a),256,r),s=k(i.encrypted_key,i.header.tag),u=await le(c).decrypt(s,p(i.header.iv));return null===u?null:le(u).decrypt(t,n,o)}}}export{U as ES256KSigner,j as EdDSASigner,R as EllipticSigner,O as NaclSigner,C as SimpleSigner,ce as createJWE,re as createJWS,te as createJWT,ee as decodeJWT,se as decryptJWE,pe as resolveX25519Encrypters,P as toEthereumAddress,oe as verifyJWS,ie as verifyJWT,ye as x25519Decrypter,de as x25519Encrypter,le as xc20pDirDecrypter,fe as xc20pDirEncrypter};
//# sourceMappingURL=index.modern.js.map

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

!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("uint8arrays"),require("@stablelib/sha256"),require("js-sha3"),require("elliptic"),require("@stablelib/ed25519"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","uint8arrays","@stablelib/sha256","js-sha3","elliptic","@stablelib/ed25519","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],e):e((r||self).didJwt={},r.uint8Arrays,r.sha256$1,r.jsSha3,r.elliptic,r.ed25519,r.xchacha20poly1305,r.x25519,r.random)}(this,function(r,e,t,n,i,o,a,u,c){function f(r){return e.toString(r,"base64url")}function s(r){var t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e.fromString(t,"base64url")}function l(r){return e.fromString(r,"base58btc")}function h(r){var t=r.startsWith("0x")?r.substring(2):r;return e.fromString(t.toLowerCase(),"base16")}function d(r){return f(e.fromString(r))}function v(r){return e.toString(s(r))}function y(r){return e.toString(r,"base16")}function p(r){return e.fromString(r)}function g(r,t){var n=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(t?65:64);if(a.set(e.fromString(n,"base16"),0),a.set(e.fromString(i,"base16"),32),t){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return f(a)}function m(r){var e=s(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:y(e.slice(0,32)),s:y(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function w(r,t){return e.concat([s(r),s(t)])}var b=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,E=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,P=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function S(r){if("string"==typeof r){if(b.test(r))return h(r);if(E.test(r))return l(r);if(P.test(r))return s(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function k(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function x(r){var n="string"==typeof r?e.fromString(r):r;return t.hash(n)}function K(r){var t,i=e.fromString(r.slice(2),"base16");return"0x"+e.toString((t=i,new Uint8Array(n.keccak_256.arrayBuffer(t))).slice(-20),"base16")}function j(r,t){void 0===t&&(t=new Uint8Array(4));var n=e.fromString(r.toString(),"base10");return t.set(n,4-n.length),t}var A=function(r){return e.concat([j(r.length),r])};function D(r,n,i){if(256!==n)throw new Error("Unsupported key length: "+n);var o=e.concat([A(e.fromString(i)),A(new Uint8Array(0)),A(new Uint8Array(0)),j(n)]);return t.hash(e.concat([j(1),r,o]))}var J=new i.ec("secp256k1");function W(r,e){void 0===e&&(e=!1);var t=S(r);if(32!==t.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+t.length);var n=J.keyFromPrivate(t);return function(r){try{var t=n.sign(x(r)),i=t.s,o=t.recoveryParam;return Promise.resolve(g({r:k(t.r.toString("hex")),s:k(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function T(r){var e=S(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var t="string"==typeof r?p(r):r,n=o.sign(e,t);return Promise.resolve(f(n))}catch(r){return Promise.reject(r)}}}function C(){return(C=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var I=new i.ec("secp256k1");function U(r,e){void 0===e&&(e=!1);var t=s(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");var n={r:y(t.slice(0,32)),s:y(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function O(r){return r.publicKeyBase58?l(r.publicKeyBase58):r.publicKeyBase64?s(r.publicKeyBase64):r.publicKeyHex?h(r.publicKeyHex):new Uint8Array}function R(r,e,t){var n;if(e.length>86)n=[U(e,!0)];else{var i=U(e,!1);n=[C({},i,{recoveryParam:0}),C({},i,{recoveryParam:1})]}var o=n.map(function(e){var n=x(r),i=I.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=K(o);return t.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function B(r,e,t){var n=p(r),i=s(e),a=t.find(function(r){return o.verify(O(r),n,i)});if(!a)throw new Error("Signature invalid for JWT");return a}var N={ES256K:function(r,e,t){var n=x(r),i=U(e),o=t.filter(function(r){return void 0===r.ethereumAddress}),a=t.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=O(r);return I.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=R(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":R,Ed25519:B,EdDSA:B};function X(r){var e=N[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function V(r){return"object"==typeof r&&"r"in r&&"s"in r}function _(r){return function(e,t){try{return Promise.resolve(t(e)).then(function(e){if(V(e))return g(e,r);if(r&&void 0===m(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function q(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(V(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}X.toSignatureObject=U;var H={ES256K:_(),"ES256K-R":_(!0),Ed25519:q(),EdDSA:q()},M=function(r,e,t){void 0===t&&(t={});try{t.alg||(t.alg=Z);var n="string"==typeof r?r:F(r),i=[F(t),n].join("."),o=function(r){var e=H[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(t.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},z={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},Z="ES256K";function F(r){return d(JSON.stringify(r))}function $(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(v(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function L(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=$(r);return Object.assign(e,{payload:JSON.parse(v(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function G(r,e){var t=r.header,n=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),X(t.alg)(n,i,e)}var Q="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Y(r,e,t){if(!r.s){if(t instanceof rr){if(!t.s)return void(t.o=Y.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(Y.bind(null,r,e),Y.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var rr=function(){function r(){}return r.prototype.then=function(e,t){var n=new r,i=this.s;if(i){var o=1&i?e:t;if(o){try{Y(n,1,o(this.v))}catch(r){Y(n,2,r)}return n}return this}return this.o=function(r){try{var i=r.v;1&r.s?Y(n,1,e?e(i):i):t?Y(n,1,t(i)):Y(n,2,i)}catch(r){Y(n,2,r)}},n},r}();function er(r){return r instanceof rr&&1&r.s}function tr(r,e){var t=r.ciphertext,n=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:f(r.iv),ciphertext:f(t),tag:f(n)};return e&&(o.aad=f(e)),i&&(o.recipients=[i]),o}function nr(r){var e=new a.XChaCha20Poly1305(r);return function(r,t){var n=c.randomBytes(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}function ir(r){var e=nr(r),t="XC20P";return{alg:"dir",enc:t,encrypt:function(r,n,i){void 0===n&&(n={});try{var o=d(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?o+"."+f(i):o));return Promise.resolve(C({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function or(r){var e=new a.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,t,n){try{return Promise.resolve(e.open(t,r,n))}catch(r){return Promise.reject(r)}}}}function ar(r,e){var t=function(t){try{var a=u.generateKeyPair(),c=nr(D(u.sharedKey(a.secretKey,r),i,n))(t),s={encrypted_key:f(c.ciphertext),header:{alg:n,iv:f(c.iv),tag:f(c.tag),epk:{kty:"OKP",crv:o,x:f(a.publicKey)}}};return e&&(s.header.kid=e),Promise.resolve(s)}catch(r){return Promise.reject(r)}},n="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:n,enc:"XC20P",encrypt:function(r,e,n){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=c.randomBytes(32);return Promise.resolve(ir(i).encrypt(r,e,n)).then(function(r){return Promise.resolve(t(i)).then(function(e){return C({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:t}}r.ES256KSigner=W,r.EdDSASigner=T,r.EllipticSigner=function(r){return W(r)},r.NaclSigner=function(r){return T(r)},r.SimpleSigner=function(r){var e=W(r,!0);return function(r){try{return Promise.resolve(e(r)).then(m)}catch(r){return Promise.reject(r)}}},r.createJWE=function(r,e,t,n){void 0===t&&(t={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,t,n)).then(function(r){return tr(r,n)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,t){if("function"==typeof r[Q]){var n,i,o,a=r[Q]();if(function r(t){try{for(;!(n=a.next()).done;)if((t=e(n.value))&&t.then){if(!er(t))return void t.then(r,o||(o=Y.bind(null,i=new rr,2)));t=t.v}i?Y(i,1,t):i=t}catch(r){Y(i||(i=new rr),2,r)}}(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,i,o=-1;return function t(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!er(a))return void a.then(t,i||(i=Y.bind(null,n=new rr,2)));a=a.v}n?Y(n,1,a):n=a}catch(r){Y(n||(n=new rr),2,r)}}(),n}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,t,n)).then(function(r){i=r.cek,o=tr(r,n)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},r.createJWS=M,r.createJWT=function(r,e,t){var n=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===t&&(t={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!n)throw new Error("No issuing DID has been configured");t.typ||(t.typ="JWT"),t.alg||(t.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=C({},u,r,{iss:n});return M(c,i,t)}catch(r){return Promise.reject(r)}},r.decodeJWT=L,r.decryptJWE=function(r,e){try{var t=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var n=JSON.parse(v(r.protected));if(n.enc!==e.enc)throw new Error("Decrypter does not support: '"+n.enc+"'");var i=w(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===n.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,s(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var t=0;return function(r,e,t){for(var n;;){var i=r();if(er(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!er(o)){n=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!er(a)){n=2;break}}}var u=new rr,c=Y.bind(null,u,2);return(0===n?i.then(s):1===n?o.then(f):a.then(l)).then(void 0,c),u;function f(n){o=n;do{if(e&&(a=e())&&a.then&&!er(a))return void a.then(l).then(void 0,c);if(!(i=r())||er(i)&&!i.v)return void Y(u,1,o);if(i.then)return void i.then(s).then(void 0,c);er(o=t())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=t())&&o.then?o.then(f).then(void 0,c):f(o):Y(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):Y(u,1,o)}}(function(){return!a&&t<r.recipients.length},function(){return t++},function(){var u=r.recipients[t];Object.assign(u.header,n);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,s(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(r){return Promise.reject(r)}},r.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var t,n=e.didResolutionMetadata,i=e.didDocument;if(null!=n&&n.error)throw new Error("Could not find x25519 key for "+r+": "+n.error+", "+n.message);if(!i.keyAgreement)throw new Error("Could not find x25519 key for "+r);var o=(null==(t=i.keyAgreement)?void 0:t.map(function(r){return"string"==typeof r?[].concat(i.publicKey||[],i.verificationMethod||[]).find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!o)throw new Error("Could not find x25519 key for "+r);return ar(l(o.publicKeyBase58),o.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},r.toEthereumAddress=K,r.verifyJWS=function(r,e){return G($(r),e)},r.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var t=L(r),n=t.payload,i=t.header,o=t.signature,a=t.data;return Promise.resolve(function(r,e,t,n){try{var i=z[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(t,{accept:"application/did+json"})).then(function(r){var o,a,u;if(null!=(o=r.didResolutionMetadata)&&o.error){var c=r.didResolutionMetadata;throw new Error("Unable to resolve DID document for "+t+": "+c.error+", "+(c.message||""))}var f=function(r,e){var t=r.filter(function(r){return e===r.id});return t.length>0?t[0]:null},s=[];r.didDocument.verificationMethod&&(a=s).push.apply(a,r.didDocument.verificationMethod),r.didDocument.publicKey&&(u=s).push.apply(u,r.didDocument.publicKey),n&&(s=(r.didDocument.authentication||[]).map(function(r){return"string"==typeof r?f(s,r):"string"==typeof r.publicKey?f(s,r.publicKey):r}).filter(function(r){return null!=r}));var l=s.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(n&&(!l||0===l.length))throw new Error("DID document for "+t+" does not have public keys suitable for authenticating user");if(!l||0===l.length)throw new Error("DID document for "+t+" does not have public keys for "+e);return{authenticators:l,issuer:t,didResolutionResult:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,n.iss,e.auth)).then(function(t){var u=t.didResolutionResult,c=t.issuer;return Promise.resolve(G({header:i,data:a,signature:o},t.authenticators)).then(function(t){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(t){var a=i+o;if(n.nbf){if(n.nbf>a)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=i-o)throw new Error("JWT has expired: exp: "+n.exp+" < now: "+i);if(n.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,didResolutionResult:u,issuer:c,signer:t,jwt:r}}})})}catch(r){return Promise.reject(r)}},r.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(t,n,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var a=s(o.header.epk.x),c=D(u.sharedKey(r,a),256,e),f=w(o.encrypted_key,o.header.tag);return Promise.resolve(or(c).decrypt(f,s(o.header.iv))).then(function(r){return null===r?null:or(r).decrypt(t,n,i)})}catch(r){return Promise.reject(r)}}}},r.x25519Encrypter=ar,r.xc20pDirDecrypter=or,r.xc20pDirEncrypter=ir});
!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("uint8arrays"),require("@stablelib/sha256"),require("js-sha3"),require("elliptic"),require("@stablelib/ed25519"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","uint8arrays","@stablelib/sha256","js-sha3","elliptic","@stablelib/ed25519","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],e):e((r||self).didJwt={},r.uint8Arrays,r.sha256$1,r.jsSha3,r.elliptic,r.ed25519,r.xchacha20poly1305,r.x25519,r.random)}(this,function(r,e,t,n,i,o,a,u,c){function f(r){return e.toString(r,"base64url")}function s(r){var t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e.fromString(t,"base64url")}function l(r){return e.fromString(r,"base58btc")}function d(r){var t=r.startsWith("0x")?r.substring(2):r;return e.fromString(t.toLowerCase(),"base16")}function h(r){return f(e.fromString(r))}function v(r){return e.toString(s(r))}function y(r){return e.toString(r,"base16")}function p(r){return e.fromString(r)}function g(r,t){var n=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(t?65:64);if(a.set(e.fromString(n,"base16"),0),a.set(e.fromString(i,"base16"),32),t){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return f(a)}function m(r){var e=s(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:y(e.slice(0,32)),s:y(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function w(r,t){return e.concat([s(r),s(t)])}var b=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,E=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,S=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function P(r){if("string"==typeof r){if(b.test(r))return d(r);if(E.test(r))return l(r);if(S.test(r))return s(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function k(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function x(r){var n="string"==typeof r?e.fromString(r):r;return t.hash(n)}function K(r){var t,i=e.fromString(r.slice(2),"base16");return"0x"+e.toString((t=i,new Uint8Array(n.keccak_256.arrayBuffer(t))).slice(-20),"base16")}function j(r,t){void 0===t&&(t=new Uint8Array(4));var n=e.fromString(r.toString(),"base10");return t.set(n,4-n.length),t}var A=function(r){return e.concat([j(r.length),r])};function D(r,n,i){if(256!==n)throw new Error("Unsupported key length: "+n);var o=e.concat([A(e.fromString(i)),A(new Uint8Array(0)),A(new Uint8Array(0)),j(n)]);return t.hash(e.concat([j(1),r,o]))}var J=new i.ec("secp256k1");function W(r,e){void 0===e&&(e=!1);var t=P(r);if(32!==t.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+t.length);var n=J.keyFromPrivate(t);return function(r){try{var t=n.sign(x(r)),i=t.s,o=t.recoveryParam;return Promise.resolve(g({r:k(t.r.toString("hex")),s:k(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function T(r){var e=P(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var t="string"==typeof r?p(r):r,n=o.sign(e,t);return Promise.resolve(f(n))}catch(r){return Promise.reject(r)}}}function C(){return(C=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var I=new i.ec("secp256k1");function U(r,e){void 0===e&&(e=!1);var t=s(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");var n={r:y(t.slice(0,32)),s:y(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function O(r){return r.publicKeyBase58?l(r.publicKeyBase58):r.publicKeyBase64?s(r.publicKeyBase64):r.publicKeyHex?d(r.publicKeyHex):new Uint8Array}function R(r,e,t){var n;if(e.length>86)n=[U(e,!0)];else{var i=U(e,!1);n=[C({},i,{recoveryParam:0}),C({},i,{recoveryParam:1})]}var o=n.map(function(e){var n=x(r),i=I.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=K(o);return t.find(function(r){var e=y(O(r));return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function B(r,e,t){var n=p(r),i=s(e),a=t.find(function(r){return o.verify(O(r),n,i)});if(!a)throw new Error("Signature invalid for JWT");return a}var N={ES256K:function(r,e,t){var n=x(r),i=U(e),o=t.filter(function(r){return void 0===r.ethereumAddress}),a=t.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=O(r);return I.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=R(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":R,Ed25519:B,EdDSA:B};function X(r){var e=N[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function M(r){return"object"==typeof r&&"r"in r&&"s"in r}function V(r){return function(e,t){try{return Promise.resolve(t(e)).then(function(e){if(M(e))return g(e,r);if(r&&void 0===m(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function _(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(M(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}X.toSignatureObject=U;var q={ES256K:V(),"ES256K-R":V(!0),Ed25519:_(),EdDSA:_()},z=function(r,e,t){void 0===t&&(t={});try{t.alg||(t.alg=Z);var n="string"==typeof r?r:F(r),i=[F(t),n].join("."),o=function(r){var e=q[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(t.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},H={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},Z="ES256K";function F(r){return h(JSON.stringify(r))}function $(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(v(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function L(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=$(r);return Object.assign(e,{payload:JSON.parse(v(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function G(r,e){var t=r.header,n=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),X(t.alg)(n,i,e)}var Q="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Y(r,e,t){if(!r.s){if(t instanceof rr){if(!t.s)return void(t.o=Y.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(Y.bind(null,r,e),Y.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var rr=function(){function r(){}return r.prototype.then=function(e,t){var n=new r,i=this.s;if(i){var o=1&i?e:t;if(o){try{Y(n,1,o(this.v))}catch(r){Y(n,2,r)}return n}return this}return this.o=function(r){try{var i=r.v;1&r.s?Y(n,1,e?e(i):i):t?Y(n,1,t(i)):Y(n,2,i)}catch(r){Y(n,2,r)}},n},r}();function er(r){return r instanceof rr&&1&r.s}function tr(r,e){var t=r.ciphertext,n=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:f(r.iv),ciphertext:f(t),tag:f(n)};return e&&(o.aad=f(e)),i&&(o.recipients=[i]),o}function nr(r){var e=new a.XChaCha20Poly1305(r);return function(r,t){var n=c.randomBytes(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}function ir(r){var e=nr(r),t="XC20P";return{alg:"dir",enc:t,encrypt:function(r,n,i){void 0===n&&(n={});try{var o=h(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?o+"."+f(i):o));return Promise.resolve(C({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function or(r){var e=new a.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,t,n){try{return Promise.resolve(e.open(t,r,n))}catch(r){return Promise.reject(r)}}}}function ar(r,e){var t=function(t){try{var a=u.generateKeyPair(),c=nr(D(u.sharedKey(a.secretKey,r),i,n))(t),s={encrypted_key:f(c.ciphertext),header:{alg:n,iv:f(c.iv),tag:f(c.tag),epk:{kty:"OKP",crv:o,x:f(a.publicKey)}}};return e&&(s.header.kid=e),Promise.resolve(s)}catch(r){return Promise.reject(r)}},n="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:n,enc:"XC20P",encrypt:function(r,e,n){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=c.randomBytes(32);return Promise.resolve(ir(i).encrypt(r,e,n)).then(function(r){return Promise.resolve(t(i)).then(function(e){return C({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:t}}r.ES256KSigner=W,r.EdDSASigner=T,r.EllipticSigner=function(r){return W(r)},r.NaclSigner=function(r){return T(r)},r.SimpleSigner=function(r){var e=W(r,!0);return function(r){try{return Promise.resolve(e(r)).then(m)}catch(r){return Promise.reject(r)}}},r.createJWE=function(r,e,t,n){void 0===t&&(t={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,t,n)).then(function(r){return tr(r,n)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,t){if("function"==typeof r[Q]){var n,i,o,a=r[Q]();if(function r(t){try{for(;!(n=a.next()).done;)if((t=e(n.value))&&t.then){if(!er(t))return void t.then(r,o||(o=Y.bind(null,i=new rr,2)));t=t.v}i?Y(i,1,t):i=t}catch(r){Y(i||(i=new rr),2,r)}}(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,i,o=-1;return function t(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!er(a))return void a.then(t,i||(i=Y.bind(null,n=new rr,2)));a=a.v}n?Y(n,1,a):n=a}catch(r){Y(n||(n=new rr),2,r)}}(),n}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,t,n)).then(function(r){i=r.cek,o=tr(r,n)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},r.createJWS=z,r.createJWT=function(r,e,t){var n=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===t&&(t={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!n)throw new Error("No issuing DID has been configured");t.typ||(t.typ="JWT"),t.alg||(t.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=C({},u,r,{iss:n});return z(c,i,t)}catch(r){return Promise.reject(r)}},r.decodeJWT=L,r.decryptJWE=function(r,e){try{var t=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var n=JSON.parse(v(r.protected));if(n.enc!==e.enc)throw new Error("Decrypter does not support: '"+n.enc+"'");var i=w(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===n.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,s(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var t=0;return function(r,e,t){for(var n;;){var i=r();if(er(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!er(o)){n=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!er(a)){n=2;break}}}var u=new rr,c=Y.bind(null,u,2);return(0===n?i.then(s):1===n?o.then(f):a.then(l)).then(void 0,c),u;function f(n){o=n;do{if(e&&(a=e())&&a.then&&!er(a))return void a.then(l).then(void 0,c);if(!(i=r())||er(i)&&!i.v)return void Y(u,1,o);if(i.then)return void i.then(s).then(void 0,c);er(o=t())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=t())&&o.then?o.then(f).then(void 0,c):f(o):Y(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):Y(u,1,o)}}(function(){return!a&&t<r.recipients.length},function(){return t++},function(){var u=r.recipients[t];Object.assign(u.header,n);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,s(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(r){return Promise.reject(r)}},r.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var t,n=e.didResolutionMetadata,i=e.didDocument;if(null!=n&&n.error)throw new Error("Could not find x25519 key for "+r+": "+n.error+", "+n.message);if(!i.keyAgreement)throw new Error("Could not find x25519 key for "+r);var o=(null==(t=i.keyAgreement)?void 0:t.map(function(r){return"string"==typeof r?[].concat(i.publicKey||[],i.verificationMethod||[]).find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!o)throw new Error("Could not find x25519 key for "+r);return ar(l(o.publicKeyBase58),o.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},r.toEthereumAddress=K,r.verifyJWS=function(r,e){return G($(r),e)},r.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var t=L(r),n=t.payload,i=t.header,o=t.signature,a=t.data;return Promise.resolve(function(r,e,t,n){try{var i=H[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(t,{accept:"application/did+json"})).then(function(r){var o,a,u;if(null!=(o=r.didResolutionMetadata)&&o.error){var c=r.didResolutionMetadata;throw new Error("Unable to resolve DID document for "+t+": "+c.error+", "+(c.message||""))}var f=function(r,e){var t=r.filter(function(r){return e===r.id});return t.length>0?t[0]:null},s=[];r.didDocument.verificationMethod&&(a=s).push.apply(a,r.didDocument.verificationMethod),r.didDocument.publicKey&&(u=s).push.apply(u,r.didDocument.publicKey),n&&(s=(r.didDocument.authentication||[]).map(function(r){return"string"==typeof r?f(s,r):"string"==typeof r.publicKey?f(s,r.publicKey):r}).filter(function(r){return null!=r}));var l=s.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(n&&(!l||0===l.length))throw new Error("DID document for "+t+" does not have public keys suitable for authenticating user");if(!l||0===l.length)throw new Error("DID document for "+t+" does not have public keys for "+e);return{authenticators:l,issuer:t,didResolutionResult:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,n.iss,e.auth)).then(function(t){var u=t.didResolutionResult,c=t.issuer;return Promise.resolve(G({header:i,data:a,signature:o},t.authenticators)).then(function(t){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(t){var a=i+o;if(n.nbf){if(n.nbf>a)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=i-o)throw new Error("JWT has expired: exp: "+n.exp+" < now: "+i);if(n.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,didResolutionResult:u,issuer:c,signer:t,jwt:r}}})})}catch(r){return Promise.reject(r)}},r.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(t,n,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var a=s(o.header.epk.x),c=D(u.sharedKey(r,a),256,e),f=w(o.encrypted_key,o.header.tag);return Promise.resolve(or(c).decrypt(f,s(o.header.iv))).then(function(r){return null===r?null:or(r).decrypt(t,n,i)})}catch(r){return Promise.reject(r)}}}},r.x25519Encrypter=ar,r.xc20pDirDecrypter=or,r.xc20pDirEncrypter=ir});
//# sourceMappingURL=index.umd.js.map

@@ -13,2 +13,3 @@ /**

export declare function base58ToBytes(s: string): Uint8Array;
export declare function bytesToBase58(b: Uint8Array): string;
export declare function hexToBytes(s: string): Uint8Array;

@@ -15,0 +16,0 @@ export declare function encodeBase64url(s: string): string;

{
"name": "did-jwt",
"version": "5.0.0",
"version": "5.0.1",
"description": "Library for Signing and Verifying JWTs compatible uPort and DID standards",

@@ -70,3 +70,3 @@ "main": "lib/index.js",

"eslint-plugin-import": "2.22.1",
"eslint-plugin-jest": "24.1.9",
"eslint-plugin-jest": "24.2.1",
"eslint-plugin-node": "11.1.0",

@@ -73,0 +73,0 @@ "eslint-plugin-promise": "4.3.1",

@@ -23,3 +23,3 @@ import VerifierAlgorithm from '../VerifierAlgorithm'

it('handles EdDSA algorithm with did:key', async () => {
const resolver = {
const resolver = ({
resolve: async () => ({

@@ -42,3 +42,3 @@ didResolutionMetadata: {},

})
} as unknown as Resolver
} as unknown) as Resolver
const jwt =

@@ -45,0 +45,0 @@ 'eyJhbGciOiJFZERTQSJ9.eyJleHAiOjE3NjQ4Nzg5MDgsImlzcyI6ImRpZDprZXk6ejZNa29USHNnTk5yYnk4SnpDTlExaVJMeVc1UVE2UjhYdXU2QUE4aWdHck1WUFVNIiwibmJmIjoxNjA3MTEyNTA4LCJzdWIiOiJkaWQ6a2V5Ono2TWtvVEhzZ05OcmJ5OEp6Q05RMWlSTHlXNVFRNlI4WHV1NkFBOGlnR3JNVlBVTSIsInZjIjp7IkBjb250ZXh0IjpbImh0dHBzOi8vd3d3LnczLm9yZy8yMDE4L2NyZWRlbnRpYWxzL3YxIiwiaHR0cHM6Ly9pZGVudGl0eS5mb3VuZGF0aW9uLy53ZWxsLWtub3duL2RpZC1jb25maWd1cmF0aW9uL3YxIl0sImNyZWRlbnRpYWxTdWJqZWN0Ijp7ImlkIjoiZGlkOmtleTp6Nk1rb1RIc2dOTnJieThKekNOUTFpUkx5VzVRUTZSOFh1dTZBQThpZ0dyTVZQVU0iLCJvcmlnaW4iOiJpZGVudGl0eS5mb3VuZGF0aW9uIn0sImV4cGlyYXRpb25EYXRlIjoiMjAyNS0xMi0wNFQxNDowODoyOC0wNjowMCIsImlzc3VhbmNlRGF0ZSI6IjIwMjAtMTItMDRUMTQ6MDg6MjgtMDY6MDAiLCJpc3N1ZXIiOiJkaWQ6a2V5Ono2TWtvVEhzZ05OcmJ5OEp6Q05RMWlSTHlXNVFRNlI4WHV1NkFBOGlnR3JNVlBVTSIsInR5cGUiOlsiVmVyaWZpYWJsZUNyZWRlbnRpYWwiLCJEb21haW5MaW5rYWdlQ3JlZGVudGlhbCJdfX0.6ovgQ-T_rmYueviySqXhzMzgqJMAizOGUKAObQr2iikoRNsb8DHfna4rh1puwWqYwgT3QJVpzdO_xZARAYM9Dw'

import { decryptJWE, createJWE, Encrypter } from '../JWE'
import vectors from './jwe-vectors.js'
import {
xc20pDirEncrypter,
xc20pDirDecrypter,
x25519Encrypter,
x25519Decrypter
} from '../xc20pEncryption'
import { xc20pDirEncrypter, xc20pDirDecrypter, x25519Encrypter, x25519Decrypter } from '../xc20pEncryption'
import { decodeBase64url } from '../util'

@@ -67,3 +62,3 @@ import * as u8a from 'uint8arrays'

expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ alg:'dir', enc:'XC20P' })
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ alg: 'dir', enc: 'XC20P' })
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)

@@ -75,3 +70,3 @@ })

expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ alg:'dir', enc:'XC20P', more: 'protected' })
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ alg: 'dir', enc: 'XC20P', more: 'protected' })
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)

@@ -84,3 +79,3 @@ })

expect(u8a.fromString(jwe.aad, 'base64url')).toEqual(aad)
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ alg:'dir', enc:'XC20P', more: 'protected' })
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ alg: 'dir', enc: 'XC20P', more: 'protected' })
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)

@@ -107,3 +102,3 @@ delete jwe.aad

expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc:'XC20P' })
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P' })
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)

@@ -115,3 +110,3 @@ })

expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc:'XC20P', more: 'protected' })
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P', more: 'protected' })
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)

@@ -124,3 +119,3 @@ })

expect(u8a.fromString(jwe.aad, 'base64url')).toEqual(aad)
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc:'XC20P', more: 'protected' })
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P', more: 'protected' })
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)

@@ -151,3 +146,3 @@ delete jwe.aad

expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc:'XC20P' })
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P' })
expect(await decryptJWE(jwe, decrypter1)).toEqual(cleartext)

@@ -160,3 +155,3 @@ expect(await decryptJWE(jwe, decrypter2)).toEqual(cleartext)

expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc:'XC20P', more: 'protected' })
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P', more: 'protected' })
expect(await decryptJWE(jwe, decrypter1)).toEqual(cleartext)

@@ -170,3 +165,3 @@ expect(await decryptJWE(jwe, decrypter2)).toEqual(cleartext)

expect(u8a.fromString(jwe.aad, 'base64url')).toEqual(aad)
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc:'XC20P', more: 'protected' })
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P', more: 'protected' })
expect(await decryptJWE(jwe, decrypter1)).toEqual(cleartext)

@@ -173,0 +168,0 @@ expect(await decryptJWE(jwe, decrypter2)).toEqual(cleartext)

@@ -166,3 +166,3 @@ import { createJWT, verifyJWT, decodeJWT, createJWS, verifyJWS, resolveAuthenticator, NBF_SKEW } from '../JWT'

describe('verifyJWT()', () => {
const resolver = { resolve: jest.fn().mockReturnValue(didDoc) } as unknown as Resolver
const resolver = ({ resolve: jest.fn().mockReturnValue(didDoc) } as unknown) as Resolver

@@ -178,3 +178,5 @@ describe('pregenerated JWT', () => {

it('verifies the JWT and return correct profile', async () => {
const { didResolutionResult: { didDocument } } = await verifyJWT(incomingJwt, { resolver })
const {
didResolutionResult: { didDocument }
} = await verifyJWT(incomingJwt, { resolver })
return expect(didDocument).toEqual(didDoc.didDocument)

@@ -270,3 +272,3 @@ })

it('handles ES256K algorithm with ethereum address - github #14', async () => {
const ethResolver = { resolve: jest.fn().mockReturnValue(didDocDefault) } as unknown as Resolver
const ethResolver = ({ resolve: jest.fn().mockReturnValue(didDocDefault) } as unknown) as Resolver
const jwt = await createJWT({ hello: 'world' }, { issuer: aud, signer, alg: 'ES256K' })

@@ -452,3 +454,3 @@ const { payload } = await verifyJWT(jwt, { resolver: ethResolver })

}
const ecKey7 = {

@@ -473,3 +475,3 @@ id: `${did}#keys-auth7`,

publicKey: [ecKey1]
},
}
}

@@ -483,3 +485,3 @@

authentication: [authKey1, authKey2, edAuthKey]
},
}
}

@@ -493,3 +495,3 @@

authentication: [authKey1, authKey2, edAuthKey, `${did}#keys-auth6`, `${did}#keys-auth7`, edKey8]
},
}
}

@@ -502,3 +504,3 @@

publicKey: [encKey1]
},
}
}

@@ -509,3 +511,3 @@ const noPublicKey = {

id: did
},
}
}

@@ -516,3 +518,7 @@

it('finds public key', async () => {
const authenticators = await resolveAuthenticator({ resolve: jest.fn().mockReturnValue(singleKey) } as unknown as Resolver, alg, did)
const authenticators = await resolveAuthenticator(
({ resolve: jest.fn().mockReturnValue(singleKey) } as unknown) as Resolver,
alg,
did
)
return expect(authenticators).toEqual({

@@ -527,3 +533,3 @@ authenticators: [ecKey1],

const authenticators = await resolveAuthenticator(
{ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown as Resolver,
({ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown) as Resolver,
alg,

@@ -541,3 +547,3 @@ did

const authenticators = await resolveAuthenticator(
{ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown as Resolver,
({ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown) as Resolver,
alg,

@@ -556,3 +562,3 @@ did,

const authenticators = await resolveAuthenticator(
{ resolve: jest.fn().mockReturnValue(multipleAuthTypes) } as unknown as Resolver,
({ resolve: jest.fn().mockReturnValue(multipleAuthTypes) } as unknown) as Resolver,
alg,

@@ -571,3 +577,7 @@ did,

return await expect(
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(unsupportedFormat) } as unknown as Resolver, alg, did)
resolveAuthenticator(
({ resolve: jest.fn().mockReturnValue(unsupportedFormat) } as unknown) as Resolver,
alg,
did
)
).rejects.toEqual(new Error(`DID document for ${did} does not have public keys for ${alg}`))

@@ -581,3 +591,3 @@ })

const authenticators = await resolveAuthenticator(
{ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown as Resolver,
({ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown) as Resolver,
alg,

@@ -595,3 +605,3 @@ did

const authenticators = await resolveAuthenticator(
{ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown as Resolver,
({ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown) as Resolver,
alg,

@@ -610,3 +620,3 @@ did,

const authenticators = await resolveAuthenticator(
{ resolve: jest.fn().mockReturnValue(multipleAuthTypes) } as unknown as Resolver,
({ resolve: jest.fn().mockReturnValue(multipleAuthTypes) } as unknown) as Resolver,
alg,

@@ -625,3 +635,7 @@ did,

return await expect(
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(unsupportedFormat) } as unknown as Resolver, alg, did)
resolveAuthenticator(
({ resolve: jest.fn().mockReturnValue(unsupportedFormat) } as unknown) as Resolver,
alg,
did
)
).rejects.toEqual(new Error(`DID document for ${did} does not have public keys for ${alg}`))

@@ -633,6 +647,4 @@ })

return await expect(
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(singleKey) } as unknown as Resolver, alg, did, true)
).rejects.toEqual(
new Error(`DID document for ${did} does not have public keys suitable for authenticating user`)
)
resolveAuthenticator(({ resolve: jest.fn().mockReturnValue(singleKey) } as unknown) as Resolver, alg, did, true)
).rejects.toEqual(new Error(`DID document for ${did} does not have public keys suitable for authenticating user`))
})

@@ -642,3 +654,3 @@

return await expect(
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(noPublicKey) } as unknown as Resolver, alg, did)
resolveAuthenticator(({ resolve: jest.fn().mockReturnValue(noPublicKey) } as unknown) as Resolver, alg, did)
).rejects.toEqual(new Error(`DID document for ${did} does not have public keys for ${alg}`))

@@ -648,8 +660,14 @@ })

it('errors if no DID document exists', async () => {
return await expect(resolveAuthenticator({ resolve: jest.fn().mockReturnValue({
didResolutionMetadata: { error: 'notFound' },
didDocument: null
}) } as unknown as Resolver, alg, did)).rejects.toEqual(
new Error(`Unable to resolve DID document for ${did}: notFound, `)
)
return await expect(
resolveAuthenticator(
({
resolve: jest.fn().mockReturnValue({
didResolutionMetadata: { error: 'notFound' },
didDocument: null
})
} as unknown) as Resolver,
alg,
did
)
).rejects.toEqual(new Error(`Unable to resolve DID document for ${did}: notFound, `))
})

@@ -659,3 +677,3 @@

return await expect(
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(singleKey) } as unknown as Resolver, 'ESBAD', did)
resolveAuthenticator(({ resolve: jest.fn().mockReturnValue(singleKey) } as unknown) as Resolver, 'ESBAD', did)
).rejects.toEqual(new Error('No supported signature types for algorithm ESBAD'))

@@ -662,0 +680,0 @@ })

@@ -8,3 +8,3 @@ import VerifierAlgorithm from '../VerifierAlgorithm'

import { ec as EC } from 'elliptic'
import { base64ToBytes, bytesToBase64 } from '../util'
import { base64ToBytes, bytesToBase58, bytesToBase64, hexToBytes } from '../util'
import * as u8a from 'uint8arrays'

@@ -38,2 +38,4 @@

const compressedPublicKey = String(kp.getPublic().encode('hex', true))
const publicKeyBase64 = bytesToBase64(hexToBytes(publicKey))
const publicKeyBase58 = bytesToBase58(hexToBytes(publicKey))
const address = toEthereumAddress(publicKey)

@@ -77,2 +79,9 @@ const signer = SimpleSigner(privateKey)

const recoveryMethod2020Key = {
id: `${did}#keys-recovery`,
type: 'EcdsaSecp256k1RecoveryMethod2020',
controller: did,
ethereumAddress: address
}
const edKey = {

@@ -127,3 +136,2 @@ id: `${did}#keys-5`,

const parts = jwt.match(/^([a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/)
const publicKeyBase58 = u8a.toString(u8a.fromString(ecKey2.publicKeyHex, 'base16'), 'base58btc')
const pubkey = Object.assign({ publicKeyBase58 }, ecKey2)

@@ -134,2 +142,10 @@ delete pubkey.publicKeyHex

it('validates with publicKeyBase64', async () => {
const jwt = await createJWT({ bla: 'bla' }, { issuer: did, signer })
const parts = jwt.match(/^([a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/)
const pubkey = Object.assign({ publicKeyBase64 }, ecKey2)
delete pubkey.publicKeyHex
return expect(verifier(parts[1], parts[2], [pubkey])).toEqual(pubkey)
})
it('validates signature with compressed public key and picks correct public key', async () => {

@@ -166,2 +182,8 @@ const jwt = await createJWT({ bla: 'bla' }, { issuer: did, signer })

})
it('validates signature produced by EcdsaSecp256k1RecoveryMethod2020 - github #152', async () => {
const jwt = await createJWT({ bla: 'bla' }, { issuer: did, signer })
const parts = jwt.match(/^([a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/)
return expect(verifier(parts[1], parts[2], [recoveryMethod2020Key])).toEqual(recoveryMethod2020Key)
})
})

@@ -190,2 +212,24 @@

it('validates signature with EcdsaSecp256k1RecoveryMethod2020 - github #152', async () => {
const jwt = await createJWT({ bla: 'bla' }, { issuer: did, signer, alg: 'ES256K-R' })
const parts = jwt.match(/^([a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/)
return expect(verifier(parts[1], parts[2], [ecKey1, recoveryMethod2020Key])).toEqual(recoveryMethod2020Key)
})
it('validates with publicKeyBase58', async () => {
const jwt = await createJWT({ bla: 'bla' }, { issuer: did, signer, alg: 'ES256K-R' })
const parts = jwt.match(/^([a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/)
const pubkey = Object.assign({ publicKeyBase58 }, ecKey2)
delete pubkey.publicKeyHex
return expect(verifier(parts[1], parts[2], [pubkey])).toEqual(pubkey)
})
it('validates with publicKeyBase64', async () => {
const jwt = await createJWT({ bla: 'bla' }, { issuer: did, signer, alg: 'ES256K-R' })
const parts = jwt.match(/^([a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/)
const pubkey = Object.assign({ publicKeyBase64 }, ecKey2)
delete pubkey.publicKeyHex
return expect(verifier(parts[1], parts[2], [pubkey])).toEqual(pubkey)
})
it('throws error if invalid signature', async () => {

@@ -192,0 +236,0 @@ const jwt = await createJWT({ bla: 'bla' }, { issuer: did, signer, alg: 'ES256K-R' })

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

import {
x25519Decrypter,
resolveX25519Encrypters
} from '../xc20pEncryption'
import { x25519Decrypter, resolveX25519Encrypters } from '../xc20pEncryption'
import { decryptJWE, createJWE } from '../JWE'

@@ -25,16 +22,19 @@ import * as u8a from 'uint8arrays'

resolver = {
resolve: jest.fn(did => {
resolve: jest.fn((did) => {
if (did === did1) {
return {
didDocument: {
verificationMethod: [{
id: did1 + '#abc',
type: 'X25519KeyAgreementKey2019',
controller: did1,
publicKeyBase58: u8a.toString(kp1.publicKey, 'base58btc')
}],
keyAgreement: [{
id: 'irrelevant key'
},
did1 + '#abc'
verificationMethod: [
{
id: did1 + '#abc',
type: 'X25519KeyAgreementKey2019',
controller: did1,
publicKeyBase58: u8a.toString(kp1.publicKey, 'base58btc')
}
],
keyAgreement: [
{
id: 'irrelevant key'
},
did1 + '#abc'
]

@@ -47,8 +47,10 @@ }

verificationMethod: [],
keyAgreement: [{
id: did2 + '#abc',
type: 'X25519KeyAgreementKey2019',
controller: did2,
publicKeyBase58: u8a.toString(kp2.publicKey, 'base58btc')
}]
keyAgreement: [
{
id: did2 + '#abc',
type: 'X25519KeyAgreementKey2019',
controller: did2,
publicKeyBase58: u8a.toString(kp2.publicKey, 'base58btc')
}
]
}

@@ -77,6 +79,10 @@ }

it('throws error if key is not found', async () => {
await expect(resolveX25519Encrypters([did3], resolver)).rejects.toThrow('Could not find x25519 key for did:test:3')
await expect(resolveX25519Encrypters([did4], resolver)).rejects.toThrow('Could not find x25519 key for did:test:4')
await expect(resolveX25519Encrypters([did3], resolver)).rejects.toThrow(
'Could not find x25519 key for did:test:3'
)
await expect(resolveX25519Encrypters([did4], resolver)).rejects.toThrow(
'Could not find x25519 key for did:test:4'
)
})
})
})

@@ -6,3 +6,3 @@ import { hash } from '@stablelib/sha256'

export function sha256(payload: string | Uint8Array): Uint8Array {
const data = (typeof payload === 'string') ? u8a.fromString(payload) : payload
const data = typeof payload === 'string' ? u8a.fromString(payload) : payload
return hash(data)

@@ -41,3 +41,3 @@ }

const roundNumber = 1
return hash(u8a.concat([ writeUint32BE(roundNumber), secret, value ]))
return hash(u8a.concat([writeUint32BE(roundNumber), secret, value]))
}

@@ -15,3 +15,3 @@ import SimpleSigner from './signers/SimpleSigner'

JWTPayload,
JWTVerified,
JWTVerified
} from './JWT'

@@ -43,3 +43,3 @@ import { toEthereumAddress } from './Digest'

JWTPayload,
JWTVerified,
JWTVerified
}

@@ -44,3 +44,8 @@ import { base64ToBytes, bytesToBase64url, decodeBase64url, toSealed } from './util'

enc: string
decrypt: (sealed: Uint8Array, iv: Uint8Array, aad?: Uint8Array, recipient?: Record<string, any>) => Promise<Uint8Array>
decrypt: (
sealed: Uint8Array,
iv: Uint8Array,
aad?: Uint8Array,
recipient?: Record<string, any>
) => Promise<Uint8Array>
}

@@ -53,3 +58,3 @@

if (jwe.recipients) {
jwe.recipients.map(rec => {
jwe.recipients.map((rec) => {
if (!(rec.header && rec.encrypted_key)) {

@@ -62,12 +67,3 @@ throw new Error('Invalid JWE')

function encodeJWE(
{
ciphertext,
tag,
iv,
protectedHeader,
recipient
}: EncryptionResult,
aad?: Uint8Array
): JWE {
function encodeJWE({ ciphertext, tag, iv, protectedHeader, recipient }: EncryptionResult, aad?: Uint8Array): JWE {
const jwe: JWE = {

@@ -84,3 +80,8 @@ protected: protectedHeader,

export async function createJWE(cleartext: Uint8Array, encrypters: Encrypter[], protectedHeader = {}, aad?: Uint8Array): Promise<JWE> {
export async function createJWE(
cleartext: Uint8Array,
encrypters: Encrypter[],
protectedHeader = {},
aad?: Uint8Array
): Promise<JWE> {
if (encrypters[0].alg === 'dir') {

@@ -87,0 +88,0 @@ if (encrypters.length > 1) throw new Error('Can only do "dir" encryption to one key.')

import VerifierAlgorithm from './VerifierAlgorithm'
import SignerAlgorithm from './SignerAlgorithm'
import { encodeBase64url, decodeBase64url, EcdsaSignature } from './util'
import type { Resolver, DIDDocument, VerificationMethod, DIDResolutionResult } from 'did-resolver'
import type { Resolver, VerificationMethod, DIDResolutionResult } from 'did-resolver'

@@ -78,12 +78,38 @@ export type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string>

ES256K: [
'EcdsaSecp256k1VerificationKey2019',
/**
* Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress
*/
'EcdsaSecp256k1RecoveryMethod2020',
/**
* @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is not an ethereumAddress
*/
'Secp256k1VerificationKey2018',
/**
* @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is not an ethereumAddress
*/
'Secp256k1SignatureVerificationKey2018',
'EcdsaPublicKeySecp256k1',
'EcdsaSecp256k1VerificationKey2019'
/**
* @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is not an ethereumAddress
*/
'EcdsaPublicKeySecp256k1'
],
'ES256K-R': [
'EcdsaSecp256k1VerificationKey2019',
/**
* Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress
*/
'EcdsaSecp256k1RecoveryMethod2020',
/**
* @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is not an ethereumAddress
*/
'Secp256k1VerificationKey2018',
/**
* @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is not an ethereumAddress
*/
'Secp256k1SignatureVerificationKey2018',
'EcdsaPublicKeySecp256k1',
'EcdsaSecp256k1VerificationKey2019'
/**
* @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is not an ethereumAddress
*/
'EcdsaPublicKeySecp256k1'
],

@@ -206,3 +232,6 @@ Ed25519: ['ED25519SignatureVerification', 'Ed25519VerificationKey2018'],

function verifyJWSDecoded({ header, data, signature }: JWSDecoded, pubkeys: VerificationMethod | VerificationMethod[]): VerificationMethod {
function verifyJWSDecoded(
{ header, data, signature }: JWSDecoded,
pubkeys: VerificationMethod | VerificationMethod[]
): VerificationMethod {
if (!Array.isArray(pubkeys)) pubkeys = [pubkeys]

@@ -209,0 +238,0 @@ const signer: VerificationMethod = VerifierAlgorithm(header.alg)(data, signature, pubkeys)

@@ -14,3 +14,5 @@ import { Signer, SignerAlgorithm } from './JWT'

} else {
if (recoverable && typeof fromJose(signature).recoveryParam === 'undefined') throw new Error(`ES256K-R not supported when signer doesn't provide a recovery param`)
if (recoverable && typeof fromJose(signature).recoveryParam === 'undefined') {
throw new Error(`ES256K-R not supported when signer doesn't provide a recovery param`)
}
return signature

@@ -17,0 +19,0 @@ }

@@ -25,3 +25,3 @@ import { sign } from '@stablelib/ed25519'

return async (data: string | Uint8Array): Promise<string> => {
const dataBytes: Uint8Array = (typeof data === 'string') ? stringToBytes(data) : data
const dataBytes: Uint8Array = typeof data === 'string' ? stringToBytes(data) : data
const sig: Uint8Array = sign(privateKeyBytes, dataBytes)

@@ -28,0 +28,0 @@ return bytesToBase64url(sig)

@@ -15,3 +15,3 @@ import { Signer } from '../JWT'

* ```
*
*
* @param {String} hexPrivateKey a hex encoded private key

@@ -18,0 +18,0 @@ * @return {Function} a configured signer function

@@ -1,9 +0,7 @@

import { sign } from '@stablelib/ed25519'
import { EdDSASigner as EdDSASigner } from './EdDSASigner'
import { Signer } from '../JWT'
import { base64ToBytes, bytesToBase64url, stringToBytes } from '../util'
/**
* @deprecated Please use EdDSASigner
*
*
* The NaclSigner returns a configured function for signing data using the Ed25519 algorithm.

@@ -10,0 +8,0 @@ *

@@ -29,2 +29,6 @@ import * as u8a from 'uint8arrays'

export function bytesToBase58(b: Uint8Array): string {
return u8a.toString(b, 'base58btc')
}
export function hexToBytes(s: string): Uint8Array {

@@ -31,0 +35,0 @@ const input = s.startsWith('0x') ? s.substring(2) : s

@@ -39,3 +39,7 @@ import { ec as EC } from 'elliptic'

export function verifyES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {
export function verifyES256K(
data: string,
signature: string,
authenticators: VerificationMethod[]
): VerificationMethod {
const hash: Uint8Array = sha256(data)

@@ -67,3 +71,7 @@ const sigObj: EcdsaSignature = toSignatureObject(signature)

export function verifyRecoverableES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {
export function verifyRecoverableES256K(
data: string,
signature: string,
authenticators: VerificationMethod[]
): VerificationMethod {
let signatures: EcdsaSignature[]

@@ -87,8 +95,10 @@ if (signature.length > 86) {

const signer: VerificationMethod = authenticators.find(
({ publicKeyHex, ethereumAddress }) =>
publicKeyHex === recoveredPublicKeyHex ||
publicKeyHex === recoveredCompressedPublicKeyHex ||
ethereumAddress === recoveredAddress
)
const signer: VerificationMethod = authenticators.find((pk: VerificationMethod) => {
const keyHex = bytesToHex(extractPublicKeyBytes(pk))
return (
keyHex === recoveredPublicKeyHex ||
keyHex === recoveredCompressedPublicKeyHex ||
pk.ethereumAddress === recoveredAddress
)
})

@@ -98,3 +108,3 @@ return signer

const signer: VerificationMethod[] = signatures.map(checkSignatureAgainstSigner).filter(key => key != null)
const signer: VerificationMethod[] = signatures.map(checkSignatureAgainstSigner).filter((key) => key != null)

@@ -105,3 +115,7 @@ if (signer.length === 0) throw new Error('Signature invalid for JWT')

export function verifyEd25519(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {
export function verifyEd25519(
data: string,
signature: string,
authenticators: VerificationMethod[]
): VerificationMethod {
const clear: Uint8Array = stringToBytes(data)

@@ -111,4 +125,3 @@ const sig: Uint8Array = base64ToBytes(signature)

return verify(extractPublicKeyBytes(pk), clear, sig)
}
)
})
if (!signer) throw new Error('Signature invalid for JWT')

@@ -115,0 +128,0 @@ return signer

@@ -30,3 +30,3 @@ import { XChaCha20Poly1305 } from '@stablelib/xchacha20poly1305'

return {
...(xc20pEncrypt(cleartext, encodedAad)),
...xc20pEncrypt(cleartext, encodedAad),
protectedHeader: protHeader

@@ -87,3 +87,5 @@ }

if (didResolutionMetadata?.error) {
throw new Error(`Could not find x25519 key for ${did}: ${didResolutionMetadata.error}, ${didResolutionMetadata.message}`)
throw new Error(
`Could not find x25519 key for ${did}: ${didResolutionMetadata.error}, ${didResolutionMetadata.message}`
)
}

@@ -93,6 +95,5 @@ if (!didDocument.keyAgreement) throw new Error(`Could not find x25519 key for ${did}`)

if (typeof key === 'string') {
return [
...(didDocument.publicKey || []),
...(didDocument.verificationMethod || [])
].find((pk) => pk.id === key)
return [...(didDocument.publicKey || []), ...(didDocument.verificationMethod || [])].find(
(pk) => pk.id === key
)
}

@@ -111,7 +112,3 @@ return key

function validateHeader(header: Record<string, any>) {
if(!(
header.epk &&
header.iv &&
header.tag
)) {
if (!(header.epk && header.iv && header.tag)) {
throw new Error('Invalid JWE')

@@ -118,0 +115,0 @@ }

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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