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
142
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.2 to 5.1.0

src/__tests__/__snapshots__/JWT.test.ts.snap

7

CHANGELOG.md

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

# [5.1.0](https://github.com/decentralized-identity/did-jwt/compare/5.0.2...5.1.0) (2021-03-24)
### Features
* adapt to did core spec ([#156](https://github.com/decentralized-identity/did-jwt/issues/156)) ([4283ab3](https://github.com/decentralized-identity/did-jwt/commit/4283ab39ce33fddfb13be09df99db0f0cd0cd988)), closes [#155](https://github.com/decentralized-identity/did-jwt/issues/155)
## [5.0.2](https://github.com/decentralized-identity/did-jwt/compare/5.0.1...5.0.2) (2021-03-23)

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

2

lib/index.esm.js

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

@@ -15,2 +15,3 @@ import { EcdsaSignature } from './util';

export interface JWTVerifyOptions {
/** @deprecated Please use `proofPurpose: 'authentication' instead` */
auth?: boolean;

@@ -21,2 +22,4 @@ audience?: string;

skewTime?: number;
/** See https://www.w3.org/TR/did-spec-registries/#verification-relationships */
proofPurpose?: 'authentication' | 'assertionMethod' | 'capabilityDelegation' | 'capabilityInvocation' | string;
}

@@ -159,5 +162,5 @@ export interface DIDAuthenticator {

* @param {Boolean} auth Restrict public keys to ones specifically listed in the 'authentication' section of DID document
* @return {Promise<Object, Error>} a promise which resolves with a response object containing an array of authenticators or if non exist rejects with an error
* @return {Promise<DIDAuthenticator>} a promise which resolves with a response object containing an array of authenticators or if non exist rejects with an error
*/
export declare function resolveAuthenticator(resolver: Resolver, alg: string, issuer: string, auth?: boolean): Promise<DIDAuthenticator>;
export declare function resolveAuthenticator(resolver: Resolver, alg: string, issuer: string, proofPurpose?: string): Promise<DIDAuthenticator>;
//# sourceMappingURL=JWT.d.ts.map
import { SignerAlgorithm } from './JWT';
export declare function ES256KSignerAlg(recoverable?: boolean): SignerAlgorithm;
export declare function Ed25519SignerAlg(): SignerAlgorithm;
declare function SignerAlgorithm(alg: string): SignerAlgorithm;
export default SignerAlgorithm;
declare function SignerAlg(alg: string): SignerAlgorithm;
export default SignerAlg;
//# sourceMappingURL=SignerAlgorithm.d.ts.map
{
"name": "did-jwt",
"version": "5.0.2",
"version": "5.1.0",
"description": "Library for Signing and Verifying JWTs compatible uPort and DID standards",

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

"jest": {
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json"
],
"coverageDirectory": "./coverage/",
"collectCoverage": true,
"clearMocks": true,
"collectCoverageFrom": [

@@ -58,7 +46,8 @@ "src/**/*.{ts,tsx}",

"testEnvironment": "node",
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/nock"
"testMatch": [
"**/__tests__/**/*.test.[jt]s"
]
},
"devDependencies": {
"@babel/preset-typescript": "^7.13.0",
"@semantic-release/changelog": "5.0.1",

@@ -65,0 +54,0 @@ "@semantic-release/git": "9.0.0",

@@ -5,2 +5,3 @@ import { EdDSASigner } from '../signers/EdDSASigner'

it('signs data with base64 key', async () => {
expect.assertions(1)
const privKey = 'nlXR4aofRVuLqtn9+XVQNlX4s1nVQvp+TOhBBtYls1IG+sHyIkDP/WN+rWZHGIQp+v2pyct+rkM4asF/YRFQdQ=='

@@ -15,2 +16,3 @@ const signer = EdDSASigner(privKey)

it('signs data with base64url key', async () => {
expect.assertions(1)
const privKey = 'nlXR4aofRVuLqtn9-XVQNlX4s1nVQvp-TOhBBtYls1IG-sHyIkDP_WN-rWZHGIQp-v2pyct-rkM4asF_YRFQdQ'

@@ -25,2 +27,3 @@ const signer = EdDSASigner(privKey)

it('signs data with base58 key', async () => {
expect.assertions(1)
const privKey = '4AcB6rb1mUBf82U7pBzPZ53ZAQycdi4Q1LWoUREvHSRXBRo9Sus9bzCJPKVTQQeDpjHMJN7fBAGWKEnJw5SPbaC4'

@@ -35,2 +38,3 @@ const signer = EdDSASigner(privKey)

it('signs data with hex key', async () => {
expect.assertions(1)
const privKey =

@@ -46,2 +50,3 @@ '9e55d1e1aa1f455b8baad9fdf975503655f8b359d542fa7e4ce84106d625b35206fac1f22240cffd637ead6647188429fafda9c9cb7eae43386ac17f61115075'

it('signs data with prefixed hex key', async () => {
expect.assertions(1)
const privKey =

@@ -57,2 +62,3 @@ '0x9e55d1e1aa1f455b8baad9fdf975503655f8b359d542fa7e4ce84106d625b35206fac1f22240cffd637ead6647188429fafda9c9cb7eae43386ac17f61115075'

it('refuses wrong key size (half)', async () => {
expect.assertions(1)
const privateKey = '278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f'

@@ -65,2 +71,3 @@ expect(() => {

it('refuses wrong key size', async () => {
expect.assertions(1)
const privateKey =

@@ -67,0 +74,0 @@ '9e55d1e1aa1f455b8baad9fdf975503655f8b359d542fa7e4ce84106d625b35206fac1f22240cffd637ead6647188429fafda9c9cb7eae43386ac17f611150'

@@ -5,37 +5,53 @@ import { ES256KSigner } from '../signers/ES256KSigner'

it('signs data, given a hex private key', async () => {
expect.assertions(1)
const privateKey = '278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f'
const signer = ES256KSigner(privateKey)
const plaintext = 'thequickbrownfoxjumpedoverthelazyprogrammer'
return await expect(signer(plaintext)).resolves.toMatchSnapshot()
await expect(signer(plaintext)).resolves.toEqual(
'jsvdLwqr-O206hkegoq6pbo7LJjCaflEKHCvfohBP9XJ4C7mG2TPL9YjyKEpYSXqqkUrfRoCxQecHR11Uh7POw'
)
})
it('signs data: privateKey with 0x prefix', async () => {
expect.assertions(1)
const privateKey = '0x278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f'
const signer2 = ES256KSigner(privateKey)
const signer = ES256KSigner(privateKey)
const plaintext = 'thequickbrownfoxjumpedoverthelazyprogrammer'
return await expect(signer2(plaintext)).resolves.toMatchSnapshot()
await expect(signer(plaintext)).resolves.toEqual(
'jsvdLwqr-O206hkegoq6pbo7LJjCaflEKHCvfohBP9XJ4C7mG2TPL9YjyKEpYSXqqkUrfRoCxQecHR11Uh7POw'
)
})
it('signs data: privateKey base58', async () => {
expect.assertions(1)
const privateKey = '3fMGokRKc5yGVqbCXyGNTrp3vP1cXs86tsVSVwzhNvXQ'
const signer2 = ES256KSigner(privateKey)
const signer = ES256KSigner(privateKey)
const plaintext = 'thequickbrownfoxjumpedoverthelazyprogrammer'
return await expect(signer2(plaintext)).resolves.toMatchSnapshot()
await expect(signer(plaintext)).resolves.toEqual(
'jsvdLwqr-O206hkegoq6pbo7LJjCaflEKHCvfohBP9XJ4C7mG2TPL9YjyKEpYSXqqkUrfRoCxQecHR11Uh7POw'
)
})
it('signs data: privateKey base64url', async () => {
expect.assertions(1)
const privateKey = 'J4pd5wDin6ro5A42bsUBK17GPTbsd-iiQXFUzB0lOD8'
const signer2 = ES256KSigner(privateKey)
const signer = ES256KSigner(privateKey)
const plaintext = 'thequickbrownfoxjumpedoverthelazyprogrammer'
return await expect(signer2(plaintext)).resolves.toMatchSnapshot()
await expect(signer(plaintext)).resolves.toEqual(
'jsvdLwqr-O206hkegoq6pbo7LJjCaflEKHCvfohBP9XJ4C7mG2TPL9YjyKEpYSXqqkUrfRoCxQecHR11Uh7POw'
)
})
it('signs data: privateKey base64', async () => {
expect.assertions(1)
const privateKey = 'J4pd5wDin6ro5A42bsUBK17GPTbsd+iiQXFUzB0lOD8='
const signer2 = ES256KSigner(privateKey)
const signer = ES256KSigner(privateKey)
const plaintext = 'thequickbrownfoxjumpedoverthelazyprogrammer'
return await expect(signer2(plaintext)).resolves.toMatchSnapshot()
await expect(signer(plaintext)).resolves.toEqual(
'jsvdLwqr-O206hkegoq6pbo7LJjCaflEKHCvfohBP9XJ4C7mG2TPL9YjyKEpYSXqqkUrfRoCxQecHR11Uh7POw'
)
})
it('refuses wrong key size (too short)', async () => {
expect.assertions(1)
const privateKey = '278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d2538'

@@ -48,2 +64,3 @@ expect(() => {

it('refuses wrong key size (double)', async () => {
expect.assertions(1)
const privateKey =

@@ -50,0 +67,0 @@ '278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f'

/* eslint-disable */
it.skip('not a test', () => {})
// it.skip('not a test', () => {})
module.exports = {

@@ -4,0 +4,0 @@ dir: {

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

@@ -20,2 +20,3 @@ export type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string>

export interface JWTVerifyOptions {
/** @deprecated Please use `proofPurpose: 'authentication' instead` */
auth?: boolean

@@ -26,2 +27,4 @@ audience?: string

skewTime?: number
/** See https://www.w3.org/TR/did-spec-registries/#verification-relationships */
proofPurpose?: 'authentication' | 'assertionMethod' | 'capabilityDelegation' | 'capabilityInvocation' | string
}

@@ -186,3 +189,3 @@

const jwtSigner: SignerAlgorithm = SignerAlgorithm(header.alg)
const jwtSigner: SignerAlgorithm = SignerAlg(header.alg)
const signature: string = await jwtSigner(signingInput, signer)

@@ -287,3 +290,4 @@ return [signingInput, signature].join('.')

callbackUrl: null,
skewTime: null
skewTime: null,
proofPurpose: null
}

@@ -293,2 +297,7 @@ ): Promise<JWTVerified> {

const { payload, header, signature, data }: JWTDecoded = decodeJWT(jwt)
const proofPurpose: string | undefined = options.hasOwnProperty('auth')
? options.auth
? 'authentication'
: undefined
: options.proofPurpose
const { didResolutionResult, authenticators, issuer }: DIDAuthenticator = await resolveAuthenticator(

@@ -298,3 +307,3 @@ options.resolver,

payload.iss,
options.auth
proofPurpose
)

@@ -345,3 +354,3 @@ const signer: VerificationMethod = await verifyJWSDecoded({ header, data, signature } as JWSDecoded, authenticators)

* @param {Boolean} auth Restrict public keys to ones specifically listed in the 'authentication' section of DID document
* @return {Promise<Object, Error>} a promise which resolves with a response object containing an array of authenticators or if non exist rejects with an error
* @return {Promise<DIDAuthenticator>} a promise which resolves with a response object containing an array of authenticators or if non exist rejects with an error
*/

@@ -352,3 +361,3 @@ export async function resolveAuthenticator(

issuer: string,
auth?: boolean
proofPurpose?: string
): Promise<DIDAuthenticator> {

@@ -359,5 +368,18 @@ const types: string[] = SUPPORTED_PUBLIC_KEY_TYPES[alg]

}
const result: DIDResolutionResult = await resolver.resolve(issuer, { accept: DID_JSON })
if (result.didResolutionMetadata?.error) {
const { error, message } = result.didResolutionMetadata
let didResult: DIDResolutionResult
const result = (await resolver.resolve(issuer, { accept: DID_JSON })) as unknown
// support legacy resolvers that do not produce DIDResolutionResult
if (Object.getOwnPropertyNames(result).indexOf('didDocument') === -1) {
didResult = {
didDocument: result as DIDDocument,
didDocumentMetadata: {},
didResolutionMetadata: { contentType: DID_JSON }
}
} else {
didResult = result as DIDResolutionResult
}
if (didResult.didResolutionMetadata?.error) {
const { error, message } = didResult.didResolutionMetadata
throw new Error(`Unable to resolve DID document for ${issuer}: ${error}, ${message || ''}`)

@@ -371,15 +393,21 @@ }

let publicKeysToCheck: VerificationMethod[] = []
if (result.didDocument.verificationMethod) publicKeysToCheck.push(...result.didDocument.verificationMethod)
if (result.didDocument.publicKey) publicKeysToCheck.push(...result.didDocument.publicKey)
if (auth) {
publicKeysToCheck = (result.didDocument.authentication || [])
.map((authEntry) => {
if (typeof authEntry === 'string') {
return getPublicKeyById(publicKeysToCheck, authEntry)
} else if (typeof (<any>authEntry).publicKey === 'string') {
let publicKeysToCheck: VerificationMethod[] = [
...(didResult?.didDocument?.verificationMethod || []),
...(didResult?.didDocument?.publicKey || [])
]
if (typeof proofPurpose === 'string') {
// support legacy DID Documents that do not list assertionMethod
if (proofPurpose.startsWith('assertion') && !didResult.didDocument.hasOwnProperty('assertionMethod')) {
didResult.didDocument.assertionMethod = [...publicKeysToCheck.map((pk) => pk.id)]
}
publicKeysToCheck = (didResult.didDocument[proofPurpose] || [])
.map((verificationMethod) => {
if (typeof verificationMethod === 'string') {
return getPublicKeyById(publicKeysToCheck, verificationMethod)
} else if (typeof (<any>verificationMethod).publicKey === 'string') {
// this is a legacy format
return getPublicKeyById(publicKeysToCheck, (<any>authEntry).publicKey)
return getPublicKeyById(publicKeysToCheck, (<any>verificationMethod).publicKey)
} else {
return <VerificationMethod>authEntry
return <VerificationMethod>verificationMethod
}

@@ -394,4 +422,6 @@ })

if (auth && (!authenticators || authenticators.length === 0)) {
throw new Error(`DID document for ${issuer} does not have public keys suitable for authenticating user`)
if (typeof proofPurpose === 'string' && (!authenticators || authenticators.length === 0)) {
throw new Error(
`DID document for ${issuer} does not have public keys suitable for ${alg} with ${proofPurpose} purpose`
)
}

@@ -401,3 +431,3 @@ if (!authenticators || authenticators.length === 0) {

}
return { authenticators, issuer, didResolutionResult: result }
return { authenticators, issuer, didResolutionResult: didResult }
}

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

function SignerAlgorithm(alg: string): SignerAlgorithm {
function SignerAlg(alg: string): SignerAlgorithm {
const impl: SignerAlgorithm = algorithms[alg]

@@ -55,2 +55,2 @@ if (!impl) throw new Error(`Unsupported algorithm ${alg}`)

export default SignerAlgorithm
export default SignerAlg

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

const sigObj: EcdsaSignature = toSignatureObject(signature)
const fullPublicKeys = authenticators.filter(({ ethereumAddress }) => {
return typeof ethereumAddress === 'undefined'
const fullPublicKeys = authenticators.filter(({ ethereumAddress, blockchainAccountId }) => {
return typeof ethereumAddress === 'undefined' && typeof blockchainAccountId === 'undefined'
})
const ethAddressKeys = authenticators.filter(({ ethereumAddress }) => {
return typeof ethereumAddress !== 'undefined'
const ethAddressKeys = authenticators.filter(({ ethereumAddress, blockchainAccountId }) => {
return typeof ethereumAddress !== 'undefined' || typeof blockchainAccountId !== undefined
})

@@ -99,3 +99,4 @@

keyHex === recoveredCompressedPublicKeyHex ||
pk.ethereumAddress === recoveredAddress
pk.ethereumAddress?.toLowerCase() === recoveredAddress ||
pk.blockchainAccountId?.split('@eip155')?.[0].toLowerCase() === recoveredAddress
)

@@ -102,0 +103,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

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