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.1.2 to 5.2.0

7

CHANGELOG.md

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

# [5.2.0](https://github.com/decentralized-identity/did-jwt/compare/5.1.2...5.2.0) (2021-04-22)
### Features
* add support for secp256k1 publicKeyJwk ([#160](https://github.com/decentralized-identity/did-jwt/issues/160)) ([1d578ba](https://github.com/decentralized-identity/did-jwt/commit/1d578ba9ab6afc48c9b7449ce3e495cd7a4d8449))
## [5.1.2](https://github.com/decentralized-identity/did-jwt/compare/5.1.1...5.1.2) (2021-03-26)

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

2

lib/index.esm.js

@@ -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 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};
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})$/,K=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function x(e){if("string"==typeof e){if(k.test(e))return y(e);if(S.test(e))return p(e);if(K.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=x(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=x(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):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?y(M.keyFromPublic({x:m(h(e.publicKeyJwk.x)),y:m(h(e.publicKeyJwk.y))}).getPublic("hex")):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 F(){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 L={ES256K:Z(),"ES256K-R":Z(!0),Ed25519:F(),EdDSA:F()},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=L[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 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;
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 k(t){const n="string"==typeof t?e.fromString(t):t;return r.hash(n)}function x(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 J=new n.ec("secp256k1");function $(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=J.keyFromPrivate(t);return function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(k(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):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?l(W.keyFromPublic({x:p(s(e.publicKeyJwk.x)),y:p(s(e.publicKeyJwk.y))}).getPublic("hex")):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=k(e),o=W.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),c=o.encode("hex",!0),u=x(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=k(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 F({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),U(e.alg)(r,t,n)}const L="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=$,exports.EdDSASigner=j,exports.EllipticSigner=function(e){return $(e)},exports.NaclSigner=function(e){return j(e)},exports.SimpleSigner=function(e){const r=$(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[L]){var n,o,i,c=e[L]();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=x,exports.verifyJWS=function(e,r){return F(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(F({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 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};
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 K=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,x=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function $(e){if("string"==typeof e){if(K.test(e))return h(e);if(S.test(e))return y(e);if(x.test(e))return p(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function A(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function P(e){const t="string"==typeof e?r(e):e;return n(t)}function D(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(P(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):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?h(N.keyFromPublic({x:b(p(e.publicKeyJwk.x)),y:b(p(e.publicKeyJwk.y))}).getPublic("hex")):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=P(e),o=N.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),a=o.encode("hex",!0),c=D(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=P(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 F(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 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,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,D 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(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});
!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,u,a){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 J=e=>r.concat([A(e.length),e]);function $(e,n,o){if(256!==n)throw new Error(`Unsupported key length: ${n}`);const i=r.concat([J(r.fromString(o)),J(new Uint8Array(0)),J(new Uint8Array(0)),A(n)]);return t.hash(r.concat([A(1),e,i]))}const D=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=D.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):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?d(T.keyFromPublic({x:p(f(e.publicKeyJwk.x)),y:p(f(e.publicKeyJwk.y))}).getPublic("hex")):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),u=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())===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 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 u=i.find(e=>{try{const r=C(e);return T.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!u&&c.length>0&&(u=O(e,r,c)),!u)throw new Error("Signature invalid for JWT");return u},"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 F(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 L(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=F(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=a.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=u.generateKeyPair(),a=ne($(u.sharedKey(c.secretKey,e),o,n))(t),f={encrypted_key:s(a.ciphertext),header:{alg:n,iv:s(a.iv),tag:s(a.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=a.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 u=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 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(!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}(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=te(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)}},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 u={...c,...e,iss:r};return _(u,t,i)}catch(e){return Promise.reject(e)}},e.decodeJWT=L,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 u="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 u=new ee,a=Y.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&&!re(c))return void c.then(l).then(void 0,a);if(!(o=e())||re(o)&&!o.v)return void Y(u,1,i);if(o.then)return void o.then(f).then(void 0,a);re(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):Y(u,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,a):f(o):Y(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,f(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)}},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(F(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}=L(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,u,a,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==(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(G({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)}},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),a=$(u.sharedKey(e,c),256,r),s=w(i.encrypted_key,i.header.tag);return Promise.resolve(ie(a).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
{
"name": "did-jwt",
"version": "5.1.2",
"version": "5.2.0",
"description": "Library for Signing and Verifying JWTs compatible uPort and DID standards",

@@ -56,8 +56,8 @@ "main": "lib/index.js",

"codecov": "3.8.1",
"eslint": "7.22.0",
"eslint": "7.24.0",
"eslint-config-standard": "16.0.2",
"eslint-plugin-import": "2.22.1",
"eslint-plugin-jest": "24.3.2",
"eslint-plugin-jest": "24.3.5",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "4.3.1",
"eslint-plugin-promise": "5.1.0",
"eslint-plugin-standard": "5.0.0",

@@ -74,3 +74,3 @@ "jest": "26.6.3",

"standard": "16.0.3",
"ts-jest": "26.5.4",
"ts-jest": "26.5.5",
"tslint": "6.1.3",

@@ -80,5 +80,5 @@ "tslint-config-prettier": "1.18.0",

"tweetnacl": "1.0.3",
"typescript": "4.2.3",
"webpack": "5.28.0",
"webpack-cli": "4.5.0"
"typescript": "4.2.4",
"webpack": "5.35.0",
"webpack-cli": "4.6.0"
},

@@ -85,0 +85,0 @@ "dependencies": {

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

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

@@ -40,2 +40,8 @@ import { EdDSASigner } from '../signers/EdDSASigner'

const publicKeyBase58 = bytesToBase58(hexToBytes(publicKey))
const publicKeyJwk = {
crv: 'secp256k1',
kty: 'EC',
x: bytesToBase64url(hexToBytes(kp.getPublic().getX().toString('hex'))),
y: bytesToBase64url(hexToBytes(kp.getPublic().getY().toString('hex')))
}
const address = toEthereumAddress(publicKey)

@@ -159,2 +165,11 @@ const signer = ES256KSigner(privateKey)

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

@@ -267,2 +282,11 @@ expect.assertions(1)

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

@@ -269,0 +293,0 @@ expect.assertions(1)

@@ -35,2 +35,11 @@ import { ec as EC } from 'elliptic'

return hexToBytes(pk.publicKeyHex)
} else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'secp256k1') {
return hexToBytes(
secp256k1
.keyFromPublic({
x: bytesToHex(base64ToBytes(pk.publicKeyJwk.x)),
y: bytesToHex(base64ToBytes(pk.publicKeyJwk.y))
})
.getPublic('hex')
)
}

@@ -37,0 +46,0 @@ return new Uint8Array()

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

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