Comparing version 4.7.1 to 4.8.0
@@ -0,1 +1,8 @@ | ||
# [4.8.0](https://github.com/decentralized-identity/did-jwt/compare/4.7.1...4.8.0) (2020-12-09) | ||
### Features | ||
* **did auth:** update resolution of authentication entries in DIDDocument ([#143](https://github.com/decentralized-identity/did-jwt/issues/143)) ([a10ca34](https://github.com/decentralized-identity/did-jwt/commit/a10ca34ddea10019b09f71e81e83ad5e6696ac8d)) | ||
## [4.7.1](https://github.com/decentralized-identity/did-jwt/compare/4.7.0...4.7.1) (2020-12-08) | ||
@@ -2,0 +9,0 @@ |
@@ -1,2 +0,2 @@ | ||
import{ec as r}from"elliptic";import{hash as e}from"@stablelib/sha256";import{fromString as n,toString as t,concat as i}from"uint8arrays";import{keccak_256 as o}from"js-sha3";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(r){return e(n(r))}function v(r){var e,i=n(r.slice(2),"base16");return"0x"+t((e=i,new Uint8Array(o.arrayBuffer(e))).slice(-20),"base16")}function d(r,e){void 0===e&&(e=new Uint8Array(4));var t=n(r.toString(),"base10");return e.set(t,4-t.length),e}var p=function(r){return i([d(r.length),r])};function y(r,t,o){if(256!==t)throw new Error("Unsupported key length: "+t);var a=i([p(n(o)),p(new Uint8Array(0)),p(new Uint8Array(0)),d(t)]);return e(i([d(1),r,a]))}var g=new r("secp256k1");function m(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function w(r){r.startsWith("0x")&&(r=r.substring(2));var e=g.keyFromPrivate(r);return function(r){try{var n=e.sign(h(r)),t=n.s,i=n.recoveryParam;return Promise.resolve({r:m(n.r.toString("hex")),s:m(t.toString("hex")),recoveryParam:i})}catch(r){return Promise.reject(r)}}}function b(r){return t(r,"base64url")}function E(r){return n(r,"base64url")}function P(r){return n(r,"base64pad")}function S(r){return n(r,"base58btc")}function k(r){return b(n(r))}function K(r){return t(E(r))}function x(r){return t(r,"base16")}function j(r){return n(r)}function A(r,e){var t=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(e?65:64);if(a.set(n(t,"base16"),0),a.set(n(i,"base16"),32),e){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return b(a)}function J(r,e){return i([E(r),E(e)])}function D(r){var e=w(r);return function(r){try{return Promise.resolve(e(r)).then(function(r){return A(r)})}catch(r){return Promise.reject(r)}}}function W(r){var e=P(r);return function(r){try{var n=j(r),t=b(a(e,n));return Promise.resolve(t)}catch(r){return Promise.reject(r)}}}function T(){return(T=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 O=new r("secp256k1");function I(r,e){void 0===e&&(e=!1);var n=E(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:x(n.slice(0,32)),s:x(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function U(r){return r.publicKeyBase58?S(r.publicKeyBase58):r.publicKeyBase64?P(r.publicKeyBase64):r.publicKeyHex?n(r.publicKeyHex,"base16"):new Uint8Array}function C(r,e,n){var t;if(e.length>86)t=[I(e,!0)];else{var i=I(e,!1);t=[T({},i,{recoveryParam:0}),T({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=h(r),i=O.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=v(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 B(r,e,n){var t=j(r),i=E(e),o=n.find(function(r){return u(U(r),t,i)});if(!o)throw new Error("Signature invalid for JWT");return o}var V={ES256K:function(r,e,n){var t=h(r),i=I(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=U(r);return O.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=C(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":C,Ed25519:B,EdDSA:B};function X(r){var e=V[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function N(r){return"object"==typeof r&&"r"in r&&"s"in r}function H(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(N(e))return A(e,r);if(r)throw new Error("ES256K-R not supported when signer function returns string");return e})}catch(r){return Promise.reject(r)}}}function _(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(N(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=I;var R={ES256K:H(),"ES256K-R":H(!0),Ed25519:_(),EdDSA:_()},z=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=Q(r),t=n.payload,i=n.header,o=n.signature,a=n.data;return Promise.resolve(function(r,e,n,t){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(n)).then(function(r){if(!r)throw new Error("Unable to resolve DID document for "+n);var o=!t||(r.authentication||[]).map(function(r){return r.publicKey}),a=(r.publicKey||[]).filter(function(r){var e=r.type,n=r.id;return i.find(function(r){return r===e&&(!t||Array.isArray(o)&&o.indexOf(n)>=0)})});if(t&&(!a||0===a.length))throw new Error("DID document for "+n+" does not have public keys suitable for authenticationg user");if(!a||0===a.length)throw new Error("DID document for "+n+" does not have public keys for "+e);return{authenticators:a,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(Y({header:i,data:a,signature:o},n.authenticators)).then(function(n){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:$;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)}},F=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=T({},u,r,{iss:t});return L(c,i,n)}catch(r){return Promise.reject(r)}},L=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=Z);var t="string"==typeof r?r:q(r),i=[q(n),t].join("."),o=function(r){var e=R[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)}},M={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},Z="ES256K";function q(r){return k(JSON.stringify(r))}var $=300;function G(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(K(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function Q(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=G(r);return Object.assign(e,{payload:JSON.parse(K(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function Y(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),X(n.alg)(t,i,e)}function rr(r,e){return Y(G(r),e)}var er=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(K(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=J(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,E(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(or(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!or(o)){t=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!or(a)){t=2;break}}}var u=new ir,c=tr.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&&!or(a))return void a.then(l).then(void 0,c);if(!(i=r())||or(i)&&!i.v)return void tr(u,1,o);if(i.then)return void i.then(s).then(void 0,c);or(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):tr(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):tr(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,E(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)}},nr="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function tr(r,e,n){if(!r.s){if(n instanceof ir){if(!n.s)return void(n.o=tr.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(tr.bind(null,r,e),tr.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var ir=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{tr(t,1,o(this.v))}catch(r){tr(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?tr(t,1,e?e(i):i):n?tr(t,1,n(i)):tr(t,2,i)}catch(r){tr(t,2,r)}},t},r}();function or(r){return r instanceof ir&&1&r.s}function ar(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:b(r.iv),ciphertext:b(n),tag:b(t)};return e&&(o.aad=b(e)),i&&(o.recipients=[i]),o}var ur=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 ar(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[nr]){var t,i,o,a=r[nr]();if(function r(n){try{for(;!(t=a.next()).done;)if((n=e(t.value))&&n.then){if(!or(n))return void n.then(r,o||(o=tr.bind(null,i=new ir,2)));n=n.v}i?tr(i,1,n):i=n}catch(r){tr(i||(i=new ir),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(!or(a))return void a.then(n,i||(i=tr.bind(null,t=new ir,2)));a=a.v}t?tr(t,1,a):t=a}catch(r){tr(t||(t=new ir),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=ar(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 cr(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 fr=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 hr(S(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}};function sr(r){var e=cr(r);return{alg:"dir",enc:"XC20P",encrypt:function(r,n,t){void 0===n&&(n={});try{var i=k(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?i+"."+b(t):i));return Promise.resolve(T({},e(r,o),{protectedHeader:i}))}catch(r){return Promise.reject(r)}}}}function lr(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 hr(r,e){var n=function(n){try{var a=f(),u=cr(y(s(a.secretKey,r),i,t))(n),c={encrypted_key:b(u.ciphertext),header:{alg:t,iv:b(u.iv),tag:b(u.tag),epk:{kty:"OKP",crv:o,x:b(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(sr(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return T({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}function vr(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=E(o.header.epk.x),u=y(s(r,a),256,e),c=J(o.encrypted_key,o.header.tag);return Promise.resolve(lr(u).decrypt(c,E(o.header.iv))).then(function(r){return null===r?null:lr(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}}export{D as EllipticSigner,W as NaclSigner,w as SimpleSigner,ur as createJWE,L as createJWS,F as createJWT,Q as decodeJWT,er as decryptJWE,fr as resolveX25519Encrypters,v as toEthereumAddress,rr as verifyJWS,z as verifyJWT,vr as x25519Decrypter,hr as x25519Encrypter,lr as xc20pDirDecrypter,sr as xc20pDirEncrypter}; | ||
import{ec as r}from"elliptic";import{hash as e}from"@stablelib/sha256";import{fromString as n,toString as t,concat as i}from"uint8arrays";import{keccak_256 as o}from"js-sha3";import{sign as u,verify as a}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(r){return e(n(r))}function v(r){var e,i=n(r.slice(2),"base16");return"0x"+t((e=i,new Uint8Array(o.arrayBuffer(e))).slice(-20),"base16")}function d(r,e){void 0===e&&(e=new Uint8Array(4));var t=n(r.toString(),"base10");return e.set(t,4-t.length),e}var p=function(r){return i([d(r.length),r])};function y(r,t,o){if(256!==t)throw new Error("Unsupported key length: "+t);var u=i([p(n(o)),p(new Uint8Array(0)),p(new Uint8Array(0)),d(t)]);return e(i([d(1),r,u]))}var g=new r("secp256k1");function m(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function w(r){r.startsWith("0x")&&(r=r.substring(2));var e=g.keyFromPrivate(r);return function(r){try{var n=e.sign(h(r)),t=n.s,i=n.recoveryParam;return Promise.resolve({r:m(n.r.toString("hex")),s:m(t.toString("hex")),recoveryParam:i})}catch(r){return Promise.reject(r)}}}function b(r){return t(r,"base64url")}function E(r){return n(r,"base64url")}function P(r){return n(r,"base64pad")}function S(r){return n(r,"base58btc")}function k(r){return b(n(r))}function K(r){return t(E(r))}function x(r){return t(r,"base16")}function j(r){return n(r)}function A(r,e){var t=r.r,i=r.s,o=r.recoveryParam,u=new Uint8Array(e?65:64);if(u.set(n(t,"base16"),0),u.set(n(i,"base16"),32),e){if(void 0===o)throw new Error("Signer did not return a recoveryParam");u[64]=o}return b(u)}function J(r,e){return i([E(r),E(e)])}function D(r){var e=w(r);return function(r){try{return Promise.resolve(e(r)).then(function(r){return A(r)})}catch(r){return Promise.reject(r)}}}function W(r){var e=P(r);return function(r){try{var n=j(r),t=b(u(e,n));return Promise.resolve(t)}catch(r){return Promise.reject(r)}}}function T(){return(T=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 I=new r("secp256k1");function O(r,e){void 0===e&&(e=!1);var n=E(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:x(n.slice(0,32)),s:x(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function U(r){return r.publicKeyBase58?S(r.publicKeyBase58):r.publicKeyBase64?P(r.publicKeyBase64):r.publicKeyHex?n(r.publicKeyHex,"base16"):new Uint8Array}function C(r,e,n){var t;if(e.length>86)t=[O(e,!0)];else{var i=O(e,!1);t=[T({},i,{recoveryParam:0}),T({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=h(r),i=I.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),u=i.encode("hex",!0),a=v(o);return n.find(function(r){var e=r.publicKeyHex;return e===o||e===u||r.ethereumAddress===a})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function B(r,e,n){var t=j(r),i=E(e),o=n.find(function(r){return a(U(r),t,i)});if(!o)throw new Error("Signature invalid for JWT");return o}var V={ES256K:function(r,e,n){var t=h(r),i=O(e),o=n.filter(function(r){return void 0===r.ethereumAddress}),u=n.filter(function(r){return void 0!==r.ethereumAddress}),a=o.find(function(r){try{var e=U(r);return I.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!a&&u.length>0&&(a=C(r,e,u)),!a)throw new Error("Signature invalid for JWT");return a},"ES256K-R":C,Ed25519:B,EdDSA:B};function X(r){var e=V[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function N(r){return"object"==typeof r&&"r"in r&&"s"in r}function H(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(N(e))return A(e,r);if(r)throw new Error("ES256K-R not supported when signer function returns string");return e})}catch(r){return Promise.reject(r)}}}function _(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(N(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=O;var R={ES256K:H(),"ES256K-R":H(!0),Ed25519:_(),EdDSA:_()},z=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=Q(r),t=n.payload,i=n.header,o=n.signature,u=n.data;return Promise.resolve(function(r,e,n,t){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(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},u=r.publicKey||[];t&&(u=(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 a=u.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(t&&(!a||0===a.length))throw new Error("DID document for "+n+" does not have public keys suitable for authenticating user");if(!a||0===a.length)throw new Error("DID document for "+n+" does not have public keys for "+e);return{authenticators:a,issuer:n,doc:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,t.iss,e.auth)).then(function(n){var a=n.doc,c=n.issuer;return Promise.resolve(Y({header:i,data:u,signature:o},n.authenticators)).then(function(n){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:$;if(n){var u=i+o;if(t.nbf){if(t.nbf>u)throw new Error("JWT not valid before nbf: "+t.nbf)}else if(t.iat&&t.iat>u)throw new Error("JWT not valid yet (issued in the future) iat: "+t.iat);if(t.exp&&t.exp<=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:a,issuer:c,signer:n,jwt:r}}})})}catch(r){return Promise.reject(r)}},F=function(r,e,n){var t=e.issuer,i=e.signer,o=e.alg,u=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 a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(u){if("number"!=typeof u)throw new Error("JWT expiresIn is not a number");a.exp=(r.nbf||a.iat)+Math.floor(u)}var c=T({},a,r,{iss:t});return L(c,i,n)}catch(r){return Promise.reject(r)}},L=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=Z);var t="string"==typeof r?r:q(r),i=[q(n),t].join("."),o=function(r){var e=R[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)}},M={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},Z="ES256K";function q(r){return k(JSON.stringify(r))}var $=300;function G(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(K(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function Q(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=G(r);return Object.assign(e,{payload:JSON.parse(K(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function Y(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),X(n.alg)(t,i,e)}function rr(r,e){return Y(G(r),e)}var er=function(r,e){try{var n=function(r){if(null===u)throw new Error("Failed to decrypt");return u};!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(K(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=J(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),u=null,a="dir"===t.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,E(r.iv),o)).then(function(r){u=r}):function(){if(r.recipients&&0!==r.recipients.length){var n=0;return function(r,e,n){for(var t;;){var i=r();if(or(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!or(o)){t=1;break}o=o.s}if(e){var u=e();if(u&&u.then&&!or(u)){t=2;break}}}var a=new ir,c=tr.bind(null,a,2);return(0===t?i.then(s):1===t?o.then(f):u.then(l)).then(void 0,c),a;function f(t){o=t;do{if(e&&(u=e())&&u.then&&!or(u))return void u.then(l).then(void 0,c);if(!(i=r())||or(i)&&!i.v)return void tr(a,1,o);if(i.then)return void i.then(s).then(void 0,c);or(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):tr(a,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):tr(a,1,o)}}(function(){return!u&&n<r.recipients.length},function(){return n++},function(){var a=r.recipients[n];Object.assign(a.header,t);var c=function(){if(a.header.alg===e.alg)return Promise.resolve(e.decrypt(i,E(r.iv),o,a)).then(function(r){u=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(a&&a.then?a.then(n):n())}catch(r){return Promise.reject(r)}},nr="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function tr(r,e,n){if(!r.s){if(n instanceof ir){if(!n.s)return void(n.o=tr.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(tr.bind(null,r,e),tr.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var ir=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{tr(t,1,o(this.v))}catch(r){tr(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?tr(t,1,e?e(i):i):n?tr(t,1,n(i)):tr(t,2,i)}catch(r){tr(t,2,r)}},t},r}();function or(r){return r instanceof ir&&1&r.s}function ur(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:b(r.iv),ciphertext:b(n),tag:b(t)};return e&&(o.aad=b(e)),i&&(o.recipients=[i]),o}var ar=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 ur(r,t)})}var i,o,u=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===u},!0))throw new Error("Incompatible encrypters passed");var a=function(r,e,n){if("function"==typeof r[nr]){var t,i,o,u=r[nr]();if(function r(n){try{for(;!(t=u.next()).done;)if((n=e(t.value))&&n.then){if(!or(n))return void n.then(r,o||(o=tr.bind(null,i=new ir,2)));n=n.v}i?tr(i,1,n):i=n}catch(r){tr(i||(i=new ir),2,r)}}(),u.return){var a=function(r){try{t.done||u.return()}catch(r){}return r};if(i&&i.then)return i.then(a,function(r){throw a(r)});a()}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(u){try{for(;++o<r.length;)if((u=e(o))&&u.then){if(!or(u))return void u.then(n,i||(i=tr.bind(null,t=new ir,2)));u=u.v}t?tr(t,1,u):t=u}catch(r){tr(t||(t=new ir),2,r)}}(),t}(c,function(r){return e(c[r])})}(e,function(e){var u=function(){if(i){var u=o.recipients,a=u.push;return Promise.resolve(e.encryptCek(i)).then(function(r){a.call(u,r)})}return Promise.resolve(e.encrypt(r,n,t)).then(function(r){i=r.cek,o=ur(r,t)})}();if(u&&u.then)return u.then(function(){})});return Promise.resolve(a&&a.then?a.then(function(){return o}):o)}catch(r){return Promise.reject(r)}};function cr(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 fr=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 hr(S(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}};function sr(r){var e=cr(r);return{alg:"dir",enc:"XC20P",encrypt:function(r,n,t){void 0===n&&(n={});try{var i=k(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?i+"."+b(t):i));return Promise.resolve(T({},e(r,o),{protectedHeader:i}))}catch(r){return Promise.reject(r)}}}}function lr(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 hr(r,e){var n=function(n){try{var u=f(),a=cr(y(s(u.secretKey,r),i,t))(n),c={encrypted_key:b(a.ciphertext),header:{alg:t,iv:b(a.iv),tag:b(a.tag),epk:{kty:"OKP",crv:o,x:b(u.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(sr(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return T({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}function vr(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 u=E(o.header.epk.x),a=y(s(r,u),256,e),c=J(o.encrypted_key,o.header.tag);return Promise.resolve(lr(a).decrypt(c,E(o.header.iv))).then(function(r){return null===r?null:lr(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}}export{D as EllipticSigner,W as NaclSigner,w as SimpleSigner,ar as createJWE,L as createJWS,F as createJWT,Q as decodeJWT,er as decryptJWE,fr as resolveX25519Encrypters,v as toEthereumAddress,rr as verifyJWS,z as verifyJWT,vr as x25519Decrypter,hr as x25519Encrypter,lr as xc20pDirDecrypter,sr as xc20pDirEncrypter}; | ||
//# sourceMappingURL=index.esm.js.map |
@@ -1,2 +0,2 @@ | ||
var r=require("elliptic"),e=require("@stablelib/sha256"),n=require("uint8arrays"),t=require("js-sha3"),i=require("@stablelib/ed25519"),o=require("@stablelib/xchacha20poly1305"),a=require("@stablelib/x25519"),u=require("@stablelib/random");function c(r){return e.hash(n.fromString(r))}function f(r){var e,i=n.fromString(r.slice(2),"base16");return"0x"+n.toString((e=i,new Uint8Array(t.keccak_256.arrayBuffer(e))).slice(-20),"base16")}function s(r,e){void 0===e&&(e=new Uint8Array(4));var t=n.fromString(r.toString(),"base10");return e.set(t,4-t.length),e}var h=function(r){return n.concat([s(r.length),r])};function l(r,t,i){if(256!==t)throw new Error("Unsupported key length: "+t);var o=n.concat([h(n.fromString(i)),h(new Uint8Array(0)),h(new Uint8Array(0)),s(t)]);return e.hash(n.concat([s(1),r,o]))}var d=new r.ec("secp256k1");function v(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function p(r){r.startsWith("0x")&&(r=r.substring(2));var e=d.keyFromPrivate(r);return function(r){try{var n=e.sign(c(r)),t=n.s,i=n.recoveryParam;return Promise.resolve({r:v(n.r.toString("hex")),s:v(t.toString("hex")),recoveryParam:i})}catch(r){return Promise.reject(r)}}}function y(r){return n.toString(r,"base64url")}function g(r){return n.fromString(r,"base64url")}function m(r){return n.fromString(r,"base64pad")}function w(r){return n.fromString(r,"base58btc")}function b(r){return y(n.fromString(r))}function E(r){return n.toString(g(r))}function P(r){return n.toString(r,"base16")}function S(r){return n.fromString(r)}function x(r,e){var t=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(e?65:64);if(a.set(n.fromString(t,"base16"),0),a.set(n.fromString(i,"base16"),32),e){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return y(a)}function k(r,e){return n.concat([g(r),g(e)])}function K(){return(K=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 j=new r.ec("secp256k1");function J(r,e){void 0===e&&(e=!1);var n=g(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:P(n.slice(0,32)),s:P(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function W(r){return r.publicKeyBase58?w(r.publicKeyBase58):r.publicKeyBase64?m(r.publicKeyBase64):r.publicKeyHex?n.fromString(r.publicKeyHex,"base16"):new Uint8Array}function A(r,e,n){var t;if(e.length>86)t=[J(e,!0)];else{var i=J(e,!1);t=[K({},i,{recoveryParam:0}),K({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=c(r),i=j.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=f(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 D(r,e,n){var t=S(r),o=g(e),a=n.find(function(r){return i.verify(W(r),t,o)});if(!a)throw new Error("Signature invalid for JWT");return a}var T={ES256K:function(r,e,n){var t=c(r),i=J(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=W(r);return j.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=A(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":A,Ed25519:D,EdDSA:D};function C(r){var e=T[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function O(r){return"object"==typeof r&&"r"in r&&"s"in r}function I(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(O(e))return x(e,r);if(r)throw new Error("ES256K-R not supported when signer function returns string");return e})}catch(r){return Promise.reject(r)}}}function U(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(O(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}C.toSignatureObject=J;var X={ES256K:I(),"ES256K-R":I(!0),Ed25519:U(),EdDSA:U()},B=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=V);var t="string"==typeof r?r:q(r),i=[q(n),t].join("."),o=function(r){var e=X[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)}},N={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},V="ES256K";function q(r){return b(JSON.stringify(r))}function H(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(E(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=H(r);return Object.assign(e,{payload:JSON.parse(E(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function R(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),C(n.alg)(t,i,e)}var z="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function F(r,e,n){if(!r.s){if(n instanceof L){if(!n.s)return void(n.o=F.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(F.bind(null,r,e),F.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var L=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{F(t,1,o(this.v))}catch(r){F(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?F(t,1,e?e(i):i):n?F(t,1,n(i)):F(t,2,i)}catch(r){F(t,2,r)}},t},r}();function M(r){return r instanceof L&&1&r.s}function Z(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:y(r.iv),ciphertext:y(n),tag:y(t)};return e&&(o.aad=y(e)),i&&(o.recipients=[i]),o}function $(r){var e=new o.XChaCha20Poly1305(r);return function(r,n){var t=u.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 G(r){var e=$(r);return{alg:"dir",enc:"XC20P",encrypt:function(r,n,t){void 0===n&&(n={});try{var i=b(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?i+"."+y(t):i));return Promise.resolve(K({},e(r,o),{protectedHeader:i}))}catch(r){return Promise.reject(r)}}}}function Q(r){var e=new o.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 Y(r,e){var n=function(n){try{var u=a.generateKeyPair(),c=$(l(a.sharedKey(u.secretKey,r),i,t))(n),f={encrypted_key:y(c.ciphertext),header:{alg:t,iv:y(c.iv),tag:y(c.tag),epk:{kty:"OKP",crv:o,x:y(u.publicKey)}}};return e&&(f.header.kid=e),Promise.resolve(f)}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=u.randomBytes(32);return Promise.resolve(G(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return K({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}exports.EllipticSigner=function(r){var e=p(r);return function(r){try{return Promise.resolve(e(r)).then(function(r){return x(r)})}catch(r){return Promise.reject(r)}}},exports.NaclSigner=function(r){var e=m(r);return function(r){try{var n=S(r),t=y(i.sign(e,n));return Promise.resolve(t)}catch(r){return Promise.reject(r)}}},exports.SimpleSigner=p,exports.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 Z(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[z]){var t,i,o,a=r[z]();if(function r(n){try{for(;!(t=a.next()).done;)if((n=e(t.value))&&n.then){if(!M(n))return void n.then(r,o||(o=F.bind(null,i=new L,2)));n=n.v}i?F(i,1,n):i=n}catch(r){F(i||(i=new L),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(!M(a))return void a.then(n,i||(i=F.bind(null,t=new L,2)));a=a.v}t?F(t,1,a):t=a}catch(r){F(t||(t=new L),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=Z(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)}},exports.createJWS=B,exports.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=K({},u,r,{iss:t});return B(c,i,n)}catch(r){return Promise.reject(r)}},exports.decodeJWT=_,exports.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(E(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=k(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,g(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(M(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!M(o)){t=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!M(a)){t=2;break}}}var u=new L,c=F.bind(null,u,2);return(0===t?i.then(s):1===t?o.then(f):a.then(h)).then(void 0,c),u;function f(t){o=t;do{if(e&&(a=e())&&a.then&&!M(a))return void a.then(h).then(void 0,c);if(!(i=r())||M(i)&&!i.v)return void F(u,1,o);if(i.then)return void i.then(s).then(void 0,c);M(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):F(u,1,o)}function h(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):F(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,g(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)}},exports.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 Y(w(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},exports.toEthereumAddress=f,exports.verifyJWS=function(r,e){return R(H(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 n=_(r),t=n.payload,i=n.header,o=n.signature,a=n.data;return Promise.resolve(function(r,e,n,t){try{var i=N[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=!t||(r.authentication||[]).map(function(r){return r.publicKey}),a=(r.publicKey||[]).filter(function(r){var e=r.type,n=r.id;return i.find(function(r){return r===e&&(!t||Array.isArray(o)&&o.indexOf(n)>=0)})});if(t&&(!a||0===a.length))throw new Error("DID document for "+n+" does not have public keys suitable for authenticationg user");if(!a||0===a.length)throw new Error("DID document for "+n+" does not have public keys for "+e);return{authenticators:a,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(R({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)}},exports.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 u=g(o.header.epk.x),c=l(a.sharedKey(r,u),256,e),f=k(o.encrypted_key,o.header.tag);return Promise.resolve(Q(c).decrypt(f,g(o.header.iv))).then(function(r){return null===r?null:Q(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}},exports.x25519Encrypter=Y,exports.xc20pDirDecrypter=Q,exports.xc20pDirEncrypter=G; | ||
var r=require("elliptic"),e=require("@stablelib/sha256"),n=require("uint8arrays"),t=require("js-sha3"),i=require("@stablelib/ed25519"),o=require("@stablelib/xchacha20poly1305"),a=require("@stablelib/x25519"),u=require("@stablelib/random");function c(r){return e.hash(n.fromString(r))}function f(r){var e,i=n.fromString(r.slice(2),"base16");return"0x"+n.toString((e=i,new Uint8Array(t.keccak_256.arrayBuffer(e))).slice(-20),"base16")}function s(r,e){void 0===e&&(e=new Uint8Array(4));var t=n.fromString(r.toString(),"base10");return e.set(t,4-t.length),e}var l=function(r){return n.concat([s(r.length),r])};function h(r,t,i){if(256!==t)throw new Error("Unsupported key length: "+t);var o=n.concat([l(n.fromString(i)),l(new Uint8Array(0)),l(new Uint8Array(0)),s(t)]);return e.hash(n.concat([s(1),r,o]))}var d=new r.ec("secp256k1");function v(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function p(r){r.startsWith("0x")&&(r=r.substring(2));var e=d.keyFromPrivate(r);return function(r){try{var n=e.sign(c(r)),t=n.s,i=n.recoveryParam;return Promise.resolve({r:v(n.r.toString("hex")),s:v(t.toString("hex")),recoveryParam:i})}catch(r){return Promise.reject(r)}}}function y(r){return n.toString(r,"base64url")}function g(r){return n.fromString(r,"base64url")}function m(r){return n.fromString(r,"base64pad")}function w(r){return n.fromString(r,"base58btc")}function b(r){return y(n.fromString(r))}function E(r){return n.toString(g(r))}function P(r){return n.toString(r,"base16")}function S(r){return n.fromString(r)}function x(r,e){var t=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(e?65:64);if(a.set(n.fromString(t,"base16"),0),a.set(n.fromString(i,"base16"),32),e){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return y(a)}function k(r,e){return n.concat([g(r),g(e)])}function K(){return(K=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 j=new r.ec("secp256k1");function J(r,e){void 0===e&&(e=!1);var n=g(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:P(n.slice(0,32)),s:P(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function W(r){return r.publicKeyBase58?w(r.publicKeyBase58):r.publicKeyBase64?m(r.publicKeyBase64):r.publicKeyHex?n.fromString(r.publicKeyHex,"base16"):new Uint8Array}function D(r,e,n){var t;if(e.length>86)t=[J(e,!0)];else{var i=J(e,!1);t=[K({},i,{recoveryParam:0}),K({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=c(r),i=j.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=f(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 A(r,e,n){var t=S(r),o=g(e),a=n.find(function(r){return i.verify(W(r),t,o)});if(!a)throw new Error("Signature invalid for JWT");return a}var T={ES256K:function(r,e,n){var t=c(r),i=J(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=W(r);return j.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=D(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":D,Ed25519:A,EdDSA:A};function C(r){var e=T[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function I(r){return"object"==typeof r&&"r"in r&&"s"in r}function O(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(I(e))return x(e,r);if(r)throw new Error("ES256K-R not supported when signer function returns string");return e})}catch(r){return Promise.reject(r)}}}function U(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(I(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}C.toSignatureObject=J;var X={ES256K:O(),"ES256K-R":O(!0),Ed25519:U(),EdDSA:U()},B=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=V);var t="string"==typeof r?r:q(r),i=[q(n),t].join("."),o=function(r){var e=X[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)}},N={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},V="ES256K";function q(r){return b(JSON.stringify(r))}function H(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(E(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=H(r);return Object.assign(e,{payload:JSON.parse(E(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function R(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),C(n.alg)(t,i,e)}var z="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function F(r,e,n){if(!r.s){if(n instanceof L){if(!n.s)return void(n.o=F.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(F.bind(null,r,e),F.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var L=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{F(t,1,o(this.v))}catch(r){F(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?F(t,1,e?e(i):i):n?F(t,1,n(i)):F(t,2,i)}catch(r){F(t,2,r)}},t},r}();function M(r){return r instanceof L&&1&r.s}function Z(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:y(r.iv),ciphertext:y(n),tag:y(t)};return e&&(o.aad=y(e)),i&&(o.recipients=[i]),o}function $(r){var e=new o.XChaCha20Poly1305(r);return function(r,n){var t=u.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 G(r){var e=$(r);return{alg:"dir",enc:"XC20P",encrypt:function(r,n,t){void 0===n&&(n={});try{var i=b(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?i+"."+y(t):i));return Promise.resolve(K({},e(r,o),{protectedHeader:i}))}catch(r){return Promise.reject(r)}}}}function Q(r){var e=new o.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 Y(r,e){var n=function(n){try{var u=a.generateKeyPair(),c=$(h(a.sharedKey(u.secretKey,r),i,t))(n),f={encrypted_key:y(c.ciphertext),header:{alg:t,iv:y(c.iv),tag:y(c.tag),epk:{kty:"OKP",crv:o,x:y(u.publicKey)}}};return e&&(f.header.kid=e),Promise.resolve(f)}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=u.randomBytes(32);return Promise.resolve(G(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return K({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}exports.EllipticSigner=function(r){var e=p(r);return function(r){try{return Promise.resolve(e(r)).then(function(r){return x(r)})}catch(r){return Promise.reject(r)}}},exports.NaclSigner=function(r){var e=m(r);return function(r){try{var n=S(r),t=y(i.sign(e,n));return Promise.resolve(t)}catch(r){return Promise.reject(r)}}},exports.SimpleSigner=p,exports.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 Z(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[z]){var t,i,o,a=r[z]();if(function r(n){try{for(;!(t=a.next()).done;)if((n=e(t.value))&&n.then){if(!M(n))return void n.then(r,o||(o=F.bind(null,i=new L,2)));n=n.v}i?F(i,1,n):i=n}catch(r){F(i||(i=new L),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(!M(a))return void a.then(n,i||(i=F.bind(null,t=new L,2)));a=a.v}t?F(t,1,a):t=a}catch(r){F(t||(t=new L),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=Z(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)}},exports.createJWS=B,exports.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=K({},u,r,{iss:t});return B(c,i,n)}catch(r){return Promise.reject(r)}},exports.decodeJWT=_,exports.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(E(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=k(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,g(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(M(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!M(o)){t=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!M(a)){t=2;break}}}var u=new L,c=F.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&&!M(a))return void a.then(l).then(void 0,c);if(!(i=r())||M(i)&&!i.v)return void F(u,1,o);if(i.then)return void i.then(s).then(void 0,c);M(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):F(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):F(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,g(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)}},exports.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 Y(w(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},exports.toEthereumAddress=f,exports.verifyJWS=function(r,e){return R(H(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 n=_(r),t=n.payload,i=n.header,o=n.signature,a=n.data;return Promise.resolve(function(r,e,n,t){try{var i=N[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(R({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)}},exports.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 u=g(o.header.epk.x),c=h(a.sharedKey(r,u),256,e),f=k(o.encrypted_key,o.header.tag);return Promise.resolve(Q(c).decrypt(f,g(o.header.iv))).then(function(r){return null===r?null:Q(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}},exports.x25519Encrypter=Y,exports.xc20pDirDecrypter=Q,exports.xc20pDirEncrypter=G; | ||
//# sourceMappingURL=index.js.map |
@@ -1,2 +0,2 @@ | ||
import{ec as r}from"elliptic";import{hash as e}from"@stablelib/sha256";import{fromString as n,toString as t,concat as i}from"uint8arrays";import{keccak_256 as o}from"js-sha3";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(n(r))}function p(r){const e=n(r.slice(2),"base16");return"0x"+t((i=e,new Uint8Array(o.arrayBuffer(i))).slice(-20),"base16");var i}function y(r,e=new Uint8Array(4)){const t=n(r.toString(),"base10");return e.set(t,4-t.length),e}const h=r=>i([y(r.length),r]);function w(r,t,o){if(256!==t)throw new Error("Unsupported key length: "+t);const a=i([h(n(o)),h(new Uint8Array(0)),h(new Uint8Array(0)),y(t)]);return e(i([y(1),r,a]))}const g=new r("secp256k1");function b(r,e=64){return r.length===e?r:"0".repeat(e-r.length)+r}function E(r){r.startsWith("0x")&&(r=r.substring(2));const e=g.keyFromPrivate(r);return async r=>{const{r:n,s:t,recoveryParam:i}=e.sign(d(r));return{r:b(n.toString("hex")),s:b(t.toString("hex")),recoveryParam:i}}}function m(r){return t(r,"base64url")}function v(r){return n(r,"base64url")}function k(r){return n(r,"base64pad")}function S(r){return n(r,"base58btc")}function K(r){return m(n(r))}function x(r){return t(v(r))}function A(r){return t(r,"base16")}function J(r){return n(r)}function P({r,s:e,recoveryParam:t},i){const o=new Uint8Array(i?65:64);if(o.set(n(r,"base16"),0),o.set(n(e,"base16"),32),i){if(void 0===t)throw new Error("Signer did not return a recoveryParam");o[64]=t}return m(o)}function D(r,e){return i([v(r),v(e)])}function W(r){const e=E(r);return async r=>P(await e(r))}function T(r){const e=k(r);return async r=>{const n=J(r);return m(a(e,n))}}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)}const O=new r("secp256k1");function U(r,e=!1){const n=v(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");const t={r:A(n.slice(0,32)),s:A(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function C(r){return r.publicKeyBase58?S(r.publicKeyBase58):r.publicKeyBase64?k(r.publicKeyBase64):r.publicKeyHex?n(r.publicKeyHex,"base16"):new Uint8Array}function j(r,e,n){let t;if(e.length>86)t=[U(e,!0)];else{const r=U(e,!1);t=[I({},r,{recoveryParam:0}),I({},r,{recoveryParam:1})]}const i=t.map(e=>{const t=d(r),i=O.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),c=p(o);return n.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 $(r,e,n){const t=J(r),i=v(e),o=n.find(r=>c(C(r),t,i));if(!o)throw new Error("Signature invalid for JWT");return o}const B={ES256K:function(r,e,n){const t=d(r),i=U(e),o=n.filter(({ethereumAddress:r})=>void 0===r),a=n.filter(({ethereumAddress:r})=>void 0!==r);let c=o.find(r=>{try{const e=C(r);return O.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!c&&a.length>0&&(c=j(r,e,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":j,Ed25519:$,EdDSA:$};function V(r){const 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 N(r){return async function(e,n){const t=await n(e);if(X(t))return P(t,r);if(r)throw new Error("ES256K-R not supported when signer function returns string");return t}}function H(){return async function(r,e){const n=await e(r);if(X(n))throw new Error("expected a signer function that returns a string instead of signature object");return n}}V.toSignatureObject=U;const _={ES256K:N(),"ES256K-R":N(!0),Ed25519:H(),EdDSA:H()},R={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function z(r){return K(JSON.stringify(r))}function F(r){const e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(x(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{const e=F(r);return Object.assign(e,{payload:JSON.parse(x(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}async function M(r,e,n={}){n.alg||(n.alg="ES256K");const t="string"==typeof r?r:z(r),i=[z(n),t].join("."),o=function(r){const e=_[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(n.alg);return[i,await o(i,e)].join(".")}async function Z(r,{issuer:e,signer:n,alg:t,expiresIn:i},o={}){if(!n)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=t);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 M(I({},a,r,{iss:e}),n,o)}function q({header:r,data:e,signature:n},t){return Array.isArray(t)||(t=[t]),V(r.alg)(e,n,t)}function G(r,e){return q(F(r),e)}async function Q(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:n,header:t,signature:i,data:o}=L(r),{doc:a,authenticators:c,issuer:s}=await async function(r,e,n,t){const i=R[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);const o=await r.resolve(n);if(!o)throw new Error("Unable to resolve DID document for "+n);const a=!t||(o.authentication||[]).map(({publicKey:r})=>r),c=(o.publicKey||[]).filter(({type:r,id:e})=>i.find(n=>n===r&&(!t||Array.isArray(a)&&a.indexOf(e)>=0)));if(t&&(!c||0===c.length))throw new Error(`DID document for ${n} does not have public keys suitable for authenticationg user`);if(!c||0===c.length)throw new Error(`DID document for ${n} does not have public keys for ${e}`);return{authenticators:c,issuer:n,doc:o}}(e.resolver,t.alg,n.iss,e.auth),u=await q({header:t,data:o,signature:i},c),f=Math.floor(Date.now()/1e3),l=e.skewTime>=0?e.skewTime:300;if(u){const t=f+l;if(n.nbf){if(n.nbf>t)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>t)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=f-l)throw new Error(`JWT has expired: exp: ${n.exp} < now: ${f}`);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(r=>e.audience===r||e.callbackUrl===r))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,doc:a,issuer:s,signer:u,jwt:r}}}function Y({ciphertext:r,tag:e,iv:n,protectedHeader:t,recipient:i},o){const a={protected:t,iv:m(n),ciphertext:m(r),tag:m(e)};return o&&(a.aad=m(o)),i&&(a.recipients=[i]),a}async function rr(r,e,n={},t){if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Y(await e[0].encrypt(r,n,t),t)}{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,n,t);o=e.cek,a=Y(e,t)}return a}}async function er(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 n=JSON.parse(x(r.protected));if(n.enc!==e.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const t=D(r.ciphertext,r.tag),i=new Uint8Array(Buffer.from(r.aad?`${r.protected}.${r.aad}`:r.protected));let o=null;if("dir"===n.alg&&"dir"===e.alg)o=await e.decrypt(t,v(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,n),c.header.alg===e.alg&&(o=await e.decrypt(t,v(r.iv),i,c))}}if(null===o)throw new Error("Failed to decrypt");return o}function nr(r){const e=new s(r);return(r,n)=>{const 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}}}function tr(r){const e=nr(r);return{alg:"dir",enc:"XC20P",encrypt:async function(r,n={},t){const i=K(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?`${i}.${m(t)}`:i));return I({},e(r,o),{protectedHeader:i})}}}function ir(r){const e=new s(r);return{alg:"dir",enc:"XC20P",decrypt:async function(r,n,t){return e.open(n,r,t)}}}function or(r,e){const n="ECDH-ES+XC20PKW";async function t(t){const i=u(),o=nr(w(f(i.secretKey,r),256,n))(t),a={encrypted_key:m(o.ciphertext),header:{alg:n,iv:m(o.iv),tag:m(o.tag),epk:{kty:"OKP",crv:"X25519",x:m(i.publicKey)}}};return e&&(a.header.kid=e),a}return{alg:n,enc:"XC20P",encrypt:async function(r,e={},n){Object.assign(e,{alg:void 0});const i=l(32);return I({},await tr(i).encrypt(r,e,n),{recipient:await t(i),cek:i})},encryptCek:t}}async function ar(r,e){return Promise.all(r.map(async r=>{var n;const t=await e.resolve(r);if(!t.keyAgreement)throw new Error("Could not find x25519 key for "+r);const i=(null==(n=t.keyAgreement)?void 0:n.map(r=>"string"==typeof r?t.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 or(S(i.publicKeyBase58),i.id)}))}function cr(r){const e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:async function(n,t,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=v(o.header.epk.x),c=w(f(r,a),256,e),s=D(o.encrypted_key,o.header.tag),u=await ir(c).decrypt(s,v(o.header.iv));return null===u?null:ir(u).decrypt(n,t,i)}}}export{W as EllipticSigner,T as NaclSigner,E as SimpleSigner,rr as createJWE,M as createJWS,Z as createJWT,L as decodeJWT,er as decryptJWE,ar as resolveX25519Encrypters,p as toEthereumAddress,G as verifyJWS,Q as verifyJWT,cr as x25519Decrypter,or as x25519Encrypter,ir as xc20pDirDecrypter,tr as xc20pDirEncrypter}; | ||
import{ec as e}from"elliptic";import{hash as r}from"@stablelib/sha256";import{fromString as n,toString as t,concat as i}from"uint8arrays";import{keccak_256 as o}from"js-sha3";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(e){return r(n(e))}function p(e){const r=n(e.slice(2),"base16");return"0x"+t((i=r,new Uint8Array(o.arrayBuffer(i))).slice(-20),"base16");var i}function y(e,r=new Uint8Array(4)){const t=n(e.toString(),"base10");return r.set(t,4-t.length),r}const h=e=>i([y(e.length),e]);function w(e,t,o){if(256!==t)throw new Error("Unsupported key length: "+t);const a=i([h(n(o)),h(new Uint8Array(0)),h(new Uint8Array(0)),y(t)]);return r(i([y(1),e,a]))}const g=new e("secp256k1");function b(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function E(e){e.startsWith("0x")&&(e=e.substring(2));const r=g.keyFromPrivate(e);return async e=>{const{r:n,s:t,recoveryParam:i}=r.sign(d(e));return{r:b(n.toString("hex")),s:b(t.toString("hex")),recoveryParam:i}}}function m(e){return t(e,"base64url")}function v(e){return n(e,"base64url")}function k(e){return n(e,"base64pad")}function K(e){return n(e,"base58btc")}function S(e){return m(n(e))}function x(e){return t(v(e))}function A(e){return t(e,"base16")}function J(e){return n(e)}function P({r:e,s:r,recoveryParam:t},i){const o=new Uint8Array(i?65:64);if(o.set(n(e,"base16"),0),o.set(n(r,"base16"),32),i){if(void 0===t)throw new Error("Signer did not return a recoveryParam");o[64]=t}return m(o)}function D(e,r){return i([v(e),v(r)])}function W(e){const r=E(e);return async e=>P(await r(e))}function T(e){const r=k(e);return async e=>{const n=J(e);return m(a(r,n))}}function I(){return(I=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var n=arguments[r];for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=n[t])}return e}).apply(this,arguments)}const U=new e("secp256k1");function C(e,r=!1){const n=v(e);if(n.length!==(r?65:64))throw new Error("wrong signature length");const t={r:A(n.slice(0,32)),s:A(n.slice(32,64))};return r&&(t.recoveryParam=n[64]),t}function O(e){return e.publicKeyBase58?K(e.publicKeyBase58):e.publicKeyBase64?k(e.publicKeyBase64):e.publicKeyHex?n(e.publicKeyHex,"base16"):new Uint8Array}function j(e,r,n){let t;if(r.length>86)t=[C(r,!0)];else{const e=C(r,!1);t=[I({},e,{recoveryParam:0}),I({},e,{recoveryParam:1})]}const i=t.map(r=>{const t=d(e),i=U.recoverPubKey(t,r,r.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),c=p(o);return n.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 $(e,r,n){const t=J(e),i=v(r),o=n.find(e=>c(O(e),t,i));if(!o)throw new Error("Signature invalid for JWT");return o}const B={ES256K:function(e,r,n){const t=d(e),i=C(r),o=n.filter(({ethereumAddress:e})=>void 0===e),a=n.filter(({ethereumAddress:e})=>void 0!==e);let c=o.find(e=>{try{const r=O(e);return U.keyFromPublic(r).verify(t,i)}catch(e){return!1}});if(!c&&a.length>0&&(c=j(e,r,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":j,Ed25519:$,EdDSA:$};function V(e){const r=B[e];if(!r)throw new Error("Unsupported algorithm "+e);return r}function X(e){return"object"==typeof e&&"r"in e&&"s"in e}function N(e){return async function(r,n){const t=await n(r);if(X(t))return P(t,e);if(e)throw new Error("ES256K-R not supported when signer function returns string");return t}}function H(){return async function(e,r){const n=await r(e);if(X(n))throw new Error("expected a signer function that returns a string instead of signature object");return n}}V.toSignatureObject=C;const _={ES256K:N(),"ES256K-R":N(!0),Ed25519:H(),EdDSA:H()},R={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function z(e){return S(JSON.stringify(e))}function F(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(x(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function L(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=F(e);return Object.assign(r,{payload:JSON.parse(x(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}async function M(e,r,n={}){n.alg||(n.alg="ES256K");const t="string"==typeof e?e:z(e),i=[z(n),t].join("."),o=function(e){const r=_[e];if(!r)throw new Error("Unsupported algorithm "+e);return r}(n.alg);return[i,await o(i,r)].join(".")}async function Z(e,{issuer:r,signer:n,alg:t,expiresIn:i},o={}){if(!n)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=t);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 M(I({},a,e,{iss:r}),n,o)}function q({header:e,data:r,signature:n},t){return Array.isArray(t)||(t=[t]),V(e.alg)(r,n,t)}function G(e,r){return q(F(e),r)}async function Q(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:n,header:t,signature:i,data:o}=L(e),{doc:a,authenticators:c,issuer:s}=await async function(e,r,n,t){const i=R[r];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+r);const o=await e.resolve(n);if(!o)throw new Error("Unable to resolve DID document for "+n);let a=(e,r)=>{const n=e.publicKey.filter(({id:e})=>r===e);return n.length>0?n[0]:null},c=o.publicKey||[];t&&(c=(o.authentication||[]).map(e=>"string"==typeof e?a(o,e):"string"==typeof e.publicKey?a(o,e.publicKey):e).filter(e=>null!=e));const s=c.filter(({type:e})=>i.find(r=>r===e));if(t&&(!s||0===s.length))throw new Error(`DID document for ${n} does not have public keys suitable for authenticating user`);if(!s||0===s.length)throw new Error(`DID document for ${n} does not have public keys for ${r}`);return{authenticators:s,issuer:n,doc:o}}(r.resolver,t.alg,n.iss,r.auth),u=await q({header:t,data:o,signature:i},c),f=Math.floor(Date.now()/1e3),l=r.skewTime>=0?r.skewTime:300;if(u){const t=f+l;if(n.nbf){if(n.nbf>t)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>t)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=f-l)throw new Error(`JWT has expired: exp: ${n.exp} < now: ${f}`);if(n.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(n.aud)?n.aud:[n.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,doc:a,issuer:s,signer:u,jwt:e}}}function Y({ciphertext:e,tag:r,iv:n,protectedHeader:t,recipient:i},o){const a={protected:t,iv:m(n),ciphertext:m(e),tag:m(r)};return o&&(a.aad=m(o)),i&&(a.recipients=[i]),a}async function ee(e,r,n={},t){if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return Y(await r[0].encrypt(e,n,t),t)}{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,n,t);o=r.cek,a=Y(r,t)}return a}}async function re(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 n=JSON.parse(x(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const t=D(e.ciphertext,e.tag),i=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let o=null;if("dir"===n.alg&&"dir"===r.alg)o=await r.decrypt(t,v(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,n),c.header.alg===r.alg&&(o=await r.decrypt(t,v(e.iv),i,c))}}if(null===o)throw new Error("Failed to decrypt");return o}function ne(e){const r=new s(e);return(e,n)=>{const t=l(r.nonceLength),i=r.seal(t,e,n);return{ciphertext:i.subarray(0,i.length-r.tagLength),tag:i.subarray(i.length-r.tagLength),iv:t}}}function te(e){const r=ne(e);return{alg:"dir",enc:"XC20P",encrypt:async function(e,n={},t){const i=S(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?`${i}.${m(t)}`:i));return I({},r(e,o),{protectedHeader:i})}}}function ie(e){const r=new s(e);return{alg:"dir",enc:"XC20P",decrypt:async function(e,n,t){return r.open(n,e,t)}}}function oe(e,r){const n="ECDH-ES+XC20PKW";async function t(t){const i=u(),o=ne(w(f(i.secretKey,e),256,n))(t),a={encrypted_key:m(o.ciphertext),header:{alg:n,iv:m(o.iv),tag:m(o.tag),epk:{kty:"OKP",crv:"X25519",x:m(i.publicKey)}}};return r&&(a.header.kid=r),a}return{alg:n,enc:"XC20P",encrypt:async function(e,r={},n){Object.assign(r,{alg:void 0});const i=l(32);return I({},await te(i).encrypt(e,r,n),{recipient:await t(i),cek:i})},encryptCek:t}}async function ae(e,r){return Promise.all(e.map(async e=>{var n;const t=await r.resolve(e);if(!t.keyAgreement)throw new Error("Could not find x25519 key for "+e);const i=(null==(n=t.keyAgreement)?void 0:n.map(e=>"string"==typeof e?t.publicKey.find(r=>r.id===e):e)).find(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!i)throw new Error("Could not find x25519 key for "+e);return oe(K(i.publicKeyBase58),i.id)}))}function ce(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:async function(n,t,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=v(o.header.epk.x),c=w(f(e,a),256,r),s=D(o.encrypted_key,o.header.tag),u=await ie(c).decrypt(s,v(o.header.iv));return null===u?null:ie(u).decrypt(n,t,i)}}}export{W as EllipticSigner,T as NaclSigner,E as SimpleSigner,ee as createJWE,M as createJWS,Z as createJWT,L as decodeJWT,re as decryptJWE,ae as resolveX25519Encrypters,p as toEthereumAddress,G as verifyJWS,Q as verifyJWT,ce as x25519Decrypter,oe as x25519Encrypter,ie as xc20pDirDecrypter,te as xc20pDirEncrypter}; | ||
//# sourceMappingURL=index.modern.js.map |
@@ -1,2 +0,2 @@ | ||
!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("elliptic"),require("@stablelib/sha256"),require("uint8arrays"),require("js-sha3"),require("@stablelib/ed25519"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","elliptic","@stablelib/sha256","uint8arrays","js-sha3","@stablelib/ed25519","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],e):e((r=r||self).didJwt={},r.elliptic,r.sha256$1,r.uint8Arrays,r.jsSha3,r.ed25519,r.xchacha20poly1305,r.x25519,r.random)}(this,function(r,e,n,t,i,o,a,u,c){function f(r){return n.hash(t.fromString(r))}function s(r){var e,n=t.fromString(r.slice(2),"base16");return"0x"+t.toString((e=n,new Uint8Array(i.keccak_256.arrayBuffer(e))).slice(-20),"base16")}function l(r,e){void 0===e&&(e=new Uint8Array(4));var n=t.fromString(r.toString(),"base10");return e.set(n,4-n.length),e}var h=function(r){return t.concat([l(r.length),r])};function d(r,e,i){if(256!==e)throw new Error("Unsupported key length: "+e);var o=t.concat([h(t.fromString(i)),h(new Uint8Array(0)),h(new Uint8Array(0)),l(e)]);return n.hash(t.concat([l(1),r,o]))}var v=new e.ec("secp256k1");function y(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function p(r){r.startsWith("0x")&&(r=r.substring(2));var e=v.keyFromPrivate(r);return function(r){try{var n=e.sign(f(r)),t=n.s,i=n.recoveryParam;return Promise.resolve({r:y(n.r.toString("hex")),s:y(t.toString("hex")),recoveryParam:i})}catch(r){return Promise.reject(r)}}}function g(r){return t.toString(r,"base64url")}function m(r){return t.fromString(r,"base64url")}function w(r){return t.fromString(r,"base64pad")}function b(r){return t.fromString(r,"base58btc")}function E(r){return g(t.fromString(r))}function P(r){return t.toString(m(r))}function S(r){return t.toString(r,"base16")}function k(r){return t.fromString(r)}function x(r,e){var n=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(e?65:64);if(a.set(t.fromString(n,"base16"),0),a.set(t.fromString(i,"base16"),32),e){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return g(a)}function K(r,e){return t.concat([m(r),m(e)])}function j(){return(j=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 J=new e.ec("secp256k1");function A(r,e){void 0===e&&(e=!1);var n=m(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:S(n.slice(0,32)),s:S(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function W(r){return r.publicKeyBase58?b(r.publicKeyBase58):r.publicKeyBase64?w(r.publicKeyBase64):r.publicKeyHex?t.fromString(r.publicKeyHex,"base16"):new Uint8Array}function D(r,e,n){var t;if(e.length>86)t=[A(e,!0)];else{var i=A(e,!1);t=[j({},i,{recoveryParam:0}),j({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=f(r),i=J.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=s(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 T(r,e,n){var t=k(r),i=m(e),a=n.find(function(r){return o.verify(W(r),t,i)});if(!a)throw new Error("Signature invalid for JWT");return a}var C={ES256K:function(r,e,n){var t=f(r),i=A(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=W(r);return J.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=D(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":D,Ed25519:T,EdDSA:T};function O(r){var e=C[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function I(r){return"object"==typeof r&&"r"in r&&"s"in r}function U(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(I(e))return x(e,r);if(r)throw new Error("ES256K-R not supported when signer function returns string");return e})}catch(r){return Promise.reject(r)}}}function X(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(I(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}O.toSignatureObject=A;var B={ES256K:U(),"ES256K-R":U(!0),Ed25519:X(),EdDSA:X()},N=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=q);var t="string"==typeof r?r:H(r),i=[H(n),t].join("."),o=function(r){var e=B[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)}},V={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},q="ES256K";function H(r){return E(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(P(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function R(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=_(r);return Object.assign(e,{payload:JSON.parse(P(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function z(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),O(n.alg)(t,i,e)}var F="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function L(r,e,n){if(!r.s){if(n instanceof M){if(!n.s)return void(n.o=L.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(L.bind(null,r,e),L.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var M=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{L(t,1,o(this.v))}catch(r){L(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?L(t,1,e?e(i):i):n?L(t,1,n(i)):L(t,2,i)}catch(r){L(t,2,r)}},t},r}();function Z(r){return r instanceof M&&1&r.s}function $(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:g(r.iv),ciphertext:g(n),tag:g(t)};return e&&(o.aad=g(e)),i&&(o.recipients=[i]),o}function G(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 Q(r){var e=G(r);return{alg:"dir",enc:"XC20P",encrypt:function(r,n,t){void 0===n&&(n={});try{var i=E(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?i+"."+g(t):i));return Promise.resolve(j({},e(r,o),{protectedHeader:i}))}catch(r){return Promise.reject(r)}}}}function Y(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 rr(r,e){var n=function(n){try{var a=u.generateKeyPair(),c=G(d(u.sharedKey(a.secretKey,r),i,t))(n),f={encrypted_key:g(c.ciphertext),header:{alg:t,iv:g(c.iv),tag:g(c.tag),epk:{kty:"OKP",crv:o,x:g(a.publicKey)}}};return e&&(f.header.kid=e),Promise.resolve(f)}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(Q(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return j({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}r.EllipticSigner=function(r){var e=p(r);return function(r){try{return Promise.resolve(e(r)).then(function(r){return x(r)})}catch(r){return Promise.reject(r)}}},r.NaclSigner=function(r){var e=w(r);return function(r){try{var n=k(r),t=g(o.sign(e,n));return Promise.resolve(t)}catch(r){return Promise.reject(r)}}},r.SimpleSigner=p,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 $(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[F]){var t,i,o,a=r[F]();if(function r(n){try{for(;!(t=a.next()).done;)if((n=e(t.value))&&n.then){if(!Z(n))return void n.then(r,o||(o=L.bind(null,i=new M,2)));n=n.v}i?L(i,1,n):i=n}catch(r){L(i||(i=new M),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(!Z(a))return void a.then(n,i||(i=L.bind(null,t=new M,2)));a=a.v}t?L(t,1,a):t=a}catch(r){L(t||(t=new M),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=$(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=N,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=j({},u,r,{iss:t});return N(c,i,n)}catch(r){return Promise.reject(r)}},r.decodeJWT=R,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(P(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=K(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,m(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(Z(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!Z(o)){t=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!Z(a)){t=2;break}}}var u=new M,c=L.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&&!Z(a))return void a.then(l).then(void 0,c);if(!(i=r())||Z(i)&&!i.v)return void L(u,1,o);if(i.then)return void i.then(s).then(void 0,c);Z(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):L(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):L(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,m(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 rr(b(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},r.toEthereumAddress=s,r.verifyJWS=function(r,e){return z(_(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=R(r),t=n.payload,i=n.header,o=n.signature,a=n.data;return Promise.resolve(function(r,e,n,t){try{var i=V[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=!t||(r.authentication||[]).map(function(r){return r.publicKey}),a=(r.publicKey||[]).filter(function(r){var e=r.type,n=r.id;return i.find(function(r){return r===e&&(!t||Array.isArray(o)&&o.indexOf(n)>=0)})});if(t&&(!a||0===a.length))throw new Error("DID document for "+n+" does not have public keys suitable for authenticationg user");if(!a||0===a.length)throw new Error("DID document for "+n+" does not have public keys for "+e);return{authenticators:a,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(z({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=m(o.header.epk.x),c=d(u.sharedKey(r,a),256,e),f=K(o.encrypted_key,o.header.tag);return Promise.resolve(Y(c).decrypt(f,m(o.header.iv))).then(function(r){return null===r?null:Y(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}},r.x25519Encrypter=rr,r.xc20pDirDecrypter=Y,r.xc20pDirEncrypter=Q}); | ||
!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("elliptic"),require("@stablelib/sha256"),require("uint8arrays"),require("js-sha3"),require("@stablelib/ed25519"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","elliptic","@stablelib/sha256","uint8arrays","js-sha3","@stablelib/ed25519","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],e):e((r=r||self).didJwt={},r.elliptic,r.sha256$1,r.uint8Arrays,r.jsSha3,r.ed25519,r.xchacha20poly1305,r.x25519,r.random)}(this,function(r,e,n,t,i,o,a,u,c){function f(r){return n.hash(t.fromString(r))}function s(r){var e,n=t.fromString(r.slice(2),"base16");return"0x"+t.toString((e=n,new Uint8Array(i.keccak_256.arrayBuffer(e))).slice(-20),"base16")}function l(r,e){void 0===e&&(e=new Uint8Array(4));var n=t.fromString(r.toString(),"base10");return e.set(n,4-n.length),e}var h=function(r){return t.concat([l(r.length),r])};function d(r,e,i){if(256!==e)throw new Error("Unsupported key length: "+e);var o=t.concat([h(t.fromString(i)),h(new Uint8Array(0)),h(new Uint8Array(0)),l(e)]);return n.hash(t.concat([l(1),r,o]))}var v=new e.ec("secp256k1");function y(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function p(r){r.startsWith("0x")&&(r=r.substring(2));var e=v.keyFromPrivate(r);return function(r){try{var n=e.sign(f(r)),t=n.s,i=n.recoveryParam;return Promise.resolve({r:y(n.r.toString("hex")),s:y(t.toString("hex")),recoveryParam:i})}catch(r){return Promise.reject(r)}}}function g(r){return t.toString(r,"base64url")}function m(r){return t.fromString(r,"base64url")}function w(r){return t.fromString(r,"base64pad")}function b(r){return t.fromString(r,"base58btc")}function E(r){return g(t.fromString(r))}function P(r){return t.toString(m(r))}function S(r){return t.toString(r,"base16")}function k(r){return t.fromString(r)}function x(r,e){var n=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(e?65:64);if(a.set(t.fromString(n,"base16"),0),a.set(t.fromString(i,"base16"),32),e){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return g(a)}function K(r,e){return t.concat([m(r),m(e)])}function j(){return(j=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 J=new e.ec("secp256k1");function W(r,e){void 0===e&&(e=!1);var n=m(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:S(n.slice(0,32)),s:S(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function A(r){return r.publicKeyBase58?b(r.publicKeyBase58):r.publicKeyBase64?w(r.publicKeyBase64):r.publicKeyHex?t.fromString(r.publicKeyHex,"base16"):new Uint8Array}function D(r,e,n){var t;if(e.length>86)t=[W(e,!0)];else{var i=W(e,!1);t=[j({},i,{recoveryParam:0}),j({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=f(r),i=J.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=s(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 T(r,e,n){var t=k(r),i=m(e),a=n.find(function(r){return o.verify(A(r),t,i)});if(!a)throw new Error("Signature invalid for JWT");return a}var C={ES256K:function(r,e,n){var t=f(r),i=W(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=A(r);return J.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=D(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":D,Ed25519:T,EdDSA:T};function I(r){var e=C[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function O(r){return"object"==typeof r&&"r"in r&&"s"in r}function U(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(O(e))return x(e,r);if(r)throw new Error("ES256K-R not supported when signer function returns string");return e})}catch(r){return Promise.reject(r)}}}function X(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(O(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}I.toSignatureObject=W;var B={ES256K:U(),"ES256K-R":U(!0),Ed25519:X(),EdDSA:X()},N=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=q);var t="string"==typeof r?r:H(r),i=[H(n),t].join("."),o=function(r){var e=B[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)}},V={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},q="ES256K";function H(r){return E(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(P(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function R(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=_(r);return Object.assign(e,{payload:JSON.parse(P(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function z(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),I(n.alg)(t,i,e)}var F="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function L(r,e,n){if(!r.s){if(n instanceof M){if(!n.s)return void(n.o=L.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(L.bind(null,r,e),L.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var M=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{L(t,1,o(this.v))}catch(r){L(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?L(t,1,e?e(i):i):n?L(t,1,n(i)):L(t,2,i)}catch(r){L(t,2,r)}},t},r}();function Z(r){return r instanceof M&&1&r.s}function $(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:g(r.iv),ciphertext:g(n),tag:g(t)};return e&&(o.aad=g(e)),i&&(o.recipients=[i]),o}function G(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 Q(r){var e=G(r);return{alg:"dir",enc:"XC20P",encrypt:function(r,n,t){void 0===n&&(n={});try{var i=E(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?i+"."+g(t):i));return Promise.resolve(j({},e(r,o),{protectedHeader:i}))}catch(r){return Promise.reject(r)}}}}function Y(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 rr(r,e){var n=function(n){try{var a=u.generateKeyPair(),c=G(d(u.sharedKey(a.secretKey,r),i,t))(n),f={encrypted_key:g(c.ciphertext),header:{alg:t,iv:g(c.iv),tag:g(c.tag),epk:{kty:"OKP",crv:o,x:g(a.publicKey)}}};return e&&(f.header.kid=e),Promise.resolve(f)}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(Q(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return j({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}r.EllipticSigner=function(r){var e=p(r);return function(r){try{return Promise.resolve(e(r)).then(function(r){return x(r)})}catch(r){return Promise.reject(r)}}},r.NaclSigner=function(r){var e=w(r);return function(r){try{var n=k(r),t=g(o.sign(e,n));return Promise.resolve(t)}catch(r){return Promise.reject(r)}}},r.SimpleSigner=p,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 $(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[F]){var t,i,o,a=r[F]();if(function r(n){try{for(;!(t=a.next()).done;)if((n=e(t.value))&&n.then){if(!Z(n))return void n.then(r,o||(o=L.bind(null,i=new M,2)));n=n.v}i?L(i,1,n):i=n}catch(r){L(i||(i=new M),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(!Z(a))return void a.then(n,i||(i=L.bind(null,t=new M,2)));a=a.v}t?L(t,1,a):t=a}catch(r){L(t||(t=new M),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=$(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=N,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=j({},u,r,{iss:t});return N(c,i,n)}catch(r){return Promise.reject(r)}},r.decodeJWT=R,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(P(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=K(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,m(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(Z(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!Z(o)){t=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!Z(a)){t=2;break}}}var u=new M,c=L.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&&!Z(a))return void a.then(l).then(void 0,c);if(!(i=r())||Z(i)&&!i.v)return void L(u,1,o);if(i.then)return void i.then(s).then(void 0,c);Z(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):L(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):L(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,m(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 rr(b(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},r.toEthereumAddress=s,r.verifyJWS=function(r,e){return z(_(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=R(r),t=n.payload,i=n.header,o=n.signature,a=n.data;return Promise.resolve(function(r,e,n,t){try{var i=V[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(z({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=m(o.header.epk.x),c=d(u.sharedKey(r,a),256,e),f=K(o.encrypted_key,o.header.tag);return Promise.resolve(Y(c).decrypt(f,m(o.header.iv))).then(function(r){return null===r?null:Y(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}},r.x25519Encrypter=rr,r.xc20pDirDecrypter=Y,r.xc20pDirEncrypter=Q}); | ||
//# sourceMappingURL=index.umd.js.map |
{ | ||
"name": "did-jwt", | ||
"version": "4.7.1", | ||
"version": "4.8.0", | ||
"description": "Library for Signing and Verifying JWTs compatible uPort and DID standards", | ||
@@ -65,3 +65,3 @@ "main": "lib/index.js", | ||
"@types/elliptic": "6.4.12", | ||
"@types/jest": "26.0.16", | ||
"@types/jest": "26.0.18", | ||
"codecov": "3.8.1", | ||
@@ -102,3 +102,3 @@ "eslint": "7.15.0", | ||
"@stablelib/xchacha20poly1305": "^1.0.0", | ||
"did-resolver": "^2.1.1", | ||
"did-resolver": "^2.1.2", | ||
"elliptic": "^6.5.3", | ||
@@ -105,0 +105,0 @@ "js-sha3": "^0.8.0", |
@@ -439,2 +439,23 @@ import { createJWT, verifyJWT, decodeJWT, createJWS, verifyJWS, resolveAuthenticator, NBF_SKEW } from '../JWT' | ||
const edKey6 = { | ||
id: `${did}#keys-auth6`, | ||
type: 'ED25519SignatureVerification', | ||
owner: did, | ||
publicKeyBase58: 'dummyvalue' | ||
} | ||
const ecKey7 = { | ||
id: `${did}#keys-auth7`, | ||
type: 'EcdsaSecp256k1VerificationKey2019', | ||
owner: did, | ||
publicKeyBase58: 'dummyvalue' | ||
} | ||
const edKey8 = { | ||
id: `${did}#keys-auth8`, | ||
type: 'Ed25519VerificationKey2018', | ||
owner: did, | ||
publicKeyBase58: 'dummyvalue' | ||
} | ||
const singleKey = { | ||
@@ -453,2 +474,9 @@ '@context': 'https://w3id.org/did/v1', | ||
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] | ||
} | ||
const unsupportedFormat = { | ||
@@ -502,2 +530,16 @@ '@context': 'https://w3id.org/did/v1', | ||
it('lists authenticators with multiple key types in doc', async () => { | ||
const authenticators = await resolveAuthenticator( | ||
{ resolve: jest.fn().mockReturnValue(multipleAuthTypes) }, | ||
alg, | ||
did, | ||
true | ||
) | ||
return expect(authenticators).toEqual({ | ||
authenticators: [ecKey1, ecKey2, ecKey7], | ||
issuer: did, | ||
doc: multipleAuthTypes | ||
}) | ||
}) | ||
it('errors if no suitable public keys exist', async () => { | ||
@@ -539,2 +581,16 @@ return await expect( | ||
it('lists authenticators with multiple key types in doc', async () => { | ||
const authenticators = await resolveAuthenticator( | ||
{ resolve: jest.fn().mockReturnValue(multipleAuthTypes) }, | ||
alg, | ||
did, | ||
true | ||
) | ||
return expect(authenticators).toEqual({ | ||
authenticators: [edKey, edKey6, edKey8], | ||
issuer: did, | ||
doc: multipleAuthTypes | ||
}) | ||
}) | ||
it('errors if no suitable public keys exist', async () => { | ||
@@ -551,3 +607,3 @@ return await expect( | ||
).rejects.toEqual( | ||
new Error(`DID document for ${did} does not have public keys suitable for authenticationg user`) | ||
new Error(`DID document for ${did} does not have public keys suitable for authenticating user`) | ||
) | ||
@@ -554,0 +610,0 @@ }) |
import VerifierAlgorithm from './VerifierAlgorithm' | ||
import SignerAlgorithm from './SignerAlgorithm' | ||
import { encodeBase64url, decodeBase64url, EcdsaSignature } from './util' | ||
import { DIDDocument, PublicKey } from 'did-resolver' | ||
import { DIDDocument, PublicKey, Authentication } from 'did-resolver' | ||
@@ -78,4 +78,14 @@ export type Signer = (data: string) => Promise<EcdsaSignature | string> | ||
export const SUPPORTED_PUBLIC_KEY_TYPES: PublicKeyTypes = { | ||
ES256K: ['Secp256k1VerificationKey2018', 'Secp256k1SignatureVerificationKey2018', 'EcdsaPublicKeySecp256k1', 'EcdsaSecp256k1VerificationKey2019'], | ||
'ES256K-R': ['Secp256k1VerificationKey2018', 'Secp256k1SignatureVerificationKey2018', 'EcdsaPublicKeySecp256k1', 'EcdsaSecp256k1VerificationKey2019'], | ||
ES256K: [ | ||
'Secp256k1VerificationKey2018', | ||
'Secp256k1SignatureVerificationKey2018', | ||
'EcdsaPublicKeySecp256k1', | ||
'EcdsaSecp256k1VerificationKey2019' | ||
], | ||
'ES256K-R': [ | ||
'Secp256k1VerificationKey2018', | ||
'Secp256k1SignatureVerificationKey2018', | ||
'EcdsaPublicKeySecp256k1', | ||
'EcdsaSecp256k1VerificationKey2019' | ||
], | ||
Ed25519: ['ED25519SignatureVerification', 'Ed25519VerificationKey2018'], | ||
@@ -123,3 +133,3 @@ EdDSA: ['ED25519SignatureVerification', 'Ed25519VerificationKey2018'] | ||
return decodedJwt | ||
} catch(e) { | ||
} catch (e) { | ||
throw new Error('Incorrect format JWT') | ||
@@ -141,3 +151,7 @@ } | ||
*/ | ||
export async function createJWS(payload: string | any, signer: Signer, header: Partial<JWTHeader> = {}): Promise<string> { | ||
export async function createJWS( | ||
payload: string | any, | ||
signer: Signer, | ||
header: Partial<JWTHeader> = {} | ||
): Promise<string> { | ||
if (!header.alg) header.alg = defaultAlg | ||
@@ -275,3 +289,3 @@ const encodedPayload = typeof payload === 'string' ? payload : encodeSection(payload) | ||
const audArray = Array.isArray(payload.aud) ? payload.aud : [payload.aud] | ||
const matchedAudience = audArray.find(item => options.audience === item || options.callbackUrl === item) | ||
const matchedAudience = audArray.find((item) => options.audience === item || options.callbackUrl === item) | ||
@@ -314,15 +328,29 @@ if (typeof matchedAudience === 'undefined') { | ||
if (!doc) throw new Error(`Unable to resolve DID document for ${issuer}`) | ||
// is there some way to have authenticationKeys be a single type? | ||
const authenticationKeys: boolean | string[] = auth | ||
? (doc.authentication || []).map(({ publicKey }) => publicKey) | ||
: true | ||
const authenticators: PublicKey[] = (doc.publicKey || []).filter(({ type, id }) => | ||
types.find( | ||
supported => | ||
supported === type && (!auth || (Array.isArray(authenticationKeys) && authenticationKeys.indexOf(id) >= 0)) | ||
) | ||
let getPublicKeyById = (doc: DIDDocument, pubid: string): PublicKey | null => { | ||
const filtered = doc.publicKey.filter(({ id }) => pubid === id) | ||
return filtered.length > 0 ? filtered[0] : null | ||
} | ||
let publicKeysToCheck: PublicKey[] = doc.publicKey || [] | ||
if (auth) { | ||
publicKeysToCheck = (doc.authentication || []) | ||
.map((authEntry) => { | ||
if (typeof authEntry === 'string') { | ||
return getPublicKeyById(doc, authEntry) | ||
} else if (typeof (<Authentication>authEntry).publicKey === 'string') { | ||
return getPublicKeyById(doc, (<Authentication>authEntry).publicKey) | ||
} else { | ||
return <PublicKey>authEntry | ||
} | ||
}) | ||
.filter((key) => key != null) | ||
} | ||
const authenticators: PublicKey[] = publicKeysToCheck.filter(({ type }) => | ||
types.find((supported) => supported === type) | ||
) | ||
if (auth && (!authenticators || authenticators.length === 0)) { | ||
throw new Error(`DID document for ${issuer} does not have public keys suitable for authenticationg user`) | ||
throw new Error(`DID document for ${issuer} does not have public keys suitable for authenticating user`) | ||
} | ||
@@ -329,0 +357,0 @@ if (!authenticators || authenticators.length === 0) { |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
921854
4343
0
Updateddid-resolver@^2.1.2