Comparing version 5.4.0 to 5.4.1
@@ -0,1 +1,8 @@ | ||
## [5.4.1](https://github.com/decentralized-identity/did-jwt/compare/5.4.0...5.4.1) (2021-05-19) | ||
### Bug Fixes | ||
* don't run JSON.stringify on canonicalized data ([#172](https://github.com/decentralized-identity/did-jwt/issues/172)) ([5480bfc](https://github.com/decentralized-identity/did-jwt/commit/5480bfc55989620ff248540921563679bd204635)), closes [#171](https://github.com/decentralized-identity/did-jwt/issues/171) | ||
# [5.4.0](https://github.com/decentralized-identity/did-jwt/compare/5.3.1...5.4.0) (2021-05-18) | ||
@@ -2,0 +9,0 @@ |
@@ -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 a from"canonicalize";import{XChaCha20Poly1305 as s}from"@stablelib/xchacha20poly1305";import{generateKeyPair as f,sharedKey as l}from"@stablelib/x25519";import{randomBytes as h}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 g(e){const t=e.startsWith("0x")?e.substring(2):e;return r(t.toLowerCase(),"base16")}function m(e){return d(r(e))}function v(r){return e(p(r))}function w(r){return e(r,"base16")}function b(e){return r(e)}function E({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 P(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:w(r.slice(0,32)),s:w(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 g(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 j(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 c=t([W(r(i)),W(new Uint8Array(0)),W(new Uint8Array(0)),J(o)]);return n(t([J(1),e,c]))}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 function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(j(e));return Promise.resolve(E({r:A(t.toString("hex")),s:A(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function C(e){const r=O(e,!0);return function(e){try{return Promise.resolve(r(e)).then(P)}catch(e){return Promise.reject(e)}}}function R(e){return O(e)}function U(e){const r=$(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?b(e):e,n=c(r,t);return Promise.resolve(d(n))}catch(e){return Promise.reject(e)}}}function M(e){return U(e)}function z(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(z(r))return E(r,e);if(e&&void 0===P(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(z(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}const V={ES256K:N(),"ES256K-R":N(!0),Ed25519:B(),EdDSA:B()},X=new i("secp256k1");function _(e,r=!1){const t=p(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:w(t.slice(0,32)),s:w(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function H(e){return e.publicKeyBase58?y(e.publicKeyBase58):e.publicKeyBase64?p(e.publicKeyBase64):e.publicKeyHex?g(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?g(X.keyFromPublic({x:w(p(e.publicKeyJwk.x)),y:w(p(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function Z(e,r,t){let n;if(r.length>86)n=[_(r,!0)];else{const e=_(r,!1);n=[{...e,recoveryParam:0},{...e,recoveryParam:1}]}const o=n.map(r=>{const n=j(e),o=X.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),c=o.encode("hex",!0),u=D(i);return t.find(e=>{const r=w(H(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===u||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===u})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function F(e,r,t){const n=b(e),o=p(r),i=t.find(e=>u(H(e),n,o));if(!i)throw new Error("Signature invalid for JWT");return i}const L={ES256K:function(e,r,t){const n=j(e),o=_(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=H(e);return X.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!u&&c.length>0&&(u=Z(e,r,c)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":Z,Ed25519:F,EdDSA:F};function q(e){const r=L[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}q.toSignatureObject=_;const G=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}=ce(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=ee[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:te})).then(function(e){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:te}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let u=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...u.map(e=>e.id)]),u=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(u,e):"string"==typeof e.publicKey?c(u,e.publicKey):e).filter(e=>null!=e));const a=u.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!a||0===a.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!a||0===a.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:a,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(ue({header:n,data:i,signature:o},u)).then(function(n){const o=Math.floor(Date.now()/1e3),i=r.skewTime>=0?r.skewTime:oe;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)}},Q=function(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},c={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");c.typ||(c.typ="JWT"),c.alg||(c.alg=n);const u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(o){if("number"!=typeof o)throw new Error("JWT expiresIn is not a number");u.exp=(e.nbf||u.iat)+Math.floor(o)}const a={...u,...e,iss:r};return Y(a,t,c,{canonicalize:i})}catch(e){return Promise.reject(e)}},Y=function(e,r,t={},n={}){try{t.alg||(t.alg=re);const o="string"==typeof e?e:ne(e,n.canonicalize),i=[ne(t,n.canonicalize),o].join("."),c=function(e){const r=V[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(c(i,r)).then(function(e){return[i,e].join(".")})}catch(e){return Promise.reject(e)}},ee={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},re="ES256K",te="application/did+json";function ne(e,r=!1){return m(r?JSON.stringify(a(e)):JSON.stringify(e))}const oe=300;function ie(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(v(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function ce(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=ie(e);return Object.assign(r,{payload:JSON.parse(v(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function ue({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),q(e.alg)(r,t,n)}function ae(e,r){return ue(ie(e),r)}const se=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(v(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const o=k(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,p(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 he,a=le.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 le(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):le(u,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,a):f(o):le(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,p(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)}},fe="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function le(e,r,t){if(!e.s){if(t instanceof he){if(!t.s)return void(t.o=le.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(le.bind(null,e,r),le.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const he=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{le(n,1,e(this.v))}catch(e){le(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?le(n,1,r?r(o):o):t?le(n,1,t(o)):le(n,2,o)}catch(e){le(n,2,e)}},n},e}();function de(e){return e instanceof he&&1&e.s}function pe({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 ye=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 pe(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[fe]){var n,o,i,c=e[fe]();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=le.bind(null,o=new he,2)));t=t.v}o?le(o,1,t):o=t}catch(e){le(o||(o=new he),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=le.bind(null,n=new he,2)));c=c.v}n?le(n,1,c):n=c}catch(e){le(n||(n=new he),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=pe(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)}},ge=function(e,r){try{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(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 n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>Ee(y(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(me)}catch(e){return Promise.reject(e)}},me=e=>[].concat.apply([],e);function ve(e){const r=new s(e);return(e,t)=>{const n=h(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 we(e){const r=ve(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=m(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 be(e){const r=new s(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 Ee(e,r){const t=function(t){try{const c=f(),u=ve(I(l(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=h(32);return Promise.resolve(we(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 Pe(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=p(i.header.epk.x),u=I(l(e,c),256,r),a=k(i.encrypted_key,i.header.tag);return Promise.resolve(be(u).decrypt(a,p(i.header.iv))).then(function(e){return null===e?null:be(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}}export{O as ES256KSigner,U as EdDSASigner,R as EllipticSigner,M as NaclSigner,C as SimpleSigner,ye as createJWE,Y as createJWS,Q as createJWT,ce as decodeJWT,se as decryptJWE,ge as resolveX25519Encrypters,D as toEthereumAddress,ae as verifyJWS,G as verifyJWT,Pe as x25519Decrypter,Ee as x25519Encrypter,be as xc20pDirDecrypter,we 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 a from"canonicalize";import{XChaCha20Poly1305 as s}from"@stablelib/xchacha20poly1305";import{generateKeyPair as f,sharedKey as l}from"@stablelib/x25519";import{randomBytes as h}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 g(e){const t=e.startsWith("0x")?e.substring(2):e;return r(t.toLowerCase(),"base16")}function m(e){return d(r(e))}function v(r){return e(p(r))}function w(r){return e(r,"base16")}function b(e){return r(e)}function E({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 P(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:w(r.slice(0,32)),s:w(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 g(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 j(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 c=t([W(r(i)),W(new Uint8Array(0)),W(new Uint8Array(0)),J(o)]);return n(t([J(1),e,c]))}const T=new i("secp256k1");function C(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 function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(j(e));return Promise.resolve(E({r:A(t.toString("hex")),s:A(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function O(e){const r=C(e,!0);return function(e){try{return Promise.resolve(r(e)).then(P)}catch(e){return Promise.reject(e)}}}function R(e){return C(e)}function U(e){const r=$(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?b(e):e,n=c(r,t);return Promise.resolve(d(n))}catch(e){return Promise.reject(e)}}}function M(e){return U(e)}function z(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(z(r))return E(r,e);if(e&&void 0===P(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(z(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}const V={ES256K:N(),"ES256K-R":N(!0),Ed25519:B(),EdDSA:B()},X=new i("secp256k1");function _(e,r=!1){const t=p(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:w(t.slice(0,32)),s:w(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function H(e){return e.publicKeyBase58?y(e.publicKeyBase58):e.publicKeyBase64?p(e.publicKeyBase64):e.publicKeyHex?g(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?g(X.keyFromPublic({x:w(p(e.publicKeyJwk.x)),y:w(p(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function Z(e,r,t){let n;if(r.length>86)n=[_(r,!0)];else{const e=_(r,!1);n=[{...e,recoveryParam:0},{...e,recoveryParam:1}]}const o=n.map(r=>{const n=j(e),o=X.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),c=o.encode("hex",!0),u=D(i);return t.find(e=>{const r=w(H(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===u||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===u})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function F(e,r,t){const n=b(e),o=p(r),i=t.find(e=>u(H(e),n,o));if(!i)throw new Error("Signature invalid for JWT");return i}const L={ES256K:function(e,r,t){const n=j(e),o=_(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=H(e);return X.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!u&&c.length>0&&(u=Z(e,r,c)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":Z,Ed25519:F,EdDSA:F};function q(e){const r=L[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}q.toSignatureObject=_;const G=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}=ce(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=ee[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:te})).then(function(e){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:te}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let u=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...u.map(e=>e.id)]),u=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(u,e):"string"==typeof e.publicKey?c(u,e.publicKey):e).filter(e=>null!=e));const a=u.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!a||0===a.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!a||0===a.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:a,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(ue({header:n,data:i,signature:o},u)).then(function(n){const o=Math.floor(Date.now()/1e3),i=r.skewTime>=0?r.skewTime:oe;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)}},Q=function(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},c={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");c.typ||(c.typ="JWT"),c.alg||(c.alg=n);const u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(o){if("number"!=typeof o)throw new Error("JWT expiresIn is not a number");u.exp=(e.nbf||u.iat)+Math.floor(o)}const a={...u,...e,iss:r};return Y(a,t,c,{canonicalize:i})}catch(e){return Promise.reject(e)}},Y=function(e,r,t={},n={}){try{t.alg||(t.alg=re);const o="string"==typeof e?e:ne(e,n.canonicalize),i=[ne(t,n.canonicalize),o].join("."),c=function(e){const r=V[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(c(i,r)).then(function(e){return[i,e].join(".")})}catch(e){return Promise.reject(e)}},ee={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},re="ES256K",te="application/did+json";function ne(e,r=!1){return m(r?a(e):JSON.stringify(e))}const oe=300;function ie(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(v(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function ce(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=ie(e);return Object.assign(r,{payload:JSON.parse(v(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function ue({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),q(e.alg)(r,t,n)}function ae(e,r){return ue(ie(e),r)}const se=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(v(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const o=k(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,p(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 he,a=le.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 le(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):le(u,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,a):f(o):le(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,p(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)}},fe="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function le(e,r,t){if(!e.s){if(t instanceof he){if(!t.s)return void(t.o=le.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(le.bind(null,e,r),le.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const he=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{le(n,1,e(this.v))}catch(e){le(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?le(n,1,r?r(o):o):t?le(n,1,t(o)):le(n,2,o)}catch(e){le(n,2,e)}},n},e}();function de(e){return e instanceof he&&1&e.s}function pe({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 ye=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 pe(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[fe]){var n,o,i,c=e[fe]();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=le.bind(null,o=new he,2)));t=t.v}o?le(o,1,t):o=t}catch(e){le(o||(o=new he),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=le.bind(null,n=new he,2)));c=c.v}n?le(n,1,c):n=c}catch(e){le(n||(n=new he),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=pe(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)}},ge=function(e,r){try{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(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 n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>Ee(y(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(me)}catch(e){return Promise.reject(e)}},me=e=>[].concat.apply([],e);function ve(e){const r=new s(e);return(e,t)=>{const n=h(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 we(e){const r=ve(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=m(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 be(e){const r=new s(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 Ee(e,r){const t=function(t){try{const c=f(),u=ve(I(l(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=h(32);return Promise.resolve(we(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 Pe(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=p(i.header.epk.x),u=I(l(e,c),256,r),a=k(i.encrypted_key,i.header.tag);return Promise.resolve(be(u).decrypt(a,p(i.header.iv))).then(function(e){return null===e?null:be(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}}export{C as ES256KSigner,U as EdDSASigner,R as EllipticSigner,M as NaclSigner,O as SimpleSigner,ye as createJWE,Y as createJWS,Q as createJWT,ce as decodeJWT,se as decryptJWE,ge as resolveX25519Encrypters,D as toEthereumAddress,ae as verifyJWS,G as verifyJWT,Pe as x25519Decrypter,Ee as x25519Encrypter,be as xc20pDirDecrypter,we 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("canonicalize"),c=require("@stablelib/xchacha20poly1305"),a=require("@stablelib/x25519"),u=require("@stablelib/random");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var f=s(i);function l(r){return e.toString(r,"base64url")}function d(r){const t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e.fromString(t,"base64url")}function h(r){return e.fromString(r,"base58btc")}function p(r){const t=r.startsWith("0x")?r.substring(2):r;return e.fromString(t.toLowerCase(),"base16")}function y(r){return l(e.fromString(r))}function g(r){return e.toString(d(r))}function v(r){return e.toString(r,"base16")}function m(r){return e.fromString(r)}function w({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 l(i)}function b(e){const r=d(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:v(r.slice(0,32)),s:v(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function E(r,t){return e.concat([d(r),d(t)])}const P=/^(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(P.test(e))return p(e);if(S.test(e))return h(e);if(k.test(e))return d(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 J(t){const n="string"==typeof t?e.fromString(t):t;return r.hash(n)}function A(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 D(r,t=new Uint8Array(4)){const n=e.fromString(r.toString(),"base10");return t.set(n,4-n.length),t}const $=r=>e.concat([D(r.length),r]);function j(t,n,o){if(256!==n)throw new Error(`Unsupported key length: ${n}`);const i=e.concat([$(e.fromString(o)),$(new Uint8Array(0)),$(new Uint8Array(0)),D(n)]);return r.hash(e.concat([D(1),t,i]))}const W=new n.ec("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=W.keyFromPrivate(t);return function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(J(e));return Promise.resolve(w({r:K(t.toString("hex")),s:K(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function I(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?m(e):e,n=o.sign(r,t);return Promise.resolve(l(n))}catch(e){return Promise.reject(e)}}}function C(e){return"object"==typeof e&&"r"in e&&"s"in e}function O(e){return function(r,t){try{return Promise.resolve(t(r)).then(function(r){if(C(r))return w(r,e);if(e&&void 0===b(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 R(){return function(e,r){try{return Promise.resolve(r(e)).then(function(e){if(C(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}const U={ES256K:O(),"ES256K-R":O(!0),Ed25519:R(),EdDSA:R()},M=new n.ec("secp256k1");function N(e,r=!1){const t=d(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:v(t.slice(0,32)),s:v(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function z(e){return e.publicKeyBase58?h(e.publicKeyBase58):e.publicKeyBase64?d(e.publicKeyBase64):e.publicKeyHex?p(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?p(M.keyFromPublic({x:v(d(e.publicKeyJwk.x)),y:v(d(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function B(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=J(e),o=M.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),c=o.encode("hex",!0),a=A(i);return t.find(e=>{const r=v(z(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===a||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===a})}).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=m(e),i=d(r),c=t.find(e=>o.verify(z(e),n,i));if(!c)throw new Error("Signature invalid for JWT");return c}const q={ES256K:function(e,r,t){const n=J(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 a=i.find(e=>{try{const r=z(e);return M.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!a&&c.length>0&&(a=B(e,r,c)),!a)throw new Error("Signature invalid for JWT");return a},"ES256K-R":B,Ed25519:X,EdDSA:X};function V(e){const r=q[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}V.toSignatureObject=N;const _=function(e,r,t={},n={}){try{t.alg||(t.alg=Z);const o="string"==typeof e?e:F(e,n.canonicalize),i=[F(t,n.canonicalize),o].join("."),c=function(e){const r=U[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(c(i,r)).then(function(e){return[i,e].join(".")})}catch(e){return Promise.reject(e)}},H={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},Z="ES256K";function F(e,r=!1){return y(r?JSON.stringify(f.default(e)):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(g(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function G(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=L(e);return Object.assign(r,{payload:JSON.parse(g(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function Q({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),V(e.alg)(r,t,n)}const Y="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function ee(e,r,t){if(!e.s){if(t instanceof re){if(!t.s)return void(t.o=ee.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(ee.bind(null,e,r),ee.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const re=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{ee(n,1,e(this.v))}catch(e){ee(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?ee(n,1,r?r(o):o):t?ee(n,1,t(o)):ee(n,2,o)}catch(e){ee(n,2,e)}},n},e}();function te(e){return e instanceof re&&1&e.s}function ne({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const c={protected:n,iv:l(t),ciphertext:l(e),tag:l(r)};return i&&(c.aad=l(i)),o&&(c.recipients=[o]),c}const oe=e=>[].concat.apply([],e);function ie(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 ce(e){const r=ie(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=y(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),c=new Uint8Array(Buffer.from(o?`${i}.${l(o)}`:i));return Promise.resolve({...r(e,c),protectedHeader:i})}catch(e){return Promise.reject(e)}}}}function ae(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 ue(e,r){const t=function(t){try{const c=a.generateKeyPair(),u=ie(j(a.sharedKey(c.secretKey,e),o,n))(t),s={encrypted_key:l(u.ciphertext),header:{alg:n,iv:l(u.iv),tag:l(u.tag),epk:{kty:"OKP",crv:i,x:l(c.publicKey)}}};return r&&(s.header.kid=r),Promise.resolve(s)}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(ce(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=T,exports.EdDSASigner=I,exports.EllipticSigner=function(e){return T(e)},exports.NaclSigner=function(e){return I(e)},exports.SimpleSigner=function(e){const r=T(e,!0);return function(e){try{return Promise.resolve(r(e)).then(b)}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 ne(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[Y]){var n,o,i,c=e[Y]();if(function e(t){try{for(;!(n=c.next()).done;)if((t=r(n.value))&&t.then){if(!te(t))return void t.then(e,i||(i=ee.bind(null,o=new re,2)));t=t.v}o?ee(o,1,t):o=t}catch(e){ee(o||(o=new re),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(!te(c))return void c.then(t,o||(o=ee.bind(null,n=new re,2)));c=c.v}n?ee(n,1,c):n=c}catch(e){ee(n||(n=new re),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=ne(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)}},exports.createJWS=_,exports.createJWT=function(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},c={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");c.typ||(c.typ="JWT"),c.alg||(c.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)}const u={...a,...e,iss:r};return _(u,t,c,{canonicalize:i})}catch(e){return Promise.reject(e)}},exports.decodeJWT=G,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(g(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const o=E(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,d(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(te(o)&&(o=o.v),!o)return i;if(o.then){n=0;break}var i=t();if(i&&i.then){if(!te(i)){n=1;break}i=i.s}if(r){var c=r();if(c&&c.then&&!te(c)){n=2;break}}}var a=new re,u=ee.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&&!te(c))return void c.then(l).then(void 0,u);if(!(o=e())||te(o)&&!o.v)return void ee(a,1,i);if(o.then)return void o.then(f).then(void 0,u);te(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):ee(a,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,u):f(o):ee(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,d(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)}},exports.resolveX25519Encrypters=function(e,r){try{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(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 n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>ue(h(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(oe)}catch(e){return Promise.reject(e)}},exports.toEthereumAddress=A,exports.verifyJWS=function(e,r){return Q(L(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}=G(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=H[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){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:"application/did+json"}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let a=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...a.map(e=>e.id)]),a=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(a,e):"string"==typeof e.publicKey?c(a,e.publicKey):e).filter(e=>null!=e));const u=a.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!u||0===u.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!u||0===u.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:u,issuer:t,didResolutionResult: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(Q({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)}},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 c=d(i.header.epk.x),u=j(a.sharedKey(e,c),256,r),s=E(i.encrypted_key,i.header.tag);return Promise.resolve(ae(u).decrypt(s,d(i.header.iv))).then(function(e){return null===e?null:ae(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}},exports.x25519Encrypter=ue,exports.xc20pDirDecrypter=ae,exports.xc20pDirEncrypter=ce; | ||
var e=require("uint8arrays"),r=require("@stablelib/sha256"),t=require("js-sha3"),n=require("elliptic"),o=require("@stablelib/ed25519"),i=require("canonicalize"),c=require("@stablelib/xchacha20poly1305"),a=require("@stablelib/x25519"),u=require("@stablelib/random");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var f=s(i);function l(r){return e.toString(r,"base64url")}function d(r){const t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e.fromString(t,"base64url")}function h(r){return e.fromString(r,"base58btc")}function p(r){const t=r.startsWith("0x")?r.substring(2):r;return e.fromString(t.toLowerCase(),"base16")}function y(r){return l(e.fromString(r))}function g(r){return e.toString(d(r))}function v(r){return e.toString(r,"base16")}function m(r){return e.fromString(r)}function w({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 l(i)}function b(e){const r=d(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:v(r.slice(0,32)),s:v(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function E(r,t){return e.concat([d(r),d(t)])}const P=/^(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(P.test(e))return p(e);if(S.test(e))return h(e);if(k.test(e))return d(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 A(t){const n="string"==typeof t?e.fromString(t):t;return r.hash(n)}function D(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 J(r,t=new Uint8Array(4)){const n=e.fromString(r.toString(),"base10");return t.set(n,4-n.length),t}const $=r=>e.concat([J(r.length),r]);function j(t,n,o){if(256!==n)throw new Error(`Unsupported key length: ${n}`);const i=e.concat([$(e.fromString(o)),$(new Uint8Array(0)),$(new Uint8Array(0)),J(n)]);return r.hash(e.concat([J(1),t,i]))}const W=new n.ec("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=W.keyFromPrivate(t);return function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(A(e));return Promise.resolve(w({r:K(t.toString("hex")),s:K(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function I(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?m(e):e,n=o.sign(r,t);return Promise.resolve(l(n))}catch(e){return Promise.reject(e)}}}function C(e){return"object"==typeof e&&"r"in e&&"s"in e}function O(e){return function(r,t){try{return Promise.resolve(t(r)).then(function(r){if(C(r))return w(r,e);if(e&&void 0===b(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 R(){return function(e,r){try{return Promise.resolve(r(e)).then(function(e){if(C(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}const U={ES256K:O(),"ES256K-R":O(!0),Ed25519:R(),EdDSA:R()},M=new n.ec("secp256k1");function z(e,r=!1){const t=d(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:v(t.slice(0,32)),s:v(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function N(e){return e.publicKeyBase58?h(e.publicKeyBase58):e.publicKeyBase64?d(e.publicKeyBase64):e.publicKeyHex?p(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?p(M.keyFromPublic({x:v(d(e.publicKeyJwk.x)),y:v(d(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function B(e,r,t){let n;if(r.length>86)n=[z(r,!0)];else{const e=z(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),a=D(i);return t.find(e=>{const r=v(N(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===a||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===a})}).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=m(e),i=d(r),c=t.find(e=>o.verify(N(e),n,i));if(!c)throw new Error("Signature invalid for JWT");return c}const q={ES256K:function(e,r,t){const n=A(e),o=z(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=N(e);return M.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!a&&c.length>0&&(a=B(e,r,c)),!a)throw new Error("Signature invalid for JWT");return a},"ES256K-R":B,Ed25519:X,EdDSA:X};function V(e){const r=q[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}V.toSignatureObject=z;const _=function(e,r,t={},n={}){try{t.alg||(t.alg=Z);const o="string"==typeof e?e:F(e,n.canonicalize),i=[F(t,n.canonicalize),o].join("."),c=function(e){const r=U[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(c(i,r)).then(function(e){return[i,e].join(".")})}catch(e){return Promise.reject(e)}},H={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},Z="ES256K";function F(e,r=!1){return y(r?f.default(e):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(g(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function G(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=L(e);return Object.assign(r,{payload:JSON.parse(g(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function Q({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),V(e.alg)(r,t,n)}const Y="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function ee(e,r,t){if(!e.s){if(t instanceof re){if(!t.s)return void(t.o=ee.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(ee.bind(null,e,r),ee.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const re=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{ee(n,1,e(this.v))}catch(e){ee(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?ee(n,1,r?r(o):o):t?ee(n,1,t(o)):ee(n,2,o)}catch(e){ee(n,2,e)}},n},e}();function te(e){return e instanceof re&&1&e.s}function ne({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const c={protected:n,iv:l(t),ciphertext:l(e),tag:l(r)};return i&&(c.aad=l(i)),o&&(c.recipients=[o]),c}const oe=e=>[].concat.apply([],e);function ie(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 ce(e){const r=ie(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=y(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),c=new Uint8Array(Buffer.from(o?`${i}.${l(o)}`:i));return Promise.resolve({...r(e,c),protectedHeader:i})}catch(e){return Promise.reject(e)}}}}function ae(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 ue(e,r){const t=function(t){try{const c=a.generateKeyPair(),u=ie(j(a.sharedKey(c.secretKey,e),o,n))(t),s={encrypted_key:l(u.ciphertext),header:{alg:n,iv:l(u.iv),tag:l(u.tag),epk:{kty:"OKP",crv:i,x:l(c.publicKey)}}};return r&&(s.header.kid=r),Promise.resolve(s)}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(ce(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=T,exports.EdDSASigner=I,exports.EllipticSigner=function(e){return T(e)},exports.NaclSigner=function(e){return I(e)},exports.SimpleSigner=function(e){const r=T(e,!0);return function(e){try{return Promise.resolve(r(e)).then(b)}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 ne(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[Y]){var n,o,i,c=e[Y]();if(function e(t){try{for(;!(n=c.next()).done;)if((t=r(n.value))&&t.then){if(!te(t))return void t.then(e,i||(i=ee.bind(null,o=new re,2)));t=t.v}o?ee(o,1,t):o=t}catch(e){ee(o||(o=new re),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(!te(c))return void c.then(t,o||(o=ee.bind(null,n=new re,2)));c=c.v}n?ee(n,1,c):n=c}catch(e){ee(n||(n=new re),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=ne(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)}},exports.createJWS=_,exports.createJWT=function(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},c={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");c.typ||(c.typ="JWT"),c.alg||(c.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)}const u={...a,...e,iss:r};return _(u,t,c,{canonicalize:i})}catch(e){return Promise.reject(e)}},exports.decodeJWT=G,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(g(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const o=E(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,d(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(te(o)&&(o=o.v),!o)return i;if(o.then){n=0;break}var i=t();if(i&&i.then){if(!te(i)){n=1;break}i=i.s}if(r){var c=r();if(c&&c.then&&!te(c)){n=2;break}}}var a=new re,u=ee.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&&!te(c))return void c.then(l).then(void 0,u);if(!(o=e())||te(o)&&!o.v)return void ee(a,1,i);if(o.then)return void o.then(f).then(void 0,u);te(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):ee(a,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,u):f(o):ee(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,d(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)}},exports.resolveX25519Encrypters=function(e,r){try{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(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 n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>ue(h(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(oe)}catch(e){return Promise.reject(e)}},exports.toEthereumAddress=D,exports.verifyJWS=function(e,r){return Q(L(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}=G(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=H[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){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:"application/did+json"}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let a=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...a.map(e=>e.id)]),a=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(a,e):"string"==typeof e.publicKey?c(a,e.publicKey):e).filter(e=>null!=e));const u=a.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!u||0===u.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!u||0===u.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:u,issuer:t,didResolutionResult: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(Q({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)}},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 c=d(i.header.epk.x),u=j(a.sharedKey(e,c),256,r),s=E(i.encrypted_key,i.header.tag);return Promise.resolve(ae(u).decrypt(s,d(i.header.iv))).then(function(e){return null===e?null:ae(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}},exports.x25519Encrypter=ue,exports.xc20pDirDecrypter=ae,exports.xc20pDirEncrypter=ce; | ||
//# 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 s from"canonicalize";import{XChaCha20Poly1305 as u}from"@stablelib/xchacha20poly1305";import{generateKeyPair as l,sharedKey as f}from"@stablelib/x25519";import{randomBytes as d}from"@stablelib/random";function p(r){return e(r,"base64url")}function y(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r(t,"base64url")}function h(e){return r(e,"base58btc")}function g(e){const t=e.startsWith("0x")?e.substring(2):e;return r(t.toLowerCase(),"base16")}function w(e){return p(r(e))}function b(r){return e(y(r))}function m(r){return e(r,"base16")}function v(e){return r(e)}function E({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 p(i)}function k(e){const r=y(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 S(e,r){return t([y(e),y(r)])}const K=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,x=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,$=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function A(e){if("string"==typeof e){if(K.test(e))return g(e);if(x.test(e))return h(e);if($.test(e))return y(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function P(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 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 W(e,t=new Uint8Array(4)){const n=r(e.toString(),"base10");return t.set(n,4-n.length),t}const I=e=>t([W(e.length),e]);function O(e,o,i){if(256!==o)throw new Error(`Unsupported key length: ${o}`);const a=t([I(r(i)),I(new Uint8Array(0)),I(new Uint8Array(0)),W(o)]);return n(t([W(1),e,a]))}const T=new i("secp256k1");function C(e,r=!1){const t=A(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 E({r:P(t.toString("hex")),s:P(o.toString("hex")),recoveryParam:i},r)}}function j(e){const r=C(e,!0);return async e=>k(await r(e))}function R(e){return C(e)}function U(e){const r=A(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 p(a(r,t))}}function M(e){return U(e)}function z(){return(z=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)}function N(e){return"object"==typeof e&&"r"in e&&"s"in e}function B(e){return async function(r,t){const n=await t(r);if(N(n))return E(n,e);if(e&&void 0===k(n).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return n}}function V(){return async function(e,r){const t=await r(e);if(N(t))throw new Error("expected a signer function that returns a string instead of signature object");return t}}const X={ES256K:B(),"ES256K-R":B(!0),Ed25519:V(),EdDSA:V()},_=new i("secp256k1");function H(e,r=!1){const t=y(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 Z(e){return e.publicKeyBase58?h(e.publicKeyBase58):e.publicKeyBase64?y(e.publicKeyBase64):e.publicKeyHex?g(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?g(_.keyFromPublic({x:m(y(e.publicKeyJwk.x)),y:m(y(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function F(e,r,t){let n;if(r.length>86)n=[H(r,!0)];else{const e=H(r,!1);n=[z({},e,{recoveryParam:0}),z({},e,{recoveryParam:1})]}const o=n.map(r=>{const n=D(e),o=_.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),a=o.encode("hex",!0),c=J(i);return t.find(e=>{var r,t,n;const o=m(Z(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 L(e,r,t){const n=v(e),o=y(r),i=t.find(e=>c(Z(e),n,o));if(!i)throw new Error("Signature invalid for JWT");return i}const q={ES256K:function(e,r,t){const n=D(e),o=H(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=Z(e);return _.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!c&&a.length>0&&(c=F(e,r,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":F,Ed25519:L,EdDSA:L};function G(e){const r=q[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}G.toSignatureObject=H;const Q={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function Y(e,r=!1){return w(r?JSON.stringify(s(e)):JSON.stringify(e))}function ee(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(b(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function re(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=ee(e);return Object.assign(r,{payload:JSON.parse(b(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}async function te(e,r,t={},n={}){t.alg||(t.alg="ES256K");const o="string"==typeof e?e:Y(e,n.canonicalize),i=[Y(t,n.canonicalize),o].join("."),a=function(e){const r=X[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return[i,await a(i,r)].join(".")}async function ne(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},a={}){if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");a.typ||(a.typ="JWT"),a.alg||(a.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)}return te(z({},c,e,{iss:r}),t,a,{canonicalize:i})}function oe({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),G(e.alg)(r,t,n)}function ie(e,r){return oe(ee(e),r)}async function ae(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}=re(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=Q[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 oe({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 ce({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const a={protected:n,iv:p(t),ciphertext:p(e),tag:p(r)};return i&&(a.aad=p(i)),o&&(a.recipients=[o]),a}async function se(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 ce(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=ce(r,n)}return a}}async function ue(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(b(e.protected));if(t.enc!==r.enc)throw new Error(`Decrypter does not support: '${t.enc}'`);const n=S(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,y(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,y(e.iv),o,c))}}if(null===i)throw new Error("Failed to decrypt");return i}function le(e){const r=new u(e);return(e,t)=>{const n=d(r.nonceLength),o=r.seal(n,e,t);return{ciphertext:o.subarray(0,o.length-r.tagLength),tag:o.subarray(o.length-r.tagLength),iv:n}}}function fe(e){const r=le(e),t="XC20P";return{alg:"dir",enc:t,encrypt:async function(e,n={},o){const i=w(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(o?`${i}.${p(o)}`:i));return z({},r(e,a),{protectedHeader:i})}}}function de(e){const r=new u(e);return{alg:"dir",enc:"XC20P",decrypt:async function(e,t,n){return r.open(t,e,n)}}}function pe(e,r){const t="ECDH-ES+XC20PKW";async function n(n){const o=l(),i=le(O(f(o.secretKey,e),256,t))(n),a={encrypted_key:p(i.ciphertext),header:{alg:t,iv:p(i.iv),tag:p(i.tag),epk:{kty:"OKP",crv:"X25519",x:p(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=d(32);return z({},await fe(o).encrypt(e,r,t),{recipient:await n(o),cek:o})},encryptCek:n}}async function ye(e,r){const t=e.map(e=>(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)).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!i.length)throw new Error(`Could not find x25519 key for ${e}`);return i.map(e=>pe(h(e.publicKeyBase58),e.id))})(e)),n=await Promise.all(t);return[].concat.apply([],n)}function he(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=y(i.header.epk.x),c=O(f(e,a),256,r),s=S(i.encrypted_key,i.header.tag),u=await de(c).decrypt(s,y(i.header.iv));return null===u?null:de(u).decrypt(t,n,o)}}}export{C as ES256KSigner,U as EdDSASigner,R as EllipticSigner,M as NaclSigner,j as SimpleSigner,se as createJWE,te as createJWS,ne as createJWT,re as decodeJWT,ue as decryptJWE,ye as resolveX25519Encrypters,J as toEthereumAddress,ie as verifyJWS,ae as verifyJWT,he as x25519Decrypter,pe as x25519Encrypter,de as xc20pDirDecrypter,fe as xc20pDirEncrypter}; | ||
import{toString as e,fromString as r,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as o}from"js-sha3";import{ec as i}from"elliptic";import{sign as a,verify as c}from"@stablelib/ed25519";import s from"canonicalize";import{XChaCha20Poly1305 as u}from"@stablelib/xchacha20poly1305";import{generateKeyPair as l,sharedKey as f}from"@stablelib/x25519";import{randomBytes as d}from"@stablelib/random";function p(r){return e(r,"base64url")}function y(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r(t,"base64url")}function h(e){return r(e,"base58btc")}function g(e){const t=e.startsWith("0x")?e.substring(2):e;return r(t.toLowerCase(),"base16")}function w(e){return p(r(e))}function b(r){return e(y(r))}function m(r){return e(r,"base16")}function v(e){return r(e)}function E({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 p(i)}function k(e){const r=y(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 K(e,r){return t([y(e),y(r)])}const S=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,x=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,$=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function A(e){if("string"==typeof e){if(S.test(e))return g(e);if(x.test(e))return h(e);if($.test(e))return y(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function P(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 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 W(e,t=new Uint8Array(4)){const n=r(e.toString(),"base10");return t.set(n,4-n.length),t}const I=e=>t([W(e.length),e]);function T(e,o,i){if(256!==o)throw new Error(`Unsupported key length: ${o}`);const a=t([I(r(i)),I(new Uint8Array(0)),I(new Uint8Array(0)),W(o)]);return n(t([W(1),e,a]))}const O=new i("secp256k1");function C(e,r=!1){const t=A(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=O.keyFromPrivate(t);return async e=>{const{r:t,s:o,recoveryParam:i}=n.sign(D(e));return E({r:P(t.toString("hex")),s:P(o.toString("hex")),recoveryParam:i},r)}}function j(e){const r=C(e,!0);return async e=>k(await r(e))}function R(e){return C(e)}function U(e){const r=A(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 p(a(r,t))}}function M(e){return U(e)}function z(){return(z=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)}function N(e){return"object"==typeof e&&"r"in e&&"s"in e}function B(e){return async function(r,t){const n=await t(r);if(N(n))return E(n,e);if(e&&void 0===k(n).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return n}}function V(){return async function(e,r){const t=await r(e);if(N(t))throw new Error("expected a signer function that returns a string instead of signature object");return t}}const X={ES256K:B(),"ES256K-R":B(!0),Ed25519:V(),EdDSA:V()},_=new i("secp256k1");function H(e,r=!1){const t=y(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 Z(e){return e.publicKeyBase58?h(e.publicKeyBase58):e.publicKeyBase64?y(e.publicKeyBase64):e.publicKeyHex?g(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?g(_.keyFromPublic({x:m(y(e.publicKeyJwk.x)),y:m(y(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function F(e,r,t){let n;if(r.length>86)n=[H(r,!0)];else{const e=H(r,!1);n=[z({},e,{recoveryParam:0}),z({},e,{recoveryParam:1})]}const o=n.map(r=>{const n=D(e),o=_.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),a=o.encode("hex",!0),c=J(i);return t.find(e=>{var r,t,n;const o=m(Z(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 L(e,r,t){const n=v(e),o=y(r),i=t.find(e=>c(Z(e),n,o));if(!i)throw new Error("Signature invalid for JWT");return i}const q={ES256K:function(e,r,t){const n=D(e),o=H(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=Z(e);return _.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!c&&a.length>0&&(c=F(e,r,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":F,Ed25519:L,EdDSA:L};function G(e){const r=q[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}G.toSignatureObject=H;const Q={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function Y(e,r=!1){return w(r?s(e):JSON.stringify(e))}function ee(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(b(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function re(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=ee(e);return Object.assign(r,{payload:JSON.parse(b(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}async function te(e,r,t={},n={}){t.alg||(t.alg="ES256K");const o="string"==typeof e?e:Y(e,n.canonicalize),i=[Y(t,n.canonicalize),o].join("."),a=function(e){const r=X[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return[i,await a(i,r)].join(".")}async function ne(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},a={}){if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");a.typ||(a.typ="JWT"),a.alg||(a.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)}return te(z({},c,e,{iss:r}),t,a,{canonicalize:i})}function oe({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),G(e.alg)(r,t,n)}function ie(e,r){return oe(ee(e),r)}async function ae(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}=re(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=Q[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 oe({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 ce({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const a={protected:n,iv:p(t),ciphertext:p(e),tag:p(r)};return i&&(a.aad=p(i)),o&&(a.recipients=[o]),a}async function se(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 ce(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=ce(r,n)}return a}}async function ue(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(b(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,y(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,y(e.iv),o,c))}}if(null===i)throw new Error("Failed to decrypt");return i}function le(e){const r=new u(e);return(e,t)=>{const n=d(r.nonceLength),o=r.seal(n,e,t);return{ciphertext:o.subarray(0,o.length-r.tagLength),tag:o.subarray(o.length-r.tagLength),iv:n}}}function fe(e){const r=le(e),t="XC20P";return{alg:"dir",enc:t,encrypt:async function(e,n={},o){const i=w(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(o?`${i}.${p(o)}`:i));return z({},r(e,a),{protectedHeader:i})}}}function de(e){const r=new u(e);return{alg:"dir",enc:"XC20P",decrypt:async function(e,t,n){return r.open(t,e,n)}}}function pe(e,r){const t="ECDH-ES+XC20PKW";async function n(n){const o=l(),i=le(T(f(o.secretKey,e),256,t))(n),a={encrypted_key:p(i.ciphertext),header:{alg:t,iv:p(i.iv),tag:p(i.tag),epk:{kty:"OKP",crv:"X25519",x:p(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=d(32);return z({},await fe(o).encrypt(e,r,t),{recipient:await n(o),cek:o})},encryptCek:n}}async function ye(e,r){const t=e.map(e=>(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)).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!i.length)throw new Error(`Could not find x25519 key for ${e}`);return i.map(e=>pe(h(e.publicKeyBase58),e.id))})(e)),n=await Promise.all(t);return[].concat.apply([],n)}function he(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=y(i.header.epk.x),c=T(f(e,a),256,r),s=K(i.encrypted_key,i.header.tag),u=await de(c).decrypt(s,y(i.header.iv));return null===u?null:de(u).decrypt(t,n,o)}}}export{C as ES256KSigner,U as EdDSASigner,R as EllipticSigner,M as NaclSigner,j as SimpleSigner,se as createJWE,te as createJWS,ne as createJWT,re as decodeJWT,ue as decryptJWE,ye as resolveX25519Encrypters,J as toEthereumAddress,ie as verifyJWS,ae as verifyJWT,he as x25519Decrypter,pe as x25519Encrypter,de as xc20pDirDecrypter,fe 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("canonicalize"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","uint8arrays","@stablelib/sha256","js-sha3","elliptic","@stablelib/ed25519","canonicalize","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],r):r((e||self).didJwt={},e.uint8Arrays,e.sha256$1,e.jsSha3,e.elliptic,e.ed25519,e.canonicalize,e.xchacha20poly1305,e.x25519,e.random)}(this,function(e,r,t,n,o,i,c,a,u,s){function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=f(c);function d(e){return r.toString(e,"base64url")}function h(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r.fromString(t,"base64url")}function y(e){return r.fromString(e,"base58btc")}function p(e){const t=e.startsWith("0x")?e.substring(2):e;return r.fromString(t.toLowerCase(),"base16")}function g(e){return d(r.fromString(e))}function m(e){return r.toString(h(e))}function v(e){return r.toString(e,"base16")}function w(e){return r.fromString(e)}function b({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 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:v(r.slice(0,32)),s:v(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function P(e,t){return r.concat([h(e),h(t)])}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 K(e){if("string"==typeof e){if(S.test(e))return p(e);if(k.test(e))return y(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 J(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function A(e){const n="string"==typeof e?r.fromString(e):e;return t.hash(n)}function $(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 j(e,t=new Uint8Array(4)){const n=r.fromString(e.toString(),"base10");return t.set(n,4-n.length),t}const D=e=>r.concat([j(e.length),e]);function W(e,n,o){if(256!==n)throw new Error(`Unsupported key length: ${n}`);const i=r.concat([D(r.fromString(o)),D(new Uint8Array(0)),D(new Uint8Array(0)),j(n)]);return t.hash(r.concat([j(1),e,i]))}const T=new o.ec("secp256k1");function I(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=T.keyFromPrivate(t);return function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(A(e));return Promise.resolve(b({r:J(t.toString("hex")),s:J(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function C(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=i.sign(r,t);return Promise.resolve(d(n))}catch(e){return Promise.reject(e)}}}function O(e){return"object"==typeof e&&"r"in e&&"s"in e}function R(e){return function(r,t){try{return Promise.resolve(t(r)).then(function(r){if(O(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 U(){return function(e,r){try{return Promise.resolve(r(e)).then(function(e){if(O(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}const z={ES256K:R(),"ES256K-R":R(!0),Ed25519:U(),EdDSA:U()},M=new o.ec("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:v(t.slice(0,32)),s:v(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function B(e){return e.publicKeyBase58?y(e.publicKeyBase58):e.publicKeyBase64?h(e.publicKeyBase64):e.publicKeyHex?p(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?p(M.keyFromPublic({x:v(h(e.publicKeyJwk.x)),y:v(h(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function X(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),a=$(i);return t.find(e=>{const r=v(B(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===a||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===a})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function q(e,r,t){const n=w(e),o=h(r),c=t.find(e=>i.verify(B(e),n,o));if(!c)throw new Error("Signature invalid for JWT");return c}const V={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 a=i.find(e=>{try{const r=B(e);return M.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!a&&c.length>0&&(a=X(e,r,c)),!a)throw new Error("Signature invalid for JWT");return a},"ES256K-R":X,Ed25519:q,EdDSA:q};function _(e){const r=V[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}_.toSignatureObject=N;const H=function(e,r,t={},n={}){try{t.alg||(t.alg=F);const o="string"==typeof e?e:G(e,n.canonicalize),i=[G(t,n.canonicalize),o].join("."),c=function(e){const r=z[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(c(i,r)).then(function(e){return[i,e].join(".")})}catch(e){return Promise.reject(e)}},Z={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},F="ES256K",L="application/did+json";function G(e,r=!1){return g(r?JSON.stringify(l.default(e)):JSON.stringify(e))}function Q(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(m(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function Y(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=Q(e);return Object.assign(r,{payload:JSON.parse(m(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function ee({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),_(e.alg)(r,t,n)}const re="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function te(e,r,t){if(!e.s){if(t instanceof ne){if(!t.s)return void(t.o=te.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(te.bind(null,e,r),te.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const ne=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{te(n,1,e(this.v))}catch(e){te(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?te(n,1,r?r(o):o):t?te(n,1,t(o)):te(n,2,o)}catch(e){te(n,2,e)}},n},e}();function oe(e){return e instanceof ne&&1&e.s}function ie({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 ce=e=>[].concat.apply([],e);function ae(e){const r=new a.XChaCha20Poly1305(e);return(e,t)=>{const n=s.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 ue(e){const r=ae(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=g(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 se(e){const r=new a.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 fe(e,r){const t=function(t){try{const c=u.generateKeyPair(),a=ae(W(u.sharedKey(c.secretKey,e),o,n))(t),s={encrypted_key:d(a.ciphertext),header:{alg:n,iv:d(a.iv),tag:d(a.tag),epk:{kty:"OKP",crv:i,x:d(c.publicKey)}}};return r&&(s.header.kid=r),Promise.resolve(s)}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=s.randomBytes(32);return Promise.resolve(ue(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=I,e.EdDSASigner=C,e.EllipticSigner=function(e){return I(e)},e.NaclSigner=function(e){return C(e)},e.SimpleSigner=function(e){const r=I(e,!0);return function(e){try{return Promise.resolve(r(e)).then(E)}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 ie(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[re]){var n,o,i,c=e[re]();if(function e(t){try{for(;!(n=c.next()).done;)if((t=r(n.value))&&t.then){if(!oe(t))return void t.then(e,i||(i=te.bind(null,o=new ne,2)));t=t.v}o?te(o,1,t):o=t}catch(e){te(o||(o=new ne),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(!oe(c))return void c.then(t,o||(o=te.bind(null,n=new ne,2)));c=c.v}n?te(n,1,c):n=c}catch(e){te(n||(n=new ne),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=ie(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=H,e.createJWT=function(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},c={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");c.typ||(c.typ="JWT"),c.alg||(c.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)}const u={...a,...e,iss:r};return H(u,t,c,{canonicalize:i})}catch(e){return Promise.reject(e)}},e.decodeJWT=Y,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(m(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 a="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(oe(o)&&(o=o.v),!o)return i;if(o.then){n=0;break}var i=t();if(i&&i.then){if(!oe(i)){n=1;break}i=i.s}if(r){var c=r();if(c&&c.then&&!oe(c)){n=2;break}}}var a=new ne,u=te.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&&!oe(c))return void c.then(l).then(void 0,u);if(!(o=e())||oe(o)&&!o.v)return void te(a,1,i);if(o.then)return void o.then(f).then(void 0,u);oe(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):te(a,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,u):f(o):te(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,h(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{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(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 n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>fe(y(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(ce)}catch(e){return Promise.reject(e)}},e.toEthereumAddress=$,e.verifyJWS=function(e,r){return ee(Q(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}=Y(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=Z[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:L})).then(function(e){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:L}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let a=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...a.map(e=>e.id)]),a=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(a,e):"string"==typeof e.publicKey?c(a,e.publicKey):e).filter(e=>null!=e));const u=a.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!u||0===u.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!u||0===u.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:u,issuer:t,didResolutionResult: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(ee({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=h(i.header.epk.x),a=W(u.sharedKey(e,c),256,r),s=P(i.encrypted_key,i.header.tag);return Promise.resolve(se(a).decrypt(s,h(i.header.iv))).then(function(e){return null===e?null:se(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}},e.x25519Encrypter=fe,e.xc20pDirDecrypter=se,e.xc20pDirEncrypter=ue}); | ||
!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("canonicalize"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","uint8arrays","@stablelib/sha256","js-sha3","elliptic","@stablelib/ed25519","canonicalize","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],r):r((e||self).didJwt={},e.uint8Arrays,e.sha256$1,e.jsSha3,e.elliptic,e.ed25519,e.canonicalize,e.xchacha20poly1305,e.x25519,e.random)}(this,function(e,r,t,n,o,i,c,a,u,s){function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=f(c);function d(e){return r.toString(e,"base64url")}function h(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r.fromString(t,"base64url")}function y(e){return r.fromString(e,"base58btc")}function p(e){const t=e.startsWith("0x")?e.substring(2):e;return r.fromString(t.toLowerCase(),"base16")}function g(e){return d(r.fromString(e))}function m(e){return r.toString(h(e))}function v(e){return r.toString(e,"base16")}function w(e){return r.fromString(e)}function b({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 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:v(r.slice(0,32)),s:v(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function P(e,t){return r.concat([h(e),h(t)])}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 K(e){if("string"==typeof e){if(S.test(e))return p(e);if(k.test(e))return y(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 A(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function J(e){const n="string"==typeof e?r.fromString(e):e;return t.hash(n)}function $(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 j(e,t=new Uint8Array(4)){const n=r.fromString(e.toString(),"base10");return t.set(n,4-n.length),t}const D=e=>r.concat([j(e.length),e]);function W(e,n,o){if(256!==n)throw new Error(`Unsupported key length: ${n}`);const i=r.concat([D(r.fromString(o)),D(new Uint8Array(0)),D(new Uint8Array(0)),j(n)]);return t.hash(r.concat([j(1),e,i]))}const T=new o.ec("secp256k1");function I(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=T.keyFromPrivate(t);return function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(J(e));return Promise.resolve(b({r:A(t.toString("hex")),s:A(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function C(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=i.sign(r,t);return Promise.resolve(d(n))}catch(e){return Promise.reject(e)}}}function O(e){return"object"==typeof e&&"r"in e&&"s"in e}function R(e){return function(r,t){try{return Promise.resolve(t(r)).then(function(r){if(O(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 U(){return function(e,r){try{return Promise.resolve(r(e)).then(function(e){if(O(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}const z={ES256K:R(),"ES256K-R":R(!0),Ed25519:U(),EdDSA:U()},M=new o.ec("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:v(t.slice(0,32)),s:v(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function B(e){return e.publicKeyBase58?y(e.publicKeyBase58):e.publicKeyBase64?h(e.publicKeyBase64):e.publicKeyHex?p(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?p(M.keyFromPublic({x:v(h(e.publicKeyJwk.x)),y:v(h(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function X(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=J(e),o=M.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),c=o.encode("hex",!0),a=$(i);return t.find(e=>{const r=v(B(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===a||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===a})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function q(e,r,t){const n=w(e),o=h(r),c=t.find(e=>i.verify(B(e),n,o));if(!c)throw new Error("Signature invalid for JWT");return c}const V={ES256K:function(e,r,t){const n=J(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 a=i.find(e=>{try{const r=B(e);return M.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!a&&c.length>0&&(a=X(e,r,c)),!a)throw new Error("Signature invalid for JWT");return a},"ES256K-R":X,Ed25519:q,EdDSA:q};function _(e){const r=V[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}_.toSignatureObject=N;const H=function(e,r,t={},n={}){try{t.alg||(t.alg=F);const o="string"==typeof e?e:G(e,n.canonicalize),i=[G(t,n.canonicalize),o].join("."),c=function(e){const r=z[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(c(i,r)).then(function(e){return[i,e].join(".")})}catch(e){return Promise.reject(e)}},Z={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},F="ES256K",L="application/did+json";function G(e,r=!1){return g(r?l.default(e):JSON.stringify(e))}function Q(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(m(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function Y(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=Q(e);return Object.assign(r,{payload:JSON.parse(m(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function ee({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),_(e.alg)(r,t,n)}const re="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function te(e,r,t){if(!e.s){if(t instanceof ne){if(!t.s)return void(t.o=te.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(te.bind(null,e,r),te.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const ne=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{te(n,1,e(this.v))}catch(e){te(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?te(n,1,r?r(o):o):t?te(n,1,t(o)):te(n,2,o)}catch(e){te(n,2,e)}},n},e}();function oe(e){return e instanceof ne&&1&e.s}function ie({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 ce=e=>[].concat.apply([],e);function ae(e){const r=new a.XChaCha20Poly1305(e);return(e,t)=>{const n=s.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 ue(e){const r=ae(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=g(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 se(e){const r=new a.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 fe(e,r){const t=function(t){try{const c=u.generateKeyPair(),a=ae(W(u.sharedKey(c.secretKey,e),o,n))(t),s={encrypted_key:d(a.ciphertext),header:{alg:n,iv:d(a.iv),tag:d(a.tag),epk:{kty:"OKP",crv:i,x:d(c.publicKey)}}};return r&&(s.header.kid=r),Promise.resolve(s)}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=s.randomBytes(32);return Promise.resolve(ue(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=I,e.EdDSASigner=C,e.EllipticSigner=function(e){return I(e)},e.NaclSigner=function(e){return C(e)},e.SimpleSigner=function(e){const r=I(e,!0);return function(e){try{return Promise.resolve(r(e)).then(E)}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 ie(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[re]){var n,o,i,c=e[re]();if(function e(t){try{for(;!(n=c.next()).done;)if((t=r(n.value))&&t.then){if(!oe(t))return void t.then(e,i||(i=te.bind(null,o=new ne,2)));t=t.v}o?te(o,1,t):o=t}catch(e){te(o||(o=new ne),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(!oe(c))return void c.then(t,o||(o=te.bind(null,n=new ne,2)));c=c.v}n?te(n,1,c):n=c}catch(e){te(n||(n=new ne),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=ie(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=H,e.createJWT=function(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},c={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");c.typ||(c.typ="JWT"),c.alg||(c.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)}const u={...a,...e,iss:r};return H(u,t,c,{canonicalize:i})}catch(e){return Promise.reject(e)}},e.decodeJWT=Y,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(m(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 a="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(oe(o)&&(o=o.v),!o)return i;if(o.then){n=0;break}var i=t();if(i&&i.then){if(!oe(i)){n=1;break}i=i.s}if(r){var c=r();if(c&&c.then&&!oe(c)){n=2;break}}}var a=new ne,u=te.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&&!oe(c))return void c.then(l).then(void 0,u);if(!(o=e())||oe(o)&&!o.v)return void te(a,1,i);if(o.then)return void o.then(f).then(void 0,u);oe(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):te(a,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,u):f(o):te(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,h(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{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(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 n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>fe(y(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(ce)}catch(e){return Promise.reject(e)}},e.toEthereumAddress=$,e.verifyJWS=function(e,r){return ee(Q(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}=Y(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=Z[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:L})).then(function(e){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:L}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let a=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...a.map(e=>e.id)]),a=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(a,e):"string"==typeof e.publicKey?c(a,e.publicKey):e).filter(e=>null!=e));const u=a.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!u||0===u.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!u||0===u.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:u,issuer:t,didResolutionResult: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(ee({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=h(i.header.epk.x),a=W(u.sharedKey(e,c),256,r),s=P(i.encrypted_key,i.header.tag);return Promise.resolve(se(a).decrypt(s,h(i.header.iv))).then(function(e){return null===e?null:se(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}},e.x25519Encrypter=fe,e.xc20pDirDecrypter=se,e.xc20pDirEncrypter=ue}); | ||
//# sourceMappingURL=index.umd.js.map |
{ | ||
"name": "did-jwt", | ||
"version": "5.4.0", | ||
"version": "5.4.1", | ||
"description": "Library for Signing and Verifying JWTs compatible uPort and DID standards", | ||
@@ -5,0 +5,0 @@ "main": "lib/index.js", |
@@ -554,7 +554,9 @@ import { VerificationMethod } from 'did-resolver' | ||
it('createJWS can canonicalize a JSON payload', async () => { | ||
expect.assertions(2) | ||
expect.assertions(3) | ||
const payload = { z: 'z', a: 'a' } | ||
const jws = await createJWS(payload, signer, {}, { canonicalize: true }) | ||
expect(jws).toMatchSnapshot() | ||
expect(JSON.parse(decodeBase64url(jws.split('.')[1]))).toEqual(JSON.stringify({ a: 'a', z: 'z' })) | ||
const parsedPayload = JSON.parse(decodeBase64url(jws.split('.')[1])) | ||
expect(parsedPayload).toEqual(payload) | ||
expect(JSON.stringify(parsedPayload)).toEqual(JSON.stringify({ a: 'a', z: 'z' })) | ||
}) | ||
@@ -561,0 +563,0 @@ |
@@ -133,3 +133,3 @@ import canonicalizeData from 'canonicalize' | ||
if (shouldCanonicalize) { | ||
return encodeBase64url(JSON.stringify(canonicalizeData(data))) | ||
return encodeBase64url(canonicalizeData(data)) | ||
} else { | ||
@@ -136,0 +136,0 @@ return encodeBase64url(JSON.stringify(data)) |
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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
737837
3705