Comparing version 5.3.1 to 5.4.0
@@ -0,1 +1,8 @@ | ||
# [5.4.0](https://github.com/decentralized-identity/did-jwt/compare/5.3.1...5.4.0) (2021-05-18) | ||
### Features | ||
* add option to canonicalize JSON payloads ([#161](https://github.com/decentralized-identity/did-jwt/issues/161)) ([4cfd3ee](https://github.com/decentralized-identity/did-jwt/commit/4cfd3eef41d93cd0829b50c9a9bde9be3a0512d0)) | ||
## [5.3.1](https://github.com/decentralized-identity/did-jwt/compare/5.3.0...5.3.1) (2021-05-15) | ||
@@ -2,0 +9,0 @@ |
@@ -1,2 +0,2 @@ | ||
import{toString as e,fromString as r,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as o}from"js-sha3";import{ec as i}from"elliptic";import{sign as c,verify as u}from"@stablelib/ed25519";import{XChaCha20Poly1305 as a}from"@stablelib/xchacha20poly1305";import{generateKeyPair as s,sharedKey as f}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function h(r){return e(r,"base64url")}function d(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r(t,"base64url")}function p(e){return r(e,"base58btc")}function y(e){const t=e.startsWith("0x")?e.substring(2):e;return r(t.toLowerCase(),"base16")}function g(e){return h(r(e))}function m(r){return e(d(r))}function v(r){return e(r,"base16")}function w(e){return r(e)}function b({r:e,s:t,recoveryParam:n},o){const i=new Uint8Array(o?65:64);if(i.set(r(e,"base16"),0),i.set(r(t,"base16"),32),o){if(void 0===n)throw new Error("Signer did not return a recoveryParam");i[64]=n}return h(i)}function E(e){const r=d(e);if(r.length<64||r.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${r.length}`);return{r:v(r.slice(0,32)),s:v(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function P(e,r){return t([d(e),d(r)])}const k=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,K=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function x(e){if("string"==typeof e){if(k.test(e))return y(e);if(S.test(e))return p(e);if(K.test(e))return d(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function $(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function A(e){const t="string"==typeof e?r(e):e;return n(t)}function j(t){const n=r(t.slice(2),"base16");return`0x${e((i=n,new Uint8Array(o.arrayBuffer(i))).slice(-20),"base16")}`;var i}function D(e,t=new Uint8Array(4)){const n=r(e.toString(),"base10");return t.set(n,4-n.length),t}const J=e=>t([D(e.length),e]);function W(e,o,i){if(256!==o)throw new Error(`Unsupported key length: ${o}`);const c=t([J(r(i)),J(new Uint8Array(0)),J(new Uint8Array(0)),D(o)]);return n(t([D(1),e,c]))}const I=new i("secp256k1");function T(e,r=!1){const t=x(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=I.keyFromPrivate(t);return function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(A(e));return Promise.resolve(b({r:$(t.toString("hex")),s:$(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function C(e){const r=T(e,!0);return function(e){try{return Promise.resolve(r(e)).then(E)}catch(e){return Promise.reject(e)}}}function O(e){return T(e)}function R(e){const r=x(e);if(64!==r.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${r.length}`);return function(e){try{const t="string"==typeof e?w(e):e,n=c(r,t);return Promise.resolve(h(n))}catch(e){return Promise.reject(e)}}}function U(e){return R(e)}const M=new i("secp256k1");function N(e,r=!1){const t=d(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:v(t.slice(0,32)),s:v(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function B(e){return e.publicKeyBase58?p(e.publicKeyBase58):e.publicKeyBase64?d(e.publicKeyBase64):e.publicKeyHex?y(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?y(M.keyFromPublic({x:v(d(e.publicKeyJwk.x)),y:v(d(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function V(e,r,t){let n;if(r.length>86)n=[N(r,!0)];else{const e=N(r,!1);n=[{...e,recoveryParam:0},{...e,recoveryParam:1}]}const o=n.map(r=>{const n=A(e),o=M.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),c=o.encode("hex",!0),u=j(i);return t.find(e=>{const r=v(B(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===u||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===u})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function X(e,r,t){const n=w(e),o=d(r),i=t.find(e=>u(B(e),n,o));if(!i)throw new Error("Signature invalid for JWT");return i}const _={ES256K:function(e,r,t){const n=A(e),o=N(r),i=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0===e&&void 0===r),c=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0!==e||void 0!==typeof r);let u=i.find(e=>{try{const r=B(e);return M.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!u&&c.length>0&&(u=V(e,r,c)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":V,Ed25519:X,EdDSA:X};function z(e){const r=_[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}function H(e){return"object"==typeof e&&"r"in e&&"s"in e}function Z(e){return function(r,t){try{return Promise.resolve(t(r)).then(function(r){if(H(r))return b(r,e);if(e&&void 0===E(r).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return r})}catch(e){return Promise.reject(e)}}}function F(){return function(e,r){try{return Promise.resolve(r(e)).then(function(e){if(H(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}z.toSignatureObject=N;const L={ES256K:Z(),"ES256K-R":Z(!0),Ed25519:F(),EdDSA:F()},q=function(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null,proofPurpose:null}){try{if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:o,data:i}=ie(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=Y[r];if(!o||0===o.length)throw new Error(`No supported signature types for algorithm ${r}`);let i;return Promise.resolve(e.resolve(t,{accept:re})).then(function(e){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:re}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let u=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...u.map(e=>e.id)]),u=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(u,e):"string"==typeof e.publicKey?c(u,e.publicKey):e).filter(e=>null!=e));const a=u.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!a||0===a.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!a||0===a.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:a,issuer:t,didResolutionResult:i}})}catch(e){return Promise.reject(e)}}(r.resolver,n.alg,t.iss,c)).then(function({didResolutionResult:c,authenticators:u,issuer:a}){return Promise.resolve(ce({header:n,data:i,signature:o},u)).then(function(n){const o=Math.floor(Date.now()/1e3),i=r.skewTime>=0?r.skewTime:ne;if(n){const u=o+i;if(t.nbf){if(t.nbf>u)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>u)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=o-i)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${o}`);if(t.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,didResolutionResult:c,issuer:a,signer:n,jwt:e}}})})}catch(e){return Promise.reject(e)}},G=function(e,{issuer:r,signer:t,alg:n,expiresIn:o},i={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");i.typ||(i.typ="JWT"),i.alg||(i.alg=n);const c={iat:Math.floor(Date.now()/1e3),exp:void 0};if(o){if("number"!=typeof o)throw new Error("JWT expiresIn is not a number");c.exp=(e.nbf||c.iat)+Math.floor(o)}const u={...c,...e,iss:r};return Q(u,t,i)}catch(e){return Promise.reject(e)}},Q=function(e,r,t={}){try{t.alg||(t.alg=ee);const n="string"==typeof e?e:te(e),o=[te(t),n].join("."),i=function(e){const r=L[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(i(o,r)).then(function(e){return[o,e].join(".")})}catch(e){return Promise.reject(e)}},Y={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},ee="ES256K",re="application/did+json";function te(e){return g(JSON.stringify(e))}const ne=300;function oe(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(m(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function ie(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=oe(e);return Object.assign(r,{payload:JSON.parse(m(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function ce({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),z(e.alg)(r,t,n)}function ue(e,r){return ce(oe(e),r)}const ae=function(e,r){try{function t(e){if(null===c)throw new Error("Failed to decrypt");return c}!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const n=JSON.parse(m(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const o=P(e.ciphertext,e.tag),i=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let c=null;const u="dir"===n.alg&&"dir"===r.alg?Promise.resolve(r.decrypt(o,d(e.iv),i)).then(function(e){c=e}):function(){if(e.recipients&&0!==e.recipients.length){let t=0;return function(e,r,t){for(var n;;){var o=e();if(he(o)&&(o=o.v),!o)return i;if(o.then){n=0;break}var i=t();if(i&&i.then){if(!he(i)){n=1;break}i=i.s}if(r){var c=r();if(c&&c.then&&!he(c)){n=2;break}}}var u=new le,a=fe.bind(null,u,2);return(0===n?o.then(f):1===n?i.then(s):c.then(l)).then(void 0,a),u;function s(n){i=n;do{if(r&&(c=r())&&c.then&&!he(c))return void c.then(l).then(void 0,a);if(!(o=e())||he(o)&&!o.v)return void fe(u,1,i);if(o.then)return void o.then(f).then(void 0,a);he(i=t())&&(i=i.v)}while(!i||!i.then);i.then(s).then(void 0,a)}function f(e){e?(i=t())&&i.then?i.then(s).then(void 0,a):s(i):fe(u,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,a):f(o):fe(u,1,i)}}(function(){return!c&&t<e.recipients.length},function(){return t++},function(){const u=e.recipients[t];Object.assign(u.header,n);const a=function(){if(u.header.alg===r.alg)return Promise.resolve(r.decrypt(o,d(e.iv),i,u)).then(function(e){c=e})}();if(a&&a.then)return a.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(e){return Promise.reject(e)}},se="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function fe(e,r,t){if(!e.s){if(t instanceof le){if(!t.s)return void(t.o=fe.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(fe.bind(null,e,r),fe.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const le=function(){function e(){}return e.prototype.then=function(r,t){const n=new e,o=this.s;if(o){const e=1&o?r:t;if(e){try{fe(n,1,e(this.v))}catch(e){fe(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?fe(n,1,r?r(o):o):t?fe(n,1,t(o)):fe(n,2,o)}catch(e){fe(n,2,e)}},n},e}();function he(e){return e instanceof le&&1&e.s}function de({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const c={protected:n,iv:h(t),ciphertext:h(e),tag:h(r)};return i&&(c.aad=h(i)),o&&(c.recipients=[o]),c}const pe=function(e,r,t={},n){try{if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(r[0].encrypt(e,t,n)).then(function(e){return de(e,n)})}{const o=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===o,!0))throw new Error("Incompatible encrypters passed");let i,c;const u=function(e,r,t){if("function"==typeof e[se]){var n,o,i,c=e[se]();if(function e(t){try{for(;!(n=c.next()).done;)if((t=r(n.value))&&t.then){if(!he(t))return void t.then(e,i||(i=fe.bind(null,o=new le,2)));t=t.v}o?fe(o,1,t):o=t}catch(e){fe(o||(o=new le),2,e)}}(),c.return){var u=function(e){try{n.done||c.return()}catch(e){}return e};if(o&&o.then)return o.then(u,function(e){throw u(e)});u()}return o}if(!("length"in e))throw new TypeError("Object is not iterable");for(var a=[],s=0;s<e.length;s++)a.push(e[s]);return function(e,r,t){var n,o,i=-1;return function t(c){try{for(;++i<e.length;)if((c=r(i))&&c.then){if(!he(c))return void c.then(t,o||(o=fe.bind(null,n=new le,2)));c=c.v}n?fe(n,1,c):n=c}catch(e){fe(n||(n=new le),2,e)}}(),n}(a,function(e){return r(a[e])})}(r,function(r){const o=function(){if(i){const e=c.recipients,t=e.push;return Promise.resolve(r.encryptCek(i)).then(function(r){t.call(e,r)})}return Promise.resolve(r.encrypt(e,t,n)).then(function(e){i=e.cek,c=de(e,n)})}();if(o&&o.then)return o.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return c}):c)}}catch(e){return Promise.reject(e)}},ye=function(e,r){try{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(r?.error)throw new Error(`Could not find x25519 key for ${e}: ${r.error}, ${r.message}`);if(!t.keyAgreement)throw new Error(`Could not find x25519 key for ${e}`);const n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>be(p(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(ge)}catch(e){return Promise.reject(e)}},ge=e=>[].concat.apply([],e);function me(e){const r=new a(e);return(e,t)=>{const n=l(r.nonceLength),o=r.seal(n,e,t);return{ciphertext:o.subarray(0,o.length-r.tagLength),tag:o.subarray(o.length-r.tagLength),iv:n}}}function ve(e){const r=me(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=g(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),c=new Uint8Array(Buffer.from(o?`${i}.${h(o)}`:i));return Promise.resolve({...r(e,c),protectedHeader:i})}catch(e){return Promise.reject(e)}}}}function we(e){const r=new a(e);return{alg:"dir",enc:"XC20P",decrypt:function(e,t,n){try{return Promise.resolve(r.open(t,e,n))}catch(e){return Promise.reject(e)}}}}function be(e,r){const t=function(t){try{const c=s(),u=me(W(f(c.secretKey,e),o,n))(t),a={encrypted_key:h(u.ciphertext),header:{alg:n,iv:h(u.iv),tag:h(u.tag),epk:{kty:"OKP",crv:i,x:h(c.publicKey)}}};return r&&(a.header.kid=r),Promise.resolve(a)}catch(e){return Promise.reject(e)}},n="ECDH-ES+XC20PKW",o=256,i="X25519";return{alg:n,enc:"XC20P",encrypt:function(e,r={},n){try{Object.assign(r,{alg:void 0});const o=l(32);return Promise.resolve(ve(o).encrypt(e,r,n)).then(function(e){return Promise.resolve(t(o)).then(function(r){return{...e,recipient:r,cek:o}})})}catch(e){return Promise.reject(e)}},encryptCek:t}}function Ee(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:function(t,n,o,i){try{if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(i.header),"X25519"!==i.header.epk.crv)return Promise.resolve(null);const c=d(i.header.epk.x),u=W(f(e,c),256,r),a=P(i.encrypted_key,i.header.tag);return Promise.resolve(we(u).decrypt(a,d(i.header.iv))).then(function(e){return null===e?null:we(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}}export{T as ES256KSigner,R as EdDSASigner,O as EllipticSigner,U as NaclSigner,C as SimpleSigner,pe as createJWE,Q as createJWS,G as createJWT,ie as decodeJWT,ae as decryptJWE,ye as resolveX25519Encrypters,j as toEthereumAddress,ue as verifyJWS,q as verifyJWT,Ee as x25519Decrypter,be as x25519Encrypter,we as xc20pDirDecrypter,ve as xc20pDirEncrypter}; | ||
import{toString as e,fromString as r,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as o}from"js-sha3";import{ec as i}from"elliptic";import{sign as c,verify as u}from"@stablelib/ed25519";import a from"canonicalize";import{XChaCha20Poly1305 as s}from"@stablelib/xchacha20poly1305";import{generateKeyPair as f,sharedKey as l}from"@stablelib/x25519";import{randomBytes as h}from"@stablelib/random";function d(r){return e(r,"base64url")}function p(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r(t,"base64url")}function y(e){return r(e,"base58btc")}function g(e){const t=e.startsWith("0x")?e.substring(2):e;return r(t.toLowerCase(),"base16")}function m(e){return d(r(e))}function v(r){return e(p(r))}function w(r){return e(r,"base16")}function b(e){return r(e)}function E({r:e,s:t,recoveryParam:n},o){const i=new Uint8Array(o?65:64);if(i.set(r(e,"base16"),0),i.set(r(t,"base16"),32),o){if(void 0===n)throw new Error("Signer did not return a recoveryParam");i[64]=n}return d(i)}function P(e){const r=p(e);if(r.length<64||r.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${r.length}`);return{r:w(r.slice(0,32)),s:w(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function k(e,r){return t([p(e),p(r)])}const S=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,K=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,x=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function $(e){if("string"==typeof e){if(S.test(e))return g(e);if(K.test(e))return y(e);if(x.test(e))return p(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function A(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function j(e){const t="string"==typeof e?r(e):e;return n(t)}function D(t){const n=r(t.slice(2),"base16");return`0x${e((i=n,new Uint8Array(o.arrayBuffer(i))).slice(-20),"base16")}`;var i}function J(e,t=new Uint8Array(4)){const n=r(e.toString(),"base10");return t.set(n,4-n.length),t}const W=e=>t([J(e.length),e]);function I(e,o,i){if(256!==o)throw new Error(`Unsupported key length: ${o}`);const c=t([W(r(i)),W(new Uint8Array(0)),W(new Uint8Array(0)),J(o)]);return n(t([J(1),e,c]))}const T=new i("secp256k1");function O(e,r=!1){const t=$(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=T.keyFromPrivate(t);return function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(j(e));return Promise.resolve(E({r:A(t.toString("hex")),s:A(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function C(e){const r=O(e,!0);return function(e){try{return Promise.resolve(r(e)).then(P)}catch(e){return Promise.reject(e)}}}function R(e){return O(e)}function U(e){const r=$(e);if(64!==r.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${r.length}`);return function(e){try{const t="string"==typeof e?b(e):e,n=c(r,t);return Promise.resolve(d(n))}catch(e){return Promise.reject(e)}}}function M(e){return U(e)}function z(e){return"object"==typeof e&&"r"in e&&"s"in e}function N(e){return function(r,t){try{return Promise.resolve(t(r)).then(function(r){if(z(r))return E(r,e);if(e&&void 0===P(r).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return r})}catch(e){return Promise.reject(e)}}}function B(){return function(e,r){try{return Promise.resolve(r(e)).then(function(e){if(z(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}const V={ES256K:N(),"ES256K-R":N(!0),Ed25519:B(),EdDSA:B()},X=new i("secp256k1");function _(e,r=!1){const t=p(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:w(t.slice(0,32)),s:w(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function H(e){return e.publicKeyBase58?y(e.publicKeyBase58):e.publicKeyBase64?p(e.publicKeyBase64):e.publicKeyHex?g(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?g(X.keyFromPublic({x:w(p(e.publicKeyJwk.x)),y:w(p(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function Z(e,r,t){let n;if(r.length>86)n=[_(r,!0)];else{const e=_(r,!1);n=[{...e,recoveryParam:0},{...e,recoveryParam:1}]}const o=n.map(r=>{const n=j(e),o=X.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),c=o.encode("hex",!0),u=D(i);return t.find(e=>{const r=w(H(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===u||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===u})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function F(e,r,t){const n=b(e),o=p(r),i=t.find(e=>u(H(e),n,o));if(!i)throw new Error("Signature invalid for JWT");return i}const L={ES256K:function(e,r,t){const n=j(e),o=_(r),i=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0===e&&void 0===r),c=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0!==e||void 0!==typeof r);let u=i.find(e=>{try{const r=H(e);return X.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!u&&c.length>0&&(u=Z(e,r,c)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":Z,Ed25519:F,EdDSA:F};function q(e){const r=L[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}q.toSignatureObject=_;const G=function(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null,proofPurpose:null}){try{if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:o,data:i}=ce(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=ee[r];if(!o||0===o.length)throw new Error(`No supported signature types for algorithm ${r}`);let i;return Promise.resolve(e.resolve(t,{accept:te})).then(function(e){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:te}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let u=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...u.map(e=>e.id)]),u=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(u,e):"string"==typeof e.publicKey?c(u,e.publicKey):e).filter(e=>null!=e));const a=u.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!a||0===a.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!a||0===a.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:a,issuer:t,didResolutionResult:i}})}catch(e){return Promise.reject(e)}}(r.resolver,n.alg,t.iss,c)).then(function({didResolutionResult:c,authenticators:u,issuer:a}){return Promise.resolve(ue({header:n,data:i,signature:o},u)).then(function(n){const o=Math.floor(Date.now()/1e3),i=r.skewTime>=0?r.skewTime:oe;if(n){const u=o+i;if(t.nbf){if(t.nbf>u)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>u)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=o-i)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${o}`);if(t.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,didResolutionResult:c,issuer:a,signer:n,jwt:e}}})})}catch(e){return Promise.reject(e)}},Q=function(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},c={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");c.typ||(c.typ="JWT"),c.alg||(c.alg=n);const u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(o){if("number"!=typeof o)throw new Error("JWT expiresIn is not a number");u.exp=(e.nbf||u.iat)+Math.floor(o)}const a={...u,...e,iss:r};return Y(a,t,c,{canonicalize:i})}catch(e){return Promise.reject(e)}},Y=function(e,r,t={},n={}){try{t.alg||(t.alg=re);const o="string"==typeof e?e:ne(e,n.canonicalize),i=[ne(t,n.canonicalize),o].join("."),c=function(e){const r=V[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(c(i,r)).then(function(e){return[i,e].join(".")})}catch(e){return Promise.reject(e)}},ee={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},re="ES256K",te="application/did+json";function ne(e,r=!1){return m(r?JSON.stringify(a(e)):JSON.stringify(e))}const oe=300;function ie(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(v(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function ce(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=ie(e);return Object.assign(r,{payload:JSON.parse(v(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function ue({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),q(e.alg)(r,t,n)}function ae(e,r){return ue(ie(e),r)}const se=function(e,r){try{function t(e){if(null===c)throw new Error("Failed to decrypt");return c}!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const n=JSON.parse(v(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const o=k(e.ciphertext,e.tag),i=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let c=null;const u="dir"===n.alg&&"dir"===r.alg?Promise.resolve(r.decrypt(o,p(e.iv),i)).then(function(e){c=e}):function(){if(e.recipients&&0!==e.recipients.length){let t=0;return function(e,r,t){for(var n;;){var o=e();if(de(o)&&(o=o.v),!o)return i;if(o.then){n=0;break}var i=t();if(i&&i.then){if(!de(i)){n=1;break}i=i.s}if(r){var c=r();if(c&&c.then&&!de(c)){n=2;break}}}var u=new he,a=le.bind(null,u,2);return(0===n?o.then(f):1===n?i.then(s):c.then(l)).then(void 0,a),u;function s(n){i=n;do{if(r&&(c=r())&&c.then&&!de(c))return void c.then(l).then(void 0,a);if(!(o=e())||de(o)&&!o.v)return void le(u,1,i);if(o.then)return void o.then(f).then(void 0,a);de(i=t())&&(i=i.v)}while(!i||!i.then);i.then(s).then(void 0,a)}function f(e){e?(i=t())&&i.then?i.then(s).then(void 0,a):s(i):le(u,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,a):f(o):le(u,1,i)}}(function(){return!c&&t<e.recipients.length},function(){return t++},function(){const u=e.recipients[t];Object.assign(u.header,n);const a=function(){if(u.header.alg===r.alg)return Promise.resolve(r.decrypt(o,p(e.iv),i,u)).then(function(e){c=e})}();if(a&&a.then)return a.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(e){return Promise.reject(e)}},fe="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function le(e,r,t){if(!e.s){if(t instanceof he){if(!t.s)return void(t.o=le.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(le.bind(null,e,r),le.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const he=function(){function e(){}return e.prototype.then=function(r,t){const n=new e,o=this.s;if(o){const e=1&o?r:t;if(e){try{le(n,1,e(this.v))}catch(e){le(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?le(n,1,r?r(o):o):t?le(n,1,t(o)):le(n,2,o)}catch(e){le(n,2,e)}},n},e}();function de(e){return e instanceof he&&1&e.s}function pe({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const c={protected:n,iv:d(t),ciphertext:d(e),tag:d(r)};return i&&(c.aad=d(i)),o&&(c.recipients=[o]),c}const ye=function(e,r,t={},n){try{if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(r[0].encrypt(e,t,n)).then(function(e){return pe(e,n)})}{const o=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===o,!0))throw new Error("Incompatible encrypters passed");let i,c;const u=function(e,r,t){if("function"==typeof e[fe]){var n,o,i,c=e[fe]();if(function e(t){try{for(;!(n=c.next()).done;)if((t=r(n.value))&&t.then){if(!de(t))return void t.then(e,i||(i=le.bind(null,o=new he,2)));t=t.v}o?le(o,1,t):o=t}catch(e){le(o||(o=new he),2,e)}}(),c.return){var u=function(e){try{n.done||c.return()}catch(e){}return e};if(o&&o.then)return o.then(u,function(e){throw u(e)});u()}return o}if(!("length"in e))throw new TypeError("Object is not iterable");for(var a=[],s=0;s<e.length;s++)a.push(e[s]);return function(e,r,t){var n,o,i=-1;return function t(c){try{for(;++i<e.length;)if((c=r(i))&&c.then){if(!de(c))return void c.then(t,o||(o=le.bind(null,n=new he,2)));c=c.v}n?le(n,1,c):n=c}catch(e){le(n||(n=new he),2,e)}}(),n}(a,function(e){return r(a[e])})}(r,function(r){const o=function(){if(i){const e=c.recipients,t=e.push;return Promise.resolve(r.encryptCek(i)).then(function(r){t.call(e,r)})}return Promise.resolve(r.encrypt(e,t,n)).then(function(e){i=e.cek,c=pe(e,n)})}();if(o&&o.then)return o.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return c}):c)}}catch(e){return Promise.reject(e)}},ge=function(e,r){try{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(r?.error)throw new Error(`Could not find x25519 key for ${e}: ${r.error}, ${r.message}`);if(!t.keyAgreement)throw new Error(`Could not find x25519 key for ${e}`);const n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>Ee(y(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(me)}catch(e){return Promise.reject(e)}},me=e=>[].concat.apply([],e);function ve(e){const r=new s(e);return(e,t)=>{const n=h(r.nonceLength),o=r.seal(n,e,t);return{ciphertext:o.subarray(0,o.length-r.tagLength),tag:o.subarray(o.length-r.tagLength),iv:n}}}function we(e){const r=ve(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=m(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),c=new Uint8Array(Buffer.from(o?`${i}.${d(o)}`:i));return Promise.resolve({...r(e,c),protectedHeader:i})}catch(e){return Promise.reject(e)}}}}function be(e){const r=new s(e);return{alg:"dir",enc:"XC20P",decrypt:function(e,t,n){try{return Promise.resolve(r.open(t,e,n))}catch(e){return Promise.reject(e)}}}}function Ee(e,r){const t=function(t){try{const c=f(),u=ve(I(l(c.secretKey,e),o,n))(t),a={encrypted_key:d(u.ciphertext),header:{alg:n,iv:d(u.iv),tag:d(u.tag),epk:{kty:"OKP",crv:i,x:d(c.publicKey)}}};return r&&(a.header.kid=r),Promise.resolve(a)}catch(e){return Promise.reject(e)}},n="ECDH-ES+XC20PKW",o=256,i="X25519";return{alg:n,enc:"XC20P",encrypt:function(e,r={},n){try{Object.assign(r,{alg:void 0});const o=h(32);return Promise.resolve(we(o).encrypt(e,r,n)).then(function(e){return Promise.resolve(t(o)).then(function(r){return{...e,recipient:r,cek:o}})})}catch(e){return Promise.reject(e)}},encryptCek:t}}function Pe(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:function(t,n,o,i){try{if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(i.header),"X25519"!==i.header.epk.crv)return Promise.resolve(null);const c=p(i.header.epk.x),u=I(l(e,c),256,r),a=k(i.encrypted_key,i.header.tag);return Promise.resolve(be(u).decrypt(a,p(i.header.iv))).then(function(e){return null===e?null:be(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}}export{O as ES256KSigner,U as EdDSASigner,R as EllipticSigner,M as NaclSigner,C as SimpleSigner,ye as createJWE,Y as createJWS,Q as createJWT,ce as decodeJWT,se as decryptJWE,ge as resolveX25519Encrypters,D as toEthereumAddress,ae as verifyJWS,G as verifyJWT,Pe as x25519Decrypter,Ee as x25519Encrypter,be as xc20pDirDecrypter,we as xc20pDirEncrypter}; | ||
//# sourceMappingURL=index.esm.js.map |
@@ -1,2 +0,2 @@ | ||
var e=require("uint8arrays"),r=require("@stablelib/sha256"),t=require("js-sha3"),n=require("elliptic"),o=require("@stablelib/ed25519"),i=require("@stablelib/xchacha20poly1305"),c=require("@stablelib/x25519"),u=require("@stablelib/random");function a(r){return e.toString(r,"base64url")}function s(r){const t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e.fromString(t,"base64url")}function f(r){return e.fromString(r,"base58btc")}function l(r){const t=r.startsWith("0x")?r.substring(2):r;return e.fromString(t.toLowerCase(),"base16")}function h(r){return a(e.fromString(r))}function d(r){return e.toString(s(r))}function p(r){return e.toString(r,"base16")}function y(r){return e.fromString(r)}function g({r:r,s:t,recoveryParam:n},o){const i=new Uint8Array(o?65:64);if(i.set(e.fromString(r,"base16"),0),i.set(e.fromString(t,"base16"),32),o){if(void 0===n)throw new Error("Signer did not return a recoveryParam");i[64]=n}return a(i)}function v(e){const r=s(e);if(r.length<64||r.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${r.length}`);return{r:p(r.slice(0,32)),s:p(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function m(r,t){return e.concat([s(r),s(t)])}const w=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,b=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,E=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function P(e){if("string"==typeof e){if(w.test(e))return l(e);if(b.test(e))return f(e);if(E.test(e))return s(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function S(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function k(t){const n="string"==typeof t?e.fromString(t):t;return r.hash(n)}function x(r){const n=e.fromString(r.slice(2),"base16");return`0x${e.toString((o=n,new Uint8Array(t.keccak_256.arrayBuffer(o))).slice(-20),"base16")}`;var o}function K(r,t=new Uint8Array(4)){const n=e.fromString(r.toString(),"base10");return t.set(n,4-n.length),t}const A=r=>e.concat([K(r.length),r]);function D(t,n,o){if(256!==n)throw new Error(`Unsupported key length: ${n}`);const i=e.concat([A(e.fromString(o)),A(new Uint8Array(0)),A(new Uint8Array(0)),K(n)]);return r.hash(e.concat([K(1),t,i]))}const J=new n.ec("secp256k1");function $(e,r=!1){const t=P(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=J.keyFromPrivate(t);return function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(k(e));return Promise.resolve(g({r:S(t.toString("hex")),s:S(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function j(e){const r=P(e);if(64!==r.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${r.length}`);return function(e){try{const t="string"==typeof e?y(e):e,n=o.sign(r,t);return Promise.resolve(a(n))}catch(e){return Promise.reject(e)}}}const W=new n.ec("secp256k1");function T(e,r=!1){const t=s(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:p(t.slice(0,32)),s:p(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function I(e){return e.publicKeyBase58?f(e.publicKeyBase58):e.publicKeyBase64?s(e.publicKeyBase64):e.publicKeyHex?l(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?l(W.keyFromPublic({x:p(s(e.publicKeyJwk.x)),y:p(s(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function C(e,r,t){let n;if(r.length>86)n=[T(r,!0)];else{const e=T(r,!1);n=[{...e,recoveryParam:0},{...e,recoveryParam:1}]}const o=n.map(r=>{const n=k(e),o=W.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),c=o.encode("hex",!0),u=x(i);return t.find(e=>{const r=p(I(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===u||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===u})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function O(e,r,t){const n=y(e),i=s(r),c=t.find(e=>o.verify(I(e),n,i));if(!c)throw new Error("Signature invalid for JWT");return c}const R={ES256K:function(e,r,t){const n=k(e),o=T(r),i=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0===e&&void 0===r),c=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0!==e||void 0!==typeof r);let u=i.find(e=>{try{const r=I(e);return W.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!u&&c.length>0&&(u=C(e,r,c)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":C,Ed25519:O,EdDSA:O};function U(e){const r=R[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}function M(e){return"object"==typeof e&&"r"in e&&"s"in e}function N(e){return function(r,t){try{return Promise.resolve(t(r)).then(function(r){if(M(r))return g(r,e);if(e&&void 0===v(r).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return r})}catch(e){return Promise.reject(e)}}}function B(){return function(e,r){try{return Promise.resolve(r(e)).then(function(e){if(M(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}U.toSignatureObject=T;const X={ES256K:N(),"ES256K-R":N(!0),Ed25519:B(),EdDSA:B()},V=function(e,r,t={}){try{t.alg||(t.alg=q);const n="string"==typeof e?e:z(e),o=[z(t),n].join("."),i=function(e){const r=X[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(i(o,r)).then(function(e){return[o,e].join(".")})}catch(e){return Promise.reject(e)}},_={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},q="ES256K";function z(e){return h(JSON.stringify(e))}function H(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(d(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function Z(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=H(e);return Object.assign(r,{payload:JSON.parse(d(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function F({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),U(e.alg)(r,t,n)}const L="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function G(e,r,t){if(!e.s){if(t instanceof Q){if(!t.s)return void(t.o=G.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(G.bind(null,e,r),G.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const Q=function(){function e(){}return e.prototype.then=function(r,t){const n=new e,o=this.s;if(o){const e=1&o?r:t;if(e){try{G(n,1,e(this.v))}catch(e){G(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?G(n,1,r?r(o):o):t?G(n,1,t(o)):G(n,2,o)}catch(e){G(n,2,e)}},n},e}();function Y(e){return e instanceof Q&&1&e.s}function ee({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const c={protected:n,iv:a(t),ciphertext:a(e),tag:a(r)};return i&&(c.aad=a(i)),o&&(c.recipients=[o]),c}const re=e=>[].concat.apply([],e);function te(e){const r=new i.XChaCha20Poly1305(e);return(e,t)=>{const n=u.randomBytes(r.nonceLength),o=r.seal(n,e,t);return{ciphertext:o.subarray(0,o.length-r.tagLength),tag:o.subarray(o.length-r.tagLength),iv:n}}}function ne(e){const r=te(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=h(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),c=new Uint8Array(Buffer.from(o?`${i}.${a(o)}`:i));return Promise.resolve({...r(e,c),protectedHeader:i})}catch(e){return Promise.reject(e)}}}}function oe(e){const r=new i.XChaCha20Poly1305(e);return{alg:"dir",enc:"XC20P",decrypt:function(e,t,n){try{return Promise.resolve(r.open(t,e,n))}catch(e){return Promise.reject(e)}}}}function ie(e,r){const t=function(t){try{const u=c.generateKeyPair(),s=te(D(c.sharedKey(u.secretKey,e),o,n))(t),f={encrypted_key:a(s.ciphertext),header:{alg:n,iv:a(s.iv),tag:a(s.tag),epk:{kty:"OKP",crv:i,x:a(u.publicKey)}}};return r&&(f.header.kid=r),Promise.resolve(f)}catch(e){return Promise.reject(e)}},n="ECDH-ES+XC20PKW",o=256,i="X25519";return{alg:n,enc:"XC20P",encrypt:function(e,r={},n){try{Object.assign(r,{alg:void 0});const o=u.randomBytes(32);return Promise.resolve(ne(o).encrypt(e,r,n)).then(function(e){return Promise.resolve(t(o)).then(function(r){return{...e,recipient:r,cek:o}})})}catch(e){return Promise.reject(e)}},encryptCek:t}}exports.ES256KSigner=$,exports.EdDSASigner=j,exports.EllipticSigner=function(e){return $(e)},exports.NaclSigner=function(e){return j(e)},exports.SimpleSigner=function(e){const r=$(e,!0);return function(e){try{return Promise.resolve(r(e)).then(v)}catch(e){return Promise.reject(e)}}},exports.createJWE=function(e,r,t={},n){try{if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(r[0].encrypt(e,t,n)).then(function(e){return ee(e,n)})}{const o=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===o,!0))throw new Error("Incompatible encrypters passed");let i,c;const u=function(e,r,t){if("function"==typeof e[L]){var n,o,i,c=e[L]();if(function e(t){try{for(;!(n=c.next()).done;)if((t=r(n.value))&&t.then){if(!Y(t))return void t.then(e,i||(i=G.bind(null,o=new Q,2)));t=t.v}o?G(o,1,t):o=t}catch(e){G(o||(o=new Q),2,e)}}(),c.return){var u=function(e){try{n.done||c.return()}catch(e){}return e};if(o&&o.then)return o.then(u,function(e){throw u(e)});u()}return o}if(!("length"in e))throw new TypeError("Object is not iterable");for(var a=[],s=0;s<e.length;s++)a.push(e[s]);return function(e,r,t){var n,o,i=-1;return function t(c){try{for(;++i<e.length;)if((c=r(i))&&c.then){if(!Y(c))return void c.then(t,o||(o=G.bind(null,n=new Q,2)));c=c.v}n?G(n,1,c):n=c}catch(e){G(n||(n=new Q),2,e)}}(),n}(a,function(e){return r(a[e])})}(r,function(r){const o=function(){if(i){const e=c.recipients,t=e.push;return Promise.resolve(r.encryptCek(i)).then(function(r){t.call(e,r)})}return Promise.resolve(r.encrypt(e,t,n)).then(function(e){i=e.cek,c=ee(e,n)})}();if(o&&o.then)return o.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return c}):c)}}catch(e){return Promise.reject(e)}},exports.createJWS=V,exports.createJWT=function(e,{issuer:r,signer:t,alg:n,expiresIn:o},i={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");i.typ||(i.typ="JWT"),i.alg||(i.alg=n);const c={iat:Math.floor(Date.now()/1e3),exp:void 0};if(o){if("number"!=typeof o)throw new Error("JWT expiresIn is not a number");c.exp=(e.nbf||c.iat)+Math.floor(o)}const u={...c,...e,iss:r};return V(u,t,i)}catch(e){return Promise.reject(e)}},exports.decodeJWT=Z,exports.decryptJWE=function(e,r){try{function t(e){if(null===c)throw new Error("Failed to decrypt");return c}!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const n=JSON.parse(d(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const o=m(e.ciphertext,e.tag),i=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let c=null;const u="dir"===n.alg&&"dir"===r.alg?Promise.resolve(r.decrypt(o,s(e.iv),i)).then(function(e){c=e}):function(){if(e.recipients&&0!==e.recipients.length){let t=0;return function(e,r,t){for(var n;;){var o=e();if(Y(o)&&(o=o.v),!o)return i;if(o.then){n=0;break}var i=t();if(i&&i.then){if(!Y(i)){n=1;break}i=i.s}if(r){var c=r();if(c&&c.then&&!Y(c)){n=2;break}}}var u=new Q,a=G.bind(null,u,2);return(0===n?o.then(f):1===n?i.then(s):c.then(l)).then(void 0,a),u;function s(n){i=n;do{if(r&&(c=r())&&c.then&&!Y(c))return void c.then(l).then(void 0,a);if(!(o=e())||Y(o)&&!o.v)return void G(u,1,i);if(o.then)return void o.then(f).then(void 0,a);Y(i=t())&&(i=i.v)}while(!i||!i.then);i.then(s).then(void 0,a)}function f(e){e?(i=t())&&i.then?i.then(s).then(void 0,a):s(i):G(u,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,a):f(o):G(u,1,i)}}(function(){return!c&&t<e.recipients.length},function(){return t++},function(){const u=e.recipients[t];Object.assign(u.header,n);const a=function(){if(u.header.alg===r.alg)return Promise.resolve(r.decrypt(o,s(e.iv),i,u)).then(function(e){c=e})}();if(a&&a.then)return a.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(e){return Promise.reject(e)}},exports.resolveX25519Encrypters=function(e,r){try{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(r?.error)throw new Error(`Could not find x25519 key for ${e}: ${r.error}, ${r.message}`);if(!t.keyAgreement)throw new Error(`Could not find x25519 key for ${e}`);const n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>ie(f(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(re)}catch(e){return Promise.reject(e)}},exports.toEthereumAddress=x,exports.verifyJWS=function(e,r){return F(H(e),r)},exports.verifyJWT=function(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null,proofPurpose:null}){try{if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:o,data:i}=Z(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=_[r];if(!o||0===o.length)throw new Error(`No supported signature types for algorithm ${r}`);let i;return Promise.resolve(e.resolve(t,{accept:"application/did+json"})).then(function(e){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:"application/did+json"}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let u=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...u.map(e=>e.id)]),u=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(u,e):"string"==typeof e.publicKey?c(u,e.publicKey):e).filter(e=>null!=e));const a=u.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!a||0===a.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!a||0===a.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:a,issuer:t,didResolutionResult:i}})}catch(e){return Promise.reject(e)}}(r.resolver,n.alg,t.iss,c)).then(function({didResolutionResult:c,authenticators:u,issuer:a}){return Promise.resolve(F({header:n,data:i,signature:o},u)).then(function(n){const o=Math.floor(Date.now()/1e3),i=r.skewTime>=0?r.skewTime:300;if(n){const u=o+i;if(t.nbf){if(t.nbf>u)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>u)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=o-i)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${o}`);if(t.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,didResolutionResult:c,issuer:a,signer:n,jwt:e}}})})}catch(e){return Promise.reject(e)}},exports.x25519Decrypter=function(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:function(t,n,o,i){try{if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(i.header),"X25519"!==i.header.epk.crv)return Promise.resolve(null);const u=s(i.header.epk.x),a=D(c.sharedKey(e,u),256,r),f=m(i.encrypted_key,i.header.tag);return Promise.resolve(oe(a).decrypt(f,s(i.header.iv))).then(function(e){return null===e?null:oe(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}},exports.x25519Encrypter=ie,exports.xc20pDirDecrypter=oe,exports.xc20pDirEncrypter=ne; | ||
var e=require("uint8arrays"),r=require("@stablelib/sha256"),t=require("js-sha3"),n=require("elliptic"),o=require("@stablelib/ed25519"),i=require("canonicalize"),c=require("@stablelib/xchacha20poly1305"),a=require("@stablelib/x25519"),u=require("@stablelib/random");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var f=s(i);function l(r){return e.toString(r,"base64url")}function d(r){const t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e.fromString(t,"base64url")}function h(r){return e.fromString(r,"base58btc")}function p(r){const t=r.startsWith("0x")?r.substring(2):r;return e.fromString(t.toLowerCase(),"base16")}function y(r){return l(e.fromString(r))}function g(r){return e.toString(d(r))}function v(r){return e.toString(r,"base16")}function m(r){return e.fromString(r)}function w({r:r,s:t,recoveryParam:n},o){const i=new Uint8Array(o?65:64);if(i.set(e.fromString(r,"base16"),0),i.set(e.fromString(t,"base16"),32),o){if(void 0===n)throw new Error("Signer did not return a recoveryParam");i[64]=n}return l(i)}function b(e){const r=d(e);if(r.length<64||r.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${r.length}`);return{r:v(r.slice(0,32)),s:v(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function E(r,t){return e.concat([d(r),d(t)])}const P=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,k=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function x(e){if("string"==typeof e){if(P.test(e))return p(e);if(S.test(e))return h(e);if(k.test(e))return d(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function K(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function J(t){const n="string"==typeof t?e.fromString(t):t;return r.hash(n)}function A(r){const n=e.fromString(r.slice(2),"base16");return`0x${e.toString((o=n,new Uint8Array(t.keccak_256.arrayBuffer(o))).slice(-20),"base16")}`;var o}function D(r,t=new Uint8Array(4)){const n=e.fromString(r.toString(),"base10");return t.set(n,4-n.length),t}const $=r=>e.concat([D(r.length),r]);function j(t,n,o){if(256!==n)throw new Error(`Unsupported key length: ${n}`);const i=e.concat([$(e.fromString(o)),$(new Uint8Array(0)),$(new Uint8Array(0)),D(n)]);return r.hash(e.concat([D(1),t,i]))}const W=new n.ec("secp256k1");function T(e,r=!1){const t=x(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=W.keyFromPrivate(t);return function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(J(e));return Promise.resolve(w({r:K(t.toString("hex")),s:K(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function I(e){const r=x(e);if(64!==r.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${r.length}`);return function(e){try{const t="string"==typeof e?m(e):e,n=o.sign(r,t);return Promise.resolve(l(n))}catch(e){return Promise.reject(e)}}}function C(e){return"object"==typeof e&&"r"in e&&"s"in e}function O(e){return function(r,t){try{return Promise.resolve(t(r)).then(function(r){if(C(r))return w(r,e);if(e&&void 0===b(r).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return r})}catch(e){return Promise.reject(e)}}}function R(){return function(e,r){try{return Promise.resolve(r(e)).then(function(e){if(C(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}const U={ES256K:O(),"ES256K-R":O(!0),Ed25519:R(),EdDSA:R()},M=new n.ec("secp256k1");function N(e,r=!1){const t=d(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:v(t.slice(0,32)),s:v(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function z(e){return e.publicKeyBase58?h(e.publicKeyBase58):e.publicKeyBase64?d(e.publicKeyBase64):e.publicKeyHex?p(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?p(M.keyFromPublic({x:v(d(e.publicKeyJwk.x)),y:v(d(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function B(e,r,t){let n;if(r.length>86)n=[N(r,!0)];else{const e=N(r,!1);n=[{...e,recoveryParam:0},{...e,recoveryParam:1}]}const o=n.map(r=>{const n=J(e),o=M.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),c=o.encode("hex",!0),a=A(i);return t.find(e=>{const r=v(z(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===a||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===a})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function X(e,r,t){const n=m(e),i=d(r),c=t.find(e=>o.verify(z(e),n,i));if(!c)throw new Error("Signature invalid for JWT");return c}const q={ES256K:function(e,r,t){const n=J(e),o=N(r),i=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0===e&&void 0===r),c=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0!==e||void 0!==typeof r);let a=i.find(e=>{try{const r=z(e);return M.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!a&&c.length>0&&(a=B(e,r,c)),!a)throw new Error("Signature invalid for JWT");return a},"ES256K-R":B,Ed25519:X,EdDSA:X};function V(e){const r=q[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}V.toSignatureObject=N;const _=function(e,r,t={},n={}){try{t.alg||(t.alg=Z);const o="string"==typeof e?e:F(e,n.canonicalize),i=[F(t,n.canonicalize),o].join("."),c=function(e){const r=U[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(c(i,r)).then(function(e){return[i,e].join(".")})}catch(e){return Promise.reject(e)}},H={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},Z="ES256K";function F(e,r=!1){return y(r?JSON.stringify(f.default(e)):JSON.stringify(e))}function L(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(g(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function G(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=L(e);return Object.assign(r,{payload:JSON.parse(g(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function Q({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),V(e.alg)(r,t,n)}const Y="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function ee(e,r,t){if(!e.s){if(t instanceof re){if(!t.s)return void(t.o=ee.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(ee.bind(null,e,r),ee.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const re=function(){function e(){}return e.prototype.then=function(r,t){const n=new e,o=this.s;if(o){const e=1&o?r:t;if(e){try{ee(n,1,e(this.v))}catch(e){ee(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?ee(n,1,r?r(o):o):t?ee(n,1,t(o)):ee(n,2,o)}catch(e){ee(n,2,e)}},n},e}();function te(e){return e instanceof re&&1&e.s}function ne({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const c={protected:n,iv:l(t),ciphertext:l(e),tag:l(r)};return i&&(c.aad=l(i)),o&&(c.recipients=[o]),c}const oe=e=>[].concat.apply([],e);function ie(e){const r=new c.XChaCha20Poly1305(e);return(e,t)=>{const n=u.randomBytes(r.nonceLength),o=r.seal(n,e,t);return{ciphertext:o.subarray(0,o.length-r.tagLength),tag:o.subarray(o.length-r.tagLength),iv:n}}}function ce(e){const r=ie(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=y(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),c=new Uint8Array(Buffer.from(o?`${i}.${l(o)}`:i));return Promise.resolve({...r(e,c),protectedHeader:i})}catch(e){return Promise.reject(e)}}}}function ae(e){const r=new c.XChaCha20Poly1305(e);return{alg:"dir",enc:"XC20P",decrypt:function(e,t,n){try{return Promise.resolve(r.open(t,e,n))}catch(e){return Promise.reject(e)}}}}function ue(e,r){const t=function(t){try{const c=a.generateKeyPair(),u=ie(j(a.sharedKey(c.secretKey,e),o,n))(t),s={encrypted_key:l(u.ciphertext),header:{alg:n,iv:l(u.iv),tag:l(u.tag),epk:{kty:"OKP",crv:i,x:l(c.publicKey)}}};return r&&(s.header.kid=r),Promise.resolve(s)}catch(e){return Promise.reject(e)}},n="ECDH-ES+XC20PKW",o=256,i="X25519";return{alg:n,enc:"XC20P",encrypt:function(e,r={},n){try{Object.assign(r,{alg:void 0});const o=u.randomBytes(32);return Promise.resolve(ce(o).encrypt(e,r,n)).then(function(e){return Promise.resolve(t(o)).then(function(r){return{...e,recipient:r,cek:o}})})}catch(e){return Promise.reject(e)}},encryptCek:t}}exports.ES256KSigner=T,exports.EdDSASigner=I,exports.EllipticSigner=function(e){return T(e)},exports.NaclSigner=function(e){return I(e)},exports.SimpleSigner=function(e){const r=T(e,!0);return function(e){try{return Promise.resolve(r(e)).then(b)}catch(e){return Promise.reject(e)}}},exports.createJWE=function(e,r,t={},n){try{if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(r[0].encrypt(e,t,n)).then(function(e){return ne(e,n)})}{const o=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===o,!0))throw new Error("Incompatible encrypters passed");let i,c;const a=function(e,r,t){if("function"==typeof e[Y]){var n,o,i,c=e[Y]();if(function e(t){try{for(;!(n=c.next()).done;)if((t=r(n.value))&&t.then){if(!te(t))return void t.then(e,i||(i=ee.bind(null,o=new re,2)));t=t.v}o?ee(o,1,t):o=t}catch(e){ee(o||(o=new re),2,e)}}(),c.return){var a=function(e){try{n.done||c.return()}catch(e){}return e};if(o&&o.then)return o.then(a,function(e){throw a(e)});a()}return o}if(!("length"in e))throw new TypeError("Object is not iterable");for(var u=[],s=0;s<e.length;s++)u.push(e[s]);return function(e,r,t){var n,o,i=-1;return function t(c){try{for(;++i<e.length;)if((c=r(i))&&c.then){if(!te(c))return void c.then(t,o||(o=ee.bind(null,n=new re,2)));c=c.v}n?ee(n,1,c):n=c}catch(e){ee(n||(n=new re),2,e)}}(),n}(u,function(e){return r(u[e])})}(r,function(r){const o=function(){if(i){const e=c.recipients,t=e.push;return Promise.resolve(r.encryptCek(i)).then(function(r){t.call(e,r)})}return Promise.resolve(r.encrypt(e,t,n)).then(function(e){i=e.cek,c=ne(e,n)})}();if(o&&o.then)return o.then(function(){})});return Promise.resolve(a&&a.then?a.then(function(){return c}):c)}}catch(e){return Promise.reject(e)}},exports.createJWS=_,exports.createJWT=function(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},c={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");c.typ||(c.typ="JWT"),c.alg||(c.alg=n);const a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(o){if("number"!=typeof o)throw new Error("JWT expiresIn is not a number");a.exp=(e.nbf||a.iat)+Math.floor(o)}const u={...a,...e,iss:r};return _(u,t,c,{canonicalize:i})}catch(e){return Promise.reject(e)}},exports.decodeJWT=G,exports.decryptJWE=function(e,r){try{function t(e){if(null===c)throw new Error("Failed to decrypt");return c}!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const n=JSON.parse(g(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const o=E(e.ciphertext,e.tag),i=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let c=null;const a="dir"===n.alg&&"dir"===r.alg?Promise.resolve(r.decrypt(o,d(e.iv),i)).then(function(e){c=e}):function(){if(e.recipients&&0!==e.recipients.length){let t=0;return function(e,r,t){for(var n;;){var o=e();if(te(o)&&(o=o.v),!o)return i;if(o.then){n=0;break}var i=t();if(i&&i.then){if(!te(i)){n=1;break}i=i.s}if(r){var c=r();if(c&&c.then&&!te(c)){n=2;break}}}var a=new re,u=ee.bind(null,a,2);return(0===n?o.then(f):1===n?i.then(s):c.then(l)).then(void 0,u),a;function s(n){i=n;do{if(r&&(c=r())&&c.then&&!te(c))return void c.then(l).then(void 0,u);if(!(o=e())||te(o)&&!o.v)return void ee(a,1,i);if(o.then)return void o.then(f).then(void 0,u);te(i=t())&&(i=i.v)}while(!i||!i.then);i.then(s).then(void 0,u)}function f(e){e?(i=t())&&i.then?i.then(s).then(void 0,u):s(i):ee(a,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,u):f(o):ee(a,1,i)}}(function(){return!c&&t<e.recipients.length},function(){return t++},function(){const a=e.recipients[t];Object.assign(a.header,n);const u=function(){if(a.header.alg===r.alg)return Promise.resolve(r.decrypt(o,d(e.iv),i,a)).then(function(e){c=e})}();if(u&&u.then)return u.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(a&&a.then?a.then(t):t())}catch(e){return Promise.reject(e)}},exports.resolveX25519Encrypters=function(e,r){try{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(r?.error)throw new Error(`Could not find x25519 key for ${e}: ${r.error}, ${r.message}`);if(!t.keyAgreement)throw new Error(`Could not find x25519 key for ${e}`);const n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>ue(h(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(oe)}catch(e){return Promise.reject(e)}},exports.toEthereumAddress=A,exports.verifyJWS=function(e,r){return Q(L(e),r)},exports.verifyJWT=function(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null,proofPurpose:null}){try{if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:o,data:i}=G(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=H[r];if(!o||0===o.length)throw new Error(`No supported signature types for algorithm ${r}`);let i;return Promise.resolve(e.resolve(t,{accept:"application/did+json"})).then(function(e){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:"application/did+json"}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let a=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...a.map(e=>e.id)]),a=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(a,e):"string"==typeof e.publicKey?c(a,e.publicKey):e).filter(e=>null!=e));const u=a.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!u||0===u.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!u||0===u.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:u,issuer:t,didResolutionResult:i}})}catch(e){return Promise.reject(e)}}(r.resolver,n.alg,t.iss,c)).then(function({didResolutionResult:c,authenticators:a,issuer:u}){return Promise.resolve(Q({header:n,data:i,signature:o},a)).then(function(n){const o=Math.floor(Date.now()/1e3),i=r.skewTime>=0?r.skewTime:300;if(n){const a=o+i;if(t.nbf){if(t.nbf>a)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>a)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=o-i)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${o}`);if(t.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,didResolutionResult:c,issuer:u,signer:n,jwt:e}}})})}catch(e){return Promise.reject(e)}},exports.x25519Decrypter=function(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:function(t,n,o,i){try{if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(i.header),"X25519"!==i.header.epk.crv)return Promise.resolve(null);const c=d(i.header.epk.x),u=j(a.sharedKey(e,c),256,r),s=E(i.encrypted_key,i.header.tag);return Promise.resolve(ae(u).decrypt(s,d(i.header.iv))).then(function(e){return null===e?null:ae(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}},exports.x25519Encrypter=ue,exports.xc20pDirDecrypter=ae,exports.xc20pDirEncrypter=ce; | ||
//# sourceMappingURL=index.js.map |
@@ -1,2 +0,2 @@ | ||
import{toString as e,fromString as r,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as o}from"js-sha3";import{ec as i}from"elliptic";import{sign as a,verify as c}from"@stablelib/ed25519";import{XChaCha20Poly1305 as s}from"@stablelib/xchacha20poly1305";import{generateKeyPair as u,sharedKey as l}from"@stablelib/x25519";import{randomBytes as f}from"@stablelib/random";function d(r){return e(r,"base64url")}function p(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r(t,"base64url")}function y(e){return r(e,"base58btc")}function h(e){const t=e.startsWith("0x")?e.substring(2):e;return r(t.toLowerCase(),"base16")}function g(e){return d(r(e))}function w(r){return e(p(r))}function b(r){return e(r,"base16")}function m(e){return r(e)}function v({r:e,s:t,recoveryParam:n},o){const i=new Uint8Array(o?65:64);if(i.set(r(e,"base16"),0),i.set(r(t,"base16"),32),o){if(void 0===n)throw new Error("Signer did not return a recoveryParam");i[64]=n}return d(i)}function E(e){const r=p(e);if(r.length<64||r.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${r.length}`);return{r:b(r.slice(0,32)),s:b(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function k(e,r){return t([p(e),p(r)])}const K=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,x=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function $(e){if("string"==typeof e){if(K.test(e))return h(e);if(S.test(e))return y(e);if(x.test(e))return p(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function A(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function P(e){const t="string"==typeof e?r(e):e;return n(t)}function D(t){const n=r(t.slice(2),"base16");return`0x${e((i=n,new Uint8Array(o.arrayBuffer(i))).slice(-20),"base16")}`;var i}function J(e,t=new Uint8Array(4)){const n=r(e.toString(),"base10");return t.set(n,4-n.length),t}const W=e=>t([J(e.length),e]);function I(e,o,i){if(256!==o)throw new Error(`Unsupported key length: ${o}`);const a=t([W(r(i)),W(new Uint8Array(0)),W(new Uint8Array(0)),J(o)]);return n(t([J(1),e,a]))}const T=new i("secp256k1");function O(e,r=!1){const t=$(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=T.keyFromPrivate(t);return async e=>{const{r:t,s:o,recoveryParam:i}=n.sign(P(e));return v({r:A(t.toString("hex")),s:A(o.toString("hex")),recoveryParam:i},r)}}function C(e){const r=O(e,!0);return async e=>E(await r(e))}function j(e){return O(e)}function R(e){const r=$(e);if(64!==r.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${r.length}`);return async e=>{const t="string"==typeof e?m(e):e;return d(a(r,t))}}function U(e){return R(e)}function M(){return(M=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}const N=new i("secp256k1");function B(e,r=!1){const t=p(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:b(t.slice(0,32)),s:b(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function V(e){return e.publicKeyBase58?y(e.publicKeyBase58):e.publicKeyBase64?p(e.publicKeyBase64):e.publicKeyHex?h(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?h(N.keyFromPublic({x:b(p(e.publicKeyJwk.x)),y:b(p(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function X(e,r,t){let n;if(r.length>86)n=[B(r,!0)];else{const e=B(r,!1);n=[M({},e,{recoveryParam:0}),M({},e,{recoveryParam:1})]}const o=n.map(r=>{const n=P(e),o=N.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),a=o.encode("hex",!0),c=D(i);return t.find(e=>{var r,t,n;const o=b(V(e));return o===i||o===a||(null==(r=e.ethereumAddress)?void 0:r.toLowerCase())===c||(null==(t=e.blockchainAccountId)||null==(n=t.split("@eip155"))?void 0:n[0].toLowerCase())===c})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function _(e,r,t){const n=m(e),o=p(r),i=t.find(e=>c(V(e),n,o));if(!i)throw new Error("Signature invalid for JWT");return i}const z={ES256K:function(e,r,t){const n=P(e),o=B(r),i=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0===e&&void 0===r),a=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0!==e||void 0!==typeof r);let c=i.find(e=>{try{const r=V(e);return N.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!c&&a.length>0&&(c=X(e,r,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":X,Ed25519:_,EdDSA:_};function H(e){const r=z[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}function Z(e){return"object"==typeof e&&"r"in e&&"s"in e}function F(e){return async function(r,t){const n=await t(r);if(Z(n))return v(n,e);if(e&&void 0===E(n).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return n}}function L(){return async function(e,r){const t=await r(e);if(Z(t))throw new Error("expected a signer function that returns a string instead of signature object");return t}}H.toSignatureObject=B;const q={ES256K:F(),"ES256K-R":F(!0),Ed25519:L(),EdDSA:L()},G={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function Q(e){return g(JSON.stringify(e))}function Y(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(w(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function ee(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=Y(e);return Object.assign(r,{payload:JSON.parse(w(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}async function re(e,r,t={}){t.alg||(t.alg="ES256K");const n="string"==typeof e?e:Q(e),o=[Q(t),n].join("."),i=function(e){const r=q[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return[o,await i(o,r)].join(".")}async function te(e,{issuer:r,signer:t,alg:n,expiresIn:o},i={}){if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");i.typ||(i.typ="JWT"),i.alg||(i.alg=n);const a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(o){if("number"!=typeof o)throw new Error("JWT expiresIn is not a number");a.exp=(e.nbf||a.iat)+Math.floor(o)}return re(M({},a,e,{iss:r}),t,i)}function ne({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),H(e.alg)(r,t,n)}function oe(e,r){return ne(Y(e),r)}async function ie(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null,proofPurpose:null}){if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:o,data:i}=ee(e),a=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose,{didResolutionResult:c,authenticators:s,issuer:u}=await async function(e,r,t,n){var o,i,a,c,s;const u=G[r];if(!u||0===u.length)throw new Error(`No supported signature types for algorithm ${r}`);let l;const f=await e.resolve(t,{accept:"application/did+json"});if(l=-1===Object.getOwnPropertyNames(f).indexOf("didDocument")?{didDocument:f,didDocumentMetadata:{},didResolutionMetadata:{contentType:"application/did+json"}}:f,null!=(o=l.didResolutionMetadata)&&o.error){const{error:e,message:r}=l.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const d=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let p=[...(null==(i=l)||null==(a=i.didDocument)?void 0:a.verificationMethod)||[],...(null==(c=l)||null==(s=c.didDocument)?void 0:s.publicKey)||[]];"string"==typeof n&&(n.startsWith("assertion")&&!l.didDocument.hasOwnProperty("assertionMethod")&&(l.didDocument.assertionMethod=[...p.map(e=>e.id)]),p=(l.didDocument[n]||[]).map(e=>"string"==typeof e?d(p,e):"string"==typeof e.publicKey?d(p,e.publicKey):e).filter(e=>null!=e));const y=p.filter(({type:e})=>u.find(r=>r===e));if("string"==typeof n&&(!y||0===y.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!y||0===y.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:y,issuer:t,didResolutionResult:l}}(r.resolver,n.alg,t.iss,a),l=await ne({header:n,data:i,signature:o},s),f=Math.floor(Date.now()/1e3),d=r.skewTime>=0?r.skewTime:300;if(l){const n=f+d;if(t.nbf){if(t.nbf>n)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>n)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=f-d)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${f}`);if(t.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,didResolutionResult:c,issuer:u,signer:l,jwt:e}}}function ae({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const a={protected:n,iv:d(t),ciphertext:d(e),tag:d(r)};return i&&(a.aad=d(i)),o&&(a.recipients=[o]),a}async function ce(e,r,t={},n){if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return ae(await r[0].encrypt(e,t,n),n)}{const o=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===o,!0))throw new Error("Incompatible encrypters passed");let i,a;for(const o of r)if(i)a.recipients.push(await o.encryptCek(i));else{const r=await o.encrypt(e,t,n);i=r.cek,a=ae(r,n)}return a}}async function se(e,r){!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const t=JSON.parse(w(e.protected));if(t.enc!==r.enc)throw new Error(`Decrypter does not support: '${t.enc}'`);const n=k(e.ciphertext,e.tag),o=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let i=null;if("dir"===t.alg&&"dir"===r.alg)i=await r.decrypt(n,p(e.iv),o);else{if(!e.recipients||0===e.recipients.length)throw new Error("Invalid JWE");for(let a=0;!i&&a<e.recipients.length;a++){const c=e.recipients[a];Object.assign(c.header,t),c.header.alg===r.alg&&(i=await r.decrypt(n,p(e.iv),o,c))}}if(null===i)throw new Error("Failed to decrypt");return i}function ue(e){const r=new s(e);return(e,t)=>{const n=f(r.nonceLength),o=r.seal(n,e,t);return{ciphertext:o.subarray(0,o.length-r.tagLength),tag:o.subarray(o.length-r.tagLength),iv:n}}}function le(e){const r=ue(e),t="XC20P";return{alg:"dir",enc:t,encrypt:async function(e,n={},o){const i=g(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(o?`${i}.${d(o)}`:i));return M({},r(e,a),{protectedHeader:i})}}}function fe(e){const r=new s(e);return{alg:"dir",enc:"XC20P",decrypt:async function(e,t,n){return r.open(t,e,n)}}}function de(e,r){const t="ECDH-ES+XC20PKW";async function n(n){const o=u(),i=ue(I(l(o.secretKey,e),256,t))(n),a={encrypted_key:d(i.ciphertext),header:{alg:t,iv:d(i.iv),tag:d(i.tag),epk:{kty:"OKP",crv:"X25519",x:d(o.publicKey)}}};return r&&(a.header.kid=r),a}return{alg:t,enc:"XC20P",encrypt:async function(e,r={},t){Object.assign(r,{alg:void 0});const o=f(32);return M({},await le(o).encrypt(e,r,t),{recipient:await n(o),cek:o})},encryptCek:n}}async function pe(e,r){const t=e.map(e=>(async e=>{var t;const{didResolutionMetadata:n,didDocument:o}=await r.resolve(e);if(null!=n&&n.error)throw new Error(`Could not find x25519 key for ${e}: ${n.error}, ${n.message}`);if(!o.keyAgreement)throw new Error(`Could not find x25519 key for ${e}`);const i=(null==(t=o.keyAgreement)?void 0:t.map(e=>"string"==typeof e?[...o.publicKey||[],...o.verificationMethod||[]].find(r=>r.id===e):e)).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!i.length)throw new Error(`Could not find x25519 key for ${e}`);return i.map(e=>de(y(e.publicKeyBase58),e.id))})(e)),n=await Promise.all(t);return[].concat.apply([],n)}function ye(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:async function(t,n,o,i){if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(i.header),"X25519"!==i.header.epk.crv)return null;const a=p(i.header.epk.x),c=I(l(e,a),256,r),s=k(i.encrypted_key,i.header.tag),u=await fe(c).decrypt(s,p(i.header.iv));return null===u?null:fe(u).decrypt(t,n,o)}}}export{O as ES256KSigner,R as EdDSASigner,j as EllipticSigner,U as NaclSigner,C as SimpleSigner,ce as createJWE,re as createJWS,te as createJWT,ee as decodeJWT,se as decryptJWE,pe as resolveX25519Encrypters,D as toEthereumAddress,oe as verifyJWS,ie as verifyJWT,ye as x25519Decrypter,de as x25519Encrypter,fe as xc20pDirDecrypter,le as xc20pDirEncrypter}; | ||
import{toString as e,fromString as r,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as o}from"js-sha3";import{ec as i}from"elliptic";import{sign as a,verify as c}from"@stablelib/ed25519";import s from"canonicalize";import{XChaCha20Poly1305 as u}from"@stablelib/xchacha20poly1305";import{generateKeyPair as l,sharedKey as f}from"@stablelib/x25519";import{randomBytes as d}from"@stablelib/random";function p(r){return e(r,"base64url")}function y(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r(t,"base64url")}function h(e){return r(e,"base58btc")}function g(e){const t=e.startsWith("0x")?e.substring(2):e;return r(t.toLowerCase(),"base16")}function w(e){return p(r(e))}function b(r){return e(y(r))}function m(r){return e(r,"base16")}function v(e){return r(e)}function E({r:e,s:t,recoveryParam:n},o){const i=new Uint8Array(o?65:64);if(i.set(r(e,"base16"),0),i.set(r(t,"base16"),32),o){if(void 0===n)throw new Error("Signer did not return a recoveryParam");i[64]=n}return p(i)}function k(e){const r=y(e);if(r.length<64||r.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${r.length}`);return{r:m(r.slice(0,32)),s:m(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function S(e,r){return t([y(e),y(r)])}const K=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,x=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,$=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function A(e){if("string"==typeof e){if(K.test(e))return g(e);if(x.test(e))return h(e);if($.test(e))return y(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function P(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function D(e){const t="string"==typeof e?r(e):e;return n(t)}function J(t){const n=r(t.slice(2),"base16");return`0x${e((i=n,new Uint8Array(o.arrayBuffer(i))).slice(-20),"base16")}`;var i}function W(e,t=new Uint8Array(4)){const n=r(e.toString(),"base10");return t.set(n,4-n.length),t}const I=e=>t([W(e.length),e]);function O(e,o,i){if(256!==o)throw new Error(`Unsupported key length: ${o}`);const a=t([I(r(i)),I(new Uint8Array(0)),I(new Uint8Array(0)),W(o)]);return n(t([W(1),e,a]))}const T=new i("secp256k1");function C(e,r=!1){const t=A(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=T.keyFromPrivate(t);return async e=>{const{r:t,s:o,recoveryParam:i}=n.sign(D(e));return E({r:P(t.toString("hex")),s:P(o.toString("hex")),recoveryParam:i},r)}}function j(e){const r=C(e,!0);return async e=>k(await r(e))}function R(e){return C(e)}function U(e){const r=A(e);if(64!==r.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${r.length}`);return async e=>{const t="string"==typeof e?v(e):e;return p(a(r,t))}}function M(e){return U(e)}function z(){return(z=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}function N(e){return"object"==typeof e&&"r"in e&&"s"in e}function B(e){return async function(r,t){const n=await t(r);if(N(n))return E(n,e);if(e&&void 0===k(n).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return n}}function V(){return async function(e,r){const t=await r(e);if(N(t))throw new Error("expected a signer function that returns a string instead of signature object");return t}}const X={ES256K:B(),"ES256K-R":B(!0),Ed25519:V(),EdDSA:V()},_=new i("secp256k1");function H(e,r=!1){const t=y(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:m(t.slice(0,32)),s:m(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function Z(e){return e.publicKeyBase58?h(e.publicKeyBase58):e.publicKeyBase64?y(e.publicKeyBase64):e.publicKeyHex?g(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?g(_.keyFromPublic({x:m(y(e.publicKeyJwk.x)),y:m(y(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function F(e,r,t){let n;if(r.length>86)n=[H(r,!0)];else{const e=H(r,!1);n=[z({},e,{recoveryParam:0}),z({},e,{recoveryParam:1})]}const o=n.map(r=>{const n=D(e),o=_.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),a=o.encode("hex",!0),c=J(i);return t.find(e=>{var r,t,n;const o=m(Z(e));return o===i||o===a||(null==(r=e.ethereumAddress)?void 0:r.toLowerCase())===c||(null==(t=e.blockchainAccountId)||null==(n=t.split("@eip155"))?void 0:n[0].toLowerCase())===c})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function L(e,r,t){const n=v(e),o=y(r),i=t.find(e=>c(Z(e),n,o));if(!i)throw new Error("Signature invalid for JWT");return i}const q={ES256K:function(e,r,t){const n=D(e),o=H(r),i=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0===e&&void 0===r),a=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0!==e||void 0!==typeof r);let c=i.find(e=>{try{const r=Z(e);return _.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!c&&a.length>0&&(c=F(e,r,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":F,Ed25519:L,EdDSA:L};function G(e){const r=q[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}G.toSignatureObject=H;const Q={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function Y(e,r=!1){return w(r?JSON.stringify(s(e)):JSON.stringify(e))}function ee(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(b(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function re(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=ee(e);return Object.assign(r,{payload:JSON.parse(b(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}async function te(e,r,t={},n={}){t.alg||(t.alg="ES256K");const o="string"==typeof e?e:Y(e,n.canonicalize),i=[Y(t,n.canonicalize),o].join("."),a=function(e){const r=X[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return[i,await a(i,r)].join(".")}async function ne(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},a={}){if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");a.typ||(a.typ="JWT"),a.alg||(a.alg=n);const c={iat:Math.floor(Date.now()/1e3),exp:void 0};if(o){if("number"!=typeof o)throw new Error("JWT expiresIn is not a number");c.exp=(e.nbf||c.iat)+Math.floor(o)}return te(z({},c,e,{iss:r}),t,a,{canonicalize:i})}function oe({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),G(e.alg)(r,t,n)}function ie(e,r){return oe(ee(e),r)}async function ae(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null,proofPurpose:null}){if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:o,data:i}=re(e),a=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose,{didResolutionResult:c,authenticators:s,issuer:u}=await async function(e,r,t,n){var o,i,a,c,s;const u=Q[r];if(!u||0===u.length)throw new Error(`No supported signature types for algorithm ${r}`);let l;const f=await e.resolve(t,{accept:"application/did+json"});if(l=-1===Object.getOwnPropertyNames(f).indexOf("didDocument")?{didDocument:f,didDocumentMetadata:{},didResolutionMetadata:{contentType:"application/did+json"}}:f,null!=(o=l.didResolutionMetadata)&&o.error){const{error:e,message:r}=l.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const d=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let p=[...(null==(i=l)||null==(a=i.didDocument)?void 0:a.verificationMethod)||[],...(null==(c=l)||null==(s=c.didDocument)?void 0:s.publicKey)||[]];"string"==typeof n&&(n.startsWith("assertion")&&!l.didDocument.hasOwnProperty("assertionMethod")&&(l.didDocument.assertionMethod=[...p.map(e=>e.id)]),p=(l.didDocument[n]||[]).map(e=>"string"==typeof e?d(p,e):"string"==typeof e.publicKey?d(p,e.publicKey):e).filter(e=>null!=e));const y=p.filter(({type:e})=>u.find(r=>r===e));if("string"==typeof n&&(!y||0===y.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!y||0===y.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:y,issuer:t,didResolutionResult:l}}(r.resolver,n.alg,t.iss,a),l=await oe({header:n,data:i,signature:o},s),f=Math.floor(Date.now()/1e3),d=r.skewTime>=0?r.skewTime:300;if(l){const n=f+d;if(t.nbf){if(t.nbf>n)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>n)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=f-d)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${f}`);if(t.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,didResolutionResult:c,issuer:u,signer:l,jwt:e}}}function ce({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const a={protected:n,iv:p(t),ciphertext:p(e),tag:p(r)};return i&&(a.aad=p(i)),o&&(a.recipients=[o]),a}async function se(e,r,t={},n){if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return ce(await r[0].encrypt(e,t,n),n)}{const o=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===o,!0))throw new Error("Incompatible encrypters passed");let i,a;for(const o of r)if(i)a.recipients.push(await o.encryptCek(i));else{const r=await o.encrypt(e,t,n);i=r.cek,a=ce(r,n)}return a}}async function ue(e,r){!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const t=JSON.parse(b(e.protected));if(t.enc!==r.enc)throw new Error(`Decrypter does not support: '${t.enc}'`);const n=S(e.ciphertext,e.tag),o=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let i=null;if("dir"===t.alg&&"dir"===r.alg)i=await r.decrypt(n,y(e.iv),o);else{if(!e.recipients||0===e.recipients.length)throw new Error("Invalid JWE");for(let a=0;!i&&a<e.recipients.length;a++){const c=e.recipients[a];Object.assign(c.header,t),c.header.alg===r.alg&&(i=await r.decrypt(n,y(e.iv),o,c))}}if(null===i)throw new Error("Failed to decrypt");return i}function le(e){const r=new u(e);return(e,t)=>{const n=d(r.nonceLength),o=r.seal(n,e,t);return{ciphertext:o.subarray(0,o.length-r.tagLength),tag:o.subarray(o.length-r.tagLength),iv:n}}}function fe(e){const r=le(e),t="XC20P";return{alg:"dir",enc:t,encrypt:async function(e,n={},o){const i=w(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(o?`${i}.${p(o)}`:i));return z({},r(e,a),{protectedHeader:i})}}}function de(e){const r=new u(e);return{alg:"dir",enc:"XC20P",decrypt:async function(e,t,n){return r.open(t,e,n)}}}function pe(e,r){const t="ECDH-ES+XC20PKW";async function n(n){const o=l(),i=le(O(f(o.secretKey,e),256,t))(n),a={encrypted_key:p(i.ciphertext),header:{alg:t,iv:p(i.iv),tag:p(i.tag),epk:{kty:"OKP",crv:"X25519",x:p(o.publicKey)}}};return r&&(a.header.kid=r),a}return{alg:t,enc:"XC20P",encrypt:async function(e,r={},t){Object.assign(r,{alg:void 0});const o=d(32);return z({},await fe(o).encrypt(e,r,t),{recipient:await n(o),cek:o})},encryptCek:n}}async function ye(e,r){const t=e.map(e=>(async e=>{var t;const{didResolutionMetadata:n,didDocument:o}=await r.resolve(e);if(null!=n&&n.error)throw new Error(`Could not find x25519 key for ${e}: ${n.error}, ${n.message}`);if(!o.keyAgreement)throw new Error(`Could not find x25519 key for ${e}`);const i=(null==(t=o.keyAgreement)?void 0:t.map(e=>"string"==typeof e?[...o.publicKey||[],...o.verificationMethod||[]].find(r=>r.id===e):e)).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!i.length)throw new Error(`Could not find x25519 key for ${e}`);return i.map(e=>pe(h(e.publicKeyBase58),e.id))})(e)),n=await Promise.all(t);return[].concat.apply([],n)}function he(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:async function(t,n,o,i){if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(i.header),"X25519"!==i.header.epk.crv)return null;const a=y(i.header.epk.x),c=O(f(e,a),256,r),s=S(i.encrypted_key,i.header.tag),u=await de(c).decrypt(s,y(i.header.iv));return null===u?null:de(u).decrypt(t,n,o)}}}export{C as ES256KSigner,U as EdDSASigner,R as EllipticSigner,M as NaclSigner,j as SimpleSigner,se as createJWE,te as createJWS,ne as createJWT,re as decodeJWT,ue as decryptJWE,ye as resolveX25519Encrypters,J as toEthereumAddress,ie as verifyJWS,ae as verifyJWT,he as x25519Decrypter,pe as x25519Encrypter,de as xc20pDirDecrypter,fe as xc20pDirEncrypter}; | ||
//# sourceMappingURL=index.modern.js.map |
@@ -1,2 +0,2 @@ | ||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("uint8arrays"),require("@stablelib/sha256"),require("js-sha3"),require("elliptic"),require("@stablelib/ed25519"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","uint8arrays","@stablelib/sha256","js-sha3","elliptic","@stablelib/ed25519","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],r):r((e||self).didJwt={},e.uint8Arrays,e.sha256$1,e.jsSha3,e.elliptic,e.ed25519,e.xchacha20poly1305,e.x25519,e.random)}(this,function(e,r,t,n,o,i,c,a,u){function s(e){return r.toString(e,"base64url")}function f(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r.fromString(t,"base64url")}function l(e){return r.fromString(e,"base58btc")}function d(e){const t=e.startsWith("0x")?e.substring(2):e;return r.fromString(t.toLowerCase(),"base16")}function h(e){return s(r.fromString(e))}function y(e){return r.toString(f(e))}function p(e){return r.toString(e,"base16")}function g(e){return r.fromString(e)}function m({r:e,s:t,recoveryParam:n},o){const i=new Uint8Array(o?65:64);if(i.set(r.fromString(e,"base16"),0),i.set(r.fromString(t,"base16"),32),o){if(void 0===n)throw new Error("Signer did not return a recoveryParam");i[64]=n}return s(i)}function v(e){const r=f(e);if(r.length<64||r.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${r.length}`);return{r:p(r.slice(0,32)),s:p(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function w(e,t){return r.concat([f(e),f(t)])}const b=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,E=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,P=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function S(e){if("string"==typeof e){if(b.test(e))return d(e);if(E.test(e))return l(e);if(P.test(e))return f(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function k(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function x(e){const n="string"==typeof e?r.fromString(e):e;return t.hash(n)}function K(e){const t=r.fromString(e.slice(2),"base16");return`0x${r.toString((o=t,new Uint8Array(n.keccak_256.arrayBuffer(o))).slice(-20),"base16")}`;var o}function A(e,t=new Uint8Array(4)){const n=r.fromString(e.toString(),"base10");return t.set(n,4-n.length),t}const J=e=>r.concat([A(e.length),e]);function $(e,n,o){if(256!==n)throw new Error(`Unsupported key length: ${n}`);const i=r.concat([J(r.fromString(o)),J(new Uint8Array(0)),J(new Uint8Array(0)),A(n)]);return t.hash(r.concat([A(1),e,i]))}const D=new o.ec("secp256k1");function j(e,r=!1){const t=S(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=D.keyFromPrivate(t);return function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(x(e));return Promise.resolve(m({r:k(t.toString("hex")),s:k(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function W(e){const r=S(e);if(64!==r.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${r.length}`);return function(e){try{const t="string"==typeof e?g(e):e,n=i.sign(r,t);return Promise.resolve(s(n))}catch(e){return Promise.reject(e)}}}const T=new o.ec("secp256k1");function I(e,r=!1){const t=f(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:p(t.slice(0,32)),s:p(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function C(e){return e.publicKeyBase58?l(e.publicKeyBase58):e.publicKeyBase64?f(e.publicKeyBase64):e.publicKeyHex?d(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?d(T.keyFromPublic({x:p(f(e.publicKeyJwk.x)),y:p(f(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function O(e,r,t){let n;if(r.length>86)n=[I(r,!0)];else{const e=I(r,!1);n=[{...e,recoveryParam:0},{...e,recoveryParam:1}]}const o=n.map(r=>{const n=x(e),o=T.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),c=o.encode("hex",!0),a=K(i);return t.find(e=>{const r=p(C(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===a||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===a})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function R(e,r,t){const n=g(e),o=f(r),c=t.find(e=>i.verify(C(e),n,o));if(!c)throw new Error("Signature invalid for JWT");return c}const U={ES256K:function(e,r,t){const n=x(e),o=I(r),i=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0===e&&void 0===r),c=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0!==e||void 0!==typeof r);let a=i.find(e=>{try{const r=C(e);return T.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!a&&c.length>0&&(a=O(e,r,c)),!a)throw new Error("Signature invalid for JWT");return a},"ES256K-R":O,Ed25519:R,EdDSA:R};function M(e){const r=U[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}function N(e){return"object"==typeof e&&"r"in e&&"s"in e}function B(e){return function(r,t){try{return Promise.resolve(t(r)).then(function(r){if(N(r))return m(r,e);if(e&&void 0===v(r).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return r})}catch(e){return Promise.reject(e)}}}function X(){return function(e,r){try{return Promise.resolve(r(e)).then(function(e){if(N(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}M.toSignatureObject=I;const V={ES256K:B(),"ES256K-R":B(!0),Ed25519:X(),EdDSA:X()},_=function(e,r,t={}){try{t.alg||(t.alg=z);const n="string"==typeof e?e:Z(e),o=[Z(t),n].join("."),i=function(e){const r=V[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(i(o,r)).then(function(e){return[o,e].join(".")})}catch(e){return Promise.reject(e)}},q={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},z="ES256K",H="application/did+json";function Z(e){return h(JSON.stringify(e))}function F(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(y(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function L(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=F(e);return Object.assign(r,{payload:JSON.parse(y(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function G({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),M(e.alg)(r,t,n)}const Q="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Y(e,r,t){if(!e.s){if(t instanceof ee){if(!t.s)return void(t.o=Y.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(Y.bind(null,e,r),Y.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const ee=function(){function e(){}return e.prototype.then=function(r,t){const n=new e,o=this.s;if(o){const e=1&o?r:t;if(e){try{Y(n,1,e(this.v))}catch(e){Y(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?Y(n,1,r?r(o):o):t?Y(n,1,t(o)):Y(n,2,o)}catch(e){Y(n,2,e)}},n},e}();function re(e){return e instanceof ee&&1&e.s}function te({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const c={protected:n,iv:s(t),ciphertext:s(e),tag:s(r)};return i&&(c.aad=s(i)),o&&(c.recipients=[o]),c}const ne=e=>[].concat.apply([],e);function oe(e){const r=new c.XChaCha20Poly1305(e);return(e,t)=>{const n=u.randomBytes(r.nonceLength),o=r.seal(n,e,t);return{ciphertext:o.subarray(0,o.length-r.tagLength),tag:o.subarray(o.length-r.tagLength),iv:n}}}function ie(e){const r=oe(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=h(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),c=new Uint8Array(Buffer.from(o?`${i}.${s(o)}`:i));return Promise.resolve({...r(e,c),protectedHeader:i})}catch(e){return Promise.reject(e)}}}}function ce(e){const r=new c.XChaCha20Poly1305(e);return{alg:"dir",enc:"XC20P",decrypt:function(e,t,n){try{return Promise.resolve(r.open(t,e,n))}catch(e){return Promise.reject(e)}}}}function ae(e,r){const t=function(t){try{const c=a.generateKeyPair(),u=oe($(a.sharedKey(c.secretKey,e),o,n))(t),f={encrypted_key:s(u.ciphertext),header:{alg:n,iv:s(u.iv),tag:s(u.tag),epk:{kty:"OKP",crv:i,x:s(c.publicKey)}}};return r&&(f.header.kid=r),Promise.resolve(f)}catch(e){return Promise.reject(e)}},n="ECDH-ES+XC20PKW",o=256,i="X25519";return{alg:n,enc:"XC20P",encrypt:function(e,r={},n){try{Object.assign(r,{alg:void 0});const o=u.randomBytes(32);return Promise.resolve(ie(o).encrypt(e,r,n)).then(function(e){return Promise.resolve(t(o)).then(function(r){return{...e,recipient:r,cek:o}})})}catch(e){return Promise.reject(e)}},encryptCek:t}}e.ES256KSigner=j,e.EdDSASigner=W,e.EllipticSigner=function(e){return j(e)},e.NaclSigner=function(e){return W(e)},e.SimpleSigner=function(e){const r=j(e,!0);return function(e){try{return Promise.resolve(r(e)).then(v)}catch(e){return Promise.reject(e)}}},e.createJWE=function(e,r,t={},n){try{if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(r[0].encrypt(e,t,n)).then(function(e){return te(e,n)})}{const o=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===o,!0))throw new Error("Incompatible encrypters passed");let i,c;const a=function(e,r,t){if("function"==typeof e[Q]){var n,o,i,c=e[Q]();if(function e(t){try{for(;!(n=c.next()).done;)if((t=r(n.value))&&t.then){if(!re(t))return void t.then(e,i||(i=Y.bind(null,o=new ee,2)));t=t.v}o?Y(o,1,t):o=t}catch(e){Y(o||(o=new ee),2,e)}}(),c.return){var a=function(e){try{n.done||c.return()}catch(e){}return e};if(o&&o.then)return o.then(a,function(e){throw a(e)});a()}return o}if(!("length"in e))throw new TypeError("Object is not iterable");for(var u=[],s=0;s<e.length;s++)u.push(e[s]);return function(e,r,t){var n,o,i=-1;return function t(c){try{for(;++i<e.length;)if((c=r(i))&&c.then){if(!re(c))return void c.then(t,o||(o=Y.bind(null,n=new ee,2)));c=c.v}n?Y(n,1,c):n=c}catch(e){Y(n||(n=new ee),2,e)}}(),n}(u,function(e){return r(u[e])})}(r,function(r){const o=function(){if(i){const e=c.recipients,t=e.push;return Promise.resolve(r.encryptCek(i)).then(function(r){t.call(e,r)})}return Promise.resolve(r.encrypt(e,t,n)).then(function(e){i=e.cek,c=te(e,n)})}();if(o&&o.then)return o.then(function(){})});return Promise.resolve(a&&a.then?a.then(function(){return c}):c)}}catch(e){return Promise.reject(e)}},e.createJWS=_,e.createJWT=function(e,{issuer:r,signer:t,alg:n,expiresIn:o},i={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");i.typ||(i.typ="JWT"),i.alg||(i.alg=n);const c={iat:Math.floor(Date.now()/1e3),exp:void 0};if(o){if("number"!=typeof o)throw new Error("JWT expiresIn is not a number");c.exp=(e.nbf||c.iat)+Math.floor(o)}const a={...c,...e,iss:r};return _(a,t,i)}catch(e){return Promise.reject(e)}},e.decodeJWT=L,e.decryptJWE=function(e,r){try{function t(e){if(null===c)throw new Error("Failed to decrypt");return c}!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const n=JSON.parse(y(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const o=w(e.ciphertext,e.tag),i=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let c=null;const a="dir"===n.alg&&"dir"===r.alg?Promise.resolve(r.decrypt(o,f(e.iv),i)).then(function(e){c=e}):function(){if(e.recipients&&0!==e.recipients.length){let t=0;return function(e,r,t){for(var n;;){var o=e();if(re(o)&&(o=o.v),!o)return i;if(o.then){n=0;break}var i=t();if(i&&i.then){if(!re(i)){n=1;break}i=i.s}if(r){var c=r();if(c&&c.then&&!re(c)){n=2;break}}}var a=new ee,u=Y.bind(null,a,2);return(0===n?o.then(f):1===n?i.then(s):c.then(l)).then(void 0,u),a;function s(n){i=n;do{if(r&&(c=r())&&c.then&&!re(c))return void c.then(l).then(void 0,u);if(!(o=e())||re(o)&&!o.v)return void Y(a,1,i);if(o.then)return void o.then(f).then(void 0,u);re(i=t())&&(i=i.v)}while(!i||!i.then);i.then(s).then(void 0,u)}function f(e){e?(i=t())&&i.then?i.then(s).then(void 0,u):s(i):Y(a,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,u):f(o):Y(a,1,i)}}(function(){return!c&&t<e.recipients.length},function(){return t++},function(){const a=e.recipients[t];Object.assign(a.header,n);const u=function(){if(a.header.alg===r.alg)return Promise.resolve(r.decrypt(o,f(e.iv),i,a)).then(function(e){c=e})}();if(u&&u.then)return u.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(a&&a.then?a.then(t):t())}catch(e){return Promise.reject(e)}},e.resolveX25519Encrypters=function(e,r){try{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(r?.error)throw new Error(`Could not find x25519 key for ${e}: ${r.error}, ${r.message}`);if(!t.keyAgreement)throw new Error(`Could not find x25519 key for ${e}`);const n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>ae(l(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(ne)}catch(e){return Promise.reject(e)}},e.toEthereumAddress=K,e.verifyJWS=function(e,r){return G(F(e),r)},e.verifyJWT=function(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null,proofPurpose:null}){try{if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:o,data:i}=L(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=q[r];if(!o||0===o.length)throw new Error(`No supported signature types for algorithm ${r}`);let i;return Promise.resolve(e.resolve(t,{accept:H})).then(function(e){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:H}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let a=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...a.map(e=>e.id)]),a=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(a,e):"string"==typeof e.publicKey?c(a,e.publicKey):e).filter(e=>null!=e));const u=a.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!u||0===u.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!u||0===u.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:u,issuer:t,didResolutionResult:i}})}catch(e){return Promise.reject(e)}}(r.resolver,n.alg,t.iss,c)).then(function({didResolutionResult:c,authenticators:a,issuer:u}){return Promise.resolve(G({header:n,data:i,signature:o},a)).then(function(n){const o=Math.floor(Date.now()/1e3),i=r.skewTime>=0?r.skewTime:300;if(n){const a=o+i;if(t.nbf){if(t.nbf>a)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>a)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=o-i)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${o}`);if(t.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,didResolutionResult:c,issuer:u,signer:n,jwt:e}}})})}catch(e){return Promise.reject(e)}},e.x25519Decrypter=function(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:function(t,n,o,i){try{if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(i.header),"X25519"!==i.header.epk.crv)return Promise.resolve(null);const c=f(i.header.epk.x),u=$(a.sharedKey(e,c),256,r),s=w(i.encrypted_key,i.header.tag);return Promise.resolve(ce(u).decrypt(s,f(i.header.iv))).then(function(e){return null===e?null:ce(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}},e.x25519Encrypter=ae,e.xc20pDirDecrypter=ce,e.xc20pDirEncrypter=ie}); | ||
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("uint8arrays"),require("@stablelib/sha256"),require("js-sha3"),require("elliptic"),require("@stablelib/ed25519"),require("canonicalize"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","uint8arrays","@stablelib/sha256","js-sha3","elliptic","@stablelib/ed25519","canonicalize","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],r):r((e||self).didJwt={},e.uint8Arrays,e.sha256$1,e.jsSha3,e.elliptic,e.ed25519,e.canonicalize,e.xchacha20poly1305,e.x25519,e.random)}(this,function(e,r,t,n,o,i,c,a,u,s){function f(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var l=f(c);function d(e){return r.toString(e,"base64url")}function h(e){const t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r.fromString(t,"base64url")}function y(e){return r.fromString(e,"base58btc")}function p(e){const t=e.startsWith("0x")?e.substring(2):e;return r.fromString(t.toLowerCase(),"base16")}function g(e){return d(r.fromString(e))}function m(e){return r.toString(h(e))}function v(e){return r.toString(e,"base16")}function w(e){return r.fromString(e)}function b({r:e,s:t,recoveryParam:n},o){const i=new Uint8Array(o?65:64);if(i.set(r.fromString(e,"base16"),0),i.set(r.fromString(t,"base16"),32),o){if(void 0===n)throw new Error("Signer did not return a recoveryParam");i[64]=n}return d(i)}function E(e){const r=h(e);if(r.length<64||r.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${r.length}`);return{r:v(r.slice(0,32)),s:v(r.slice(32,64)),recoveryParam:65===r.length?r[64]:void 0}}function P(e,t){return r.concat([h(e),h(t)])}const S=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,k=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,x=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function K(e){if("string"==typeof e){if(S.test(e))return p(e);if(k.test(e))return y(e);if(x.test(e))return h(e);throw TypeError("Invalid private key format")}if(e instanceof Uint8Array)return e;throw TypeError("Invalid private key format")}function J(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function A(e){const n="string"==typeof e?r.fromString(e):e;return t.hash(n)}function $(e){const t=r.fromString(e.slice(2),"base16");return`0x${r.toString((o=t,new Uint8Array(n.keccak_256.arrayBuffer(o))).slice(-20),"base16")}`;var o}function j(e,t=new Uint8Array(4)){const n=r.fromString(e.toString(),"base10");return t.set(n,4-n.length),t}const D=e=>r.concat([j(e.length),e]);function W(e,n,o){if(256!==n)throw new Error(`Unsupported key length: ${n}`);const i=r.concat([D(r.fromString(o)),D(new Uint8Array(0)),D(new Uint8Array(0)),j(n)]);return t.hash(r.concat([j(1),e,i]))}const T=new o.ec("secp256k1");function I(e,r=!1){const t=K(e);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=T.keyFromPrivate(t);return function(e){try{const{r:t,s:o,recoveryParam:i}=n.sign(A(e));return Promise.resolve(b({r:J(t.toString("hex")),s:J(o.toString("hex")),recoveryParam:i},r))}catch(e){return Promise.reject(e)}}}function C(e){const r=K(e);if(64!==r.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${r.length}`);return function(e){try{const t="string"==typeof e?w(e):e,n=i.sign(r,t);return Promise.resolve(d(n))}catch(e){return Promise.reject(e)}}}function O(e){return"object"==typeof e&&"r"in e&&"s"in e}function R(e){return function(r,t){try{return Promise.resolve(t(r)).then(function(r){if(O(r))return b(r,e);if(e&&void 0===E(r).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return r})}catch(e){return Promise.reject(e)}}}function U(){return function(e,r){try{return Promise.resolve(r(e)).then(function(e){if(O(e))throw new Error("expected a signer function that returns a string instead of signature object");return e})}catch(e){return Promise.reject(e)}}}const z={ES256K:R(),"ES256K-R":R(!0),Ed25519:U(),EdDSA:U()},M=new o.ec("secp256k1");function N(e,r=!1){const t=h(e);if(t.length!==(r?65:64))throw new Error("wrong signature length");const n={r:v(t.slice(0,32)),s:v(t.slice(32,64))};return r&&(n.recoveryParam=t[64]),n}function B(e){return e.publicKeyBase58?y(e.publicKeyBase58):e.publicKeyBase64?h(e.publicKeyBase64):e.publicKeyHex?p(e.publicKeyHex):e.publicKeyJwk&&"secp256k1"===e.publicKeyJwk.crv?p(M.keyFromPublic({x:v(h(e.publicKeyJwk.x)),y:v(h(e.publicKeyJwk.y))}).getPublic("hex")):new Uint8Array}function X(e,r,t){let n;if(r.length>86)n=[N(r,!0)];else{const e=N(r,!1);n=[{...e,recoveryParam:0},{...e,recoveryParam:1}]}const o=n.map(r=>{const n=A(e),o=M.recoverPubKey(n,r,r.recoveryParam),i=o.encode("hex"),c=o.encode("hex",!0),a=$(i);return t.find(e=>{const r=v(B(e));return r===i||r===c||e.ethereumAddress?.toLowerCase()===a||e.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===a})}).filter(e=>null!=e);if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function q(e,r,t){const n=w(e),o=h(r),c=t.find(e=>i.verify(B(e),n,o));if(!c)throw new Error("Signature invalid for JWT");return c}const V={ES256K:function(e,r,t){const n=A(e),o=N(r),i=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0===e&&void 0===r),c=t.filter(({ethereumAddress:e,blockchainAccountId:r})=>void 0!==e||void 0!==typeof r);let a=i.find(e=>{try{const r=B(e);return M.keyFromPublic(r).verify(n,o)}catch(e){return!1}});if(!a&&c.length>0&&(a=X(e,r,c)),!a)throw new Error("Signature invalid for JWT");return a},"ES256K-R":X,Ed25519:q,EdDSA:q};function _(e){const r=V[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}_.toSignatureObject=N;const H=function(e,r,t={},n={}){try{t.alg||(t.alg=F);const o="string"==typeof e?e:G(e,n.canonicalize),i=[G(t,n.canonicalize),o].join("."),c=function(e){const r=z[e];if(!r)throw new Error(`Unsupported algorithm ${e}`);return r}(t.alg);return Promise.resolve(c(i,r)).then(function(e){return[i,e].join(".")})}catch(e){return Promise.reject(e)}},Z={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},F="ES256K",L="application/did+json";function G(e,r=!1){return g(r?JSON.stringify(l.default(e)):JSON.stringify(e))}function Q(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(m(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function Y(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=Q(e);return Object.assign(r,{payload:JSON.parse(m(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}function ee({header:e,data:r,signature:t},n){return Array.isArray(n)||(n=[n]),_(e.alg)(r,t,n)}const re="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function te(e,r,t){if(!e.s){if(t instanceof ne){if(!t.s)return void(t.o=te.bind(null,e,r));1&r&&(r=t.s),t=t.v}if(t&&t.then)return void t.then(te.bind(null,e,r),te.bind(null,e,2));e.s=r,e.v=t;const n=e.o;n&&n(e)}}const ne=function(){function e(){}return e.prototype.then=function(r,t){const n=new e,o=this.s;if(o){const e=1&o?r:t;if(e){try{te(n,1,e(this.v))}catch(e){te(n,2,e)}return n}return this}return this.o=function(e){try{const o=e.v;1&e.s?te(n,1,r?r(o):o):t?te(n,1,t(o)):te(n,2,o)}catch(e){te(n,2,e)}},n},e}();function oe(e){return e instanceof ne&&1&e.s}function ie({ciphertext:e,tag:r,iv:t,protectedHeader:n,recipient:o},i){const c={protected:n,iv:d(t),ciphertext:d(e),tag:d(r)};return i&&(c.aad=d(i)),o&&(c.recipients=[o]),c}const ce=e=>[].concat.apply([],e);function ae(e){const r=new a.XChaCha20Poly1305(e);return(e,t)=>{const n=s.randomBytes(r.nonceLength),o=r.seal(n,e,t);return{ciphertext:o.subarray(0,o.length-r.tagLength),tag:o.subarray(o.length-r.tagLength),iv:n}}}function ue(e){const r=ae(e),t="XC20P";return{alg:"dir",enc:t,encrypt:function(e,n={},o){try{const i=g(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),c=new Uint8Array(Buffer.from(o?`${i}.${d(o)}`:i));return Promise.resolve({...r(e,c),protectedHeader:i})}catch(e){return Promise.reject(e)}}}}function se(e){const r=new a.XChaCha20Poly1305(e);return{alg:"dir",enc:"XC20P",decrypt:function(e,t,n){try{return Promise.resolve(r.open(t,e,n))}catch(e){return Promise.reject(e)}}}}function fe(e,r){const t=function(t){try{const c=u.generateKeyPair(),a=ae(W(u.sharedKey(c.secretKey,e),o,n))(t),s={encrypted_key:d(a.ciphertext),header:{alg:n,iv:d(a.iv),tag:d(a.tag),epk:{kty:"OKP",crv:i,x:d(c.publicKey)}}};return r&&(s.header.kid=r),Promise.resolve(s)}catch(e){return Promise.reject(e)}},n="ECDH-ES+XC20PKW",o=256,i="X25519";return{alg:n,enc:"XC20P",encrypt:function(e,r={},n){try{Object.assign(r,{alg:void 0});const o=s.randomBytes(32);return Promise.resolve(ue(o).encrypt(e,r,n)).then(function(e){return Promise.resolve(t(o)).then(function(r){return{...e,recipient:r,cek:o}})})}catch(e){return Promise.reject(e)}},encryptCek:t}}e.ES256KSigner=I,e.EdDSASigner=C,e.EllipticSigner=function(e){return I(e)},e.NaclSigner=function(e){return C(e)},e.SimpleSigner=function(e){const r=I(e,!0);return function(e){try{return Promise.resolve(r(e)).then(E)}catch(e){return Promise.reject(e)}}},e.createJWE=function(e,r,t={},n){try{if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(r[0].encrypt(e,t,n)).then(function(e){return ie(e,n)})}{const o=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===o,!0))throw new Error("Incompatible encrypters passed");let i,c;const a=function(e,r,t){if("function"==typeof e[re]){var n,o,i,c=e[re]();if(function e(t){try{for(;!(n=c.next()).done;)if((t=r(n.value))&&t.then){if(!oe(t))return void t.then(e,i||(i=te.bind(null,o=new ne,2)));t=t.v}o?te(o,1,t):o=t}catch(e){te(o||(o=new ne),2,e)}}(),c.return){var a=function(e){try{n.done||c.return()}catch(e){}return e};if(o&&o.then)return o.then(a,function(e){throw a(e)});a()}return o}if(!("length"in e))throw new TypeError("Object is not iterable");for(var u=[],s=0;s<e.length;s++)u.push(e[s]);return function(e,r,t){var n,o,i=-1;return function t(c){try{for(;++i<e.length;)if((c=r(i))&&c.then){if(!oe(c))return void c.then(t,o||(o=te.bind(null,n=new ne,2)));c=c.v}n?te(n,1,c):n=c}catch(e){te(n||(n=new ne),2,e)}}(),n}(u,function(e){return r(u[e])})}(r,function(r){const o=function(){if(i){const e=c.recipients,t=e.push;return Promise.resolve(r.encryptCek(i)).then(function(r){t.call(e,r)})}return Promise.resolve(r.encrypt(e,t,n)).then(function(e){i=e.cek,c=ie(e,n)})}();if(o&&o.then)return o.then(function(){})});return Promise.resolve(a&&a.then?a.then(function(){return c}):c)}}catch(e){return Promise.reject(e)}},e.createJWS=H,e.createJWT=function(e,{issuer:r,signer:t,alg:n,expiresIn:o,canonicalize:i},c={}){try{if(!t)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");c.typ||(c.typ="JWT"),c.alg||(c.alg=n);const a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(o){if("number"!=typeof o)throw new Error("JWT expiresIn is not a number");a.exp=(e.nbf||a.iat)+Math.floor(o)}const u={...a,...e,iss:r};return H(u,t,c,{canonicalize:i})}catch(e){return Promise.reject(e)}},e.decodeJWT=Y,e.decryptJWE=function(e,r){try{function t(e){if(null===c)throw new Error("Failed to decrypt");return c}!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const n=JSON.parse(m(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const o=P(e.ciphertext,e.tag),i=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let c=null;const a="dir"===n.alg&&"dir"===r.alg?Promise.resolve(r.decrypt(o,h(e.iv),i)).then(function(e){c=e}):function(){if(e.recipients&&0!==e.recipients.length){let t=0;return function(e,r,t){for(var n;;){var o=e();if(oe(o)&&(o=o.v),!o)return i;if(o.then){n=0;break}var i=t();if(i&&i.then){if(!oe(i)){n=1;break}i=i.s}if(r){var c=r();if(c&&c.then&&!oe(c)){n=2;break}}}var a=new ne,u=te.bind(null,a,2);return(0===n?o.then(f):1===n?i.then(s):c.then(l)).then(void 0,u),a;function s(n){i=n;do{if(r&&(c=r())&&c.then&&!oe(c))return void c.then(l).then(void 0,u);if(!(o=e())||oe(o)&&!o.v)return void te(a,1,i);if(o.then)return void o.then(f).then(void 0,u);oe(i=t())&&(i=i.v)}while(!i||!i.then);i.then(s).then(void 0,u)}function f(e){e?(i=t())&&i.then?i.then(s).then(void 0,u):s(i):te(a,1,i)}function l(){(o=e())?o.then?o.then(f).then(void 0,u):f(o):te(a,1,i)}}(function(){return!c&&t<e.recipients.length},function(){return t++},function(){const a=e.recipients[t];Object.assign(a.header,n);const u=function(){if(a.header.alg===r.alg)return Promise.resolve(r.decrypt(o,h(e.iv),i,a)).then(function(e){c=e})}();if(u&&u.then)return u.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(a&&a.then?a.then(t):t())}catch(e){return Promise.reject(e)}},e.resolveX25519Encrypters=function(e,r){try{const t=function(e){try{return Promise.resolve(r.resolve(e)).then(function({didResolutionMetadata:r,didDocument:t}){if(r?.error)throw new Error(`Could not find x25519 key for ${e}: ${r.error}, ${r.message}`);if(!t.keyAgreement)throw new Error(`Could not find x25519 key for ${e}`);const n=t.keyAgreement?.map(e=>"string"==typeof e?[...t.publicKey||[],...t.verificationMethod||[]].find(r=>r.id===e):e).filter(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!n.length)throw new Error(`Could not find x25519 key for ${e}`);return n.map(e=>fe(y(e.publicKeyBase58),e.id))})}catch(e){return Promise.reject(e)}},n=e.map(e=>t(e));return Promise.resolve(Promise.all(n)).then(ce)}catch(e){return Promise.reject(e)}},e.toEthereumAddress=$,e.verifyJWS=function(e,r){return ee(Q(e),r)},e.verifyJWT=function(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null,proofPurpose:null}){try{if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:o,data:i}=Y(e),c=r.hasOwnProperty("auth")?r.auth?"authentication":void 0:r.proofPurpose;return Promise.resolve(function(e,r,t,n){try{const o=Z[r];if(!o||0===o.length)throw new Error(`No supported signature types for algorithm ${r}`);let i;return Promise.resolve(e.resolve(t,{accept:L})).then(function(e){if(i=-1===Object.getOwnPropertyNames(e).indexOf("didDocument")?{didDocument:e,didDocumentMetadata:{},didResolutionMetadata:{contentType:L}}:e,i.didResolutionMetadata?.error){const{error:e,message:r}=i.didResolutionMetadata;throw new Error(`Unable to resolve DID document for ${t}: ${e}, ${r||""}`)}const c=(e,r)=>{const t=e.filter(({id:e})=>r===e);return t.length>0?t[0]:null};let a=[...i?.didDocument?.verificationMethod||[],...i?.didDocument?.publicKey||[]];"string"==typeof n&&(n.startsWith("assertion")&&!i.didDocument.hasOwnProperty("assertionMethod")&&(i.didDocument.assertionMethod=[...a.map(e=>e.id)]),a=(i.didDocument[n]||[]).map(e=>"string"==typeof e?c(a,e):"string"==typeof e.publicKey?c(a,e.publicKey):e).filter(e=>null!=e));const u=a.filter(({type:e})=>o.find(r=>r===e));if("string"==typeof n&&(!u||0===u.length))throw new Error(`DID document for ${t} does not have public keys suitable for ${r} with ${n} purpose`);if(!u||0===u.length)throw new Error(`DID document for ${t} does not have public keys for ${r}`);return{authenticators:u,issuer:t,didResolutionResult:i}})}catch(e){return Promise.reject(e)}}(r.resolver,n.alg,t.iss,c)).then(function({didResolutionResult:c,authenticators:a,issuer:u}){return Promise.resolve(ee({header:n,data:i,signature:o},a)).then(function(n){const o=Math.floor(Date.now()/1e3),i=r.skewTime>=0?r.skewTime:300;if(n){const a=o+i;if(t.nbf){if(t.nbf>a)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>a)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=o-i)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${o}`);if(t.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,didResolutionResult:c,issuer:u,signer:n,jwt:e}}})})}catch(e){return Promise.reject(e)}},e.x25519Decrypter=function(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:function(t,n,o,i){try{if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(i.header),"X25519"!==i.header.epk.crv)return Promise.resolve(null);const c=h(i.header.epk.x),a=W(u.sharedKey(e,c),256,r),s=P(i.encrypted_key,i.header.tag);return Promise.resolve(se(a).decrypt(s,h(i.header.iv))).then(function(e){return null===e?null:se(e).decrypt(t,n,o)})}catch(e){return Promise.reject(e)}}}},e.x25519Encrypter=fe,e.xc20pDirDecrypter=se,e.xc20pDirEncrypter=ue}); | ||
//# sourceMappingURL=index.umd.js.map |
@@ -0,3 +1,3 @@ | ||
import type { DIDResolutionResult, Resolvable, VerificationMethod } from 'did-resolver'; | ||
import { EcdsaSignature } from './util'; | ||
import type { Resolvable, VerificationMethod, DIDResolutionResult } from 'did-resolver'; | ||
export declare type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string>; | ||
@@ -13,2 +13,3 @@ export declare type SignerAlgorithm = (payload: string, signer: Signer) => Promise<string>; | ||
expiresIn?: number; | ||
canonicalize?: boolean; | ||
} | ||
@@ -25,2 +26,5 @@ export interface JWTVerifyOptions { | ||
} | ||
export interface JWSCreationOptions { | ||
canonicalize?: boolean; | ||
} | ||
export interface DIDAuthenticator { | ||
@@ -94,3 +98,3 @@ authenticators: VerificationMethod[]; | ||
*/ | ||
export declare function createJWS(payload: string | any, signer: Signer, header?: Partial<JWTHeader>): Promise<string>; | ||
export declare function createJWS(payload: string | any, signer: Signer, header?: Partial<JWTHeader>, options?: JWSCreationOptions): Promise<string>; | ||
/** | ||
@@ -105,12 +109,13 @@ * Creates a signed JWT given an address which becomes the issuer, a signer, and a payload for which the signature is over. | ||
* | ||
* @param {Object} payload payload object | ||
* @param {Object} [options] an unsigned credential object | ||
* @param {String} options.issuer The DID of the issuer (signer) of JWT | ||
* @param {String} options.alg [DEPRECATED] The JWT signing algorithm to use. Supports: [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. | ||
* Please use `header.alg` to specify the algorithm | ||
* @param {Signer} options.signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner` | ||
* @param {Object} header optional object to specify or customize the JWT header | ||
* @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or rejects with an error | ||
* @param {Object} payload payload object | ||
* @param {Object} [options] an unsigned credential object | ||
* @param {String} options.issuer The DID of the issuer (signer) of JWT | ||
* @param {String} options.alg [DEPRECATED] The JWT signing algorithm to use. Supports: [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. | ||
* Please use `header.alg` to specify the algorithm | ||
* @param {Signer} options.signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner` | ||
* @param {boolean} options.canonicalize optional flag to canonicalize header and payload before signing | ||
* @param {Object} header optional object to specify or customize the JWT header | ||
* @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or rejects with an error | ||
*/ | ||
export declare function createJWT(payload: any, { issuer, signer, alg, expiresIn }: JWTOptions, header?: Partial<JWTHeader>): Promise<string>; | ||
export declare function createJWT(payload: any, { issuer, signer, alg, expiresIn, canonicalize }: JWTOptions, header?: Partial<JWTHeader>): Promise<string>; | ||
/** | ||
@@ -117,0 +122,0 @@ * Verifies given JWS. If the JWS is valid, returns the public key that was |
{ | ||
"name": "did-jwt", | ||
"version": "5.3.1", | ||
"version": "5.4.0", | ||
"description": "Library for Signing and Verifying JWTs compatible uPort and DID standards", | ||
@@ -62,3 +62,3 @@ "main": "lib/index.js", | ||
"eslint-config-standard": "16.0.2", | ||
"eslint-plugin-import": "2.23.0", | ||
"eslint-plugin-import": "2.23.2", | ||
"eslint-plugin-jest": "24.3.6", | ||
@@ -92,2 +92,3 @@ "eslint-plugin-node": "11.1.0", | ||
"@stablelib/xchacha20poly1305": "^1.0.0", | ||
"canonicalize": "^1.0.5", | ||
"did-resolver": "^3.1.0", | ||
@@ -94,0 +95,0 @@ "elliptic": "^6.5.4", |
@@ -1,8 +0,8 @@ | ||
import { createJWT, verifyJWT, decodeJWT, createJWS, verifyJWS, resolveAuthenticator, NBF_SKEW } from '../JWT' | ||
import { VerificationMethod } from 'did-resolver' | ||
import { TokenVerifier } from 'jsontokens' | ||
import { bytesToBase64url, decodeBase64url } from '../util' | ||
import MockDate from 'mockdate' | ||
import { VerificationMethod, Resolver } from 'did-resolver' | ||
import { createJWS, createJWT, decodeJWT, NBF_SKEW, resolveAuthenticator, verifyJWS, verifyJWT } from '../JWT' | ||
import { EdDSASigner } from '../signers/EdDSASigner' | ||
import { ES256KSigner } from '../signers/ES256KSigner' | ||
import { EdDSASigner } from '../signers/EdDSASigner' | ||
import { bytesToBase64url, decodeBase64url } from '../util' | ||
@@ -176,2 +176,30 @@ const NOW = 1485321133 | ||
it('can create a jwt in the default non-canonical way', async () => { | ||
expect.assertions(1) | ||
// Same payload, slightly different ordering | ||
const jwtA = await createJWT( | ||
{ reason: 'verification', requested: ['name', 'phone'] }, | ||
{ alg, issuer: did, signer } | ||
) | ||
const jwtB = await createJWT( | ||
{ requested: ['name', 'phone'], reason: 'verification' }, | ||
{ alg, issuer: did, signer } | ||
) | ||
expect(jwtA).not.toEqual(jwtB) | ||
}) | ||
it('can create a jwt in a canonical way', async () => { | ||
expect.assertions(1) | ||
// Same payload, slightly different ordering | ||
const jwtA = await createJWT( | ||
{ reason: 'verification', requested: ['name', 'phone'] }, | ||
{ alg, issuer: did, signer, canonicalize: true } | ||
) | ||
const jwtB = await createJWT( | ||
{ requested: ['name', 'phone'], reason: 'verification' }, | ||
{ alg, issuer: did, signer, canonicalize: true } | ||
) | ||
expect(jwtA).toEqual(jwtB) | ||
}) | ||
it('creates a JWT with correct format', async () => { | ||
@@ -526,2 +554,10 @@ expect.assertions(1) | ||
it('createJWS can canonicalize a JSON payload', async () => { | ||
expect.assertions(2) | ||
const payload = { z: 'z', a: 'a' } | ||
const jws = await createJWS(payload, signer, {}, { canonicalize: true }) | ||
expect(jws).toMatchSnapshot() | ||
expect(JSON.parse(decodeBase64url(jws.split('.')[1]))).toEqual(JSON.stringify({ a: 'a', z: 'z' })) | ||
}) | ||
it('createJWS works with base64url payload', async () => { | ||
@@ -528,0 +564,0 @@ expect.assertions(2) |
@@ -0,5 +1,6 @@ | ||
import canonicalizeData from 'canonicalize' | ||
import type { DIDDocument, DIDResolutionResult, Resolvable, VerificationMethod } from 'did-resolver' | ||
import SignerAlg from './SignerAlgorithm' | ||
import { decodeBase64url, EcdsaSignature, encodeBase64url } from './util' | ||
import VerifierAlgorithm from './VerifierAlgorithm' | ||
import SignerAlg from './SignerAlgorithm' | ||
import { encodeBase64url, decodeBase64url, EcdsaSignature } from './util' | ||
import type { Resolvable, VerificationMethod, DIDResolutionResult, DIDDocument } from 'did-resolver' | ||
@@ -17,2 +18,3 @@ export type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string> | ||
expiresIn?: number | ||
canonicalize?: boolean | ||
} | ||
@@ -31,2 +33,6 @@ | ||
export interface JWSCreationOptions { | ||
canonicalize?: boolean | ||
} | ||
export interface DIDAuthenticator { | ||
@@ -127,4 +133,8 @@ authenticators: VerificationMethod[] | ||
function encodeSection(data: any): string { | ||
return encodeBase64url(JSON.stringify(data)) | ||
function encodeSection(data: any, shouldCanonicalize: boolean = false): string { | ||
if (shouldCanonicalize) { | ||
return encodeBase64url(JSON.stringify(canonicalizeData(data))) | ||
} else { | ||
return encodeBase64url(JSON.stringify(data)) | ||
} | ||
} | ||
@@ -184,7 +194,8 @@ | ||
signer: Signer, | ||
header: Partial<JWTHeader> = {} | ||
header: Partial<JWTHeader> = {}, | ||
options: JWSCreationOptions = {} | ||
): Promise<string> { | ||
if (!header.alg) header.alg = defaultAlg | ||
const encodedPayload = typeof payload === 'string' ? payload : encodeSection(payload) | ||
const signingInput: string = [encodeSection(header), encodedPayload].join('.') | ||
const encodedPayload = typeof payload === 'string' ? payload : encodeSection(payload, options.canonicalize) | ||
const signingInput: string = [encodeSection(header, options.canonicalize), encodedPayload].join('.') | ||
@@ -205,14 +216,15 @@ const jwtSigner: SignerAlgorithm = SignerAlg(header.alg) | ||
* | ||
* @param {Object} payload payload object | ||
* @param {Object} [options] an unsigned credential object | ||
* @param {String} options.issuer The DID of the issuer (signer) of JWT | ||
* @param {String} options.alg [DEPRECATED] The JWT signing algorithm to use. Supports: [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. | ||
* Please use `header.alg` to specify the algorithm | ||
* @param {Signer} options.signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner` | ||
* @param {Object} header optional object to specify or customize the JWT header | ||
* @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or rejects with an error | ||
* @param {Object} payload payload object | ||
* @param {Object} [options] an unsigned credential object | ||
* @param {String} options.issuer The DID of the issuer (signer) of JWT | ||
* @param {String} options.alg [DEPRECATED] The JWT signing algorithm to use. Supports: [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. | ||
* Please use `header.alg` to specify the algorithm | ||
* @param {Signer} options.signer a `Signer` function, Please see `ES256KSigner` or `EdDSASigner` | ||
* @param {boolean} options.canonicalize optional flag to canonicalize header and payload before signing | ||
* @param {Object} header optional object to specify or customize the JWT header | ||
* @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or rejects with an error | ||
*/ | ||
export async function createJWT( | ||
payload: any, | ||
{ issuer, signer, alg, expiresIn }: JWTOptions, | ||
{ issuer, signer, alg, expiresIn, canonicalize }: JWTOptions, | ||
header: Partial<JWTHeader> = {} | ||
@@ -236,3 +248,3 @@ ): Promise<string> { | ||
const fullPayload = { ...timestamps, ...payload, iss: issuer } | ||
return createJWS(fullPayload, signer, header) | ||
return createJWS(fullPayload, signer, header, { canonicalize }) | ||
} | ||
@@ -239,0 +251,0 @@ |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
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
737544
65547
3703
10
+ Addedcanonicalize@^1.0.5
+ Addedcanonicalize@1.0.8(transitive)