Comparing version 4.9.0 to 5.0.0
@@ -0,1 +1,13 @@ | ||
# [5.0.0](https://github.com/decentralized-identity/did-jwt/compare/4.9.0...5.0.0) (2021-03-09) | ||
### Features | ||
* upgrade did-resolver to v3 ([#151](https://github.com/decentralized-identity/did-jwt/issues/151)) ([e02f56b](https://github.com/decentralized-identity/did-jwt/commit/e02f56b45a8af7031473888f8bff265268f73717)) | ||
### BREAKING CHANGES | ||
* The `Resolver` used during verification is expected to conform to the latest spec. | ||
# [4.9.0](https://github.com/decentralized-identity/did-jwt/compare/4.8.1...4.9.0) (2021-02-10) | ||
@@ -2,0 +14,0 @@ |
@@ -6,7 +6,7 @@ import SimpleSigner from './signers/SimpleSigner'; | ||
import { EdDSASigner } from './signers/EdDSASigner'; | ||
import { verifyJWT, createJWT, decodeJWT, verifyJWS, createJWS, Signer, JWTHeader, JWTPayload, JWTVerified, Resolvable } from './JWT'; | ||
import { verifyJWT, createJWT, decodeJWT, verifyJWS, createJWS, Signer, JWTHeader, JWTPayload, JWTVerified } from './JWT'; | ||
import { toEthereumAddress } from './Digest'; | ||
export { JWE, createJWE, decryptJWE, Encrypter, Decrypter } from './JWE'; | ||
export { xc20pDirEncrypter, xc20pDirDecrypter, x25519Encrypter, x25519Decrypter, resolveX25519Encrypters } from './xc20pEncryption'; | ||
export { SimpleSigner, EllipticSigner, NaclSigner, ES256KSigner, EdDSASigner, verifyJWT, createJWT, decodeJWT, verifyJWS, createJWS, toEthereumAddress, Signer, JWTHeader, JWTPayload, JWTVerified, Resolvable }; | ||
export { SimpleSigner, EllipticSigner, NaclSigner, ES256KSigner, EdDSASigner, verifyJWT, createJWT, decodeJWT, verifyJWS, createJWS, toEthereumAddress, Signer, JWTHeader, JWTPayload, JWTVerified, }; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -1,2 +0,2 @@ | ||
import{toString as r,fromString as e,concat as n}from"uint8arrays";import{hash as t}from"@stablelib/sha256";import{keccak_256 as i}from"js-sha3";import{ec as o}from"elliptic";import{sign as a,verify as u}from"@stablelib/ed25519";import{XChaCha20Poly1305 as c}from"@stablelib/xchacha20poly1305";import{generateKeyPair as f,sharedKey as s}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function h(e){return r(e,"base64url")}function v(r){var n=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e(n,"base64url")}function d(r){return e(r,"base58btc")}function p(r){var n=r.startsWith("0x")?r.substring(2):r;return e(n.toLowerCase(),"base16")}function y(r){return h(e(r))}function g(e){return r(v(e))}function m(e){return r(e,"base16")}function w(r){return e(r)}function b(r,n){var t=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(n?65:64);if(a.set(e(t,"base16"),0),a.set(e(i,"base16"),32),n){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return h(a)}function E(r){var e=v(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:m(e.slice(0,32)),s:m(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function P(r,e){return n([v(r),v(e)])}var k=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,K=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function x(r){if("string"==typeof r){if(k.test(r))return p(r);if(S.test(r))return d(r);if(K.test(r))return v(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function j(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function A(r){var n="string"==typeof r?e(r):r;return t(n)}function J(n){var t,o=e(n.slice(2),"base16");return"0x"+r((t=o,new Uint8Array(i.arrayBuffer(t))).slice(-20),"base16")}function D(r,n){void 0===n&&(n=new Uint8Array(4));var t=e(r.toString(),"base10");return n.set(t,4-t.length),n}var W=function(r){return n([D(r.length),r])};function T(r,i,o){if(256!==i)throw new Error("Unsupported key length: "+i);var a=n([W(e(o)),W(new Uint8Array(0)),W(new Uint8Array(0)),D(i)]);return t(n([D(1),r,a]))}var I=new o("secp256k1");function U(r,e){void 0===e&&(e=!1);var n=x(r);if(32!==n.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+n.length);var t=I.keyFromPrivate(n);return function(r){try{var n=t.sign(A(r)),i=n.s,o=n.recoveryParam;return Promise.resolve(b({r:j(n.r.toString("hex")),s:j(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function O(r){var e=U(r,!0);return function(r){try{return Promise.resolve(e(r)).then(E)}catch(r){return Promise.reject(r)}}}function C(r){return U(r)}function N(r){var e=x(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var n="string"==typeof r?w(r):r,t=a(e,n);return Promise.resolve(h(t))}catch(r){return Promise.reject(r)}}}function B(r){return N(r)}function V(){return(V=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(r[t]=n[t])}return r}).apply(this,arguments)}var H=new o("secp256k1");function X(r,e){void 0===e&&(e=!1);var n=v(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:m(n.slice(0,32)),s:m(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function _(r){return r.publicKeyBase58?d(r.publicKeyBase58):r.publicKeyBase64?v(r.publicKeyBase64):r.publicKeyHex?p(r.publicKeyHex):new Uint8Array}function z(r,e,n){var t;if(e.length>86)t=[X(e,!0)];else{var i=X(e,!1);t=[V({},i,{recoveryParam:0}),V({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=A(r),i=H.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=J(o);return n.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function Z(r,e,n){var t=w(r),i=v(e),o=n.find(function(r){return u(_(r),t,i)});if(!o)throw new Error("Signature invalid for JWT");return o}var F={ES256K:function(r,e,n){var t=A(r),i=X(e),o=n.filter(function(r){return void 0===r.ethereumAddress}),a=n.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=_(r);return H.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=z(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":z,Ed25519:Z,EdDSA:Z};function L(r){var e=F[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function R(r){return"object"==typeof r&&"r"in r&&"s"in r}function $(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(R(e))return b(e,r);if(r&&void 0===E(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function M(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(R(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}L.toSignatureObject=X;var q={ES256K:$(),"ES256K-R":$(!0),Ed25519:M(),EdDSA:M()},G=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var n=or(r),t=n.payload,i=n.header,o=n.signature,a=n.data;return Promise.resolve(function(r,e,n,t){try{var i=rr[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(n)).then(function(r){if(!r)throw new Error("Unable to resolve DID document for "+n);var o=function(r,e){var n=r.publicKey.filter(function(r){return e===r.id});return n.length>0?n[0]:null},a=r.publicKey||[];t&&(a=(r.authentication||[]).map(function(e){return"string"==typeof e?o(r,e):"string"==typeof e.publicKey?o(r,e.publicKey):e}).filter(function(r){return null!=r}));var u=a.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(t&&(!u||0===u.length))throw new Error("DID document for "+n+" does not have public keys suitable for authenticating user");if(!u||0===u.length)throw new Error("DID document for "+n+" does not have public keys for "+e);return{authenticators:u,issuer:n,doc:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,t.iss,e.auth)).then(function(n){var u=n.doc,c=n.issuer;return Promise.resolve(ar({header:i,data:a,signature:o},n.authenticators)).then(function(n){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:tr;if(n){var a=i+o;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<=i-o)throw new Error("JWT has expired: exp: "+t.exp+" < now: "+i);if(t.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,doc:u,issuer:c,signer:n,jwt:r}}})})}catch(r){return Promise.reject(r)}},Q=function(r,e,n){var t=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===n&&(n={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!t)throw new Error("No issuing DID has been configured");n.typ||(n.typ="JWT"),n.alg||(n.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=V({},u,r,{iss:t});return Y(c,i,n)}catch(r){return Promise.reject(r)}},Y=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=er);var t="string"==typeof r?r:nr(r),i=[nr(n),t].join("."),o=function(r){var e=q[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(n.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},rr={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},er="ES256K";function nr(r){return y(JSON.stringify(r))}var tr=300;function ir(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(g(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function or(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=ir(r);return Object.assign(e,{payload:JSON.parse(g(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function ar(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),L(n.alg)(t,i,e)}function ur(r,e){return ar(ir(r),e)}var cr=function(r,e){try{var n=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var t=JSON.parse(g(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=P(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===t.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,v(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var n=0;return function(r,e,n){for(var t;;){var i=r();if(hr(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!hr(o)){t=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!hr(a)){t=2;break}}}var u=new lr,c=sr.bind(null,u,2);return(0===t?i.then(s):1===t?o.then(f):a.then(l)).then(void 0,c),u;function f(t){o=t;do{if(e&&(a=e())&&a.then&&!hr(a))return void a.then(l).then(void 0,c);if(!(i=r())||hr(i)&&!i.v)return void sr(u,1,o);if(i.then)return void i.then(s).then(void 0,c);hr(o=n())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=n())&&o.then?o.then(f).then(void 0,c):f(o):sr(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):sr(u,1,o)}}(function(){return!a&&n<r.recipients.length},function(){return n++},function(){var u=r.recipients[n];Object.assign(u.header,t);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,v(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(n):n())}catch(r){return Promise.reject(r)}},fr="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function sr(r,e,n){if(!r.s){if(n instanceof lr){if(!n.s)return void(n.o=sr.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(sr.bind(null,r,e),sr.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var lr=function(){function r(){}return r.prototype.then=function(e,n){var t=new r,i=this.s;if(i){var o=1&i?e:n;if(o){try{sr(t,1,o(this.v))}catch(r){sr(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?sr(t,1,e?e(i):i):n?sr(t,1,n(i)):sr(t,2,i)}catch(r){sr(t,2,r)}},t},r}();function hr(r){return r instanceof lr&&1&r.s}function vr(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:h(r.iv),ciphertext:h(n),tag:h(t)};return e&&(o.aad=h(e)),i&&(o.recipients=[i]),o}var dr=function(r,e,n,t){void 0===n&&(n={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,n,t)).then(function(r){return vr(r,t)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,n){if("function"==typeof r[fr]){var t,i,o,a=r[fr]();if(function r(n){try{for(;!(t=a.next()).done;)if((n=e(t.value))&&n.then){if(!hr(n))return void n.then(r,o||(o=sr.bind(null,i=new lr,2)));n=n.v}i?sr(i,1,n):i=n}catch(r){sr(i||(i=new lr),2,r)}}(),a.return){var u=function(r){try{t.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,n){var t,i,o=-1;return function n(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!hr(a))return void a.then(n,i||(i=sr.bind(null,t=new lr,2)));a=a.v}t?sr(t,1,a):t=a}catch(r){sr(t||(t=new lr),2,r)}}(),t}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,n,t)).then(function(r){i=r.cek,o=vr(r,t)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}};function pr(r){var e=new c(r);return function(r,n){var t=l(e.nonceLength),i=e.seal(t,r,n);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:t}}}var yr=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var n;if(!e.keyAgreement)throw new Error("Could not find x25519 key for "+r);var t=(null==(n=e.keyAgreement)?void 0:n.map(function(r){return"string"==typeof r?e.publicKey.find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!t)throw new Error("Could not find x25519 key for "+r);return wr(d(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}};function gr(r){var e=pr(r),n="XC20P";return{alg:"dir",enc:n,encrypt:function(r,t,i){void 0===t&&(t={});try{var o=y(JSON.stringify(Object.assign({alg:"dir"},t,{enc:n}))),a=new Uint8Array(Buffer.from(i?o+"."+h(i):o));return Promise.resolve(V({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function mr(r){var e=new c(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,n,t){try{return Promise.resolve(e.open(n,r,t))}catch(r){return Promise.reject(r)}}}}function wr(r,e){var n=function(n){try{var a=f(),u=pr(T(s(a.secretKey,r),i,t))(n),c={encrypted_key:h(u.ciphertext),header:{alg:t,iv:h(u.iv),tag:h(u.tag),epk:{kty:"OKP",crv:o,x:h(a.publicKey)}}};return e&&(c.header.kid=e),Promise.resolve(c)}catch(r){return Promise.reject(r)}},t="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:t,enc:"XC20P",encrypt:function(r,e,t){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=l(32);return Promise.resolve(gr(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return V({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}function br(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(n,t,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var a=v(o.header.epk.x),u=T(s(r,a),256,e),c=P(o.encrypted_key,o.header.tag);return Promise.resolve(mr(u).decrypt(c,v(o.header.iv))).then(function(r){return null===r?null:mr(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}}export{U as ES256KSigner,N as EdDSASigner,C as EllipticSigner,B as NaclSigner,O as SimpleSigner,dr as createJWE,Y as createJWS,Q as createJWT,or as decodeJWT,cr as decryptJWE,yr as resolveX25519Encrypters,J as toEthereumAddress,ur as verifyJWS,G as verifyJWT,br as x25519Decrypter,wr as x25519Encrypter,mr as xc20pDirDecrypter,gr as xc20pDirEncrypter}; | ||
import{toString as r,fromString as e,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as i}from"js-sha3";import{ec as o}from"elliptic";import{sign as a,verify as u}from"@stablelib/ed25519";import{XChaCha20Poly1305 as c}from"@stablelib/xchacha20poly1305";import{generateKeyPair as f,sharedKey as s}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function h(e){return r(e,"base64url")}function d(r){var t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e(t,"base64url")}function v(r){return e(r,"base58btc")}function p(r){var t=r.startsWith("0x")?r.substring(2):r;return e(t.toLowerCase(),"base16")}function y(r){return h(e(r))}function g(e){return r(d(e))}function m(e){return r(e,"base16")}function w(r){return e(r)}function b(r,t){var n=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(t?65:64);if(a.set(e(n,"base16"),0),a.set(e(i,"base16"),32),t){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return h(a)}function E(r){var e=d(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:m(e.slice(0,32)),s:m(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function P(r,e){return t([d(r),d(e)])}var k=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,K=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function x(r){if("string"==typeof r){if(k.test(r))return p(r);if(S.test(r))return v(r);if(K.test(r))return d(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function j(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function A(r){var t="string"==typeof r?e(r):r;return n(t)}function D(t){var n,o=e(t.slice(2),"base16");return"0x"+r((n=o,new Uint8Array(i.arrayBuffer(n))).slice(-20),"base16")}function J(r,t){void 0===t&&(t=new Uint8Array(4));var n=e(r.toString(),"base10");return t.set(n,4-n.length),t}var W=function(r){return t([J(r.length),r])};function T(r,i,o){if(256!==i)throw new Error("Unsupported key length: "+i);var a=t([W(e(o)),W(new Uint8Array(0)),W(new Uint8Array(0)),J(i)]);return n(t([J(1),r,a]))}var I=new o("secp256k1");function U(r,e){void 0===e&&(e=!1);var t=x(r);if(32!==t.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+t.length);var n=I.keyFromPrivate(t);return function(r){try{var t=n.sign(A(r)),i=t.s,o=t.recoveryParam;return Promise.resolve(b({r:j(t.r.toString("hex")),s:j(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function C(r){var e=U(r,!0);return function(r){try{return Promise.resolve(e(r)).then(E)}catch(r){return Promise.reject(r)}}}function O(r){return U(r)}function R(r){var e=x(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var t="string"==typeof r?w(r):r,n=a(e,t);return Promise.resolve(h(n))}catch(r){return Promise.reject(r)}}}function N(r){return R(r)}function B(){return(B=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var V=new o("secp256k1");function H(r,e){void 0===e&&(e=!1);var t=d(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");var n={r:m(t.slice(0,32)),s:m(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function M(r){return r.publicKeyBase58?v(r.publicKeyBase58):r.publicKeyBase64?d(r.publicKeyBase64):r.publicKeyHex?p(r.publicKeyHex):new Uint8Array}function X(r,e,t){var n;if(e.length>86)n=[H(e,!0)];else{var i=H(e,!1);n=[B({},i,{recoveryParam:0}),B({},i,{recoveryParam:1})]}var o=n.map(function(e){var n=A(r),i=V.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=D(o);return t.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function _(r,e,t){var n=w(r),i=d(e),o=t.find(function(r){return u(M(r),n,i)});if(!o)throw new Error("Signature invalid for JWT");return o}var z={ES256K:function(r,e,t){var n=A(r),i=H(e),o=t.filter(function(r){return void 0===r.ethereumAddress}),a=t.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=M(r);return V.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=X(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":X,Ed25519:_,EdDSA:_};function Z(r){var e=z[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function F(r){return"object"==typeof r&&"r"in r&&"s"in r}function L(r){return function(e,t){try{return Promise.resolve(t(e)).then(function(e){if(F(e))return b(e,r);if(r&&void 0===E(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function $(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(F(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}Z.toSignatureObject=H;var q={ES256K:L(),"ES256K-R":L(!0),Ed25519:$(),EdDSA:$()},G=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var t=ar(r),n=t.payload,i=t.header,o=t.signature,a=t.data;return Promise.resolve(function(r,e,t,n){try{var i=rr[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(t,{accept:tr})).then(function(r){var o,a,u;if(null!=(o=r.didResolutionMetadata)&&o.error){var c=r.didResolutionMetadata;throw new Error("Unable to resolve DID document for "+t+": "+c.error+", "+(c.message||""))}var f=function(r,e){var t=r.filter(function(r){return e===r.id});return t.length>0?t[0]:null},s=[];r.didDocument.verificationMethod&&(a=s).push.apply(a,r.didDocument.verificationMethod),r.didDocument.publicKey&&(u=s).push.apply(u,r.didDocument.publicKey),n&&(s=(r.didDocument.authentication||[]).map(function(r){return"string"==typeof r?f(s,r):"string"==typeof r.publicKey?f(s,r.publicKey):r}).filter(function(r){return null!=r}));var l=s.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(n&&(!l||0===l.length))throw new Error("DID document for "+t+" does not have public keys suitable for authenticating user");if(!l||0===l.length)throw new Error("DID document for "+t+" does not have public keys for "+e);return{authenticators:l,issuer:t,didResolutionResult:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,n.iss,e.auth)).then(function(t){var u=t.didResolutionResult,c=t.issuer;return Promise.resolve(ur({header:i,data:a,signature:o},t.authenticators)).then(function(t){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:ir;if(t){var a=i+o;if(n.nbf){if(n.nbf>a)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=i-o)throw new Error("JWT has expired: exp: "+n.exp+" < now: "+i);if(n.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,didResolutionResult:u,issuer:c,signer:t,jwt:r}}})})}catch(r){return Promise.reject(r)}},Q=function(r,e,t){var n=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===t&&(t={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!n)throw new Error("No issuing DID has been configured");t.typ||(t.typ="JWT"),t.alg||(t.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=B({},u,r,{iss:n});return Y(c,i,t)}catch(r){return Promise.reject(r)}},Y=function(r,e,t){void 0===t&&(t={});try{t.alg||(t.alg=er);var n="string"==typeof r?r:nr(r),i=[nr(t),n].join("."),o=function(r){var e=q[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(t.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},rr={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},er="ES256K",tr="application/did+json";function nr(r){return y(JSON.stringify(r))}var ir=300;function or(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(g(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function ar(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=or(r);return Object.assign(e,{payload:JSON.parse(g(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function ur(r,e){var t=r.header,n=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),Z(t.alg)(n,i,e)}function cr(r,e){return ur(or(r),e)}var fr=function(r,e){try{var t=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var n=JSON.parse(g(r.protected));if(n.enc!==e.enc)throw new Error("Decrypter does not support: '"+n.enc+"'");var i=P(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===n.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,d(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var t=0;return function(r,e,t){for(var n;;){var i=r();if(dr(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!dr(o)){n=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!dr(a)){n=2;break}}}var u=new hr,c=lr.bind(null,u,2);return(0===n?i.then(s):1===n?o.then(f):a.then(l)).then(void 0,c),u;function f(n){o=n;do{if(e&&(a=e())&&a.then&&!dr(a))return void a.then(l).then(void 0,c);if(!(i=r())||dr(i)&&!i.v)return void lr(u,1,o);if(i.then)return void i.then(s).then(void 0,c);dr(o=t())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=t())&&o.then?o.then(f).then(void 0,c):f(o):lr(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):lr(u,1,o)}}(function(){return!a&&t<r.recipients.length},function(){return t++},function(){var u=r.recipients[t];Object.assign(u.header,n);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,d(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(r){return Promise.reject(r)}},sr="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function lr(r,e,t){if(!r.s){if(t instanceof hr){if(!t.s)return void(t.o=lr.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(lr.bind(null,r,e),lr.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var hr=function(){function r(){}return r.prototype.then=function(e,t){var n=new r,i=this.s;if(i){var o=1&i?e:t;if(o){try{lr(n,1,o(this.v))}catch(r){lr(n,2,r)}return n}return this}return this.o=function(r){try{var i=r.v;1&r.s?lr(n,1,e?e(i):i):t?lr(n,1,t(i)):lr(n,2,i)}catch(r){lr(n,2,r)}},n},r}();function dr(r){return r instanceof hr&&1&r.s}function vr(r,e){var t=r.ciphertext,n=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:h(r.iv),ciphertext:h(t),tag:h(n)};return e&&(o.aad=h(e)),i&&(o.recipients=[i]),o}var pr=function(r,e,t,n){void 0===t&&(t={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,t,n)).then(function(r){return vr(r,n)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,t){if("function"==typeof r[sr]){var n,i,o,a=r[sr]();if(function r(t){try{for(;!(n=a.next()).done;)if((t=e(n.value))&&t.then){if(!dr(t))return void t.then(r,o||(o=lr.bind(null,i=new hr,2)));t=t.v}i?lr(i,1,t):i=t}catch(r){lr(i||(i=new hr),2,r)}}(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,i,o=-1;return function t(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!dr(a))return void a.then(t,i||(i=lr.bind(null,n=new hr,2)));a=a.v}n?lr(n,1,a):n=a}catch(r){lr(n||(n=new hr),2,r)}}(),n}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,t,n)).then(function(r){i=r.cek,o=vr(r,n)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}};function yr(r){var e=new c(r);return function(r,t){var n=l(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}var gr=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var t,n=e.didResolutionMetadata,i=e.didDocument;if(null!=n&&n.error)throw new Error("Could not find x25519 key for "+r+": "+n.error+", "+n.message);if(!i.keyAgreement)throw new Error("Could not find x25519 key for "+r);var o=(null==(t=i.keyAgreement)?void 0:t.map(function(r){return"string"==typeof r?[].concat(i.publicKey||[],i.verificationMethod||[]).find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!o)throw new Error("Could not find x25519 key for "+r);return br(v(o.publicKeyBase58),o.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}};function mr(r){var e=yr(r),t="XC20P";return{alg:"dir",enc:t,encrypt:function(r,n,i){void 0===n&&(n={});try{var o=y(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?o+"."+h(i):o));return Promise.resolve(B({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function wr(r){var e=new c(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,t,n){try{return Promise.resolve(e.open(t,r,n))}catch(r){return Promise.reject(r)}}}}function br(r,e){var t=function(t){try{var a=f(),u=yr(T(s(a.secretKey,r),i,n))(t),c={encrypted_key:h(u.ciphertext),header:{alg:n,iv:h(u.iv),tag:h(u.tag),epk:{kty:"OKP",crv:o,x:h(a.publicKey)}}};return e&&(c.header.kid=e),Promise.resolve(c)}catch(r){return Promise.reject(r)}},n="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:n,enc:"XC20P",encrypt:function(r,e,n){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=l(32);return Promise.resolve(mr(i).encrypt(r,e,n)).then(function(r){return Promise.resolve(t(i)).then(function(e){return B({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:t}}function Er(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(t,n,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var a=d(o.header.epk.x),u=T(s(r,a),256,e),c=P(o.encrypted_key,o.header.tag);return Promise.resolve(wr(u).decrypt(c,d(o.header.iv))).then(function(r){return null===r?null:wr(r).decrypt(t,n,i)})}catch(r){return Promise.reject(r)}}}}export{U as ES256KSigner,R as EdDSASigner,O as EllipticSigner,N as NaclSigner,C as SimpleSigner,pr as createJWE,Y as createJWS,Q as createJWT,ar as decodeJWT,fr as decryptJWE,gr as resolveX25519Encrypters,D as toEthereumAddress,cr as verifyJWS,G as verifyJWT,Er as x25519Decrypter,br as x25519Encrypter,wr as xc20pDirDecrypter,mr as xc20pDirEncrypter}; | ||
//# sourceMappingURL=index.esm.js.map |
@@ -1,2 +0,2 @@ | ||
var r=require("uint8arrays"),e=require("@stablelib/sha256"),t=require("js-sha3"),n=require("elliptic"),i=require("@stablelib/ed25519"),o=require("@stablelib/xchacha20poly1305"),a=require("@stablelib/x25519"),u=require("@stablelib/random");function c(e){return r.toString(e,"base64url")}function f(e){var t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r.fromString(t,"base64url")}function s(e){return r.fromString(e,"base58btc")}function l(e){var t=e.startsWith("0x")?e.substring(2):e;return r.fromString(t.toLowerCase(),"base16")}function h(e){return c(r.fromString(e))}function v(e){return r.toString(f(e))}function d(e){return r.toString(e,"base16")}function p(e){return r.fromString(e)}function y(e,t){var n=e.r,i=e.s,o=e.recoveryParam,a=new Uint8Array(t?65:64);if(a.set(r.fromString(n,"base16"),0),a.set(r.fromString(i,"base16"),32),t){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return c(a)}function g(r){var e=f(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:d(e.slice(0,32)),s:d(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function w(e,t){return r.concat([f(e),f(t)])}var m=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,b=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,E=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function P(r){if("string"==typeof r){if(m.test(r))return l(r);if(b.test(r))return s(r);if(E.test(r))return f(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function S(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function x(t){var n="string"==typeof t?r.fromString(t):t;return e.hash(n)}function k(e){var n,i=r.fromString(e.slice(2),"base16");return"0x"+r.toString((n=i,new Uint8Array(t.keccak_256.arrayBuffer(n))).slice(-20),"base16")}function K(e,t){void 0===t&&(t=new Uint8Array(4));var n=r.fromString(e.toString(),"base10");return t.set(n,4-n.length),t}var A=function(e){return r.concat([K(e.length),e])};function j(t,n,i){if(256!==n)throw new Error("Unsupported key length: "+n);var o=r.concat([A(r.fromString(i)),A(new Uint8Array(0)),A(new Uint8Array(0)),K(n)]);return e.hash(r.concat([K(1),t,o]))}var J=new n.ec("secp256k1");function W(r,e){void 0===e&&(e=!1);var t=P(r);if(32!==t.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+t.length);var n=J.keyFromPrivate(t);return function(r){try{var t=n.sign(x(r)),i=t.s,o=t.recoveryParam;return Promise.resolve(y({r:S(t.r.toString("hex")),s:S(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function D(r){var e=P(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var t="string"==typeof r?p(r):r,n=i.sign(e,t);return Promise.resolve(c(n))}catch(r){return Promise.reject(r)}}}function T(){return(T=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var I=new n.ec("secp256k1");function C(r,e){void 0===e&&(e=!1);var t=f(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");var n={r:d(t.slice(0,32)),s:d(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function U(r){return r.publicKeyBase58?s(r.publicKeyBase58):r.publicKeyBase64?f(r.publicKeyBase64):r.publicKeyHex?l(r.publicKeyHex):new Uint8Array}function O(r,e,t){var n;if(e.length>86)n=[C(e,!0)];else{var i=C(e,!1);n=[T({},i,{recoveryParam:0}),T({},i,{recoveryParam:1})]}var o=n.map(function(e){var n=x(r),i=I.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=k(o);return t.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function B(r,e,t){var n=p(r),o=f(e),a=t.find(function(r){return i.verify(U(r),n,o)});if(!a)throw new Error("Signature invalid for JWT");return a}var N={ES256K:function(r,e,t){var n=x(r),i=C(e),o=t.filter(function(r){return void 0===r.ethereumAddress}),a=t.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=U(r);return I.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=O(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":O,Ed25519:B,EdDSA:B};function X(r){var e=N[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function V(r){return"object"==typeof r&&"r"in r&&"s"in r}function _(r){return function(e,t){try{return Promise.resolve(t(e)).then(function(e){if(V(e))return y(e,r);if(r&&void 0===g(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function q(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(V(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}X.toSignatureObject=C;var H={ES256K:_(),"ES256K-R":_(!0),Ed25519:q(),EdDSA:q()},z=function(r,e,t){void 0===t&&(t={});try{t.alg||(t.alg=F);var n="string"==typeof r?r:L(r),i=[L(t),n].join("."),o=function(r){var e=H[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(t.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},Z={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},F="ES256K";function L(r){return h(JSON.stringify(r))}function R(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(v(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function $(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=R(r);return Object.assign(e,{payload:JSON.parse(v(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function M(r,e){var t=r.header,n=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),X(t.alg)(n,i,e)}var G="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Q(r,e,t){if(!r.s){if(t instanceof Y){if(!t.s)return void(t.o=Q.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(Q.bind(null,r,e),Q.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var Y=function(){function r(){}return r.prototype.then=function(e,t){var n=new r,i=this.s;if(i){var o=1&i?e:t;if(o){try{Q(n,1,o(this.v))}catch(r){Q(n,2,r)}return n}return this}return this.o=function(r){try{var i=r.v;1&r.s?Q(n,1,e?e(i):i):t?Q(n,1,t(i)):Q(n,2,i)}catch(r){Q(n,2,r)}},n},r}();function rr(r){return r instanceof Y&&1&r.s}function er(r,e){var t=r.ciphertext,n=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:c(r.iv),ciphertext:c(t),tag:c(n)};return e&&(o.aad=c(e)),i&&(o.recipients=[i]),o}function tr(r){var e=new o.XChaCha20Poly1305(r);return function(r,t){var n=u.randomBytes(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}function nr(r){var e=tr(r),t="XC20P";return{alg:"dir",enc:t,encrypt:function(r,n,i){void 0===n&&(n={});try{var o=h(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?o+"."+c(i):o));return Promise.resolve(T({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function ir(r){var e=new o.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,t,n){try{return Promise.resolve(e.open(t,r,n))}catch(r){return Promise.reject(r)}}}}function or(r,e){var t=function(t){try{var u=a.generateKeyPair(),f=tr(j(a.sharedKey(u.secretKey,r),i,n))(t),s={encrypted_key:c(f.ciphertext),header:{alg:n,iv:c(f.iv),tag:c(f.tag),epk:{kty:"OKP",crv:o,x:c(u.publicKey)}}};return e&&(s.header.kid=e),Promise.resolve(s)}catch(r){return Promise.reject(r)}},n="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:n,enc:"XC20P",encrypt:function(r,e,n){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=u.randomBytes(32);return Promise.resolve(nr(i).encrypt(r,e,n)).then(function(r){return Promise.resolve(t(i)).then(function(e){return T({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:t}}exports.ES256KSigner=W,exports.EdDSASigner=D,exports.EllipticSigner=function(r){return W(r)},exports.NaclSigner=function(r){return D(r)},exports.SimpleSigner=function(r){var e=W(r,!0);return function(r){try{return Promise.resolve(e(r)).then(g)}catch(r){return Promise.reject(r)}}},exports.createJWE=function(r,e,t,n){void 0===t&&(t={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,t,n)).then(function(r){return er(r,n)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,t){if("function"==typeof r[G]){var n,i,o,a=r[G]();if(function r(t){try{for(;!(n=a.next()).done;)if((t=e(n.value))&&t.then){if(!rr(t))return void t.then(r,o||(o=Q.bind(null,i=new Y,2)));t=t.v}i?Q(i,1,t):i=t}catch(r){Q(i||(i=new Y),2,r)}}(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,i,o=-1;return function t(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!rr(a))return void a.then(t,i||(i=Q.bind(null,n=new Y,2)));a=a.v}n?Q(n,1,a):n=a}catch(r){Q(n||(n=new Y),2,r)}}(),n}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,t,n)).then(function(r){i=r.cek,o=er(r,n)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},exports.createJWS=z,exports.createJWT=function(r,e,t){var n=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===t&&(t={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!n)throw new Error("No issuing DID has been configured");t.typ||(t.typ="JWT"),t.alg||(t.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=T({},u,r,{iss:n});return z(c,i,t)}catch(r){return Promise.reject(r)}},exports.decodeJWT=$,exports.decryptJWE=function(r,e){try{var t=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var n=JSON.parse(v(r.protected));if(n.enc!==e.enc)throw new Error("Decrypter does not support: '"+n.enc+"'");var i=w(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===n.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,f(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var t=0;return function(r,e,t){for(var n;;){var i=r();if(rr(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!rr(o)){n=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!rr(a)){n=2;break}}}var u=new Y,c=Q.bind(null,u,2);return(0===n?i.then(s):1===n?o.then(f):a.then(l)).then(void 0,c),u;function f(n){o=n;do{if(e&&(a=e())&&a.then&&!rr(a))return void a.then(l).then(void 0,c);if(!(i=r())||rr(i)&&!i.v)return void Q(u,1,o);if(i.then)return void i.then(s).then(void 0,c);rr(o=t())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=t())&&o.then?o.then(f).then(void 0,c):f(o):Q(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):Q(u,1,o)}}(function(){return!a&&t<r.recipients.length},function(){return t++},function(){var u=r.recipients[t];Object.assign(u.header,n);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,f(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(r){return Promise.reject(r)}},exports.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var t;if(!e.keyAgreement)throw new Error("Could not find x25519 key for "+r);var n=(null==(t=e.keyAgreement)?void 0:t.map(function(r){return"string"==typeof r?e.publicKey.find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!n)throw new Error("Could not find x25519 key for "+r);return or(s(n.publicKeyBase58),n.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},exports.toEthereumAddress=k,exports.verifyJWS=function(r,e){return M(R(r),e)},exports.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var t=$(r),n=t.payload,i=t.header,o=t.signature,a=t.data;return Promise.resolve(function(r,e,t,n){try{var i=Z[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(t)).then(function(r){if(!r)throw new Error("Unable to resolve DID document for "+t);var o=function(r,e){var t=r.publicKey.filter(function(r){return e===r.id});return t.length>0?t[0]:null},a=r.publicKey||[];n&&(a=(r.authentication||[]).map(function(e){return"string"==typeof e?o(r,e):"string"==typeof e.publicKey?o(r,e.publicKey):e}).filter(function(r){return null!=r}));var u=a.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(n&&(!u||0===u.length))throw new Error("DID document for "+t+" does not have public keys suitable for authenticating user");if(!u||0===u.length)throw new Error("DID document for "+t+" does not have public keys for "+e);return{authenticators:u,issuer:t,doc:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,n.iss,e.auth)).then(function(t){var u=t.doc,c=t.issuer;return Promise.resolve(M({header:i,data:a,signature:o},t.authenticators)).then(function(t){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(t){var a=i+o;if(n.nbf){if(n.nbf>a)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=i-o)throw new Error("JWT has expired: exp: "+n.exp+" < now: "+i);if(n.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,doc:u,issuer:c,signer:t,jwt:r}}})})}catch(r){return Promise.reject(r)}},exports.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(t,n,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var u=f(o.header.epk.x),c=j(a.sharedKey(r,u),256,e),s=w(o.encrypted_key,o.header.tag);return Promise.resolve(ir(c).decrypt(s,f(o.header.iv))).then(function(r){return null===r?null:ir(r).decrypt(t,n,i)})}catch(r){return Promise.reject(r)}}}},exports.x25519Encrypter=or,exports.xc20pDirDecrypter=ir,exports.xc20pDirEncrypter=nr; | ||
var r=require("uint8arrays"),e=require("@stablelib/sha256"),t=require("js-sha3"),n=require("elliptic"),i=require("@stablelib/ed25519"),o=require("@stablelib/xchacha20poly1305"),a=require("@stablelib/x25519"),u=require("@stablelib/random");function c(e){return r.toString(e,"base64url")}function f(e){var t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r.fromString(t,"base64url")}function s(e){return r.fromString(e,"base58btc")}function l(e){var t=e.startsWith("0x")?e.substring(2):e;return r.fromString(t.toLowerCase(),"base16")}function h(e){return c(r.fromString(e))}function d(e){return r.toString(f(e))}function v(e){return r.toString(e,"base16")}function p(e){return r.fromString(e)}function y(e,t){var n=e.r,i=e.s,o=e.recoveryParam,a=new Uint8Array(t?65:64);if(a.set(r.fromString(n,"base16"),0),a.set(r.fromString(i,"base16"),32),t){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return c(a)}function g(r){var e=f(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:v(e.slice(0,32)),s:v(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function m(e,t){return r.concat([f(e),f(t)])}var w=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,b=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,E=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function P(r){if("string"==typeof r){if(w.test(r))return l(r);if(b.test(r))return s(r);if(E.test(r))return f(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function S(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function x(t){var n="string"==typeof t?r.fromString(t):t;return e.hash(n)}function k(e){var n,i=r.fromString(e.slice(2),"base16");return"0x"+r.toString((n=i,new Uint8Array(t.keccak_256.arrayBuffer(n))).slice(-20),"base16")}function K(e,t){void 0===t&&(t=new Uint8Array(4));var n=r.fromString(e.toString(),"base10");return t.set(n,4-n.length),t}var j=function(e){return r.concat([K(e.length),e])};function A(t,n,i){if(256!==n)throw new Error("Unsupported key length: "+n);var o=r.concat([j(r.fromString(i)),j(new Uint8Array(0)),j(new Uint8Array(0)),K(n)]);return e.hash(r.concat([K(1),t,o]))}var D=new n.ec("secp256k1");function J(r,e){void 0===e&&(e=!1);var t=P(r);if(32!==t.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+t.length);var n=D.keyFromPrivate(t);return function(r){try{var t=n.sign(x(r)),i=t.s,o=t.recoveryParam;return Promise.resolve(y({r:S(t.r.toString("hex")),s:S(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function W(r){var e=P(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var t="string"==typeof r?p(r):r,n=i.sign(e,t);return Promise.resolve(c(n))}catch(r){return Promise.reject(r)}}}function T(){return(T=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var C=new n.ec("secp256k1");function I(r,e){void 0===e&&(e=!1);var t=f(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");var n={r:v(t.slice(0,32)),s:v(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function U(r){return r.publicKeyBase58?s(r.publicKeyBase58):r.publicKeyBase64?f(r.publicKeyBase64):r.publicKeyHex?l(r.publicKeyHex):new Uint8Array}function O(r,e,t){var n;if(e.length>86)n=[I(e,!0)];else{var i=I(e,!1);n=[T({},i,{recoveryParam:0}),T({},i,{recoveryParam:1})]}var o=n.map(function(e){var n=x(r),i=C.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=k(o);return t.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function R(r,e,t){var n=p(r),o=f(e),a=t.find(function(r){return i.verify(U(r),n,o)});if(!a)throw new Error("Signature invalid for JWT");return a}var B={ES256K:function(r,e,t){var n=x(r),i=I(e),o=t.filter(function(r){return void 0===r.ethereumAddress}),a=t.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=U(r);return C.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=O(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":O,Ed25519:R,EdDSA:R};function N(r){var e=B[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function X(r){return"object"==typeof r&&"r"in r&&"s"in r}function V(r){return function(e,t){try{return Promise.resolve(t(e)).then(function(e){if(X(e))return y(e,r);if(r&&void 0===g(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function _(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(X(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}N.toSignatureObject=I;var q={ES256K:V(),"ES256K-R":V(!0),Ed25519:_(),EdDSA:_()},H=function(r,e,t){void 0===t&&(t={});try{t.alg||(t.alg=z);var n="string"==typeof r?r:Z(r),i=[Z(t),n].join("."),o=function(r){var e=q[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(t.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},M={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},z="ES256K";function Z(r){return h(JSON.stringify(r))}function F(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(d(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function L(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=F(r);return Object.assign(e,{payload:JSON.parse(d(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function $(r,e){var t=r.header,n=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),N(t.alg)(n,i,e)}var G="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Q(r,e,t){if(!r.s){if(t instanceof Y){if(!t.s)return void(t.o=Q.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(Q.bind(null,r,e),Q.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var Y=function(){function r(){}return r.prototype.then=function(e,t){var n=new r,i=this.s;if(i){var o=1&i?e:t;if(o){try{Q(n,1,o(this.v))}catch(r){Q(n,2,r)}return n}return this}return this.o=function(r){try{var i=r.v;1&r.s?Q(n,1,e?e(i):i):t?Q(n,1,t(i)):Q(n,2,i)}catch(r){Q(n,2,r)}},n},r}();function rr(r){return r instanceof Y&&1&r.s}function er(r,e){var t=r.ciphertext,n=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:c(r.iv),ciphertext:c(t),tag:c(n)};return e&&(o.aad=c(e)),i&&(o.recipients=[i]),o}function tr(r){var e=new o.XChaCha20Poly1305(r);return function(r,t){var n=u.randomBytes(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}function nr(r){var e=tr(r),t="XC20P";return{alg:"dir",enc:t,encrypt:function(r,n,i){void 0===n&&(n={});try{var o=h(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?o+"."+c(i):o));return Promise.resolve(T({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function ir(r){var e=new o.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,t,n){try{return Promise.resolve(e.open(t,r,n))}catch(r){return Promise.reject(r)}}}}function or(r,e){var t=function(t){try{var u=a.generateKeyPair(),f=tr(A(a.sharedKey(u.secretKey,r),i,n))(t),s={encrypted_key:c(f.ciphertext),header:{alg:n,iv:c(f.iv),tag:c(f.tag),epk:{kty:"OKP",crv:o,x:c(u.publicKey)}}};return e&&(s.header.kid=e),Promise.resolve(s)}catch(r){return Promise.reject(r)}},n="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:n,enc:"XC20P",encrypt:function(r,e,n){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=u.randomBytes(32);return Promise.resolve(nr(i).encrypt(r,e,n)).then(function(r){return Promise.resolve(t(i)).then(function(e){return T({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:t}}exports.ES256KSigner=J,exports.EdDSASigner=W,exports.EllipticSigner=function(r){return J(r)},exports.NaclSigner=function(r){return W(r)},exports.SimpleSigner=function(r){var e=J(r,!0);return function(r){try{return Promise.resolve(e(r)).then(g)}catch(r){return Promise.reject(r)}}},exports.createJWE=function(r,e,t,n){void 0===t&&(t={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,t,n)).then(function(r){return er(r,n)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,t){if("function"==typeof r[G]){var n,i,o,a=r[G]();if(function r(t){try{for(;!(n=a.next()).done;)if((t=e(n.value))&&t.then){if(!rr(t))return void t.then(r,o||(o=Q.bind(null,i=new Y,2)));t=t.v}i?Q(i,1,t):i=t}catch(r){Q(i||(i=new Y),2,r)}}(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,i,o=-1;return function t(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!rr(a))return void a.then(t,i||(i=Q.bind(null,n=new Y,2)));a=a.v}n?Q(n,1,a):n=a}catch(r){Q(n||(n=new Y),2,r)}}(),n}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,t,n)).then(function(r){i=r.cek,o=er(r,n)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},exports.createJWS=H,exports.createJWT=function(r,e,t){var n=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===t&&(t={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!n)throw new Error("No issuing DID has been configured");t.typ||(t.typ="JWT"),t.alg||(t.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=T({},u,r,{iss:n});return H(c,i,t)}catch(r){return Promise.reject(r)}},exports.decodeJWT=L,exports.decryptJWE=function(r,e){try{var t=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var n=JSON.parse(d(r.protected));if(n.enc!==e.enc)throw new Error("Decrypter does not support: '"+n.enc+"'");var i=m(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===n.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,f(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var t=0;return function(r,e,t){for(var n;;){var i=r();if(rr(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!rr(o)){n=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!rr(a)){n=2;break}}}var u=new Y,c=Q.bind(null,u,2);return(0===n?i.then(s):1===n?o.then(f):a.then(l)).then(void 0,c),u;function f(n){o=n;do{if(e&&(a=e())&&a.then&&!rr(a))return void a.then(l).then(void 0,c);if(!(i=r())||rr(i)&&!i.v)return void Q(u,1,o);if(i.then)return void i.then(s).then(void 0,c);rr(o=t())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=t())&&o.then?o.then(f).then(void 0,c):f(o):Q(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):Q(u,1,o)}}(function(){return!a&&t<r.recipients.length},function(){return t++},function(){var u=r.recipients[t];Object.assign(u.header,n);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,f(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(r){return Promise.reject(r)}},exports.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var t,n=e.didResolutionMetadata,i=e.didDocument;if(null!=n&&n.error)throw new Error("Could not find x25519 key for "+r+": "+n.error+", "+n.message);if(!i.keyAgreement)throw new Error("Could not find x25519 key for "+r);var o=(null==(t=i.keyAgreement)?void 0:t.map(function(r){return"string"==typeof r?[].concat(i.publicKey||[],i.verificationMethod||[]).find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!o)throw new Error("Could not find x25519 key for "+r);return or(s(o.publicKeyBase58),o.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},exports.toEthereumAddress=k,exports.verifyJWS=function(r,e){return $(F(r),e)},exports.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var t=L(r),n=t.payload,i=t.header,o=t.signature,a=t.data;return Promise.resolve(function(r,e,t,n){try{var i=M[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(t,{accept:"application/did+json"})).then(function(r){var o,a,u;if(null!=(o=r.didResolutionMetadata)&&o.error){var c=r.didResolutionMetadata;throw new Error("Unable to resolve DID document for "+t+": "+c.error+", "+(c.message||""))}var f=function(r,e){var t=r.filter(function(r){return e===r.id});return t.length>0?t[0]:null},s=[];r.didDocument.verificationMethod&&(a=s).push.apply(a,r.didDocument.verificationMethod),r.didDocument.publicKey&&(u=s).push.apply(u,r.didDocument.publicKey),n&&(s=(r.didDocument.authentication||[]).map(function(r){return"string"==typeof r?f(s,r):"string"==typeof r.publicKey?f(s,r.publicKey):r}).filter(function(r){return null!=r}));var l=s.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(n&&(!l||0===l.length))throw new Error("DID document for "+t+" does not have public keys suitable for authenticating user");if(!l||0===l.length)throw new Error("DID document for "+t+" does not have public keys for "+e);return{authenticators:l,issuer:t,didResolutionResult:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,n.iss,e.auth)).then(function(t){var u=t.didResolutionResult,c=t.issuer;return Promise.resolve($({header:i,data:a,signature:o},t.authenticators)).then(function(t){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(t){var a=i+o;if(n.nbf){if(n.nbf>a)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=i-o)throw new Error("JWT has expired: exp: "+n.exp+" < now: "+i);if(n.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,didResolutionResult:u,issuer:c,signer:t,jwt:r}}})})}catch(r){return Promise.reject(r)}},exports.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(t,n,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var u=f(o.header.epk.x),c=A(a.sharedKey(r,u),256,e),s=m(o.encrypted_key,o.header.tag);return Promise.resolve(ir(c).decrypt(s,f(o.header.iv))).then(function(r){return null===r?null:ir(r).decrypt(t,n,i)})}catch(r){return Promise.reject(r)}}}},exports.x25519Encrypter=or,exports.xc20pDirDecrypter=ir,exports.xc20pDirEncrypter=nr; | ||
//# sourceMappingURL=index.js.map |
@@ -1,2 +0,2 @@ | ||
import{toString as r,fromString as e,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as i}from"js-sha3";import{ec as o}from"elliptic";import{sign as a,verify as c}from"@stablelib/ed25519";import{XChaCha20Poly1305 as s}from"@stablelib/xchacha20poly1305";import{generateKeyPair as u,sharedKey as f}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function p(e){return r(e,"base64url")}function d(r){const t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e(t,"base64url")}function y(r){return e(r,"base58btc")}function h(r){const t=r.startsWith("0x")?r.substring(2):r;return e(t.toLowerCase(),"base16")}function g(r){return p(e(r))}function w(e){return r(d(e))}function b(e){return r(e,"base16")}function E(r){return e(r)}function v({r,s:t,recoveryParam:n},i){const o=new Uint8Array(i?65:64);if(o.set(e(r,"base16"),0),o.set(e(t,"base16"),32),i){if(void 0===n)throw new Error("Signer did not return a recoveryParam");o[64]=n}return p(o)}function m(r){const e=d(r);if(e.length<64||e.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${e.length}`);return{r:b(e.slice(0,32)),s:b(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function k(r,e){return t([d(r),d(e)])}const K=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,x=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function A(r){if("string"==typeof r){if(K.test(r))return h(r);if(S.test(r))return y(r);if(x.test(r))return d(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function $(r,e=64){return r.length===e?r:"0".repeat(e-r.length)+r}function P(r){const t="string"==typeof r?e(r):r;return n(t)}function J(t){const n=e(t.slice(2),"base16");return`0x${r((o=n,new Uint8Array(i.arrayBuffer(o))).slice(-20),"base16")}`;var o}function D(r,t=new Uint8Array(4)){const n=e(r.toString(),"base10");return t.set(n,4-n.length),t}const W=r=>t([D(r.length),r]);function I(r,i,o){if(256!==i)throw new Error(`Unsupported key length: ${i}`);const a=t([W(e(o)),W(new Uint8Array(0)),W(new Uint8Array(0)),D(i)]);return n(t([D(1),r,a]))}const T=new o("secp256k1");function U(r,e=!1){const t=A(r);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 r=>{const{r:t,s:i,recoveryParam:o}=n.sign(P(r));return v({r:$(t.toString("hex")),s:$(i.toString("hex")),recoveryParam:o},e)}}function C(r){const e=U(r,!0);return async r=>m(await e(r))}function O(r){return U(r)}function j(r){const e=A(r);if(64!==e.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${e.length}`);return async r=>{const t="string"==typeof r?E(r):r;return p(a(e,t))}}function N(r){return j(r)}function B(){return(B=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}const V=new o("secp256k1");function H(r,e=!1){const t=d(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");const n={r:b(t.slice(0,32)),s:b(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function X(r){return r.publicKeyBase58?y(r.publicKeyBase58):r.publicKeyBase64?d(r.publicKeyBase64):r.publicKeyHex?h(r.publicKeyHex):new Uint8Array}function _(r,e,t){let n;if(e.length>86)n=[H(e,!0)];else{const r=H(e,!1);n=[B({},r,{recoveryParam:0}),B({},r,{recoveryParam:1})]}const i=n.map(e=>{const n=P(r),i=V.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),c=J(o);return t.find(({publicKeyHex:r,ethereumAddress:e})=>r===o||r===a||e===c)}).filter(r=>null!=r);if(0===i.length)throw new Error("Signature invalid for JWT");return i[0]}function z(r,e,t){const n=E(r),i=d(e),o=t.find(r=>c(X(r),n,i));if(!o)throw new Error("Signature invalid for JWT");return o}const Z={ES256K:function(r,e,t){const n=P(r),i=H(e),o=t.filter(({ethereumAddress:r})=>void 0===r),a=t.filter(({ethereumAddress:r})=>void 0!==r);let c=o.find(r=>{try{const e=X(r);return V.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!c&&a.length>0&&(c=_(r,e,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":_,Ed25519:z,EdDSA:z};function F(r){const e=Z[r];if(!e)throw new Error(`Unsupported algorithm ${r}`);return e}function L(r){return"object"==typeof r&&"r"in r&&"s"in r}function R(r){return async function(e,t){const n=await t(e);if(L(n))return v(n,r);if(r&&void 0===m(n).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return n}}function M(){return async function(r,e){const t=await e(r);if(L(t))throw new Error("expected a signer function that returns a string instead of signature object");return t}}F.toSignatureObject=H;const q={ES256K:R(),"ES256K-R":R(!0),Ed25519:M(),EdDSA:M()},G={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function Q(r){return g(JSON.stringify(r))}function Y(r){const e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(w(e[1])),payload:e[2],signature:e[3],data:`${e[1]}.${e[2]}`};throw new Error("Incorrect format JWS")}function rr(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{const e=Y(r);return Object.assign(e,{payload:JSON.parse(w(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}async function er(r,e,t={}){t.alg||(t.alg="ES256K");const n="string"==typeof r?r:Q(r),i=[Q(t),n].join("."),o=function(r){const e=q[r];if(!e)throw new Error(`Unsupported algorithm ${r}`);return e}(t.alg);return[i,await o(i,e)].join(".")}async function tr(r,{issuer:e,signer:t,alg:n,expiresIn:i},o={}){if(!t)throw new Error("No Signer functionality has been configured");if(!e)throw new Error("No issuing DID has been configured");o.typ||(o.typ="JWT"),o.alg||(o.alg=n);const a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(i){if("number"!=typeof i)throw new Error("JWT expiresIn is not a number");a.exp=(r.nbf||a.iat)+Math.floor(i)}return er(B({},a,r,{iss:e}),t,o)}function nr({header:r,data:e,signature:t},n){return Array.isArray(n)||(n=[n]),F(r.alg)(e,t,n)}function ir(r,e){return nr(Y(r),e)}async function or(r,e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null}){if(!e.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:i,data:o}=rr(r),{doc:a,authenticators:c,issuer:s}=await async function(r,e,t,n){const i=G[e];if(!i||0===i.length)throw new Error(`No supported signature types for algorithm ${e}`);const o=await r.resolve(t);if(!o)throw new Error(`Unable to resolve DID document for ${t}`);const a=(r,e)=>{const t=r.publicKey.filter(({id:r})=>e===r);return t.length>0?t[0]:null};let c=o.publicKey||[];n&&(c=(o.authentication||[]).map(r=>"string"==typeof r?a(o,r):"string"==typeof r.publicKey?a(o,r.publicKey):r).filter(r=>null!=r));const s=c.filter(({type:r})=>i.find(e=>e===r));if(n&&(!s||0===s.length))throw new Error(`DID document for ${t} does not have public keys suitable for authenticating user`);if(!s||0===s.length)throw new Error(`DID document for ${t} does not have public keys for ${e}`);return{authenticators:s,issuer:t,doc:o}}(e.resolver,n.alg,t.iss,e.auth),u=await nr({header:n,data:o,signature:i},c),f=Math.floor(Date.now()/1e3),l=e.skewTime>=0?e.skewTime:300;if(u){const n=f+l;if(t.nbf){if(t.nbf>n)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>n)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=f-l)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${f}`);if(t.aud){if(!e.audience&&!e.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(r=>e.audience===r||e.callbackUrl===r))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,doc:a,issuer:s,signer:u,jwt:r}}}function ar({ciphertext:r,tag:e,iv:t,protectedHeader:n,recipient:i},o){const a={protected:n,iv:p(t),ciphertext:p(r),tag:p(e)};return o&&(a.aad=p(o)),i&&(a.recipients=[i]),a}async function cr(r,e,t={},n){if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return ar(await e[0].encrypt(r,t,n),n)}{const i=e[0].enc;if(!e.reduce((r,e)=>r&&e.enc===i,!0))throw new Error("Incompatible encrypters passed");let o,a;for(const i of e)if(o)a.recipients.push(await i.encryptCek(o));else{const e=await i.encrypt(r,t,n);o=e.cek,a=ar(e,n)}return a}}async function sr(r,e){!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(r=>{if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);const t=JSON.parse(w(r.protected));if(t.enc!==e.enc)throw new Error(`Decrypter does not support: '${t.enc}'`);const n=k(r.ciphertext,r.tag),i=new Uint8Array(Buffer.from(r.aad?`${r.protected}.${r.aad}`:r.protected));let o=null;if("dir"===t.alg&&"dir"===e.alg)o=await e.decrypt(n,d(r.iv),i);else{if(!r.recipients||0===r.recipients.length)throw new Error("Invalid JWE");for(let a=0;!o&&a<r.recipients.length;a++){const c=r.recipients[a];Object.assign(c.header,t),c.header.alg===e.alg&&(o=await e.decrypt(n,d(r.iv),i,c))}}if(null===o)throw new Error("Failed to decrypt");return o}function ur(r){const e=new s(r);return(r,t)=>{const n=l(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}function fr(r){const e=ur(r),t="XC20P";return{alg:"dir",enc:t,encrypt:async function(r,n={},i){const o=g(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?`${o}.${p(i)}`:o));return B({},e(r,a),{protectedHeader:o})}}}function lr(r){const e=new s(r);return{alg:"dir",enc:"XC20P",decrypt:async function(r,t,n){return e.open(t,r,n)}}}function pr(r,e){const t="ECDH-ES+XC20PKW";async function n(n){const i=u(),o=ur(I(f(i.secretKey,r),256,t))(n),a={encrypted_key:p(o.ciphertext),header:{alg:t,iv:p(o.iv),tag:p(o.tag),epk:{kty:"OKP",crv:"X25519",x:p(i.publicKey)}}};return e&&(a.header.kid=e),a}return{alg:t,enc:"XC20P",encrypt:async function(r,e={},t){Object.assign(e,{alg:void 0});const i=l(32);return B({},await fr(i).encrypt(r,e,t),{recipient:await n(i),cek:i})},encryptCek:n}}async function dr(r,e){return Promise.all(r.map(async r=>{var t;const n=await e.resolve(r);if(!n.keyAgreement)throw new Error(`Could not find x25519 key for ${r}`);const i=(null==(t=n.keyAgreement)?void 0:t.map(r=>"string"==typeof r?n.publicKey.find(e=>e.id===r):r)).find(r=>"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58));if(!i)throw new Error(`Could not find x25519 key for ${r}`);return pr(y(i.publicKeyBase58),i.id)}))}function yr(r){const e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:async function(t,n,i,o){if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return null;const a=d(o.header.epk.x),c=I(f(r,a),256,e),s=k(o.encrypted_key,o.header.tag),u=await lr(c).decrypt(s,d(o.header.iv));return null===u?null:lr(u).decrypt(t,n,i)}}}export{U as ES256KSigner,j as EdDSASigner,O as EllipticSigner,N as NaclSigner,C as SimpleSigner,cr as createJWE,er as createJWS,tr as createJWT,rr as decodeJWT,sr as decryptJWE,dr as resolveX25519Encrypters,J as toEthereumAddress,ir as verifyJWS,or as verifyJWT,yr as x25519Decrypter,pr as x25519Encrypter,lr as xc20pDirDecrypter,fr 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 i}from"js-sha3";import{ec as o}from"elliptic";import{sign as a,verify as c}from"@stablelib/ed25519";import{XChaCha20Poly1305 as s}from"@stablelib/xchacha20poly1305";import{generateKeyPair as u,sharedKey as f}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function d(r){return e(r,"base64url")}function p(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r(t,"base64url")}function y(e){return r(e,"base58btc")}function h(e){const t=e.startsWith("0x")?e.substring(2):e;return r(t.toLowerCase(),"base16")}function g(e){return d(r(e))}function w(r){return e(p(r))}function b(r){return e(r,"base16")}function E(e){return r(e)}function m({r:e,s:t,recoveryParam:n},i){const o=new Uint8Array(i?65:64);if(o.set(r(e,"base16"),0),o.set(r(t,"base16"),32),i){if(void 0===n)throw new Error("Signer did not return a recoveryParam");o[64]=n}return d(o)}function v(e){const r=p(e);if(r.length<64||r.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${r.length}`);return{r:b(r.slice(0,32)),s:b(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function k(e,r){return t([p(e),p(r)])}const K=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,x=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function $(e){if("string"==typeof e){if(K.test(e))return h(e);if(S.test(e))return y(e);if(x.test(e))return p(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function A(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function D(e){const t="string"==typeof e?r(e):e;return n(t)}function P(t){const n=r(t.slice(2),"base16");return`0x${e((o=n,new Uint8Array(i.arrayBuffer(o))).slice(-20),"base16")}`;var o}function J(e,t=new Uint8Array(4)){const n=r(e.toString(),"base10");return t.set(n,4-n.length),t}const W=e=>t([J(e.length),e]);function I(e,i,o){if(256!==i)throw new Error(`Unsupported key length: ${i}`);const a=t([W(r(o)),W(new Uint8Array(0)),W(new Uint8Array(0)),J(i)]);return n(t([J(1),e,a]))}const T=new o("secp256k1");function U(e,r=!1){const t=$(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=T.keyFromPrivate(t);return async e=>{const{r:t,s:i,recoveryParam:o}=n.sign(D(e));return m({r:A(t.toString("hex")),s:A(i.toString("hex")),recoveryParam:o},r)}}function C(e){const r=U(e,!0);return async e=>v(await r(e))}function j(e){return U(e)}function O(e){const r=$(e);if(64!==r.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${r.length}`);return async e=>{const t="string"==typeof e?E(e):e;return d(a(r,t))}}function R(e){return O(e)}function N(){return(N=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}const B=new o("secp256k1");function V(e,r=!1){const t=p(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:b(t.slice(0,32)),s:b(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function H(e){return e.publicKeyBase58?y(e.publicKeyBase58):e.publicKeyBase64?p(e.publicKeyBase64):e.publicKeyHex?h(e.publicKeyHex):new Uint8Array}function M(e,r,t){let n;if(r.length>86)n=[V(r,!0)];else{const e=V(r,!1);n=[N({},e,{recoveryParam:0}),N({},e,{recoveryParam:1})]}const i=n.map(r=>{const n=D(e),i=B.recoverPubKey(n,r,r.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),c=P(o);return t.find(({publicKeyHex:e,ethereumAddress:r})=>e===o||e===a||r===c)}).filter(e=>null!=e);if(0===i.length)throw new Error("Signature invalid for JWT");return i[0]}function X(e,r,t){const n=E(e),i=p(r),o=t.find(e=>c(H(e),n,i));if(!o)throw new Error("Signature invalid for JWT");return o}const _={ES256K:function(e,r,t){const n=D(e),i=V(r),o=t.filter(({ethereumAddress:e})=>void 0===e),a=t.filter(({ethereumAddress:e})=>void 0!==e);let c=o.find(e=>{try{const r=H(e);return B.keyFromPublic(r).verify(n,i)}catch(e){return!1}});if(!c&&a.length>0&&(c=M(e,r,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":M,Ed25519:X,EdDSA:X};function z(e){const r=_[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}function Z(e){return"object"==typeof e&&"r"in e&&"s"in e}function F(e){return async function(r,t){const n=await t(r);if(Z(n))return m(n,e);if(e&&void 0===v(n).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return n}}function L(){return async function(e,r){const t=await r(e);if(Z(t))throw new Error("expected a signer function that returns a string instead of signature object");return t}}z.toSignatureObject=V;const q={ES256K:F(),"ES256K-R":F(!0),Ed25519:L(),EdDSA:L()},G={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function Q(e){return g(JSON.stringify(e))}function Y(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(w(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function ee(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=Y(e);return Object.assign(r,{payload:JSON.parse(w(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}async function re(e,r,t={}){t.alg||(t.alg="ES256K");const n="string"==typeof e?e:Q(e),i=[Q(t),n].join("."),o=function(e){const r=q[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return[i,await o(i,r)].join(".")}async function te(e,{issuer:r,signer:t,alg:n,expiresIn:i},o={}){if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");o.typ||(o.typ="JWT"),o.alg||(o.alg=n);const a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(i){if("number"!=typeof i)throw new Error("JWT expiresIn is not a number");a.exp=(e.nbf||a.iat)+Math.floor(i)}return re(N({},a,e,{iss:r}),t,o)}function ne({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),z(e.alg)(r,t,n)}function ie(e,r){return ne(Y(e),r)}async function oe(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null}){if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:i,data:o}=ee(e),{didResolutionResult:a,authenticators:c,issuer:s}=await async function(e,r,t,n){var i;const o=G[r];if(!o||0===o.length)throw new Error(`No supported signature types for algorithm ${r}`);const a=await e.resolve(t,{accept:"application/did+json"});if(null!=(i=a.didResolutionMetadata)&&i.error){const{error:e,message:r}=a.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let s=[];a.didDocument.verificationMethod&&s.push(...a.didDocument.verificationMethod),a.didDocument.publicKey&&s.push(...a.didDocument.publicKey),n&&(s=(a.didDocument.authentication||[]).map(e=>"string"==typeof e?c(s,e):"string"==typeof e.publicKey?c(s,e.publicKey):e).filter(e=>null!=e));const u=s.filter(({type:e})=>o.find(r=>r===e));if(n&&(!u||0===u.length))throw new Error(`DID document for ${t} does not have public keys suitable for authenticating user`);if(!u||0===u.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:u,issuer:t,didResolutionResult:a}}(r.resolver,n.alg,t.iss,r.auth),u=await ne({header:n,data:o,signature:i},c),f=Math.floor(Date.now()/1e3),l=r.skewTime>=0?r.skewTime:300;if(u){const n=f+l;if(t.nbf){if(t.nbf>n)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>n)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=f-l)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${f}`);if(t.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,didResolutionResult:a,issuer:s,signer:u,jwt:e}}}function ae({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:i},o){const a={protected:n,iv:d(t),ciphertext:d(e),tag:d(r)};return o&&(a.aad=d(o)),i&&(a.recipients=[i]),a}async function ce(e,r,t={},n){if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return ae(await r[0].encrypt(e,t,n),n)}{const i=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===i,!0))throw new Error("Incompatible encrypters passed");let o,a;for(const i of r)if(o)a.recipients.push(await i.encryptCek(o));else{const r=await i.encrypt(e,t,n);o=r.cek,a=ae(r,n)}return a}}async function se(e,r){!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const t=JSON.parse(w(e.protected));if(t.enc!==r.enc)throw new Error(`Decrypter does not support: '${t.enc}'`);const n=k(e.ciphertext,e.tag),i=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let o=null;if("dir"===t.alg&&"dir"===r.alg)o=await r.decrypt(n,p(e.iv),i);else{if(!e.recipients||0===e.recipients.length)throw new Error("Invalid JWE");for(let a=0;!o&&a<e.recipients.length;a++){const c=e.recipients[a];Object.assign(c.header,t),c.header.alg===r.alg&&(o=await r.decrypt(n,p(e.iv),i,c))}}if(null===o)throw new Error("Failed to decrypt");return o}function ue(e){const r=new s(e);return(e,t)=>{const n=l(r.nonceLength),i=r.seal(n,e,t);return{ciphertext:i.subarray(0,i.length-r.tagLength),tag:i.subarray(i.length-r.tagLength),iv:n}}}function fe(e){const r=ue(e),t="XC20P";return{alg:"dir",enc:t,encrypt:async function(e,n={},i){const o=g(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?`${o}.${d(i)}`:o));return N({},r(e,a),{protectedHeader:o})}}}function le(e){const r=new s(e);return{alg:"dir",enc:"XC20P",decrypt:async function(e,t,n){return r.open(t,e,n)}}}function de(e,r){const t="ECDH-ES+XC20PKW";async function n(n){const i=u(),o=ue(I(f(i.secretKey,e),256,t))(n),a={encrypted_key:d(o.ciphertext),header:{alg:t,iv:d(o.iv),tag:d(o.tag),epk:{kty:"OKP",crv:"X25519",x:d(i.publicKey)}}};return r&&(a.header.kid=r),a}return{alg:t,enc:"XC20P",encrypt:async function(e,r={},t){Object.assign(r,{alg:void 0});const i=l(32);return N({},await fe(i).encrypt(e,r,t),{recipient:await n(i),cek:i})},encryptCek:n}}async function pe(e,r){return Promise.all(e.map(async e=>{var t;const{didResolutionMetadata:n,didDocument:i}=await r.resolve(e);if(null!=n&&n.error)throw new Error(`Could not find x25519 key for ${e}: ${n.error}, ${n.message}`);if(!i.keyAgreement)throw new Error(`Could not find x25519 key for ${e}`);const o=(null==(t=i.keyAgreement)?void 0:t.map(e=>"string"==typeof e?[...i.publicKey||[],...i.verificationMethod||[]].find(r=>r.id===e):e)).find(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!o)throw new Error(`Could not find x25519 key for ${e}`);return de(y(o.publicKeyBase58),o.id)}))}function ye(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:async function(t,n,i,o){if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return null;const a=p(o.header.epk.x),c=I(f(e,a),256,r),s=k(o.encrypted_key,o.header.tag),u=await le(c).decrypt(s,p(o.header.iv));return null===u?null:le(u).decrypt(t,n,i)}}}export{U as ES256KSigner,O as EdDSASigner,j as EllipticSigner,R as NaclSigner,C as SimpleSigner,ce as createJWE,re as createJWS,te as createJWT,ee as decodeJWT,se as decryptJWE,pe as resolveX25519Encrypters,P as toEthereumAddress,ie as verifyJWS,oe as verifyJWT,ye as x25519Decrypter,de as x25519Encrypter,le as xc20pDirDecrypter,fe as xc20pDirEncrypter}; | ||
//# sourceMappingURL=index.modern.js.map |
@@ -1,2 +0,2 @@ | ||
!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("uint8arrays"),require("@stablelib/sha256"),require("js-sha3"),require("elliptic"),require("@stablelib/ed25519"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","uint8arrays","@stablelib/sha256","js-sha3","elliptic","@stablelib/ed25519","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],e):e((r||self).didJwt={},r.uint8Arrays,r.sha256$1,r.jsSha3,r.elliptic,r.ed25519,r.xchacha20poly1305,r.x25519,r.random)}(this,function(r,e,n,t,i,o,a,u,c){function f(r){return e.toString(r,"base64url")}function s(r){var n=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e.fromString(n,"base64url")}function l(r){return e.fromString(r,"base58btc")}function h(r){var n=r.startsWith("0x")?r.substring(2):r;return e.fromString(n.toLowerCase(),"base16")}function d(r){return f(e.fromString(r))}function v(r){return e.toString(s(r))}function y(r){return e.toString(r,"base16")}function p(r){return e.fromString(r)}function g(r,n){var t=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(n?65:64);if(a.set(e.fromString(t,"base16"),0),a.set(e.fromString(i,"base16"),32),n){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return f(a)}function m(r){var e=s(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:y(e.slice(0,32)),s:y(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function w(r,n){return e.concat([s(r),s(n)])}var b=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,E=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,P=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function S(r){if("string"==typeof r){if(b.test(r))return h(r);if(E.test(r))return l(r);if(P.test(r))return s(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function k(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function x(r){var t="string"==typeof r?e.fromString(r):r;return n.hash(t)}function K(r){var n,i=e.fromString(r.slice(2),"base16");return"0x"+e.toString((n=i,new Uint8Array(t.keccak_256.arrayBuffer(n))).slice(-20),"base16")}function j(r,n){void 0===n&&(n=new Uint8Array(4));var t=e.fromString(r.toString(),"base10");return n.set(t,4-t.length),n}var A=function(r){return e.concat([j(r.length),r])};function J(r,t,i){if(256!==t)throw new Error("Unsupported key length: "+t);var o=e.concat([A(e.fromString(i)),A(new Uint8Array(0)),A(new Uint8Array(0)),j(t)]);return n.hash(e.concat([j(1),r,o]))}var W=new i.ec("secp256k1");function D(r,e){void 0===e&&(e=!1);var n=S(r);if(32!==n.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+n.length);var t=W.keyFromPrivate(n);return function(r){try{var n=t.sign(x(r)),i=n.s,o=n.recoveryParam;return Promise.resolve(g({r:k(n.r.toString("hex")),s:k(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function T(r){var e=S(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var n="string"==typeof r?p(r):r,t=o.sign(e,n);return Promise.resolve(f(t))}catch(r){return Promise.reject(r)}}}function I(){return(I=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(r[t]=n[t])}return r}).apply(this,arguments)}var C=new i.ec("secp256k1");function U(r,e){void 0===e&&(e=!1);var n=s(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:y(n.slice(0,32)),s:y(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function O(r){return r.publicKeyBase58?l(r.publicKeyBase58):r.publicKeyBase64?s(r.publicKeyBase64):r.publicKeyHex?h(r.publicKeyHex):new Uint8Array}function B(r,e,n){var t;if(e.length>86)t=[U(e,!0)];else{var i=U(e,!1);t=[I({},i,{recoveryParam:0}),I({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=x(r),i=C.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=K(o);return n.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function N(r,e,n){var t=p(r),i=s(e),a=n.find(function(r){return o.verify(O(r),t,i)});if(!a)throw new Error("Signature invalid for JWT");return a}var X={ES256K:function(r,e,n){var t=x(r),i=U(e),o=n.filter(function(r){return void 0===r.ethereumAddress}),a=n.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=O(r);return C.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=B(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":B,Ed25519:N,EdDSA:N};function V(r){var e=X[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function _(r){return"object"==typeof r&&"r"in r&&"s"in r}function q(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(_(e))return g(e,r);if(r&&void 0===m(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function H(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(_(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}V.toSignatureObject=U;var z={ES256K:q(),"ES256K-R":q(!0),Ed25519:H(),EdDSA:H()},Z=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=$);var t="string"==typeof r?r:L(r),i=[L(n),t].join("."),o=function(r){var e=z[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(n.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},F={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},$="ES256K";function L(r){return d(JSON.stringify(r))}function R(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(v(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function M(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=R(r);return Object.assign(e,{payload:JSON.parse(v(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function G(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),V(n.alg)(t,i,e)}var Q="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Y(r,e,n){if(!r.s){if(n instanceof rr){if(!n.s)return void(n.o=Y.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(Y.bind(null,r,e),Y.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var rr=function(){function r(){}return r.prototype.then=function(e,n){var t=new r,i=this.s;if(i){var o=1&i?e:n;if(o){try{Y(t,1,o(this.v))}catch(r){Y(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?Y(t,1,e?e(i):i):n?Y(t,1,n(i)):Y(t,2,i)}catch(r){Y(t,2,r)}},t},r}();function er(r){return r instanceof rr&&1&r.s}function nr(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:f(r.iv),ciphertext:f(n),tag:f(t)};return e&&(o.aad=f(e)),i&&(o.recipients=[i]),o}function tr(r){var e=new a.XChaCha20Poly1305(r);return function(r,n){var t=c.randomBytes(e.nonceLength),i=e.seal(t,r,n);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:t}}}function ir(r){var e=tr(r),n="XC20P";return{alg:"dir",enc:n,encrypt:function(r,t,i){void 0===t&&(t={});try{var o=d(JSON.stringify(Object.assign({alg:"dir"},t,{enc:n}))),a=new Uint8Array(Buffer.from(i?o+"."+f(i):o));return Promise.resolve(I({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function or(r){var e=new a.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,n,t){try{return Promise.resolve(e.open(n,r,t))}catch(r){return Promise.reject(r)}}}}function ar(r,e){var n=function(n){try{var a=u.generateKeyPair(),c=tr(J(u.sharedKey(a.secretKey,r),i,t))(n),s={encrypted_key:f(c.ciphertext),header:{alg:t,iv:f(c.iv),tag:f(c.tag),epk:{kty:"OKP",crv:o,x:f(a.publicKey)}}};return e&&(s.header.kid=e),Promise.resolve(s)}catch(r){return Promise.reject(r)}},t="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:t,enc:"XC20P",encrypt:function(r,e,t){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=c.randomBytes(32);return Promise.resolve(ir(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return I({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}r.ES256KSigner=D,r.EdDSASigner=T,r.EllipticSigner=function(r){return D(r)},r.NaclSigner=function(r){return T(r)},r.SimpleSigner=function(r){var e=D(r,!0);return function(r){try{return Promise.resolve(e(r)).then(m)}catch(r){return Promise.reject(r)}}},r.createJWE=function(r,e,n,t){void 0===n&&(n={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,n,t)).then(function(r){return nr(r,t)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,n){if("function"==typeof r[Q]){var t,i,o,a=r[Q]();if(function r(n){try{for(;!(t=a.next()).done;)if((n=e(t.value))&&n.then){if(!er(n))return void n.then(r,o||(o=Y.bind(null,i=new rr,2)));n=n.v}i?Y(i,1,n):i=n}catch(r){Y(i||(i=new rr),2,r)}}(),a.return){var u=function(r){try{t.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,n){var t,i,o=-1;return function n(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!er(a))return void a.then(n,i||(i=Y.bind(null,t=new rr,2)));a=a.v}t?Y(t,1,a):t=a}catch(r){Y(t||(t=new rr),2,r)}}(),t}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,n,t)).then(function(r){i=r.cek,o=nr(r,t)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},r.createJWS=Z,r.createJWT=function(r,e,n){var t=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===n&&(n={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!t)throw new Error("No issuing DID has been configured");n.typ||(n.typ="JWT"),n.alg||(n.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=I({},u,r,{iss:t});return Z(c,i,n)}catch(r){return Promise.reject(r)}},r.decodeJWT=M,r.decryptJWE=function(r,e){try{var n=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var t=JSON.parse(v(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=w(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===t.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,s(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var n=0;return function(r,e,n){for(var t;;){var i=r();if(er(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!er(o)){t=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!er(a)){t=2;break}}}var u=new rr,c=Y.bind(null,u,2);return(0===t?i.then(s):1===t?o.then(f):a.then(l)).then(void 0,c),u;function f(t){o=t;do{if(e&&(a=e())&&a.then&&!er(a))return void a.then(l).then(void 0,c);if(!(i=r())||er(i)&&!i.v)return void Y(u,1,o);if(i.then)return void i.then(s).then(void 0,c);er(o=n())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=n())&&o.then?o.then(f).then(void 0,c):f(o):Y(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):Y(u,1,o)}}(function(){return!a&&n<r.recipients.length},function(){return n++},function(){var u=r.recipients[n];Object.assign(u.header,t);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,s(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(n):n())}catch(r){return Promise.reject(r)}},r.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var n;if(!e.keyAgreement)throw new Error("Could not find x25519 key for "+r);var t=(null==(n=e.keyAgreement)?void 0:n.map(function(r){return"string"==typeof r?e.publicKey.find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!t)throw new Error("Could not find x25519 key for "+r);return ar(l(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},r.toEthereumAddress=K,r.verifyJWS=function(r,e){return G(R(r),e)},r.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var n=M(r),t=n.payload,i=n.header,o=n.signature,a=n.data;return Promise.resolve(function(r,e,n,t){try{var i=F[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(n)).then(function(r){if(!r)throw new Error("Unable to resolve DID document for "+n);var o=function(r,e){var n=r.publicKey.filter(function(r){return e===r.id});return n.length>0?n[0]:null},a=r.publicKey||[];t&&(a=(r.authentication||[]).map(function(e){return"string"==typeof e?o(r,e):"string"==typeof e.publicKey?o(r,e.publicKey):e}).filter(function(r){return null!=r}));var u=a.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(t&&(!u||0===u.length))throw new Error("DID document for "+n+" does not have public keys suitable for authenticating user");if(!u||0===u.length)throw new Error("DID document for "+n+" does not have public keys for "+e);return{authenticators:u,issuer:n,doc:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,t.iss,e.auth)).then(function(n){var u=n.doc,c=n.issuer;return Promise.resolve(G({header:i,data:a,signature:o},n.authenticators)).then(function(n){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(n){var a=i+o;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<=i-o)throw new Error("JWT has expired: exp: "+t.exp+" < now: "+i);if(t.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,doc:u,issuer:c,signer:n,jwt:r}}})})}catch(r){return Promise.reject(r)}},r.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(n,t,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var a=s(o.header.epk.x),c=J(u.sharedKey(r,a),256,e),f=w(o.encrypted_key,o.header.tag);return Promise.resolve(or(c).decrypt(f,s(o.header.iv))).then(function(r){return null===r?null:or(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}},r.x25519Encrypter=ar,r.xc20pDirDecrypter=or,r.xc20pDirEncrypter=ir}); | ||
!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("uint8arrays"),require("@stablelib/sha256"),require("js-sha3"),require("elliptic"),require("@stablelib/ed25519"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","uint8arrays","@stablelib/sha256","js-sha3","elliptic","@stablelib/ed25519","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],e):e((r||self).didJwt={},r.uint8Arrays,r.sha256$1,r.jsSha3,r.elliptic,r.ed25519,r.xchacha20poly1305,r.x25519,r.random)}(this,function(r,e,t,n,i,o,a,u,c){function f(r){return e.toString(r,"base64url")}function s(r){var t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e.fromString(t,"base64url")}function l(r){return e.fromString(r,"base58btc")}function h(r){var t=r.startsWith("0x")?r.substring(2):r;return e.fromString(t.toLowerCase(),"base16")}function d(r){return f(e.fromString(r))}function v(r){return e.toString(s(r))}function y(r){return e.toString(r,"base16")}function p(r){return e.fromString(r)}function g(r,t){var n=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(t?65:64);if(a.set(e.fromString(n,"base16"),0),a.set(e.fromString(i,"base16"),32),t){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return f(a)}function m(r){var e=s(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:y(e.slice(0,32)),s:y(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function w(r,t){return e.concat([s(r),s(t)])}var b=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,E=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,P=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function S(r){if("string"==typeof r){if(b.test(r))return h(r);if(E.test(r))return l(r);if(P.test(r))return s(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function k(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function x(r){var n="string"==typeof r?e.fromString(r):r;return t.hash(n)}function K(r){var t,i=e.fromString(r.slice(2),"base16");return"0x"+e.toString((t=i,new Uint8Array(n.keccak_256.arrayBuffer(t))).slice(-20),"base16")}function j(r,t){void 0===t&&(t=new Uint8Array(4));var n=e.fromString(r.toString(),"base10");return t.set(n,4-n.length),t}var A=function(r){return e.concat([j(r.length),r])};function D(r,n,i){if(256!==n)throw new Error("Unsupported key length: "+n);var o=e.concat([A(e.fromString(i)),A(new Uint8Array(0)),A(new Uint8Array(0)),j(n)]);return t.hash(e.concat([j(1),r,o]))}var J=new i.ec("secp256k1");function W(r,e){void 0===e&&(e=!1);var t=S(r);if(32!==t.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+t.length);var n=J.keyFromPrivate(t);return function(r){try{var t=n.sign(x(r)),i=t.s,o=t.recoveryParam;return Promise.resolve(g({r:k(t.r.toString("hex")),s:k(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function T(r){var e=S(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var t="string"==typeof r?p(r):r,n=o.sign(e,t);return Promise.resolve(f(n))}catch(r){return Promise.reject(r)}}}function C(){return(C=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var I=new i.ec("secp256k1");function U(r,e){void 0===e&&(e=!1);var t=s(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");var n={r:y(t.slice(0,32)),s:y(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function O(r){return r.publicKeyBase58?l(r.publicKeyBase58):r.publicKeyBase64?s(r.publicKeyBase64):r.publicKeyHex?h(r.publicKeyHex):new Uint8Array}function R(r,e,t){var n;if(e.length>86)n=[U(e,!0)];else{var i=U(e,!1);n=[C({},i,{recoveryParam:0}),C({},i,{recoveryParam:1})]}var o=n.map(function(e){var n=x(r),i=I.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=K(o);return t.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function B(r,e,t){var n=p(r),i=s(e),a=t.find(function(r){return o.verify(O(r),n,i)});if(!a)throw new Error("Signature invalid for JWT");return a}var N={ES256K:function(r,e,t){var n=x(r),i=U(e),o=t.filter(function(r){return void 0===r.ethereumAddress}),a=t.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=O(r);return I.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=R(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":R,Ed25519:B,EdDSA:B};function X(r){var e=N[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function V(r){return"object"==typeof r&&"r"in r&&"s"in r}function _(r){return function(e,t){try{return Promise.resolve(t(e)).then(function(e){if(V(e))return g(e,r);if(r&&void 0===m(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function q(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(V(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}X.toSignatureObject=U;var H={ES256K:_(),"ES256K-R":_(!0),Ed25519:q(),EdDSA:q()},M=function(r,e,t){void 0===t&&(t={});try{t.alg||(t.alg=Z);var n="string"==typeof r?r:F(r),i=[F(t),n].join("."),o=function(r){var e=H[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(t.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},z={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},Z="ES256K";function F(r){return d(JSON.stringify(r))}function $(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(v(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function L(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=$(r);return Object.assign(e,{payload:JSON.parse(v(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function G(r,e){var t=r.header,n=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),X(t.alg)(n,i,e)}var Q="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Y(r,e,t){if(!r.s){if(t instanceof rr){if(!t.s)return void(t.o=Y.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(Y.bind(null,r,e),Y.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var rr=function(){function r(){}return r.prototype.then=function(e,t){var n=new r,i=this.s;if(i){var o=1&i?e:t;if(o){try{Y(n,1,o(this.v))}catch(r){Y(n,2,r)}return n}return this}return this.o=function(r){try{var i=r.v;1&r.s?Y(n,1,e?e(i):i):t?Y(n,1,t(i)):Y(n,2,i)}catch(r){Y(n,2,r)}},n},r}();function er(r){return r instanceof rr&&1&r.s}function tr(r,e){var t=r.ciphertext,n=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:f(r.iv),ciphertext:f(t),tag:f(n)};return e&&(o.aad=f(e)),i&&(o.recipients=[i]),o}function nr(r){var e=new a.XChaCha20Poly1305(r);return function(r,t){var n=c.randomBytes(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}function ir(r){var e=nr(r),t="XC20P";return{alg:"dir",enc:t,encrypt:function(r,n,i){void 0===n&&(n={});try{var o=d(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?o+"."+f(i):o));return Promise.resolve(C({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function or(r){var e=new a.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,t,n){try{return Promise.resolve(e.open(t,r,n))}catch(r){return Promise.reject(r)}}}}function ar(r,e){var t=function(t){try{var a=u.generateKeyPair(),c=nr(D(u.sharedKey(a.secretKey,r),i,n))(t),s={encrypted_key:f(c.ciphertext),header:{alg:n,iv:f(c.iv),tag:f(c.tag),epk:{kty:"OKP",crv:o,x:f(a.publicKey)}}};return e&&(s.header.kid=e),Promise.resolve(s)}catch(r){return Promise.reject(r)}},n="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:n,enc:"XC20P",encrypt:function(r,e,n){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=c.randomBytes(32);return Promise.resolve(ir(i).encrypt(r,e,n)).then(function(r){return Promise.resolve(t(i)).then(function(e){return C({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:t}}r.ES256KSigner=W,r.EdDSASigner=T,r.EllipticSigner=function(r){return W(r)},r.NaclSigner=function(r){return T(r)},r.SimpleSigner=function(r){var e=W(r,!0);return function(r){try{return Promise.resolve(e(r)).then(m)}catch(r){return Promise.reject(r)}}},r.createJWE=function(r,e,t,n){void 0===t&&(t={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,t,n)).then(function(r){return tr(r,n)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,t){if("function"==typeof r[Q]){var n,i,o,a=r[Q]();if(function r(t){try{for(;!(n=a.next()).done;)if((t=e(n.value))&&t.then){if(!er(t))return void t.then(r,o||(o=Y.bind(null,i=new rr,2)));t=t.v}i?Y(i,1,t):i=t}catch(r){Y(i||(i=new rr),2,r)}}(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,i,o=-1;return function t(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!er(a))return void a.then(t,i||(i=Y.bind(null,n=new rr,2)));a=a.v}n?Y(n,1,a):n=a}catch(r){Y(n||(n=new rr),2,r)}}(),n}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,t,n)).then(function(r){i=r.cek,o=tr(r,n)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},r.createJWS=M,r.createJWT=function(r,e,t){var n=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===t&&(t={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!n)throw new Error("No issuing DID has been configured");t.typ||(t.typ="JWT"),t.alg||(t.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=C({},u,r,{iss:n});return M(c,i,t)}catch(r){return Promise.reject(r)}},r.decodeJWT=L,r.decryptJWE=function(r,e){try{var t=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var n=JSON.parse(v(r.protected));if(n.enc!==e.enc)throw new Error("Decrypter does not support: '"+n.enc+"'");var i=w(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===n.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,s(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var t=0;return function(r,e,t){for(var n;;){var i=r();if(er(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!er(o)){n=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!er(a)){n=2;break}}}var u=new rr,c=Y.bind(null,u,2);return(0===n?i.then(s):1===n?o.then(f):a.then(l)).then(void 0,c),u;function f(n){o=n;do{if(e&&(a=e())&&a.then&&!er(a))return void a.then(l).then(void 0,c);if(!(i=r())||er(i)&&!i.v)return void Y(u,1,o);if(i.then)return void i.then(s).then(void 0,c);er(o=t())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=t())&&o.then?o.then(f).then(void 0,c):f(o):Y(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):Y(u,1,o)}}(function(){return!a&&t<r.recipients.length},function(){return t++},function(){var u=r.recipients[t];Object.assign(u.header,n);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,s(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(r){return Promise.reject(r)}},r.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var t,n=e.didResolutionMetadata,i=e.didDocument;if(null!=n&&n.error)throw new Error("Could not find x25519 key for "+r+": "+n.error+", "+n.message);if(!i.keyAgreement)throw new Error("Could not find x25519 key for "+r);var o=(null==(t=i.keyAgreement)?void 0:t.map(function(r){return"string"==typeof r?[].concat(i.publicKey||[],i.verificationMethod||[]).find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!o)throw new Error("Could not find x25519 key for "+r);return ar(l(o.publicKeyBase58),o.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},r.toEthereumAddress=K,r.verifyJWS=function(r,e){return G($(r),e)},r.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var t=L(r),n=t.payload,i=t.header,o=t.signature,a=t.data;return Promise.resolve(function(r,e,t,n){try{var i=z[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(t,{accept:"application/did+json"})).then(function(r){var o,a,u;if(null!=(o=r.didResolutionMetadata)&&o.error){var c=r.didResolutionMetadata;throw new Error("Unable to resolve DID document for "+t+": "+c.error+", "+(c.message||""))}var f=function(r,e){var t=r.filter(function(r){return e===r.id});return t.length>0?t[0]:null},s=[];r.didDocument.verificationMethod&&(a=s).push.apply(a,r.didDocument.verificationMethod),r.didDocument.publicKey&&(u=s).push.apply(u,r.didDocument.publicKey),n&&(s=(r.didDocument.authentication||[]).map(function(r){return"string"==typeof r?f(s,r):"string"==typeof r.publicKey?f(s,r.publicKey):r}).filter(function(r){return null!=r}));var l=s.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(n&&(!l||0===l.length))throw new Error("DID document for "+t+" does not have public keys suitable for authenticating user");if(!l||0===l.length)throw new Error("DID document for "+t+" does not have public keys for "+e);return{authenticators:l,issuer:t,didResolutionResult:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,n.iss,e.auth)).then(function(t){var u=t.didResolutionResult,c=t.issuer;return Promise.resolve(G({header:i,data:a,signature:o},t.authenticators)).then(function(t){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(t){var a=i+o;if(n.nbf){if(n.nbf>a)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=i-o)throw new Error("JWT has expired: exp: "+n.exp+" < now: "+i);if(n.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,didResolutionResult:u,issuer:c,signer:t,jwt:r}}})})}catch(r){return Promise.reject(r)}},r.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(t,n,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var a=s(o.header.epk.x),c=D(u.sharedKey(r,a),256,e),f=w(o.encrypted_key,o.header.tag);return Promise.resolve(or(c).decrypt(f,s(o.header.iv))).then(function(r){return null===r?null:or(r).decrypt(t,n,i)})}catch(r){return Promise.reject(r)}}}},r.x25519Encrypter=ar,r.xc20pDirDecrypter=or,r.xc20pDirEncrypter=ir}); | ||
//# sourceMappingURL=index.umd.js.map |
import { EcdsaSignature } from './util'; | ||
import { DIDDocument, PublicKey } from 'did-resolver'; | ||
import type { Resolver, VerificationMethod, DIDResolutionResult } from 'did-resolver'; | ||
export declare type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string>; | ||
@@ -14,5 +14,2 @@ export declare type SignerAlgorithm = (payload: string, signer: Signer) => Promise<string>; | ||
} | ||
export interface Resolvable { | ||
resolve: (did: string) => Promise<DIDDocument | null>; | ||
} | ||
export interface JWTVerifyOptions { | ||
@@ -22,9 +19,9 @@ auth?: boolean; | ||
callbackUrl?: string; | ||
resolver?: Resolvable; | ||
resolver?: Resolver; | ||
skewTime?: number; | ||
} | ||
export interface DIDAuthenticator { | ||
authenticators: PublicKey[]; | ||
authenticators: VerificationMethod[]; | ||
issuer: string; | ||
doc: DIDDocument; | ||
didResolutionResult: DIDResolutionResult; | ||
} | ||
@@ -61,3 +58,3 @@ export interface JWTHeader { | ||
payload: any; | ||
doc: DIDDocument; | ||
didResolutionResult: DIDResolutionResult; | ||
issuer: string; | ||
@@ -123,6 +120,6 @@ signer: object; | ||
* @param {String} jws A JWS string to verify | ||
* @param {Array<PublicKey> | PublicKey} pubkeys The public keys used to verify the JWS | ||
* @return {PublicKey} The public key used to sign the JWS | ||
* @param {Array<VerificationMethod> | VerificationMethod} pubkeys The public keys used to verify the JWS | ||
* @return {VerificationMethod} The public key used to sign the JWS | ||
*/ | ||
export declare function verifyJWS(jws: string, pubkeys: PublicKey | PublicKey[]): PublicKey; | ||
export declare function verifyJWS(jws: string, pubkeys: VerificationMethod | VerificationMethod[]): VerificationMethod; | ||
/** | ||
@@ -166,3 +163,3 @@ * Verifies given JWT. If the JWT is valid, the promise returns an object including the JWT, the payload of the JWT, | ||
*/ | ||
export declare function resolveAuthenticator(resolver: Resolvable, alg: string, issuer: string, auth?: boolean): Promise<DIDAuthenticator>; | ||
export declare function resolveAuthenticator(resolver: Resolver, alg: string, issuer: string, auth?: boolean): Promise<DIDAuthenticator>; | ||
//# sourceMappingURL=JWT.d.ts.map |
@@ -1,8 +0,8 @@ | ||
import { PublicKey } from 'did-resolver'; | ||
import type { VerificationMethod } from 'did-resolver'; | ||
import { EcdsaSignature } from './util'; | ||
export declare function toSignatureObject(signature: string, recoverable?: boolean): EcdsaSignature; | ||
export declare function verifyES256K(data: string, signature: string, authenticators: PublicKey[]): PublicKey; | ||
export declare function verifyRecoverableES256K(data: string, signature: string, authenticators: PublicKey[]): PublicKey; | ||
export declare function verifyEd25519(data: string, signature: string, authenticators: PublicKey[]): PublicKey; | ||
declare type Verifier = (data: string, signature: string, authenticators: PublicKey[]) => PublicKey; | ||
export declare function verifyES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod; | ||
export declare function verifyRecoverableES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod; | ||
export declare function verifyEd25519(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod; | ||
declare type Verifier = (data: string, signature: string, authenticators: VerificationMethod[]) => VerificationMethod; | ||
declare function VerifierAlgorithm(alg: string): Verifier; | ||
@@ -9,0 +9,0 @@ declare namespace VerifierAlgorithm { |
{ | ||
"name": "did-jwt", | ||
"version": "4.9.0", | ||
"version": "5.0.0", | ||
"description": "Library for Signing and Verifying JWTs compatible uPort and DID standards", | ||
@@ -67,8 +67,8 @@ "main": "lib/index.js", | ||
"codecov": "3.8.1", | ||
"eslint": "7.18.0", | ||
"eslint": "7.21.0", | ||
"eslint-config-standard": "14.1.1", | ||
"eslint-plugin-import": "2.22.1", | ||
"eslint-plugin-jest": "24.1.3", | ||
"eslint-plugin-jest": "24.1.9", | ||
"eslint-plugin-node": "11.1.0", | ||
"eslint-plugin-promise": "4.2.1", | ||
"eslint-plugin-promise": "4.3.1", | ||
"eslint-plugin-standard": "4.1.0", | ||
@@ -83,6 +83,6 @@ "jest": "26.6.3", | ||
"regenerator-runtime": "0.13.7", | ||
"semantic-release": "17.3.7", | ||
"semantic-release": "17.4.1", | ||
"sinon": "9.2.4", | ||
"standard": "14.3.4", | ||
"ts-jest": "26.4.4", | ||
"ts-jest": "26.5.3", | ||
"tslint": "6.1.3", | ||
@@ -92,4 +92,4 @@ "tslint-config-prettier": "1.18.0", | ||
"tweetnacl": "1.0.3", | ||
"typescript": "4.1.3", | ||
"webpack": "4.44.2", | ||
"typescript": "4.2.3", | ||
"webpack": "4.46.0", | ||
"webpack-cli": "3.3.12" | ||
@@ -104,3 +104,3 @@ }, | ||
"@stablelib/xchacha20poly1305": "^1.0.0", | ||
"did-resolver": "^2.1.2", | ||
"did-resolver": "^3.0.1", | ||
"elliptic": "^6.5.3", | ||
@@ -107,0 +107,0 @@ "js-sha3": "^0.8.0", |
import VerifierAlgorithm from '../VerifierAlgorithm' | ||
import { verifyJWT } from '../JWT' | ||
import type { Resolver } from 'did-resolver' | ||
@@ -23,16 +24,20 @@ const edKey58 = { | ||
const resolver = { | ||
resolve: jest.fn().mockReturnValue({ | ||
'@context': 'https://w3id.org/did/v1', | ||
id: 'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM', | ||
publicKey: [ | ||
{ | ||
id: | ||
'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM#z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM', | ||
type: 'Ed25519VerificationKey2018', | ||
controller: 'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM', | ||
publicKeyBase58: 'A12q688RGRdqshXhL9TW8QXQaX9H82ejU9DnqztLaAgy' | ||
} | ||
] | ||
resolve: async () => ({ | ||
didResolutionMetadata: {}, | ||
didDocumentMetadata: {}, | ||
didDocument: { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: 'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM', | ||
publicKey: [ | ||
{ | ||
id: | ||
'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM#z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM', | ||
type: 'Ed25519VerificationKey2018', | ||
controller: 'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM', | ||
publicKeyBase58: 'A12q688RGRdqshXhL9TW8QXQaX9H82ejU9DnqztLaAgy' | ||
} | ||
] | ||
} | ||
}) | ||
} | ||
} as unknown as Resolver | ||
const jwt = | ||
@@ -39,0 +44,0 @@ 'eyJhbGciOiJFZERTQSJ9.eyJleHAiOjE3NjQ4Nzg5MDgsImlzcyI6ImRpZDprZXk6ejZNa29USHNnTk5yYnk4SnpDTlExaVJMeVc1UVE2UjhYdXU2QUE4aWdHck1WUFVNIiwibmJmIjoxNjA3MTEyNTA4LCJzdWIiOiJkaWQ6a2V5Ono2TWtvVEhzZ05OcmJ5OEp6Q05RMWlSTHlXNVFRNlI4WHV1NkFBOGlnR3JNVlBVTSIsInZjIjp7IkBjb250ZXh0IjpbImh0dHBzOi8vd3d3LnczLm9yZy8yMDE4L2NyZWRlbnRpYWxzL3YxIiwiaHR0cHM6Ly9pZGVudGl0eS5mb3VuZGF0aW9uLy53ZWxsLWtub3duL2RpZC1jb25maWd1cmF0aW9uL3YxIl0sImNyZWRlbnRpYWxTdWJqZWN0Ijp7ImlkIjoiZGlkOmtleTp6Nk1rb1RIc2dOTnJieThKekNOUTFpUkx5VzVRUTZSOFh1dTZBQThpZ0dyTVZQVU0iLCJvcmlnaW4iOiJpZGVudGl0eS5mb3VuZGF0aW9uIn0sImV4cGlyYXRpb25EYXRlIjoiMjAyNS0xMi0wNFQxNDowODoyOC0wNjowMCIsImlzc3VhbmNlRGF0ZSI6IjIwMjAtMTItMDRUMTQ6MDg6MjgtMDY6MDAiLCJpc3N1ZXIiOiJkaWQ6a2V5Ono2TWtvVEhzZ05OcmJ5OEp6Q05RMWlSTHlXNVFRNlI4WHV1NkFBOGlnR3JNVlBVTSIsInR5cGUiOlsiVmVyaWZpYWJsZUNyZWRlbnRpYWwiLCJEb21haW5MaW5rYWdlQ3JlZGVudGlhbCJdfX0.6ovgQ-T_rmYueviySqXhzMzgqJMAizOGUKAObQr2iikoRNsb8DHfna4rh1puwWqYwgT3QJVpzdO_xZARAYM9Dw' |
@@ -8,3 +8,3 @@ import { createJWT, verifyJWT, decodeJWT, createJWS, verifyJWS, resolveAuthenticator, NBF_SKEW } from '../JWT' | ||
import MockDate from 'mockdate' | ||
import { PublicKey } from 'did-resolver' | ||
import { VerificationMethod, Resolver } from 'did-resolver' | ||
@@ -26,37 +26,41 @@ const NOW = 1485321133 | ||
const didDoc = { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [ | ||
{ | ||
id: `${did}#keys-1`, | ||
type: 'Secp256k1VerificationKey2018', | ||
owner: did, | ||
publicKeyHex: publicKey | ||
} | ||
], | ||
authentication: [ | ||
{ | ||
type: 'Secp256k1SignatureAuthentication2018', | ||
publicKey: `${did}#keys-1` | ||
} | ||
] | ||
didDocument: { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [ | ||
{ | ||
id: `${did}#keys-1`, | ||
type: 'Secp256k1VerificationKey2018', | ||
owner: did, | ||
publicKeyHex: publicKey | ||
} | ||
], | ||
authentication: [ | ||
{ | ||
type: 'Secp256k1SignatureAuthentication2018', | ||
publicKey: `${did}#keys-1` | ||
} | ||
] | ||
} | ||
} | ||
const didDocDefault = { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [ | ||
{ | ||
id: `${did}#keys-1`, | ||
type: 'Secp256k1VerificationKey2018', | ||
owner: did, | ||
ethereumAddress: address | ||
} | ||
], | ||
authentication: [ | ||
{ | ||
type: 'Secp256k1SignatureAuthentication2018', | ||
publicKey: `${did}#keys-1` | ||
} | ||
] | ||
didDocument: { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [ | ||
{ | ||
id: `${did}#keys-1`, | ||
type: 'Secp256k1VerificationKey2018', | ||
owner: did, | ||
ethereumAddress: address | ||
} | ||
], | ||
authentication: [ | ||
{ | ||
type: 'Secp256k1SignatureAuthentication2018', | ||
publicKey: `${did}#keys-1` | ||
} | ||
] | ||
} | ||
} | ||
@@ -164,3 +168,3 @@ | ||
describe('verifyJWT()', () => { | ||
const resolver = { resolve: jest.fn().mockReturnValue(didDoc) } | ||
const resolver = { resolve: jest.fn().mockReturnValue(didDoc) } as unknown as Resolver | ||
@@ -176,4 +180,4 @@ describe('pregenerated JWT', () => { | ||
it('verifies the JWT and return correct profile', async () => { | ||
const { doc } = await verifyJWT(incomingJwt, { resolver }) | ||
return expect(doc).toEqual(didDoc) | ||
const { didResolutionResult: { didDocument } } = await verifyJWT(incomingJwt, { resolver }) | ||
return expect(didDocument).toEqual(didDoc.didDocument) | ||
}) | ||
@@ -186,7 +190,7 @@ it('verifies the JWT and return correct did for the iss', async () => { | ||
const { signer } = await verifyJWT(incomingJwt, { resolver }) | ||
return expect(signer).toEqual(didDoc.publicKey[0]) | ||
return expect(signer).toEqual(didDoc.didDocument.publicKey[0]) | ||
}) | ||
it('verifies the JWT requiring authentication and return correct signer', async () => { | ||
const { signer } = await verifyJWT(incomingJwt, { resolver, auth: true }) | ||
return expect(signer).toEqual(didDoc.publicKey[0]) | ||
return expect(signer).toEqual(didDoc.didDocument.publicKey[0]) | ||
}) | ||
@@ -269,3 +273,3 @@ }) | ||
it('handles ES256K algorithm with ethereum address - github #14', async () => { | ||
const ethResolver = { resolve: jest.fn().mockReturnValue(didDocDefault) } | ||
const ethResolver = { resolve: jest.fn().mockReturnValue(didDocDefault) } as unknown as Resolver | ||
const jwt = await createJWT({ hello: 'world' }, { issuer: aud, signer, alg: 'ES256K' }) | ||
@@ -369,3 +373,3 @@ const { payload } = await verifyJWT(jwt, { resolver: ethResolver }) | ||
const jws = await createJWS(payload, signer) | ||
expect(verifyJWS(jws, { publicKeyHex: publicKey } as PublicKey)) | ||
expect(verifyJWS(jws, { publicKeyHex: publicKey } as VerificationMethod)) | ||
}) | ||
@@ -376,3 +380,3 @@ | ||
const jws = await createJWS(encodedPayload, signer) | ||
expect(verifyJWS(jws, { publicKeyHex: publicKey } as PublicKey)) | ||
expect(verifyJWS(jws, { publicKeyHex: publicKey } as VerificationMethod)) | ||
}) | ||
@@ -382,3 +386,3 @@ | ||
const badJws = 'abrewguer.fjreoiwfoiew.foirheogu.reoguhwehrg' | ||
expect(() => verifyJWS(badJws, { publicKeyHex: publicKey } as PublicKey)).toThrow('Incorrect format JWS') | ||
expect(() => verifyJWS(badJws, { publicKeyHex: publicKey } as VerificationMethod)).toThrow('Incorrect format JWS') | ||
}) | ||
@@ -470,29 +474,39 @@ }) | ||
const singleKey = { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [ecKey1] | ||
didDocument: { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [ecKey1] | ||
}, | ||
} | ||
const multipleKeys = { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [ecKey1, ecKey2, ecKey3, encKey1, edKey, edKey2], | ||
authentication: [authKey1, authKey2, edAuthKey] | ||
didDocument: { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [ecKey1, ecKey2, ecKey3, encKey1, edKey, edKey2], | ||
authentication: [authKey1, authKey2, edAuthKey] | ||
}, | ||
} | ||
const multipleAuthTypes = { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [ecKey1, ecKey2, ecKey3, encKey1, edKey, edKey2, edKey6, ecKey7], | ||
authentication: [authKey1, authKey2, edAuthKey, `${did}#keys-auth6`, `${did}#keys-auth7`, edKey8] | ||
didDocument: { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [ecKey1, ecKey2, ecKey3, encKey1, edKey, edKey2, edKey6, ecKey7], | ||
authentication: [authKey1, authKey2, edAuthKey, `${did}#keys-auth6`, `${did}#keys-auth7`, edKey8] | ||
}, | ||
} | ||
const unsupportedFormat = { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [encKey1] | ||
didDocument: { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did, | ||
publicKey: [encKey1] | ||
}, | ||
} | ||
const noPublicKey = { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did | ||
didDocument: { | ||
'@context': 'https://w3id.org/did/v1', | ||
id: did | ||
}, | ||
} | ||
@@ -503,7 +517,7 @@ | ||
it('finds public key', async () => { | ||
const authenticators = await resolveAuthenticator({ resolve: jest.fn().mockReturnValue(singleKey) }, alg, did) | ||
const authenticators = await resolveAuthenticator({ resolve: jest.fn().mockReturnValue(singleKey) } as unknown as Resolver, alg, did) | ||
return expect(authenticators).toEqual({ | ||
authenticators: [ecKey1], | ||
issuer: did, | ||
doc: singleKey | ||
didResolutionResult: singleKey | ||
}) | ||
@@ -514,3 +528,3 @@ }) | ||
const authenticators = await resolveAuthenticator( | ||
{ resolve: jest.fn().mockReturnValue(multipleKeys) }, | ||
{ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown as Resolver, | ||
alg, | ||
@@ -522,3 +536,3 @@ did | ||
issuer: did, | ||
doc: multipleKeys | ||
didResolutionResult: multipleKeys | ||
}) | ||
@@ -529,3 +543,3 @@ }) | ||
const authenticators = await resolveAuthenticator( | ||
{ resolve: jest.fn().mockReturnValue(multipleKeys) }, | ||
{ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown as Resolver, | ||
alg, | ||
@@ -538,3 +552,3 @@ did, | ||
issuer: did, | ||
doc: multipleKeys | ||
didResolutionResult: multipleKeys | ||
}) | ||
@@ -545,3 +559,3 @@ }) | ||
const authenticators = await resolveAuthenticator( | ||
{ resolve: jest.fn().mockReturnValue(multipleAuthTypes) }, | ||
{ resolve: jest.fn().mockReturnValue(multipleAuthTypes) } as unknown as Resolver, | ||
alg, | ||
@@ -554,3 +568,3 @@ did, | ||
issuer: did, | ||
doc: multipleAuthTypes | ||
didResolutionResult: multipleAuthTypes | ||
}) | ||
@@ -561,3 +575,3 @@ }) | ||
return await expect( | ||
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(unsupportedFormat) }, alg, did) | ||
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(unsupportedFormat) } as unknown as Resolver, alg, did) | ||
).rejects.toEqual(new Error(`DID document for ${did} does not have public keys for ${alg}`)) | ||
@@ -571,3 +585,3 @@ }) | ||
const authenticators = await resolveAuthenticator( | ||
{ resolve: jest.fn().mockReturnValue(multipleKeys) }, | ||
{ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown as Resolver, | ||
alg, | ||
@@ -579,3 +593,3 @@ did | ||
issuer: did, | ||
doc: multipleKeys | ||
didResolutionResult: multipleKeys | ||
}) | ||
@@ -586,3 +600,3 @@ }) | ||
const authenticators = await resolveAuthenticator( | ||
{ resolve: jest.fn().mockReturnValue(multipleKeys) }, | ||
{ resolve: jest.fn().mockReturnValue(multipleKeys) } as unknown as Resolver, | ||
alg, | ||
@@ -595,3 +609,3 @@ did, | ||
issuer: did, | ||
doc: multipleKeys | ||
didResolutionResult: multipleKeys | ||
}) | ||
@@ -602,3 +616,3 @@ }) | ||
const authenticators = await resolveAuthenticator( | ||
{ resolve: jest.fn().mockReturnValue(multipleAuthTypes) }, | ||
{ resolve: jest.fn().mockReturnValue(multipleAuthTypes) } as unknown as Resolver, | ||
alg, | ||
@@ -611,3 +625,3 @@ did, | ||
issuer: did, | ||
doc: multipleAuthTypes | ||
didResolutionResult: multipleAuthTypes | ||
}) | ||
@@ -618,3 +632,3 @@ }) | ||
return await expect( | ||
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(unsupportedFormat) }, alg, did) | ||
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(unsupportedFormat) } as unknown as Resolver, alg, did) | ||
).rejects.toEqual(new Error(`DID document for ${did} does not have public keys for ${alg}`)) | ||
@@ -626,3 +640,3 @@ }) | ||
return await expect( | ||
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(singleKey) }, alg, did, true) | ||
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(singleKey) } as unknown as Resolver, alg, did, true) | ||
).rejects.toEqual( | ||
@@ -635,3 +649,3 @@ new Error(`DID document for ${did} does not have public keys suitable for authenticating user`) | ||
return await expect( | ||
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(noPublicKey) }, alg, did) | ||
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(noPublicKey) } as unknown as Resolver, alg, did) | ||
).rejects.toEqual(new Error(`DID document for ${did} does not have public keys for ${alg}`)) | ||
@@ -641,4 +655,7 @@ }) | ||
it('errors if no DID document exists', async () => { | ||
return await expect(resolveAuthenticator({ resolve: jest.fn().mockReturnValue(null) }, alg, did)).rejects.toEqual( | ||
new Error(`Unable to resolve DID document for ${did}`) | ||
return await expect(resolveAuthenticator({ resolve: jest.fn().mockReturnValue({ | ||
didResolutionMetadata: { error: 'notFound' }, | ||
didDocument: null | ||
}) } as unknown as Resolver, alg, did)).rejects.toEqual( | ||
new Error(`Unable to resolve DID document for ${did}: notFound, `) | ||
) | ||
@@ -649,3 +666,3 @@ }) | ||
return await expect( | ||
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(singleKey) }, 'ESBAD', did) | ||
resolveAuthenticator({ resolve: jest.fn().mockReturnValue(singleKey) } as unknown as Resolver, 'ESBAD', did) | ||
).rejects.toEqual(new Error('No supported signature types for algorithm ESBAD')) | ||
@@ -652,0 +669,0 @@ }) |
@@ -28,28 +28,32 @@ import { | ||
return { | ||
publicKey: [{ | ||
id: did1 + '#abc', | ||
type: 'X25519KeyAgreementKey2019', | ||
controller: did1, | ||
publicKeyBase58: u8a.toString(kp1.publicKey, 'base58btc') | ||
}], | ||
keyAgreement: [{ | ||
id: 'irrelevant key' | ||
}, | ||
did1 + '#abc' | ||
] | ||
didDocument: { | ||
verificationMethod: [{ | ||
id: did1 + '#abc', | ||
type: 'X25519KeyAgreementKey2019', | ||
controller: did1, | ||
publicKeyBase58: u8a.toString(kp1.publicKey, 'base58btc') | ||
}], | ||
keyAgreement: [{ | ||
id: 'irrelevant key' | ||
}, | ||
did1 + '#abc' | ||
] | ||
} | ||
} | ||
} else if (did === did2) { | ||
return { | ||
publicKey: [], | ||
keyAgreement: [{ | ||
id: did2 + '#abc', | ||
type: 'X25519KeyAgreementKey2019', | ||
controller: did2, | ||
publicKeyBase58: u8a.toString(kp2.publicKey, 'base58btc') | ||
}] | ||
didDocument: { | ||
verificationMethod: [], | ||
keyAgreement: [{ | ||
id: did2 + '#abc', | ||
type: 'X25519KeyAgreementKey2019', | ||
controller: did2, | ||
publicKeyBase58: u8a.toString(kp2.publicKey, 'base58btc') | ||
}] | ||
} | ||
} | ||
} else if (did === did3) { | ||
return { publicKey: [] } | ||
return { didResolutionMetadata: { error: 'notFound' }, didDocument: null } | ||
} else if (did === did4) { | ||
return { publicKey: [], keyAgreement: [{ type: 'wrong type' }] } | ||
return { didDocument: { publicKey: [], keyAgreement: [{ type: 'wrong type' }] } } | ||
} | ||
@@ -56,0 +60,0 @@ }) |
@@ -16,3 +16,2 @@ import SimpleSigner from './signers/SimpleSigner' | ||
JWTVerified, | ||
Resolvable | ||
} from './JWT' | ||
@@ -45,3 +44,2 @@ import { toEthereumAddress } from './Digest' | ||
JWTVerified, | ||
Resolvable | ||
} |
import VerifierAlgorithm from './VerifierAlgorithm' | ||
import SignerAlgorithm from './SignerAlgorithm' | ||
import { encodeBase64url, decodeBase64url, EcdsaSignature } from './util' | ||
import { DIDDocument, PublicKey, Authentication } from 'did-resolver' | ||
import type { Resolver, DIDDocument, VerificationMethod, DIDResolutionResult } from 'did-resolver' | ||
@@ -19,6 +19,2 @@ export type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string> | ||
export interface Resolvable { | ||
resolve: (did: string) => Promise<DIDDocument | null> | ||
} | ||
export interface JWTVerifyOptions { | ||
@@ -28,3 +24,3 @@ auth?: boolean | ||
callbackUrl?: string | ||
resolver?: Resolvable | ||
resolver?: Resolver | ||
skewTime?: number | ||
@@ -34,5 +30,5 @@ } | ||
export interface DIDAuthenticator { | ||
authenticators: PublicKey[] | ||
authenticators: VerificationMethod[] | ||
issuer: string | ||
doc: DIDDocument | ||
didResolutionResult: DIDResolutionResult | ||
} | ||
@@ -74,3 +70,3 @@ | ||
payload: any | ||
doc: DIDDocument | ||
didResolutionResult: DIDResolutionResult | ||
issuer: string | ||
@@ -102,2 +98,3 @@ signer: object | ||
const defaultAlg = 'ES256K' | ||
const DID_JSON = 'application/did+json' | ||
@@ -213,5 +210,5 @@ function encodeSection(data: any): string { | ||
function verifyJWSDecoded({ header, data, signature }: JWSDecoded, pubkeys: PublicKey | PublicKey[]): PublicKey { | ||
function verifyJWSDecoded({ header, data, signature }: JWSDecoded, pubkeys: VerificationMethod | VerificationMethod[]): VerificationMethod { | ||
if (!Array.isArray(pubkeys)) pubkeys = [pubkeys] | ||
const signer: PublicKey = VerifierAlgorithm(header.alg)(data, signature, pubkeys) | ||
const signer: VerificationMethod = VerifierAlgorithm(header.alg)(data, signature, pubkeys) | ||
return signer | ||
@@ -228,6 +225,6 @@ } | ||
* @param {String} jws A JWS string to verify | ||
* @param {Array<PublicKey> | PublicKey} pubkeys The public keys used to verify the JWS | ||
* @return {PublicKey} The public key used to sign the JWS | ||
* @param {Array<VerificationMethod> | VerificationMethod} pubkeys The public keys used to verify the JWS | ||
* @return {VerificationMethod} The public key used to sign the JWS | ||
*/ | ||
export function verifyJWS(jws: string, pubkeys: PublicKey | PublicKey[]): PublicKey { | ||
export function verifyJWS(jws: string, pubkeys: VerificationMethod | VerificationMethod[]): VerificationMethod { | ||
const jwsDecoded: JWSDecoded = decodeJWS(jws) | ||
@@ -270,3 +267,3 @@ return verifyJWSDecoded(jwsDecoded, pubkeys) | ||
const { payload, header, signature, data }: JWTDecoded = decodeJWT(jwt) | ||
const { doc, authenticators, issuer }: DIDAuthenticator = await resolveAuthenticator( | ||
const { didResolutionResult, authenticators, issuer }: DIDAuthenticator = await resolveAuthenticator( | ||
options.resolver, | ||
@@ -277,3 +274,3 @@ header.alg, | ||
) | ||
const signer: PublicKey = await verifyJWSDecoded({ header, data, signature } as JWSDecoded, authenticators) | ||
const signer: VerificationMethod = await verifyJWSDecoded({ header, data, signature } as JWSDecoded, authenticators) | ||
const now: number = Math.floor(Date.now() / 1000) | ||
@@ -304,3 +301,3 @@ const skewTime = options.skewTime >= 0 ? options.skewTime : NBF_SKEW | ||
} | ||
return { payload, doc, issuer, signer, jwt } | ||
return { payload, didResolutionResult, issuer, signer, jwt } | ||
} | ||
@@ -326,3 +323,3 @@ } | ||
export async function resolveAuthenticator( | ||
resolver: Resolvable, | ||
resolver: Resolver, | ||
alg: string, | ||
@@ -336,20 +333,26 @@ issuer: string, | ||
} | ||
const doc: DIDDocument = await resolver.resolve(issuer) | ||
if (!doc) throw new Error(`Unable to resolve DID document for ${issuer}`) | ||
const result: DIDResolutionResult = await resolver.resolve(issuer, { accept: DID_JSON }) | ||
if (result.didResolutionMetadata?.error) { | ||
const { error, message } = result.didResolutionMetadata | ||
throw new Error(`Unable to resolve DID document for ${issuer}: ${error}, ${message || ''}`) | ||
} | ||
const getPublicKeyById = (doc: DIDDocument, pubid: string): PublicKey | null => { | ||
const filtered = doc.publicKey.filter(({ id }) => pubid === id) | ||
const getPublicKeyById = (verificationMethods: VerificationMethod[], pubid: string): VerificationMethod | null => { | ||
const filtered = verificationMethods.filter(({ id }) => pubid === id) | ||
return filtered.length > 0 ? filtered[0] : null | ||
} | ||
let publicKeysToCheck: PublicKey[] = doc.publicKey || [] | ||
let publicKeysToCheck: VerificationMethod[] = [] | ||
if (result.didDocument.verificationMethod) publicKeysToCheck.push(...result.didDocument.verificationMethod) | ||
if (result.didDocument.publicKey) publicKeysToCheck.push(...result.didDocument.publicKey) | ||
if (auth) { | ||
publicKeysToCheck = (doc.authentication || []) | ||
publicKeysToCheck = (result.didDocument.authentication || []) | ||
.map((authEntry) => { | ||
if (typeof authEntry === 'string') { | ||
return getPublicKeyById(doc, authEntry) | ||
} else if (typeof (<Authentication>authEntry).publicKey === 'string') { | ||
return getPublicKeyById(doc, (<Authentication>authEntry).publicKey) | ||
return getPublicKeyById(publicKeysToCheck, authEntry) | ||
} else if (typeof (<any>authEntry).publicKey === 'string') { | ||
// this is a legacy format | ||
return getPublicKeyById(publicKeysToCheck, (<any>authEntry).publicKey) | ||
} else { | ||
return <PublicKey>authEntry | ||
return <VerificationMethod>authEntry | ||
} | ||
@@ -360,3 +363,3 @@ }) | ||
const authenticators: PublicKey[] = publicKeysToCheck.filter(({ type }) => | ||
const authenticators: VerificationMethod[] = publicKeysToCheck.filter(({ type }) => | ||
types.find((supported) => supported === type) | ||
@@ -371,3 +374,3 @@ ) | ||
} | ||
return { authenticators, issuer, doc } | ||
return { authenticators, issuer, didResolutionResult: result } | ||
} |
import { ec as EC } from 'elliptic' | ||
import { sha256, toEthereumAddress } from './Digest' | ||
import { verify } from '@stablelib/ed25519' | ||
import { PublicKey } from 'did-resolver' | ||
import type { VerificationMethod } from 'did-resolver' | ||
import { hexToBytes, base58ToBytes, base64ToBytes, bytesToHex, EcdsaSignature, stringToBytes } from './util' | ||
@@ -24,7 +24,11 @@ | ||
function extractPublicKeyBytes(pk: PublicKey): Uint8Array { | ||
interface LegacyVerificationMethod extends VerificationMethod { | ||
publicKeyBase64: string | ||
} | ||
function extractPublicKeyBytes(pk: VerificationMethod): Uint8Array { | ||
if (pk.publicKeyBase58) { | ||
return base58ToBytes(pk.publicKeyBase58) | ||
} else if (pk.publicKeyBase64) { | ||
return base64ToBytes(pk.publicKeyBase64) | ||
} else if ((<LegacyVerificationMethod>pk).publicKeyBase64) { | ||
return base64ToBytes((<LegacyVerificationMethod>pk).publicKeyBase64) | ||
} else if (pk.publicKeyHex) { | ||
@@ -36,3 +40,3 @@ return hexToBytes(pk.publicKeyHex) | ||
export function verifyES256K(data: string, signature: string, authenticators: PublicKey[]): PublicKey { | ||
export function verifyES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod { | ||
const hash: Uint8Array = sha256(data) | ||
@@ -47,3 +51,3 @@ const sigObj: EcdsaSignature = toSignatureObject(signature) | ||
let signer: PublicKey = fullPublicKeys.find((pk: PublicKey) => { | ||
let signer: VerificationMethod = fullPublicKeys.find((pk: VerificationMethod) => { | ||
try { | ||
@@ -65,3 +69,3 @@ const pubBytes = extractPublicKeyBytes(pk) | ||
export function verifyRecoverableES256K(data: string, signature: string, authenticators: PublicKey[]): PublicKey { | ||
export function verifyRecoverableES256K(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod { | ||
let signatures: EcdsaSignature[] | ||
@@ -78,3 +82,3 @@ if (signature.length > 86) { | ||
const checkSignatureAgainstSigner = (sigObj: EcdsaSignature): PublicKey => { | ||
const checkSignatureAgainstSigner = (sigObj: EcdsaSignature): VerificationMethod => { | ||
const hash: Uint8Array = sha256(data) | ||
@@ -86,3 +90,3 @@ const recoveredKey: any = secp256k1.recoverPubKey(hash, sigObj, sigObj.recoveryParam) | ||
const signer: PublicKey = authenticators.find( | ||
const signer: VerificationMethod = authenticators.find( | ||
({ publicKeyHex, ethereumAddress }) => | ||
@@ -97,3 +101,3 @@ publicKeyHex === recoveredPublicKeyHex || | ||
const signer: PublicKey[] = signatures.map(checkSignatureAgainstSigner).filter(key => key != null) | ||
const signer: VerificationMethod[] = signatures.map(checkSignatureAgainstSigner).filter(key => key != null) | ||
@@ -104,6 +108,6 @@ if (signer.length === 0) throw new Error('Signature invalid for JWT') | ||
export function verifyEd25519(data: string, signature: string, authenticators: PublicKey[]): PublicKey { | ||
export function verifyEd25519(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod { | ||
const clear: Uint8Array = stringToBytes(data) | ||
const sig: Uint8Array = base64ToBytes(signature) | ||
const signer: PublicKey = authenticators.find((pk: PublicKey) => { | ||
const signer: VerificationMethod = authenticators.find((pk: VerificationMethod) => { | ||
return verify(extractPublicKeyBytes(pk), clear, sig) | ||
@@ -116,3 +120,3 @@ } | ||
type Verifier = (data: string, signature: string, authenticators: PublicKey[]) => PublicKey | ||
type Verifier = (data: string, signature: string, authenticators: VerificationMethod[]) => VerificationMethod | ||
interface Algorithms { | ||
@@ -119,0 +123,0 @@ [name: string]: Verifier |
@@ -7,3 +7,3 @@ import { XChaCha20Poly1305 } from '@stablelib/xchacha20poly1305' | ||
import { Recipient, EncryptionResult, Encrypter, Decrypter } from './JWE' | ||
import type { PublicKey, Resolver } from 'did-resolver' | ||
import type { VerificationMethod, Resolver } from 'did-resolver' | ||
@@ -85,7 +85,13 @@ function xc20pEncrypter(key: Uint8Array): (cleartext: Uint8Array, aad?: Uint8Array) => EncryptionResult { | ||
dids.map(async (did) => { | ||
const didDoc = await resolver.resolve(did) | ||
if (!didDoc.keyAgreement) throw new Error(`Could not find x25519 key for ${did}`) | ||
const agreementKeys: PublicKey[] = didDoc.keyAgreement?.map((key) => { | ||
const { didResolutionMetadata, didDocument } = await resolver.resolve(did) | ||
if (didResolutionMetadata?.error) { | ||
throw new Error(`Could not find x25519 key for ${did}: ${didResolutionMetadata.error}, ${didResolutionMetadata.message}`) | ||
} | ||
if (!didDocument.keyAgreement) throw new Error(`Could not find x25519 key for ${did}`) | ||
const agreementKeys: VerificationMethod[] = didDocument.keyAgreement?.map((key) => { | ||
if (typeof key === 'string') { | ||
return didDoc.publicKey.find((pk) => pk.id === key) | ||
return [ | ||
...(didDocument.publicKey || []), | ||
...(didDocument.verificationMethod || []) | ||
].find((pk) => pk.id === key) | ||
} | ||
@@ -92,0 +98,0 @@ return key |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
979629
4449
146
4
4
4
+ Addeddid-resolver@3.2.2(transitive)
- Removeddid-resolver@2.2.0(transitive)
Updateddid-resolver@^3.0.1