Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

did-jwt

Package Overview
Dependencies
Maintainers
8
Versions
142
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

did-jwt - npm Package Compare versions

Comparing version 4.8.1 to 4.9.0

lib/signers/EdDSASigner.d.ts

7

CHANGELOG.md

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

# [4.9.0](https://github.com/decentralized-identity/did-jwt/compare/4.8.1...4.9.0) (2021-02-10)
### Features
* add `ES256KSigner` and `EdDSASigner` with uniform APIs ([#149](https://github.com/decentralized-identity/did-jwt/issues/149))([#78](https://github.com/decentralized-identity/did-jwt/issues/78)) ([cdd3c0f](https://github.com/decentralized-identity/did-jwt/commit/cdd3c0f75915b4ff161f2813eae22a9d254fb90f))
## [4.8.1](https://github.com/decentralized-identity/did-jwt/compare/4.8.0...4.8.1) (2020-12-18)

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

2

lib/Digest.d.ts

@@ -1,2 +0,2 @@

export declare function sha256(payload: string): Uint8Array;
export declare function sha256(payload: string | Uint8Array): Uint8Array;
export declare function keccak(data: Uint8Array): Uint8Array;

@@ -3,0 +3,0 @@ export declare function toEthereumAddress(hexPublicKey: string): string;

@@ -1,4 +0,6 @@

import SimpleSigner from './SimpleSigner';
import EllipticSigner from './EllipticSigner';
import NaclSigner from './NaclSigner';
import SimpleSigner from './signers/SimpleSigner';
import EllipticSigner from './signers/EllipticSigner';
import NaclSigner from './signers/NaclSigner';
import { ES256KSigner } from './signers/ES256KSigner';
import { EdDSASigner } from './signers/EdDSASigner';
import { verifyJWT, createJWT, decodeJWT, verifyJWS, createJWS, Signer, JWTHeader, JWTPayload, JWTVerified, Resolvable } from './JWT';

@@ -8,3 +10,3 @@ import { toEthereumAddress } from './Digest';

export { xc20pDirEncrypter, xc20pDirDecrypter, x25519Encrypter, x25519Decrypter, resolveX25519Encrypters } from './xc20pEncryption';
export { SimpleSigner, EllipticSigner, NaclSigner, verifyJWT, createJWT, decodeJWT, verifyJWS, createJWS, toEthereumAddress, Signer, JWTHeader, JWTPayload, JWTVerified, Resolvable };
export { SimpleSigner, EllipticSigner, NaclSigner, ES256KSigner, EdDSASigner, verifyJWT, createJWT, decodeJWT, verifyJWS, createJWS, toEthereumAddress, Signer, JWTHeader, JWTPayload, JWTVerified, Resolvable };
//# sourceMappingURL=index.d.ts.map

@@ -1,2 +0,2 @@

import{ec as r}from"elliptic";import{hash as e}from"@stablelib/sha256";import{fromString as n,toString as t,concat as i}from"uint8arrays";import{keccak_256 as o}from"js-sha3";import{sign as u,verify as a}from"@stablelib/ed25519";import{XChaCha20Poly1305 as c}from"@stablelib/xchacha20poly1305";import{generateKeyPair as f,sharedKey as s}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function h(r){return e(n(r))}function v(r){var e,i=n(r.slice(2),"base16");return"0x"+t((e=i,new Uint8Array(o.arrayBuffer(e))).slice(-20),"base16")}function d(r,e){void 0===e&&(e=new Uint8Array(4));var t=n(r.toString(),"base10");return e.set(t,4-t.length),e}var p=function(r){return i([d(r.length),r])};function y(r,t,o){if(256!==t)throw new Error("Unsupported key length: "+t);var u=i([p(n(o)),p(new Uint8Array(0)),p(new Uint8Array(0)),d(t)]);return e(i([d(1),r,u]))}var g=new r("secp256k1");function m(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function w(r){r.startsWith("0x")&&(r=r.substring(2));var e=g.keyFromPrivate(r);return function(r){try{var n=e.sign(h(r)),t=n.s,i=n.recoveryParam;return Promise.resolve({r:m(n.r.toString("hex")),s:m(t.toString("hex")),recoveryParam:i})}catch(r){return Promise.reject(r)}}}function b(r){return t(r,"base64url")}function E(r){return n(r,"base64url")}function P(r){return n(r,"base64pad")}function S(r){return n(r,"base58btc")}function k(r){return b(n(r))}function K(r){return t(E(r))}function x(r){return t(r,"base16")}function j(r){return n(r)}function A(r,e){var t=r.r,i=r.s,o=r.recoveryParam,u=new Uint8Array(e?65:64);if(u.set(n(t,"base16"),0),u.set(n(i,"base16"),32),e){if(void 0===o)throw new Error("Signer did not return a recoveryParam");u[64]=o}return b(u)}function J(r,e){return i([E(r),E(e)])}function D(r){var e=w(r);return function(r){try{return Promise.resolve(e(r)).then(function(r){return A(r)})}catch(r){return Promise.reject(r)}}}function W(r){var e=P(r);return function(r){try{var n=j(r),t=b(u(e,n));return Promise.resolve(t)}catch(r){return Promise.reject(r)}}}function T(){return(T=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(r[t]=n[t])}return r}).apply(this,arguments)}var I=new r("secp256k1");function O(r,e){void 0===e&&(e=!1);var n=E(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:x(n.slice(0,32)),s:x(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function U(r){return r.publicKeyBase58?S(r.publicKeyBase58):r.publicKeyBase64?P(r.publicKeyBase64):r.publicKeyHex?n(r.publicKeyHex,"base16"):new Uint8Array}function C(r,e,n){var t;if(e.length>86)t=[O(e,!0)];else{var i=O(e,!1);t=[T({},i,{recoveryParam:0}),T({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=h(r),i=I.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),u=i.encode("hex",!0),a=v(o);return n.find(function(r){var e=r.publicKeyHex;return e===o||e===u||r.ethereumAddress===a})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function B(r,e,n){var t=j(r),i=E(e),o=n.find(function(r){return a(U(r),t,i)});if(!o)throw new Error("Signature invalid for JWT");return o}var V={ES256K:function(r,e,n){var t=h(r),i=O(e),o=n.filter(function(r){return void 0===r.ethereumAddress}),u=n.filter(function(r){return void 0!==r.ethereumAddress}),a=o.find(function(r){try{var e=U(r);return I.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!a&&u.length>0&&(a=C(r,e,u)),!a)throw new Error("Signature invalid for JWT");return a},"ES256K-R":C,Ed25519:B,EdDSA:B};function X(r){var e=V[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function N(r){return"object"==typeof r&&"r"in r&&"s"in r}function H(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(N(e))return A(e,r);if(r)throw new Error("ES256K-R not supported when signer function returns string");return e})}catch(r){return Promise.reject(r)}}}function _(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(N(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}X.toSignatureObject=O;var R={ES256K:H(),"ES256K-R":H(!0),Ed25519:_(),EdDSA:_()},z=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var n=Q(r),t=n.payload,i=n.header,o=n.signature,u=n.data;return Promise.resolve(function(r,e,n,t){try{var i=M[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(n)).then(function(r){if(!r)throw new Error("Unable to resolve DID document for "+n);var o=function(r,e){var n=r.publicKey.filter(function(r){return e===r.id});return n.length>0?n[0]:null},u=r.publicKey||[];t&&(u=(r.authentication||[]).map(function(e){return"string"==typeof e?o(r,e):"string"==typeof e.publicKey?o(r,e.publicKey):e}).filter(function(r){return null!=r}));var a=u.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(t&&(!a||0===a.length))throw new Error("DID document for "+n+" does not have public keys suitable for authenticating user");if(!a||0===a.length)throw new Error("DID document for "+n+" does not have public keys for "+e);return{authenticators:a,issuer:n,doc:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,t.iss,e.auth)).then(function(n){var a=n.doc,c=n.issuer;return Promise.resolve(Y({header:i,data:u,signature:o},n.authenticators)).then(function(n){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:$;if(n){var u=i+o;if(t.nbf){if(t.nbf>u)throw new Error("JWT not valid before nbf: "+t.nbf)}else if(t.iat&&t.iat>u)throw new Error("JWT not valid yet (issued in the future) iat: "+t.iat);if(t.exp&&t.exp<=i-o)throw new Error("JWT has expired: exp: "+t.exp+" < now: "+i);if(t.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,doc:a,issuer:c,signer:n,jwt:r}}})})}catch(r){return Promise.reject(r)}},F=function(r,e,n){var t=e.issuer,i=e.signer,o=e.alg,u=e.expiresIn;void 0===n&&(n={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!t)throw new Error("No issuing DID has been configured");n.typ||(n.typ="JWT"),n.alg||(n.alg=o);var a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(u){if("number"!=typeof u)throw new Error("JWT expiresIn is not a number");a.exp=(r.nbf||a.iat)+Math.floor(u)}var c=T({},a,r,{iss:t});return L(c,i,n)}catch(r){return Promise.reject(r)}},L=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=Z);var t="string"==typeof r?r:q(r),i=[q(n),t].join("."),o=function(r){var e=R[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(n.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},M={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},Z="ES256K";function q(r){return k(JSON.stringify(r))}var $=300;function G(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(K(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function Q(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=G(r);return Object.assign(e,{payload:JSON.parse(K(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function Y(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),X(n.alg)(t,i,e)}function rr(r,e){return Y(G(r),e)}var er=function(r,e){try{var n=function(r){if(null===u)throw new Error("Failed to decrypt");return u};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var t=JSON.parse(K(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=J(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),u=null,a="dir"===t.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,E(r.iv),o)).then(function(r){u=r}):function(){if(r.recipients&&0!==r.recipients.length){var n=0;return function(r,e,n){for(var t;;){var i=r();if(or(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!or(o)){t=1;break}o=o.s}if(e){var u=e();if(u&&u.then&&!or(u)){t=2;break}}}var a=new ir,c=tr.bind(null,a,2);return(0===t?i.then(s):1===t?o.then(f):u.then(l)).then(void 0,c),a;function f(t){o=t;do{if(e&&(u=e())&&u.then&&!or(u))return void u.then(l).then(void 0,c);if(!(i=r())||or(i)&&!i.v)return void tr(a,1,o);if(i.then)return void i.then(s).then(void 0,c);or(o=n())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=n())&&o.then?o.then(f).then(void 0,c):f(o):tr(a,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):tr(a,1,o)}}(function(){return!u&&n<r.recipients.length},function(){return n++},function(){var a=r.recipients[n];Object.assign(a.header,t);var c=function(){if(a.header.alg===e.alg)return Promise.resolve(e.decrypt(i,E(r.iv),o,a)).then(function(r){u=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(a&&a.then?a.then(n):n())}catch(r){return Promise.reject(r)}},nr="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function tr(r,e,n){if(!r.s){if(n instanceof ir){if(!n.s)return void(n.o=tr.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(tr.bind(null,r,e),tr.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var ir=function(){function r(){}return r.prototype.then=function(e,n){var t=new r,i=this.s;if(i){var o=1&i?e:n;if(o){try{tr(t,1,o(this.v))}catch(r){tr(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?tr(t,1,e?e(i):i):n?tr(t,1,n(i)):tr(t,2,i)}catch(r){tr(t,2,r)}},t},r}();function or(r){return r instanceof ir&&1&r.s}function ur(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:b(r.iv),ciphertext:b(n),tag:b(t)};return e&&(o.aad=b(e)),i&&(o.recipients=[i]),o}var ar=function(r,e,n,t){void 0===n&&(n={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,n,t)).then(function(r){return ur(r,t)})}var i,o,u=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===u},!0))throw new Error("Incompatible encrypters passed");var a=function(r,e,n){if("function"==typeof r[nr]){var t,i,o,u=r[nr]();if(function r(n){try{for(;!(t=u.next()).done;)if((n=e(t.value))&&n.then){if(!or(n))return void n.then(r,o||(o=tr.bind(null,i=new ir,2)));n=n.v}i?tr(i,1,n):i=n}catch(r){tr(i||(i=new ir),2,r)}}(),u.return){var a=function(r){try{t.done||u.return()}catch(r){}return r};if(i&&i.then)return i.then(a,function(r){throw a(r)});a()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,n){var t,i,o=-1;return function n(u){try{for(;++o<r.length;)if((u=e(o))&&u.then){if(!or(u))return void u.then(n,i||(i=tr.bind(null,t=new ir,2)));u=u.v}t?tr(t,1,u):t=u}catch(r){tr(t||(t=new ir),2,r)}}(),t}(c,function(r){return e(c[r])})}(e,function(e){var u=function(){if(i){var u=o.recipients,a=u.push;return Promise.resolve(e.encryptCek(i)).then(function(r){a.call(u,r)})}return Promise.resolve(e.encrypt(r,n,t)).then(function(r){i=r.cek,o=ur(r,t)})}();if(u&&u.then)return u.then(function(){})});return Promise.resolve(a&&a.then?a.then(function(){return o}):o)}catch(r){return Promise.reject(r)}};function cr(r){var e=new c(r);return function(r,n){var t=l(e.nonceLength),i=e.seal(t,r,n);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:t}}}var fr=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var n;if(!e.keyAgreement)throw new Error("Could not find x25519 key for "+r);var t=(null==(n=e.keyAgreement)?void 0:n.map(function(r){return"string"==typeof r?e.publicKey.find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!t)throw new Error("Could not find x25519 key for "+r);return hr(S(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}};function sr(r){var e=cr(r);return{alg:"dir",enc:"XC20P",encrypt:function(r,n,t){void 0===n&&(n={});try{var i=k(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?i+"."+b(t):i));return Promise.resolve(T({},e(r,o),{protectedHeader:i}))}catch(r){return Promise.reject(r)}}}}function lr(r){var e=new c(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,n,t){try{return Promise.resolve(e.open(n,r,t))}catch(r){return Promise.reject(r)}}}}function hr(r,e){var n=function(n){try{var u=f(),a=cr(y(s(u.secretKey,r),i,t))(n),c={encrypted_key:b(a.ciphertext),header:{alg:t,iv:b(a.iv),tag:b(a.tag),epk:{kty:"OKP",crv:o,x:b(u.publicKey)}}};return e&&(c.header.kid=e),Promise.resolve(c)}catch(r){return Promise.reject(r)}},t="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:t,enc:"XC20P",encrypt:function(r,e,t){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=l(32);return Promise.resolve(sr(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return T({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}function vr(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(n,t,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var u=E(o.header.epk.x),a=y(s(r,u),256,e),c=J(o.encrypted_key,o.header.tag);return Promise.resolve(lr(a).decrypt(c,E(o.header.iv))).then(function(r){return null===r?null:lr(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}}export{D as EllipticSigner,W as NaclSigner,w as SimpleSigner,ar as createJWE,L as createJWS,F as createJWT,Q as decodeJWT,er as decryptJWE,fr as resolveX25519Encrypters,v as toEthereumAddress,rr as verifyJWS,z as verifyJWT,vr as x25519Decrypter,hr as x25519Encrypter,lr as xc20pDirDecrypter,sr as xc20pDirEncrypter};
import{toString as r,fromString as e,concat as n}from"uint8arrays";import{hash as t}from"@stablelib/sha256";import{keccak_256 as i}from"js-sha3";import{ec as o}from"elliptic";import{sign as a,verify as u}from"@stablelib/ed25519";import{XChaCha20Poly1305 as c}from"@stablelib/xchacha20poly1305";import{generateKeyPair as f,sharedKey as s}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function h(e){return r(e,"base64url")}function v(r){var n=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e(n,"base64url")}function d(r){return e(r,"base58btc")}function p(r){var n=r.startsWith("0x")?r.substring(2):r;return e(n.toLowerCase(),"base16")}function y(r){return h(e(r))}function g(e){return r(v(e))}function m(e){return r(e,"base16")}function w(r){return e(r)}function b(r,n){var t=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(n?65:64);if(a.set(e(t,"base16"),0),a.set(e(i,"base16"),32),n){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return h(a)}function E(r){var e=v(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:m(e.slice(0,32)),s:m(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function P(r,e){return n([v(r),v(e)])}var k=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,K=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function x(r){if("string"==typeof r){if(k.test(r))return p(r);if(S.test(r))return d(r);if(K.test(r))return v(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function j(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function A(r){var n="string"==typeof r?e(r):r;return t(n)}function J(n){var t,o=e(n.slice(2),"base16");return"0x"+r((t=o,new Uint8Array(i.arrayBuffer(t))).slice(-20),"base16")}function D(r,n){void 0===n&&(n=new Uint8Array(4));var t=e(r.toString(),"base10");return n.set(t,4-t.length),n}var W=function(r){return n([D(r.length),r])};function T(r,i,o){if(256!==i)throw new Error("Unsupported key length: "+i);var a=n([W(e(o)),W(new Uint8Array(0)),W(new Uint8Array(0)),D(i)]);return t(n([D(1),r,a]))}var I=new o("secp256k1");function U(r,e){void 0===e&&(e=!1);var n=x(r);if(32!==n.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+n.length);var t=I.keyFromPrivate(n);return function(r){try{var n=t.sign(A(r)),i=n.s,o=n.recoveryParam;return Promise.resolve(b({r:j(n.r.toString("hex")),s:j(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function O(r){var e=U(r,!0);return function(r){try{return Promise.resolve(e(r)).then(E)}catch(r){return Promise.reject(r)}}}function C(r){return U(r)}function N(r){var e=x(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var n="string"==typeof r?w(r):r,t=a(e,n);return Promise.resolve(h(t))}catch(r){return Promise.reject(r)}}}function B(r){return N(r)}function V(){return(V=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(r[t]=n[t])}return r}).apply(this,arguments)}var H=new o("secp256k1");function X(r,e){void 0===e&&(e=!1);var n=v(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:m(n.slice(0,32)),s:m(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function _(r){return r.publicKeyBase58?d(r.publicKeyBase58):r.publicKeyBase64?v(r.publicKeyBase64):r.publicKeyHex?p(r.publicKeyHex):new Uint8Array}function z(r,e,n){var t;if(e.length>86)t=[X(e,!0)];else{var i=X(e,!1);t=[V({},i,{recoveryParam:0}),V({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=A(r),i=H.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=J(o);return n.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function Z(r,e,n){var t=w(r),i=v(e),o=n.find(function(r){return u(_(r),t,i)});if(!o)throw new Error("Signature invalid for JWT");return o}var F={ES256K:function(r,e,n){var t=A(r),i=X(e),o=n.filter(function(r){return void 0===r.ethereumAddress}),a=n.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=_(r);return H.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=z(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":z,Ed25519:Z,EdDSA:Z};function L(r){var e=F[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function R(r){return"object"==typeof r&&"r"in r&&"s"in r}function $(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(R(e))return b(e,r);if(r&&void 0===E(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function M(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(R(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}L.toSignatureObject=X;var q={ES256K:$(),"ES256K-R":$(!0),Ed25519:M(),EdDSA:M()},G=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var n=or(r),t=n.payload,i=n.header,o=n.signature,a=n.data;return Promise.resolve(function(r,e,n,t){try{var i=rr[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(n)).then(function(r){if(!r)throw new Error("Unable to resolve DID document for "+n);var o=function(r,e){var n=r.publicKey.filter(function(r){return e===r.id});return n.length>0?n[0]:null},a=r.publicKey||[];t&&(a=(r.authentication||[]).map(function(e){return"string"==typeof e?o(r,e):"string"==typeof e.publicKey?o(r,e.publicKey):e}).filter(function(r){return null!=r}));var u=a.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(t&&(!u||0===u.length))throw new Error("DID document for "+n+" does not have public keys suitable for authenticating user");if(!u||0===u.length)throw new Error("DID document for "+n+" does not have public keys for "+e);return{authenticators:u,issuer:n,doc:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,t.iss,e.auth)).then(function(n){var u=n.doc,c=n.issuer;return Promise.resolve(ar({header:i,data:a,signature:o},n.authenticators)).then(function(n){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:tr;if(n){var a=i+o;if(t.nbf){if(t.nbf>a)throw new Error("JWT not valid before nbf: "+t.nbf)}else if(t.iat&&t.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+t.iat);if(t.exp&&t.exp<=i-o)throw new Error("JWT has expired: exp: "+t.exp+" < now: "+i);if(t.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,doc:u,issuer:c,signer:n,jwt:r}}})})}catch(r){return Promise.reject(r)}},Q=function(r,e,n){var t=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===n&&(n={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!t)throw new Error("No issuing DID has been configured");n.typ||(n.typ="JWT"),n.alg||(n.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=V({},u,r,{iss:t});return Y(c,i,n)}catch(r){return Promise.reject(r)}},Y=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=er);var t="string"==typeof r?r:nr(r),i=[nr(n),t].join("."),o=function(r){var e=q[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(n.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},rr={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},er="ES256K";function nr(r){return y(JSON.stringify(r))}var tr=300;function ir(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(g(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function or(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=ir(r);return Object.assign(e,{payload:JSON.parse(g(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function ar(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),L(n.alg)(t,i,e)}function ur(r,e){return ar(ir(r),e)}var cr=function(r,e){try{var n=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var t=JSON.parse(g(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=P(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===t.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,v(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var n=0;return function(r,e,n){for(var t;;){var i=r();if(hr(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!hr(o)){t=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!hr(a)){t=2;break}}}var u=new lr,c=sr.bind(null,u,2);return(0===t?i.then(s):1===t?o.then(f):a.then(l)).then(void 0,c),u;function f(t){o=t;do{if(e&&(a=e())&&a.then&&!hr(a))return void a.then(l).then(void 0,c);if(!(i=r())||hr(i)&&!i.v)return void sr(u,1,o);if(i.then)return void i.then(s).then(void 0,c);hr(o=n())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=n())&&o.then?o.then(f).then(void 0,c):f(o):sr(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):sr(u,1,o)}}(function(){return!a&&n<r.recipients.length},function(){return n++},function(){var u=r.recipients[n];Object.assign(u.header,t);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,v(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(n):n())}catch(r){return Promise.reject(r)}},fr="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function sr(r,e,n){if(!r.s){if(n instanceof lr){if(!n.s)return void(n.o=sr.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(sr.bind(null,r,e),sr.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var lr=function(){function r(){}return r.prototype.then=function(e,n){var t=new r,i=this.s;if(i){var o=1&i?e:n;if(o){try{sr(t,1,o(this.v))}catch(r){sr(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?sr(t,1,e?e(i):i):n?sr(t,1,n(i)):sr(t,2,i)}catch(r){sr(t,2,r)}},t},r}();function hr(r){return r instanceof lr&&1&r.s}function vr(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:h(r.iv),ciphertext:h(n),tag:h(t)};return e&&(o.aad=h(e)),i&&(o.recipients=[i]),o}var dr=function(r,e,n,t){void 0===n&&(n={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,n,t)).then(function(r){return vr(r,t)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,n){if("function"==typeof r[fr]){var t,i,o,a=r[fr]();if(function r(n){try{for(;!(t=a.next()).done;)if((n=e(t.value))&&n.then){if(!hr(n))return void n.then(r,o||(o=sr.bind(null,i=new lr,2)));n=n.v}i?sr(i,1,n):i=n}catch(r){sr(i||(i=new lr),2,r)}}(),a.return){var u=function(r){try{t.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,n){var t,i,o=-1;return function n(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!hr(a))return void a.then(n,i||(i=sr.bind(null,t=new lr,2)));a=a.v}t?sr(t,1,a):t=a}catch(r){sr(t||(t=new lr),2,r)}}(),t}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,n,t)).then(function(r){i=r.cek,o=vr(r,t)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}};function pr(r){var e=new c(r);return function(r,n){var t=l(e.nonceLength),i=e.seal(t,r,n);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:t}}}var yr=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var n;if(!e.keyAgreement)throw new Error("Could not find x25519 key for "+r);var t=(null==(n=e.keyAgreement)?void 0:n.map(function(r){return"string"==typeof r?e.publicKey.find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!t)throw new Error("Could not find x25519 key for "+r);return wr(d(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}};function gr(r){var e=pr(r),n="XC20P";return{alg:"dir",enc:n,encrypt:function(r,t,i){void 0===t&&(t={});try{var o=y(JSON.stringify(Object.assign({alg:"dir"},t,{enc:n}))),a=new Uint8Array(Buffer.from(i?o+"."+h(i):o));return Promise.resolve(V({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function mr(r){var e=new c(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,n,t){try{return Promise.resolve(e.open(n,r,t))}catch(r){return Promise.reject(r)}}}}function wr(r,e){var n=function(n){try{var a=f(),u=pr(T(s(a.secretKey,r),i,t))(n),c={encrypted_key:h(u.ciphertext),header:{alg:t,iv:h(u.iv),tag:h(u.tag),epk:{kty:"OKP",crv:o,x:h(a.publicKey)}}};return e&&(c.header.kid=e),Promise.resolve(c)}catch(r){return Promise.reject(r)}},t="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:t,enc:"XC20P",encrypt:function(r,e,t){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=l(32);return Promise.resolve(gr(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return V({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}function br(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(n,t,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var a=v(o.header.epk.x),u=T(s(r,a),256,e),c=P(o.encrypted_key,o.header.tag);return Promise.resolve(mr(u).decrypt(c,v(o.header.iv))).then(function(r){return null===r?null:mr(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}}export{U as ES256KSigner,N as EdDSASigner,C as EllipticSigner,B as NaclSigner,O as SimpleSigner,dr as createJWE,Y as createJWS,Q as createJWT,or as decodeJWT,cr as decryptJWE,yr as resolveX25519Encrypters,J as toEthereumAddress,ur as verifyJWS,G as verifyJWT,br as x25519Decrypter,wr as x25519Encrypter,mr as xc20pDirDecrypter,gr as xc20pDirEncrypter};
//# sourceMappingURL=index.esm.js.map

@@ -1,2 +0,2 @@

var r=require("elliptic"),e=require("@stablelib/sha256"),n=require("uint8arrays"),t=require("js-sha3"),i=require("@stablelib/ed25519"),o=require("@stablelib/xchacha20poly1305"),a=require("@stablelib/x25519"),u=require("@stablelib/random");function c(r){return e.hash(n.fromString(r))}function f(r){var e,i=n.fromString(r.slice(2),"base16");return"0x"+n.toString((e=i,new Uint8Array(t.keccak_256.arrayBuffer(e))).slice(-20),"base16")}function s(r,e){void 0===e&&(e=new Uint8Array(4));var t=n.fromString(r.toString(),"base10");return e.set(t,4-t.length),e}var l=function(r){return n.concat([s(r.length),r])};function h(r,t,i){if(256!==t)throw new Error("Unsupported key length: "+t);var o=n.concat([l(n.fromString(i)),l(new Uint8Array(0)),l(new Uint8Array(0)),s(t)]);return e.hash(n.concat([s(1),r,o]))}var d=new r.ec("secp256k1");function v(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function p(r){r.startsWith("0x")&&(r=r.substring(2));var e=d.keyFromPrivate(r);return function(r){try{var n=e.sign(c(r)),t=n.s,i=n.recoveryParam;return Promise.resolve({r:v(n.r.toString("hex")),s:v(t.toString("hex")),recoveryParam:i})}catch(r){return Promise.reject(r)}}}function y(r){return n.toString(r,"base64url")}function g(r){return n.fromString(r,"base64url")}function m(r){return n.fromString(r,"base64pad")}function w(r){return n.fromString(r,"base58btc")}function b(r){return y(n.fromString(r))}function E(r){return n.toString(g(r))}function P(r){return n.toString(r,"base16")}function S(r){return n.fromString(r)}function x(r,e){var t=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(e?65:64);if(a.set(n.fromString(t,"base16"),0),a.set(n.fromString(i,"base16"),32),e){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return y(a)}function k(r,e){return n.concat([g(r),g(e)])}function K(){return(K=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(r[t]=n[t])}return r}).apply(this,arguments)}var j=new r.ec("secp256k1");function J(r,e){void 0===e&&(e=!1);var n=g(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:P(n.slice(0,32)),s:P(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function W(r){return r.publicKeyBase58?w(r.publicKeyBase58):r.publicKeyBase64?m(r.publicKeyBase64):r.publicKeyHex?n.fromString(r.publicKeyHex,"base16"):new Uint8Array}function D(r,e,n){var t;if(e.length>86)t=[J(e,!0)];else{var i=J(e,!1);t=[K({},i,{recoveryParam:0}),K({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=c(r),i=j.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=f(o);return n.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function A(r,e,n){var t=S(r),o=g(e),a=n.find(function(r){return i.verify(W(r),t,o)});if(!a)throw new Error("Signature invalid for JWT");return a}var T={ES256K:function(r,e,n){var t=c(r),i=J(e),o=n.filter(function(r){return void 0===r.ethereumAddress}),a=n.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=W(r);return j.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=D(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":D,Ed25519:A,EdDSA:A};function C(r){var e=T[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function I(r){return"object"==typeof r&&"r"in r&&"s"in r}function O(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(I(e))return x(e,r);if(r)throw new Error("ES256K-R not supported when signer function returns string");return e})}catch(r){return Promise.reject(r)}}}function U(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(I(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}C.toSignatureObject=J;var X={ES256K:O(),"ES256K-R":O(!0),Ed25519:U(),EdDSA:U()},B=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=V);var t="string"==typeof r?r:q(r),i=[q(n),t].join("."),o=function(r){var e=X[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(n.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},N={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},V="ES256K";function q(r){return b(JSON.stringify(r))}function H(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(E(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function _(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=H(r);return Object.assign(e,{payload:JSON.parse(E(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function R(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),C(n.alg)(t,i,e)}var z="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function F(r,e,n){if(!r.s){if(n instanceof L){if(!n.s)return void(n.o=F.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(F.bind(null,r,e),F.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var L=function(){function r(){}return r.prototype.then=function(e,n){var t=new r,i=this.s;if(i){var o=1&i?e:n;if(o){try{F(t,1,o(this.v))}catch(r){F(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?F(t,1,e?e(i):i):n?F(t,1,n(i)):F(t,2,i)}catch(r){F(t,2,r)}},t},r}();function M(r){return r instanceof L&&1&r.s}function Z(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:y(r.iv),ciphertext:y(n),tag:y(t)};return e&&(o.aad=y(e)),i&&(o.recipients=[i]),o}function $(r){var e=new o.XChaCha20Poly1305(r);return function(r,n){var t=u.randomBytes(e.nonceLength),i=e.seal(t,r,n);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:t}}}function G(r){var e=$(r);return{alg:"dir",enc:"XC20P",encrypt:function(r,n,t){void 0===n&&(n={});try{var i=b(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?i+"."+y(t):i));return Promise.resolve(K({},e(r,o),{protectedHeader:i}))}catch(r){return Promise.reject(r)}}}}function Q(r){var e=new o.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,n,t){try{return Promise.resolve(e.open(n,r,t))}catch(r){return Promise.reject(r)}}}}function Y(r,e){var n=function(n){try{var u=a.generateKeyPair(),c=$(h(a.sharedKey(u.secretKey,r),i,t))(n),f={encrypted_key:y(c.ciphertext),header:{alg:t,iv:y(c.iv),tag:y(c.tag),epk:{kty:"OKP",crv:o,x:y(u.publicKey)}}};return e&&(f.header.kid=e),Promise.resolve(f)}catch(r){return Promise.reject(r)}},t="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:t,enc:"XC20P",encrypt:function(r,e,t){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=u.randomBytes(32);return Promise.resolve(G(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return K({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}exports.EllipticSigner=function(r){var e=p(r);return function(r){try{return Promise.resolve(e(r)).then(function(r){return x(r)})}catch(r){return Promise.reject(r)}}},exports.NaclSigner=function(r){var e=m(r);return function(r){try{var n=S(r),t=y(i.sign(e,n));return Promise.resolve(t)}catch(r){return Promise.reject(r)}}},exports.SimpleSigner=p,exports.createJWE=function(r,e,n,t){void 0===n&&(n={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,n,t)).then(function(r){return Z(r,t)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,n){if("function"==typeof r[z]){var t,i,o,a=r[z]();if(function r(n){try{for(;!(t=a.next()).done;)if((n=e(t.value))&&n.then){if(!M(n))return void n.then(r,o||(o=F.bind(null,i=new L,2)));n=n.v}i?F(i,1,n):i=n}catch(r){F(i||(i=new L),2,r)}}(),a.return){var u=function(r){try{t.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,n){var t,i,o=-1;return function n(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!M(a))return void a.then(n,i||(i=F.bind(null,t=new L,2)));a=a.v}t?F(t,1,a):t=a}catch(r){F(t||(t=new L),2,r)}}(),t}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,n,t)).then(function(r){i=r.cek,o=Z(r,t)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},exports.createJWS=B,exports.createJWT=function(r,e,n){var t=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===n&&(n={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!t)throw new Error("No issuing DID has been configured");n.typ||(n.typ="JWT"),n.alg||(n.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=K({},u,r,{iss:t});return B(c,i,n)}catch(r){return Promise.reject(r)}},exports.decodeJWT=_,exports.decryptJWE=function(r,e){try{var n=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var t=JSON.parse(E(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=k(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===t.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,g(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var n=0;return function(r,e,n){for(var t;;){var i=r();if(M(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!M(o)){t=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!M(a)){t=2;break}}}var u=new L,c=F.bind(null,u,2);return(0===t?i.then(s):1===t?o.then(f):a.then(l)).then(void 0,c),u;function f(t){o=t;do{if(e&&(a=e())&&a.then&&!M(a))return void a.then(l).then(void 0,c);if(!(i=r())||M(i)&&!i.v)return void F(u,1,o);if(i.then)return void i.then(s).then(void 0,c);M(o=n())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=n())&&o.then?o.then(f).then(void 0,c):f(o):F(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):F(u,1,o)}}(function(){return!a&&n<r.recipients.length},function(){return n++},function(){var u=r.recipients[n];Object.assign(u.header,t);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,g(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(n):n())}catch(r){return Promise.reject(r)}},exports.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var n;if(!e.keyAgreement)throw new Error("Could not find x25519 key for "+r);var t=(null==(n=e.keyAgreement)?void 0:n.map(function(r){return"string"==typeof r?e.publicKey.find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!t)throw new Error("Could not find x25519 key for "+r);return Y(w(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},exports.toEthereumAddress=f,exports.verifyJWS=function(r,e){return R(H(r),e)},exports.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var n=_(r),t=n.payload,i=n.header,o=n.signature,a=n.data;return Promise.resolve(function(r,e,n,t){try{var i=N[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(n)).then(function(r){if(!r)throw new Error("Unable to resolve DID document for "+n);var o=function(r,e){var n=r.publicKey.filter(function(r){return e===r.id});return n.length>0?n[0]:null},a=r.publicKey||[];t&&(a=(r.authentication||[]).map(function(e){return"string"==typeof e?o(r,e):"string"==typeof e.publicKey?o(r,e.publicKey):e}).filter(function(r){return null!=r}));var u=a.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(t&&(!u||0===u.length))throw new Error("DID document for "+n+" does not have public keys suitable for authenticating user");if(!u||0===u.length)throw new Error("DID document for "+n+" does not have public keys for "+e);return{authenticators:u,issuer:n,doc:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,t.iss,e.auth)).then(function(n){var u=n.doc,c=n.issuer;return Promise.resolve(R({header:i,data:a,signature:o},n.authenticators)).then(function(n){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(n){var a=i+o;if(t.nbf){if(t.nbf>a)throw new Error("JWT not valid before nbf: "+t.nbf)}else if(t.iat&&t.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+t.iat);if(t.exp&&t.exp<=i-o)throw new Error("JWT has expired: exp: "+t.exp+" < now: "+i);if(t.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,doc:u,issuer:c,signer:n,jwt:r}}})})}catch(r){return Promise.reject(r)}},exports.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(n,t,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var u=g(o.header.epk.x),c=h(a.sharedKey(r,u),256,e),f=k(o.encrypted_key,o.header.tag);return Promise.resolve(Q(c).decrypt(f,g(o.header.iv))).then(function(r){return null===r?null:Q(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}},exports.x25519Encrypter=Y,exports.xc20pDirDecrypter=Q,exports.xc20pDirEncrypter=G;
var r=require("uint8arrays"),e=require("@stablelib/sha256"),t=require("js-sha3"),n=require("elliptic"),i=require("@stablelib/ed25519"),o=require("@stablelib/xchacha20poly1305"),a=require("@stablelib/x25519"),u=require("@stablelib/random");function c(e){return r.toString(e,"base64url")}function f(e){var t=e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return r.fromString(t,"base64url")}function s(e){return r.fromString(e,"base58btc")}function l(e){var t=e.startsWith("0x")?e.substring(2):e;return r.fromString(t.toLowerCase(),"base16")}function h(e){return c(r.fromString(e))}function v(e){return r.toString(f(e))}function d(e){return r.toString(e,"base16")}function p(e){return r.fromString(e)}function y(e,t){var n=e.r,i=e.s,o=e.recoveryParam,a=new Uint8Array(t?65:64);if(a.set(r.fromString(n,"base16"),0),a.set(r.fromString(i,"base16"),32),t){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return c(a)}function g(r){var e=f(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:d(e.slice(0,32)),s:d(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function w(e,t){return r.concat([f(e),f(t)])}var m=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,b=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,E=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function P(r){if("string"==typeof r){if(m.test(r))return l(r);if(b.test(r))return s(r);if(E.test(r))return f(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function S(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function x(t){var n="string"==typeof t?r.fromString(t):t;return e.hash(n)}function k(e){var n,i=r.fromString(e.slice(2),"base16");return"0x"+r.toString((n=i,new Uint8Array(t.keccak_256.arrayBuffer(n))).slice(-20),"base16")}function K(e,t){void 0===t&&(t=new Uint8Array(4));var n=r.fromString(e.toString(),"base10");return t.set(n,4-n.length),t}var A=function(e){return r.concat([K(e.length),e])};function j(t,n,i){if(256!==n)throw new Error("Unsupported key length: "+n);var o=r.concat([A(r.fromString(i)),A(new Uint8Array(0)),A(new Uint8Array(0)),K(n)]);return e.hash(r.concat([K(1),t,o]))}var J=new n.ec("secp256k1");function W(r,e){void 0===e&&(e=!1);var t=P(r);if(32!==t.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+t.length);var n=J.keyFromPrivate(t);return function(r){try{var t=n.sign(x(r)),i=t.s,o=t.recoveryParam;return Promise.resolve(y({r:S(t.r.toString("hex")),s:S(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function D(r){var e=P(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var t="string"==typeof r?p(r):r,n=i.sign(e,t);return Promise.resolve(c(n))}catch(r){return Promise.reject(r)}}}function T(){return(T=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}var I=new n.ec("secp256k1");function C(r,e){void 0===e&&(e=!1);var t=f(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");var n={r:d(t.slice(0,32)),s:d(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function U(r){return r.publicKeyBase58?s(r.publicKeyBase58):r.publicKeyBase64?f(r.publicKeyBase64):r.publicKeyHex?l(r.publicKeyHex):new Uint8Array}function O(r,e,t){var n;if(e.length>86)n=[C(e,!0)];else{var i=C(e,!1);n=[T({},i,{recoveryParam:0}),T({},i,{recoveryParam:1})]}var o=n.map(function(e){var n=x(r),i=I.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=k(o);return t.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function B(r,e,t){var n=p(r),o=f(e),a=t.find(function(r){return i.verify(U(r),n,o)});if(!a)throw new Error("Signature invalid for JWT");return a}var N={ES256K:function(r,e,t){var n=x(r),i=C(e),o=t.filter(function(r){return void 0===r.ethereumAddress}),a=t.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=U(r);return I.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=O(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":O,Ed25519:B,EdDSA:B};function X(r){var e=N[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function V(r){return"object"==typeof r&&"r"in r&&"s"in r}function _(r){return function(e,t){try{return Promise.resolve(t(e)).then(function(e){if(V(e))return y(e,r);if(r&&void 0===g(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function q(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(V(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}X.toSignatureObject=C;var H={ES256K:_(),"ES256K-R":_(!0),Ed25519:q(),EdDSA:q()},z=function(r,e,t){void 0===t&&(t={});try{t.alg||(t.alg=F);var n="string"==typeof r?r:L(r),i=[L(t),n].join("."),o=function(r){var e=H[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(t.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},Z={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},F="ES256K";function L(r){return h(JSON.stringify(r))}function R(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(v(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function $(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=R(r);return Object.assign(e,{payload:JSON.parse(v(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function M(r,e){var t=r.header,n=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),X(t.alg)(n,i,e)}var G="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Q(r,e,t){if(!r.s){if(t instanceof Y){if(!t.s)return void(t.o=Q.bind(null,r,e));1&e&&(e=t.s),t=t.v}if(t&&t.then)return void t.then(Q.bind(null,r,e),Q.bind(null,r,2));r.s=e,r.v=t;var n=r.o;n&&n(r)}}var Y=function(){function r(){}return r.prototype.then=function(e,t){var n=new r,i=this.s;if(i){var o=1&i?e:t;if(o){try{Q(n,1,o(this.v))}catch(r){Q(n,2,r)}return n}return this}return this.o=function(r){try{var i=r.v;1&r.s?Q(n,1,e?e(i):i):t?Q(n,1,t(i)):Q(n,2,i)}catch(r){Q(n,2,r)}},n},r}();function rr(r){return r instanceof Y&&1&r.s}function er(r,e){var t=r.ciphertext,n=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:c(r.iv),ciphertext:c(t),tag:c(n)};return e&&(o.aad=c(e)),i&&(o.recipients=[i]),o}function tr(r){var e=new o.XChaCha20Poly1305(r);return function(r,t){var n=u.randomBytes(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}function nr(r){var e=tr(r),t="XC20P";return{alg:"dir",enc:t,encrypt:function(r,n,i){void 0===n&&(n={});try{var o=h(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?o+"."+c(i):o));return Promise.resolve(T({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function ir(r){var e=new o.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,t,n){try{return Promise.resolve(e.open(t,r,n))}catch(r){return Promise.reject(r)}}}}function or(r,e){var t=function(t){try{var u=a.generateKeyPair(),f=tr(j(a.sharedKey(u.secretKey,r),i,n))(t),s={encrypted_key:c(f.ciphertext),header:{alg:n,iv:c(f.iv),tag:c(f.tag),epk:{kty:"OKP",crv:o,x:c(u.publicKey)}}};return e&&(s.header.kid=e),Promise.resolve(s)}catch(r){return Promise.reject(r)}},n="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:n,enc:"XC20P",encrypt:function(r,e,n){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=u.randomBytes(32);return Promise.resolve(nr(i).encrypt(r,e,n)).then(function(r){return Promise.resolve(t(i)).then(function(e){return T({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:t}}exports.ES256KSigner=W,exports.EdDSASigner=D,exports.EllipticSigner=function(r){return W(r)},exports.NaclSigner=function(r){return D(r)},exports.SimpleSigner=function(r){var e=W(r,!0);return function(r){try{return Promise.resolve(e(r)).then(g)}catch(r){return Promise.reject(r)}}},exports.createJWE=function(r,e,t,n){void 0===t&&(t={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,t,n)).then(function(r){return er(r,n)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,t){if("function"==typeof r[G]){var n,i,o,a=r[G]();if(function r(t){try{for(;!(n=a.next()).done;)if((t=e(n.value))&&t.then){if(!rr(t))return void t.then(r,o||(o=Q.bind(null,i=new Y,2)));t=t.v}i?Q(i,1,t):i=t}catch(r){Q(i||(i=new Y),2,r)}}(),a.return){var u=function(r){try{n.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,t){var n,i,o=-1;return function t(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!rr(a))return void a.then(t,i||(i=Q.bind(null,n=new Y,2)));a=a.v}n?Q(n,1,a):n=a}catch(r){Q(n||(n=new Y),2,r)}}(),n}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,t,n)).then(function(r){i=r.cek,o=er(r,n)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},exports.createJWS=z,exports.createJWT=function(r,e,t){var n=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===t&&(t={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!n)throw new Error("No issuing DID has been configured");t.typ||(t.typ="JWT"),t.alg||(t.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=T({},u,r,{iss:n});return z(c,i,t)}catch(r){return Promise.reject(r)}},exports.decodeJWT=$,exports.decryptJWE=function(r,e){try{var t=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var n=JSON.parse(v(r.protected));if(n.enc!==e.enc)throw new Error("Decrypter does not support: '"+n.enc+"'");var i=w(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===n.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,f(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var t=0;return function(r,e,t){for(var n;;){var i=r();if(rr(i)&&(i=i.v),!i)return o;if(i.then){n=0;break}var o=t();if(o&&o.then){if(!rr(o)){n=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!rr(a)){n=2;break}}}var u=new Y,c=Q.bind(null,u,2);return(0===n?i.then(s):1===n?o.then(f):a.then(l)).then(void 0,c),u;function f(n){o=n;do{if(e&&(a=e())&&a.then&&!rr(a))return void a.then(l).then(void 0,c);if(!(i=r())||rr(i)&&!i.v)return void Q(u,1,o);if(i.then)return void i.then(s).then(void 0,c);rr(o=t())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=t())&&o.then?o.then(f).then(void 0,c):f(o):Q(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):Q(u,1,o)}}(function(){return!a&&t<r.recipients.length},function(){return t++},function(){var u=r.recipients[t];Object.assign(u.header,n);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,f(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(t):t())}catch(r){return Promise.reject(r)}},exports.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var t;if(!e.keyAgreement)throw new Error("Could not find x25519 key for "+r);var n=(null==(t=e.keyAgreement)?void 0:t.map(function(r){return"string"==typeof r?e.publicKey.find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!n)throw new Error("Could not find x25519 key for "+r);return or(s(n.publicKeyBase58),n.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},exports.toEthereumAddress=k,exports.verifyJWS=function(r,e){return M(R(r),e)},exports.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var t=$(r),n=t.payload,i=t.header,o=t.signature,a=t.data;return Promise.resolve(function(r,e,t,n){try{var i=Z[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(t)).then(function(r){if(!r)throw new Error("Unable to resolve DID document for "+t);var o=function(r,e){var t=r.publicKey.filter(function(r){return e===r.id});return t.length>0?t[0]:null},a=r.publicKey||[];n&&(a=(r.authentication||[]).map(function(e){return"string"==typeof e?o(r,e):"string"==typeof e.publicKey?o(r,e.publicKey):e}).filter(function(r){return null!=r}));var u=a.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(n&&(!u||0===u.length))throw new Error("DID document for "+t+" does not have public keys suitable for authenticating user");if(!u||0===u.length)throw new Error("DID document for "+t+" does not have public keys for "+e);return{authenticators:u,issuer:t,doc:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,n.iss,e.auth)).then(function(t){var u=t.doc,c=t.issuer;return Promise.resolve(M({header:i,data:a,signature:o},t.authenticators)).then(function(t){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(t){var a=i+o;if(n.nbf){if(n.nbf>a)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=i-o)throw new Error("JWT has expired: exp: "+n.exp+" < now: "+i);if(n.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,doc:u,issuer:c,signer:t,jwt:r}}})})}catch(r){return Promise.reject(r)}},exports.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(t,n,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var u=f(o.header.epk.x),c=j(a.sharedKey(r,u),256,e),s=w(o.encrypted_key,o.header.tag);return Promise.resolve(ir(c).decrypt(s,f(o.header.iv))).then(function(r){return null===r?null:ir(r).decrypt(t,n,i)})}catch(r){return Promise.reject(r)}}}},exports.x25519Encrypter=or,exports.xc20pDirDecrypter=ir,exports.xc20pDirEncrypter=nr;
//# sourceMappingURL=index.js.map

@@ -1,2 +0,2 @@

import{ec as e}from"elliptic";import{hash as r}from"@stablelib/sha256";import{fromString as n,toString as t,concat as i}from"uint8arrays";import{keccak_256 as o}from"js-sha3";import{sign as a,verify as c}from"@stablelib/ed25519";import{XChaCha20Poly1305 as s}from"@stablelib/xchacha20poly1305";import{generateKeyPair as u,sharedKey as f}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function d(e){return r(n(e))}function p(e){const r=n(e.slice(2),"base16");return"0x"+t((i=r,new Uint8Array(o.arrayBuffer(i))).slice(-20),"base16");var i}function y(e,r=new Uint8Array(4)){const t=n(e.toString(),"base10");return r.set(t,4-t.length),r}const h=e=>i([y(e.length),e]);function w(e,t,o){if(256!==t)throw new Error("Unsupported key length: "+t);const a=i([h(n(o)),h(new Uint8Array(0)),h(new Uint8Array(0)),y(t)]);return r(i([y(1),e,a]))}const g=new e("secp256k1");function b(e,r=64){return e.length===r?e:"0".repeat(r-e.length)+e}function E(e){e.startsWith("0x")&&(e=e.substring(2));const r=g.keyFromPrivate(e);return async e=>{const{r:n,s:t,recoveryParam:i}=r.sign(d(e));return{r:b(n.toString("hex")),s:b(t.toString("hex")),recoveryParam:i}}}function m(e){return t(e,"base64url")}function v(e){return n(e,"base64url")}function k(e){return n(e,"base64pad")}function K(e){return n(e,"base58btc")}function S(e){return m(n(e))}function x(e){return t(v(e))}function A(e){return t(e,"base16")}function J(e){return n(e)}function P({r:e,s:r,recoveryParam:t},i){const o=new Uint8Array(i?65:64);if(o.set(n(e,"base16"),0),o.set(n(r,"base16"),32),i){if(void 0===t)throw new Error("Signer did not return a recoveryParam");o[64]=t}return m(o)}function D(e,r){return i([v(e),v(r)])}function W(e){const r=E(e);return async e=>P(await r(e))}function T(e){const r=k(e);return async e=>{const n=J(e);return m(a(r,n))}}function I(){return(I=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var n=arguments[r];for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=n[t])}return e}).apply(this,arguments)}const U=new e("secp256k1");function C(e,r=!1){const n=v(e);if(n.length!==(r?65:64))throw new Error("wrong signature length");const t={r:A(n.slice(0,32)),s:A(n.slice(32,64))};return r&&(t.recoveryParam=n[64]),t}function O(e){return e.publicKeyBase58?K(e.publicKeyBase58):e.publicKeyBase64?k(e.publicKeyBase64):e.publicKeyHex?n(e.publicKeyHex,"base16"):new Uint8Array}function j(e,r,n){let t;if(r.length>86)t=[C(r,!0)];else{const e=C(r,!1);t=[I({},e,{recoveryParam:0}),I({},e,{recoveryParam:1})]}const i=t.map(r=>{const t=d(e),i=U.recoverPubKey(t,r,r.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),c=p(o);return n.find(({publicKeyHex:e,ethereumAddress:r})=>e===o||e===a||r===c)}).filter(e=>null!=e);if(0===i.length)throw new Error("Signature invalid for JWT");return i[0]}function $(e,r,n){const t=J(e),i=v(r),o=n.find(e=>c(O(e),t,i));if(!o)throw new Error("Signature invalid for JWT");return o}const B={ES256K:function(e,r,n){const t=d(e),i=C(r),o=n.filter(({ethereumAddress:e})=>void 0===e),a=n.filter(({ethereumAddress:e})=>void 0!==e);let c=o.find(e=>{try{const r=O(e);return U.keyFromPublic(r).verify(t,i)}catch(e){return!1}});if(!c&&a.length>0&&(c=j(e,r,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":j,Ed25519:$,EdDSA:$};function V(e){const r=B[e];if(!r)throw new Error("Unsupported algorithm "+e);return r}function X(e){return"object"==typeof e&&"r"in e&&"s"in e}function N(e){return async function(r,n){const t=await n(r);if(X(t))return P(t,e);if(e)throw new Error("ES256K-R not supported when signer function returns string");return t}}function H(){return async function(e,r){const n=await r(e);if(X(n))throw new Error("expected a signer function that returns a string instead of signature object");return n}}V.toSignatureObject=C;const _={ES256K:N(),"ES256K-R":N(!0),Ed25519:H(),EdDSA:H()},R={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function z(e){return S(JSON.stringify(e))}function F(e){const r=e.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(r)return{header:JSON.parse(x(r[1])),payload:r[2],signature:r[3],data:`${r[1]}.${r[2]}`};throw new Error("Incorrect format JWS")}function L(e){if(!e)throw new Error("no JWT passed into decodeJWT");try{const r=F(e);return Object.assign(r,{payload:JSON.parse(x(r.payload))})}catch(e){throw new Error("Incorrect format JWT")}}async function M(e,r,n={}){n.alg||(n.alg="ES256K");const t="string"==typeof e?e:z(e),i=[z(n),t].join("."),o=function(e){const r=_[e];if(!r)throw new Error("Unsupported algorithm "+e);return r}(n.alg);return[i,await o(i,r)].join(".")}async function Z(e,{issuer:r,signer:n,alg:t,expiresIn:i},o={}){if(!n)throw new Error("No Signer functionality has been configured");if(!r)throw new Error("No issuing DID has been configured");o.typ||(o.typ="JWT"),o.alg||(o.alg=t);const a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(i){if("number"!=typeof i)throw new Error("JWT expiresIn is not a number");a.exp=(e.nbf||a.iat)+Math.floor(i)}return M(I({},a,e,{iss:r}),n,o)}function q({header:e,data:r,signature:n},t){return Array.isArray(t)||(t=[t]),V(e.alg)(r,n,t)}function G(e,r){return q(F(e),r)}async function Q(e,r={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null}){if(!r.resolver)throw new Error("No DID resolver has been configured");const{payload:n,header:t,signature:i,data:o}=L(e),{doc:a,authenticators:c,issuer:s}=await async function(e,r,n,t){const i=R[r];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+r);const o=await e.resolve(n);if(!o)throw new Error("Unable to resolve DID document for "+n);let a=(e,r)=>{const n=e.publicKey.filter(({id:e})=>r===e);return n.length>0?n[0]:null},c=o.publicKey||[];t&&(c=(o.authentication||[]).map(e=>"string"==typeof e?a(o,e):"string"==typeof e.publicKey?a(o,e.publicKey):e).filter(e=>null!=e));const s=c.filter(({type:e})=>i.find(r=>r===e));if(t&&(!s||0===s.length))throw new Error(`DID document for ${n} does not have public keys suitable for authenticating user`);if(!s||0===s.length)throw new Error(`DID document for ${n} does not have public keys for ${r}`);return{authenticators:s,issuer:n,doc:o}}(r.resolver,t.alg,n.iss,r.auth),u=await q({header:t,data:o,signature:i},c),f=Math.floor(Date.now()/1e3),l=r.skewTime>=0?r.skewTime:300;if(u){const t=f+l;if(n.nbf){if(n.nbf>t)throw new Error("JWT not valid before nbf: "+n.nbf)}else if(n.iat&&n.iat>t)throw new Error("JWT not valid yet (issued in the future) iat: "+n.iat);if(n.exp&&n.exp<=f-l)throw new Error(`JWT has expired: exp: ${n.exp} < now: ${f}`);if(n.aud){if(!r.audience&&!r.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(n.aud)?n.aud:[n.aud]).find(e=>r.audience===e||r.callbackUrl===e))throw new Error("JWT audience does not match your DID or callback url")}return{payload:n,doc:a,issuer:s,signer:u,jwt:e}}}function Y({ciphertext:e,tag:r,iv:n,protectedHeader:t,recipient:i},o){const a={protected:t,iv:m(n),ciphertext:m(e),tag:m(r)};return o&&(a.aad=m(o)),i&&(a.recipients=[i]),a}async function ee(e,r,n={},t){if("dir"===r[0].alg){if(r.length>1)throw new Error('Can only do "dir" encryption to one key.');return Y(await r[0].encrypt(e,n,t),t)}{const i=r[0].enc;if(!r.reduce((e,r)=>e&&r.enc===i,!0))throw new Error("Incompatible encrypters passed");let o,a;for(const i of r)if(o)a.recipients.push(await i.encryptCek(o));else{const r=await i.encrypt(e,n,t);o=r.cek,a=Y(r,t)}return a}}async function re(e,r){!function(e){if(!(e.protected&&e.iv&&e.ciphertext&&e.tag))throw new Error("Invalid JWE");e.recipients&&e.recipients.map(e=>{if(!e.header||!e.encrypted_key)throw new Error("Invalid JWE")})}(e);const n=JSON.parse(x(e.protected));if(n.enc!==r.enc)throw new Error(`Decrypter does not support: '${n.enc}'`);const t=D(e.ciphertext,e.tag),i=new Uint8Array(Buffer.from(e.aad?`${e.protected}.${e.aad}`:e.protected));let o=null;if("dir"===n.alg&&"dir"===r.alg)o=await r.decrypt(t,v(e.iv),i);else{if(!e.recipients||0===e.recipients.length)throw new Error("Invalid JWE");for(let a=0;!o&&a<e.recipients.length;a++){const c=e.recipients[a];Object.assign(c.header,n),c.header.alg===r.alg&&(o=await r.decrypt(t,v(e.iv),i,c))}}if(null===o)throw new Error("Failed to decrypt");return o}function ne(e){const r=new s(e);return(e,n)=>{const t=l(r.nonceLength),i=r.seal(t,e,n);return{ciphertext:i.subarray(0,i.length-r.tagLength),tag:i.subarray(i.length-r.tagLength),iv:t}}}function te(e){const r=ne(e);return{alg:"dir",enc:"XC20P",encrypt:async function(e,n={},t){const i=S(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?`${i}.${m(t)}`:i));return I({},r(e,o),{protectedHeader:i})}}}function ie(e){const r=new s(e);return{alg:"dir",enc:"XC20P",decrypt:async function(e,n,t){return r.open(n,e,t)}}}function oe(e,r){const n="ECDH-ES+XC20PKW";async function t(t){const i=u(),o=ne(w(f(i.secretKey,e),256,n))(t),a={encrypted_key:m(o.ciphertext),header:{alg:n,iv:m(o.iv),tag:m(o.tag),epk:{kty:"OKP",crv:"X25519",x:m(i.publicKey)}}};return r&&(a.header.kid=r),a}return{alg:n,enc:"XC20P",encrypt:async function(e,r={},n){Object.assign(r,{alg:void 0});const i=l(32);return I({},await te(i).encrypt(e,r,n),{recipient:await t(i),cek:i})},encryptCek:t}}async function ae(e,r){return Promise.all(e.map(async e=>{var n;const t=await r.resolve(e);if(!t.keyAgreement)throw new Error("Could not find x25519 key for "+e);const i=(null==(n=t.keyAgreement)?void 0:n.map(e=>"string"==typeof e?t.publicKey.find(r=>r.id===e):e)).find(e=>"X25519KeyAgreementKey2019"===e.type&&Boolean(e.publicKeyBase58));if(!i)throw new Error("Could not find x25519 key for "+e);return oe(K(i.publicKeyBase58),i.id)}))}function ce(e){const r="ECDH-ES+XC20PKW";return{alg:r,enc:"XC20P",decrypt:async function(n,t,i,o){if(function(e){if(!(e.epk&&e.iv&&e.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return null;const a=v(o.header.epk.x),c=w(f(e,a),256,r),s=D(o.encrypted_key,o.header.tag),u=await ie(c).decrypt(s,v(o.header.iv));return null===u?null:ie(u).decrypt(n,t,i)}}}export{W as EllipticSigner,T as NaclSigner,E as SimpleSigner,ee as createJWE,M as createJWS,Z as createJWT,L as decodeJWT,re as decryptJWE,ae as resolveX25519Encrypters,p as toEthereumAddress,G as verifyJWS,Q as verifyJWT,ce as x25519Decrypter,oe as x25519Encrypter,ie as xc20pDirDecrypter,te as xc20pDirEncrypter};
import{toString as r,fromString as e,concat as t}from"uint8arrays";import{hash as n}from"@stablelib/sha256";import{keccak_256 as i}from"js-sha3";import{ec as o}from"elliptic";import{sign as a,verify as c}from"@stablelib/ed25519";import{XChaCha20Poly1305 as s}from"@stablelib/xchacha20poly1305";import{generateKeyPair as u,sharedKey as f}from"@stablelib/x25519";import{randomBytes as l}from"@stablelib/random";function p(e){return r(e,"base64url")}function d(r){const t=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e(t,"base64url")}function y(r){return e(r,"base58btc")}function h(r){const t=r.startsWith("0x")?r.substring(2):r;return e(t.toLowerCase(),"base16")}function g(r){return p(e(r))}function w(e){return r(d(e))}function b(e){return r(e,"base16")}function E(r){return e(r)}function v({r,s:t,recoveryParam:n},i){const o=new Uint8Array(i?65:64);if(o.set(e(r,"base16"),0),o.set(e(t,"base16"),32),i){if(void 0===n)throw new Error("Signer did not return a recoveryParam");o[64]=n}return p(o)}function m(r){const e=d(r);if(e.length<64||e.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${e.length}`);return{r:b(e.slice(0,32)),s:b(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function k(r,e){return t([d(r),d(e)])}const K=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,S=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,x=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function A(r){if("string"==typeof r){if(K.test(r))return h(r);if(S.test(r))return y(r);if(x.test(r))return d(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function $(r,e=64){return r.length===e?r:"0".repeat(e-r.length)+r}function P(r){const t="string"==typeof r?e(r):r;return n(t)}function J(t){const n=e(t.slice(2),"base16");return`0x${r((o=n,new Uint8Array(i.arrayBuffer(o))).slice(-20),"base16")}`;var o}function D(r,t=new Uint8Array(4)){const n=e(r.toString(),"base10");return t.set(n,4-n.length),t}const W=r=>t([D(r.length),r]);function I(r,i,o){if(256!==i)throw new Error(`Unsupported key length: ${i}`);const a=t([W(e(o)),W(new Uint8Array(0)),W(new Uint8Array(0)),D(i)]);return n(t([D(1),r,a]))}const T=new o("secp256k1");function U(r,e=!1){const t=A(r);if(32!==t.length)throw new Error(`Invalid private key format. Expecting 32 bytes, but got ${t.length}`);const n=T.keyFromPrivate(t);return async r=>{const{r:t,s:i,recoveryParam:o}=n.sign(P(r));return v({r:$(t.toString("hex")),s:$(i.toString("hex")),recoveryParam:o},e)}}function C(r){const e=U(r,!0);return async r=>m(await e(r))}function O(r){return U(r)}function j(r){const e=A(r);if(64!==e.length)throw new Error(`Invalid private key format. Expecting 64 bytes, but got ${e.length}`);return async r=>{const t="string"==typeof r?E(r):r;return p(a(e,t))}}function N(r){return j(r)}function B(){return(B=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r}).apply(this,arguments)}const V=new o("secp256k1");function H(r,e=!1){const t=d(r);if(t.length!==(e?65:64))throw new Error("wrong signature length");const n={r:b(t.slice(0,32)),s:b(t.slice(32,64))};return e&&(n.recoveryParam=t[64]),n}function X(r){return r.publicKeyBase58?y(r.publicKeyBase58):r.publicKeyBase64?d(r.publicKeyBase64):r.publicKeyHex?h(r.publicKeyHex):new Uint8Array}function _(r,e,t){let n;if(e.length>86)n=[H(e,!0)];else{const r=H(e,!1);n=[B({},r,{recoveryParam:0}),B({},r,{recoveryParam:1})]}const i=n.map(e=>{const n=P(r),i=V.recoverPubKey(n,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),c=J(o);return t.find(({publicKeyHex:r,ethereumAddress:e})=>r===o||r===a||e===c)}).filter(r=>null!=r);if(0===i.length)throw new Error("Signature invalid for JWT");return i[0]}function z(r,e,t){const n=E(r),i=d(e),o=t.find(r=>c(X(r),n,i));if(!o)throw new Error("Signature invalid for JWT");return o}const Z={ES256K:function(r,e,t){const n=P(r),i=H(e),o=t.filter(({ethereumAddress:r})=>void 0===r),a=t.filter(({ethereumAddress:r})=>void 0!==r);let c=o.find(r=>{try{const e=X(r);return V.keyFromPublic(e).verify(n,i)}catch(r){return!1}});if(!c&&a.length>0&&(c=_(r,e,a)),!c)throw new Error("Signature invalid for JWT");return c},"ES256K-R":_,Ed25519:z,EdDSA:z};function F(r){const e=Z[r];if(!e)throw new Error(`Unsupported algorithm ${r}`);return e}function L(r){return"object"==typeof r&&"r"in r&&"s"in r}function R(r){return async function(e,t){const n=await t(e);if(L(n))return v(n,r);if(r&&void 0===m(n).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return n}}function M(){return async function(r,e){const t=await e(r);if(L(t))throw new Error("expected a signer function that returns a string instead of signature object");return t}}F.toSignatureObject=H;const q={ES256K:R(),"ES256K-R":R(!0),Ed25519:M(),EdDSA:M()},G={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]};function Q(r){return g(JSON.stringify(r))}function Y(r){const e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(w(e[1])),payload:e[2],signature:e[3],data:`${e[1]}.${e[2]}`};throw new Error("Incorrect format JWS")}function rr(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{const e=Y(r);return Object.assign(e,{payload:JSON.parse(w(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}async function er(r,e,t={}){t.alg||(t.alg="ES256K");const n="string"==typeof r?r:Q(r),i=[Q(t),n].join("."),o=function(r){const e=q[r];if(!e)throw new Error(`Unsupported algorithm ${r}`);return e}(t.alg);return[i,await o(i,e)].join(".")}async function tr(r,{issuer:e,signer:t,alg:n,expiresIn:i},o={}){if(!t)throw new Error("No Signer functionality has been configured");if(!e)throw new Error("No issuing DID has been configured");o.typ||(o.typ="JWT"),o.alg||(o.alg=n);const a={iat:Math.floor(Date.now()/1e3),exp:void 0};if(i){if("number"!=typeof i)throw new Error("JWT expiresIn is not a number");a.exp=(r.nbf||a.iat)+Math.floor(i)}return er(B({},a,r,{iss:e}),t,o)}function nr({header:r,data:e,signature:t},n){return Array.isArray(n)||(n=[n]),F(r.alg)(e,t,n)}function ir(r,e){return nr(Y(r),e)}async function or(r,e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null}){if(!e.resolver)throw new Error("No DID resolver has been configured");const{payload:t,header:n,signature:i,data:o}=rr(r),{doc:a,authenticators:c,issuer:s}=await async function(r,e,t,n){const i=G[e];if(!i||0===i.length)throw new Error(`No supported signature types for algorithm ${e}`);const o=await r.resolve(t);if(!o)throw new Error(`Unable to resolve DID document for ${t}`);const a=(r,e)=>{const t=r.publicKey.filter(({id:r})=>e===r);return t.length>0?t[0]:null};let c=o.publicKey||[];n&&(c=(o.authentication||[]).map(r=>"string"==typeof r?a(o,r):"string"==typeof r.publicKey?a(o,r.publicKey):r).filter(r=>null!=r));const s=c.filter(({type:r})=>i.find(e=>e===r));if(n&&(!s||0===s.length))throw new Error(`DID document for ${t} does not have public keys suitable for authenticating user`);if(!s||0===s.length)throw new Error(`DID document for ${t} does not have public keys for ${e}`);return{authenticators:s,issuer:t,doc:o}}(e.resolver,n.alg,t.iss,e.auth),u=await nr({header:n,data:o,signature:i},c),f=Math.floor(Date.now()/1e3),l=e.skewTime>=0?e.skewTime:300;if(u){const n=f+l;if(t.nbf){if(t.nbf>n)throw new Error(`JWT not valid before nbf: ${t.nbf}`)}else if(t.iat&&t.iat>n)throw new Error(`JWT not valid yet (issued in the future) iat: ${t.iat}`);if(t.exp&&t.exp<=f-l)throw new Error(`JWT has expired: exp: ${t.exp} < now: ${f}`);if(t.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(r=>e.audience===r||e.callbackUrl===r))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,doc:a,issuer:s,signer:u,jwt:r}}}function ar({ciphertext:r,tag:e,iv:t,protectedHeader:n,recipient:i},o){const a={protected:n,iv:p(t),ciphertext:p(r),tag:p(e)};return o&&(a.aad=p(o)),i&&(a.recipients=[i]),a}async function cr(r,e,t={},n){if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return ar(await e[0].encrypt(r,t,n),n)}{const i=e[0].enc;if(!e.reduce((r,e)=>r&&e.enc===i,!0))throw new Error("Incompatible encrypters passed");let o,a;for(const i of e)if(o)a.recipients.push(await i.encryptCek(o));else{const e=await i.encrypt(r,t,n);o=e.cek,a=ar(e,n)}return a}}async function sr(r,e){!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(r=>{if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);const t=JSON.parse(w(r.protected));if(t.enc!==e.enc)throw new Error(`Decrypter does not support: '${t.enc}'`);const n=k(r.ciphertext,r.tag),i=new Uint8Array(Buffer.from(r.aad?`${r.protected}.${r.aad}`:r.protected));let o=null;if("dir"===t.alg&&"dir"===e.alg)o=await e.decrypt(n,d(r.iv),i);else{if(!r.recipients||0===r.recipients.length)throw new Error("Invalid JWE");for(let a=0;!o&&a<r.recipients.length;a++){const c=r.recipients[a];Object.assign(c.header,t),c.header.alg===e.alg&&(o=await e.decrypt(n,d(r.iv),i,c))}}if(null===o)throw new Error("Failed to decrypt");return o}function ur(r){const e=new s(r);return(r,t)=>{const n=l(e.nonceLength),i=e.seal(n,r,t);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:n}}}function fr(r){const e=ur(r),t="XC20P";return{alg:"dir",enc:t,encrypt:async function(r,n={},i){const o=g(JSON.stringify(Object.assign({alg:"dir"},n,{enc:t}))),a=new Uint8Array(Buffer.from(i?`${o}.${p(i)}`:o));return B({},e(r,a),{protectedHeader:o})}}}function lr(r){const e=new s(r);return{alg:"dir",enc:"XC20P",decrypt:async function(r,t,n){return e.open(t,r,n)}}}function pr(r,e){const t="ECDH-ES+XC20PKW";async function n(n){const i=u(),o=ur(I(f(i.secretKey,r),256,t))(n),a={encrypted_key:p(o.ciphertext),header:{alg:t,iv:p(o.iv),tag:p(o.tag),epk:{kty:"OKP",crv:"X25519",x:p(i.publicKey)}}};return e&&(a.header.kid=e),a}return{alg:t,enc:"XC20P",encrypt:async function(r,e={},t){Object.assign(e,{alg:void 0});const i=l(32);return B({},await fr(i).encrypt(r,e,t),{recipient:await n(i),cek:i})},encryptCek:n}}async function dr(r,e){return Promise.all(r.map(async r=>{var t;const n=await e.resolve(r);if(!n.keyAgreement)throw new Error(`Could not find x25519 key for ${r}`);const i=(null==(t=n.keyAgreement)?void 0:t.map(r=>"string"==typeof r?n.publicKey.find(e=>e.id===r):r)).find(r=>"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58));if(!i)throw new Error(`Could not find x25519 key for ${r}`);return pr(y(i.publicKeyBase58),i.id)}))}function yr(r){const e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:async function(t,n,i,o){if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return null;const a=d(o.header.epk.x),c=I(f(r,a),256,e),s=k(o.encrypted_key,o.header.tag),u=await lr(c).decrypt(s,d(o.header.iv));return null===u?null:lr(u).decrypt(t,n,i)}}}export{U as ES256KSigner,j as EdDSASigner,O as EllipticSigner,N as NaclSigner,C as SimpleSigner,cr as createJWE,er as createJWS,tr as createJWT,rr as decodeJWT,sr as decryptJWE,dr as resolveX25519Encrypters,J as toEthereumAddress,ir as verifyJWS,or as verifyJWT,yr as x25519Decrypter,pr as x25519Encrypter,lr as xc20pDirDecrypter,fr as xc20pDirEncrypter};
//# sourceMappingURL=index.modern.js.map

@@ -1,2 +0,2 @@

!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("elliptic"),require("@stablelib/sha256"),require("uint8arrays"),require("js-sha3"),require("@stablelib/ed25519"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","elliptic","@stablelib/sha256","uint8arrays","js-sha3","@stablelib/ed25519","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],e):e((r=r||self).didJwt={},r.elliptic,r.sha256$1,r.uint8Arrays,r.jsSha3,r.ed25519,r.xchacha20poly1305,r.x25519,r.random)}(this,function(r,e,n,t,i,o,a,u,c){function f(r){return n.hash(t.fromString(r))}function s(r){var e,n=t.fromString(r.slice(2),"base16");return"0x"+t.toString((e=n,new Uint8Array(i.keccak_256.arrayBuffer(e))).slice(-20),"base16")}function l(r,e){void 0===e&&(e=new Uint8Array(4));var n=t.fromString(r.toString(),"base10");return e.set(n,4-n.length),e}var h=function(r){return t.concat([l(r.length),r])};function d(r,e,i){if(256!==e)throw new Error("Unsupported key length: "+e);var o=t.concat([h(t.fromString(i)),h(new Uint8Array(0)),h(new Uint8Array(0)),l(e)]);return n.hash(t.concat([l(1),r,o]))}var v=new e.ec("secp256k1");function y(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function p(r){r.startsWith("0x")&&(r=r.substring(2));var e=v.keyFromPrivate(r);return function(r){try{var n=e.sign(f(r)),t=n.s,i=n.recoveryParam;return Promise.resolve({r:y(n.r.toString("hex")),s:y(t.toString("hex")),recoveryParam:i})}catch(r){return Promise.reject(r)}}}function g(r){return t.toString(r,"base64url")}function m(r){return t.fromString(r,"base64url")}function w(r){return t.fromString(r,"base64pad")}function b(r){return t.fromString(r,"base58btc")}function E(r){return g(t.fromString(r))}function P(r){return t.toString(m(r))}function S(r){return t.toString(r,"base16")}function k(r){return t.fromString(r)}function x(r,e){var n=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(e?65:64);if(a.set(t.fromString(n,"base16"),0),a.set(t.fromString(i,"base16"),32),e){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return g(a)}function K(r,e){return t.concat([m(r),m(e)])}function j(){return(j=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(r[t]=n[t])}return r}).apply(this,arguments)}var J=new e.ec("secp256k1");function W(r,e){void 0===e&&(e=!1);var n=m(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:S(n.slice(0,32)),s:S(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function A(r){return r.publicKeyBase58?b(r.publicKeyBase58):r.publicKeyBase64?w(r.publicKeyBase64):r.publicKeyHex?t.fromString(r.publicKeyHex,"base16"):new Uint8Array}function D(r,e,n){var t;if(e.length>86)t=[W(e,!0)];else{var i=W(e,!1);t=[j({},i,{recoveryParam:0}),j({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=f(r),i=J.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=s(o);return n.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function T(r,e,n){var t=k(r),i=m(e),a=n.find(function(r){return o.verify(A(r),t,i)});if(!a)throw new Error("Signature invalid for JWT");return a}var C={ES256K:function(r,e,n){var t=f(r),i=W(e),o=n.filter(function(r){return void 0===r.ethereumAddress}),a=n.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=A(r);return J.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=D(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":D,Ed25519:T,EdDSA:T};function I(r){var e=C[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function O(r){return"object"==typeof r&&"r"in r&&"s"in r}function U(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(O(e))return x(e,r);if(r)throw new Error("ES256K-R not supported when signer function returns string");return e})}catch(r){return Promise.reject(r)}}}function X(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(O(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}I.toSignatureObject=W;var B={ES256K:U(),"ES256K-R":U(!0),Ed25519:X(),EdDSA:X()},N=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=q);var t="string"==typeof r?r:H(r),i=[H(n),t].join("."),o=function(r){var e=B[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(n.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},V={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},q="ES256K";function H(r){return E(JSON.stringify(r))}function _(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(P(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function R(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=_(r);return Object.assign(e,{payload:JSON.parse(P(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function z(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),I(n.alg)(t,i,e)}var F="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function L(r,e,n){if(!r.s){if(n instanceof M){if(!n.s)return void(n.o=L.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(L.bind(null,r,e),L.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var M=function(){function r(){}return r.prototype.then=function(e,n){var t=new r,i=this.s;if(i){var o=1&i?e:n;if(o){try{L(t,1,o(this.v))}catch(r){L(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?L(t,1,e?e(i):i):n?L(t,1,n(i)):L(t,2,i)}catch(r){L(t,2,r)}},t},r}();function Z(r){return r instanceof M&&1&r.s}function $(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:g(r.iv),ciphertext:g(n),tag:g(t)};return e&&(o.aad=g(e)),i&&(o.recipients=[i]),o}function G(r){var e=new a.XChaCha20Poly1305(r);return function(r,n){var t=c.randomBytes(e.nonceLength),i=e.seal(t,r,n);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:t}}}function Q(r){var e=G(r);return{alg:"dir",enc:"XC20P",encrypt:function(r,n,t){void 0===n&&(n={});try{var i=E(JSON.stringify(Object.assign({alg:"dir"},n,{enc:"XC20P"}))),o=new Uint8Array(Buffer.from(t?i+"."+g(t):i));return Promise.resolve(j({},e(r,o),{protectedHeader:i}))}catch(r){return Promise.reject(r)}}}}function Y(r){var e=new a.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,n,t){try{return Promise.resolve(e.open(n,r,t))}catch(r){return Promise.reject(r)}}}}function rr(r,e){var n=function(n){try{var a=u.generateKeyPair(),c=G(d(u.sharedKey(a.secretKey,r),i,t))(n),f={encrypted_key:g(c.ciphertext),header:{alg:t,iv:g(c.iv),tag:g(c.tag),epk:{kty:"OKP",crv:o,x:g(a.publicKey)}}};return e&&(f.header.kid=e),Promise.resolve(f)}catch(r){return Promise.reject(r)}},t="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:t,enc:"XC20P",encrypt:function(r,e,t){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=c.randomBytes(32);return Promise.resolve(Q(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return j({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}r.EllipticSigner=function(r){var e=p(r);return function(r){try{return Promise.resolve(e(r)).then(function(r){return x(r)})}catch(r){return Promise.reject(r)}}},r.NaclSigner=function(r){var e=w(r);return function(r){try{var n=k(r),t=g(o.sign(e,n));return Promise.resolve(t)}catch(r){return Promise.reject(r)}}},r.SimpleSigner=p,r.createJWE=function(r,e,n,t){void 0===n&&(n={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,n,t)).then(function(r){return $(r,t)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,n){if("function"==typeof r[F]){var t,i,o,a=r[F]();if(function r(n){try{for(;!(t=a.next()).done;)if((n=e(t.value))&&n.then){if(!Z(n))return void n.then(r,o||(o=L.bind(null,i=new M,2)));n=n.v}i?L(i,1,n):i=n}catch(r){L(i||(i=new M),2,r)}}(),a.return){var u=function(r){try{t.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,n){var t,i,o=-1;return function n(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!Z(a))return void a.then(n,i||(i=L.bind(null,t=new M,2)));a=a.v}t?L(t,1,a):t=a}catch(r){L(t||(t=new M),2,r)}}(),t}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,n,t)).then(function(r){i=r.cek,o=$(r,t)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},r.createJWS=N,r.createJWT=function(r,e,n){var t=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===n&&(n={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!t)throw new Error("No issuing DID has been configured");n.typ||(n.typ="JWT"),n.alg||(n.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=j({},u,r,{iss:t});return N(c,i,n)}catch(r){return Promise.reject(r)}},r.decodeJWT=R,r.decryptJWE=function(r,e){try{var n=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var t=JSON.parse(P(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=K(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===t.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,m(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var n=0;return function(r,e,n){for(var t;;){var i=r();if(Z(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!Z(o)){t=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!Z(a)){t=2;break}}}var u=new M,c=L.bind(null,u,2);return(0===t?i.then(s):1===t?o.then(f):a.then(l)).then(void 0,c),u;function f(t){o=t;do{if(e&&(a=e())&&a.then&&!Z(a))return void a.then(l).then(void 0,c);if(!(i=r())||Z(i)&&!i.v)return void L(u,1,o);if(i.then)return void i.then(s).then(void 0,c);Z(o=n())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=n())&&o.then?o.then(f).then(void 0,c):f(o):L(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):L(u,1,o)}}(function(){return!a&&n<r.recipients.length},function(){return n++},function(){var u=r.recipients[n];Object.assign(u.header,t);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,m(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(n):n())}catch(r){return Promise.reject(r)}},r.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var n;if(!e.keyAgreement)throw new Error("Could not find x25519 key for "+r);var t=(null==(n=e.keyAgreement)?void 0:n.map(function(r){return"string"==typeof r?e.publicKey.find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!t)throw new Error("Could not find x25519 key for "+r);return rr(b(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},r.toEthereumAddress=s,r.verifyJWS=function(r,e){return z(_(r),e)},r.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var n=R(r),t=n.payload,i=n.header,o=n.signature,a=n.data;return Promise.resolve(function(r,e,n,t){try{var i=V[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(n)).then(function(r){if(!r)throw new Error("Unable to resolve DID document for "+n);var o=function(r,e){var n=r.publicKey.filter(function(r){return e===r.id});return n.length>0?n[0]:null},a=r.publicKey||[];t&&(a=(r.authentication||[]).map(function(e){return"string"==typeof e?o(r,e):"string"==typeof e.publicKey?o(r,e.publicKey):e}).filter(function(r){return null!=r}));var u=a.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(t&&(!u||0===u.length))throw new Error("DID document for "+n+" does not have public keys suitable for authenticating user");if(!u||0===u.length)throw new Error("DID document for "+n+" does not have public keys for "+e);return{authenticators:u,issuer:n,doc:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,t.iss,e.auth)).then(function(n){var u=n.doc,c=n.issuer;return Promise.resolve(z({header:i,data:a,signature:o},n.authenticators)).then(function(n){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(n){var a=i+o;if(t.nbf){if(t.nbf>a)throw new Error("JWT not valid before nbf: "+t.nbf)}else if(t.iat&&t.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+t.iat);if(t.exp&&t.exp<=i-o)throw new Error("JWT has expired: exp: "+t.exp+" < now: "+i);if(t.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,doc:u,issuer:c,signer:n,jwt:r}}})})}catch(r){return Promise.reject(r)}},r.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(n,t,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var a=m(o.header.epk.x),c=d(u.sharedKey(r,a),256,e),f=K(o.encrypted_key,o.header.tag);return Promise.resolve(Y(c).decrypt(f,m(o.header.iv))).then(function(r){return null===r?null:Y(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}},r.x25519Encrypter=rr,r.xc20pDirDecrypter=Y,r.xc20pDirEncrypter=Q});
!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("uint8arrays"),require("@stablelib/sha256"),require("js-sha3"),require("elliptic"),require("@stablelib/ed25519"),require("@stablelib/xchacha20poly1305"),require("@stablelib/x25519"),require("@stablelib/random")):"function"==typeof define&&define.amd?define(["exports","uint8arrays","@stablelib/sha256","js-sha3","elliptic","@stablelib/ed25519","@stablelib/xchacha20poly1305","@stablelib/x25519","@stablelib/random"],e):e((r||self).didJwt={},r.uint8Arrays,r.sha256$1,r.jsSha3,r.elliptic,r.ed25519,r.xchacha20poly1305,r.x25519,r.random)}(this,function(r,e,n,t,i,o,a,u,c){function f(r){return e.toString(r,"base64url")}function s(r){var n=r.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return e.fromString(n,"base64url")}function l(r){return e.fromString(r,"base58btc")}function h(r){var n=r.startsWith("0x")?r.substring(2):r;return e.fromString(n.toLowerCase(),"base16")}function d(r){return f(e.fromString(r))}function v(r){return e.toString(s(r))}function y(r){return e.toString(r,"base16")}function p(r){return e.fromString(r)}function g(r,n){var t=r.r,i=r.s,o=r.recoveryParam,a=new Uint8Array(n?65:64);if(a.set(e.fromString(t,"base16"),0),a.set(e.fromString(i,"base16"),32),n){if(void 0===o)throw new Error("Signer did not return a recoveryParam");a[64]=o}return f(a)}function m(r){var e=s(r);if(e.length<64||e.length>65)throw new TypeError("Wrong size for signature. Expected 64 or 65 bytes, but got "+e.length);return{r:y(e.slice(0,32)),s:y(e.slice(32,64)),recoveryParam:65===e.length?e[64]:void 0}}function w(r,n){return e.concat([s(r),s(n)])}var b=/^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/,E=/^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/,P=/^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/;function S(r){if("string"==typeof r){if(b.test(r))return h(r);if(E.test(r))return l(r);if(P.test(r))return s(r);throw TypeError("Invalid private key format")}if(r instanceof Uint8Array)return r;throw TypeError("Invalid private key format")}function k(r,e){return void 0===e&&(e=64),r.length===e?r:"0".repeat(e-r.length)+r}function x(r){var t="string"==typeof r?e.fromString(r):r;return n.hash(t)}function K(r){var n,i=e.fromString(r.slice(2),"base16");return"0x"+e.toString((n=i,new Uint8Array(t.keccak_256.arrayBuffer(n))).slice(-20),"base16")}function j(r,n){void 0===n&&(n=new Uint8Array(4));var t=e.fromString(r.toString(),"base10");return n.set(t,4-t.length),n}var A=function(r){return e.concat([j(r.length),r])};function J(r,t,i){if(256!==t)throw new Error("Unsupported key length: "+t);var o=e.concat([A(e.fromString(i)),A(new Uint8Array(0)),A(new Uint8Array(0)),j(t)]);return n.hash(e.concat([j(1),r,o]))}var W=new i.ec("secp256k1");function D(r,e){void 0===e&&(e=!1);var n=S(r);if(32!==n.length)throw new Error("Invalid private key format. Expecting 32 bytes, but got "+n.length);var t=W.keyFromPrivate(n);return function(r){try{var n=t.sign(x(r)),i=n.s,o=n.recoveryParam;return Promise.resolve(g({r:k(n.r.toString("hex")),s:k(i.toString("hex")),recoveryParam:o},e))}catch(r){return Promise.reject(r)}}}function T(r){var e=S(r);if(64!==e.length)throw new Error("Invalid private key format. Expecting 64 bytes, but got "+e.length);return function(r){try{var n="string"==typeof r?p(r):r,t=o.sign(e,n);return Promise.resolve(f(t))}catch(r){return Promise.reject(r)}}}function I(){return(I=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(r[t]=n[t])}return r}).apply(this,arguments)}var C=new i.ec("secp256k1");function U(r,e){void 0===e&&(e=!1);var n=s(r);if(n.length!==(e?65:64))throw new Error("wrong signature length");var t={r:y(n.slice(0,32)),s:y(n.slice(32,64))};return e&&(t.recoveryParam=n[64]),t}function O(r){return r.publicKeyBase58?l(r.publicKeyBase58):r.publicKeyBase64?s(r.publicKeyBase64):r.publicKeyHex?h(r.publicKeyHex):new Uint8Array}function B(r,e,n){var t;if(e.length>86)t=[U(e,!0)];else{var i=U(e,!1);t=[I({},i,{recoveryParam:0}),I({},i,{recoveryParam:1})]}var o=t.map(function(e){var t=x(r),i=C.recoverPubKey(t,e,e.recoveryParam),o=i.encode("hex"),a=i.encode("hex",!0),u=K(o);return n.find(function(r){var e=r.publicKeyHex;return e===o||e===a||r.ethereumAddress===u})}).filter(function(r){return null!=r});if(0===o.length)throw new Error("Signature invalid for JWT");return o[0]}function N(r,e,n){var t=p(r),i=s(e),a=n.find(function(r){return o.verify(O(r),t,i)});if(!a)throw new Error("Signature invalid for JWT");return a}var X={ES256K:function(r,e,n){var t=x(r),i=U(e),o=n.filter(function(r){return void 0===r.ethereumAddress}),a=n.filter(function(r){return void 0!==r.ethereumAddress}),u=o.find(function(r){try{var e=O(r);return C.keyFromPublic(e).verify(t,i)}catch(r){return!1}});if(!u&&a.length>0&&(u=B(r,e,a)),!u)throw new Error("Signature invalid for JWT");return u},"ES256K-R":B,Ed25519:N,EdDSA:N};function V(r){var e=X[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}function _(r){return"object"==typeof r&&"r"in r&&"s"in r}function q(r){return function(e,n){try{return Promise.resolve(n(e)).then(function(e){if(_(e))return g(e,r);if(r&&void 0===m(e).recoveryParam)throw new Error("ES256K-R not supported when signer doesn't provide a recovery param");return e})}catch(r){return Promise.reject(r)}}}function H(){return function(r,e){try{return Promise.resolve(e(r)).then(function(r){if(_(r))throw new Error("expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}V.toSignatureObject=U;var z={ES256K:q(),"ES256K-R":q(!0),Ed25519:H(),EdDSA:H()},Z=function(r,e,n){void 0===n&&(n={});try{n.alg||(n.alg=$);var t="string"==typeof r?r:L(r),i=[L(n),t].join("."),o=function(r){var e=z[r];if(!e)throw new Error("Unsupported algorithm "+r);return e}(n.alg);return Promise.resolve(o(i,e)).then(function(r){return[i,r].join(".")})}catch(r){return Promise.reject(r)}},F={ES256K:["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],"ES256K-R":["Secp256k1VerificationKey2018","Secp256k1SignatureVerificationKey2018","EcdsaPublicKeySecp256k1","EcdsaSecp256k1VerificationKey2019"],Ed25519:["ED25519SignatureVerification","Ed25519VerificationKey2018"],EdDSA:["ED25519SignatureVerification","Ed25519VerificationKey2018"]},$="ES256K";function L(r){return d(JSON.stringify(r))}function R(r){var e=r.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(v(e[1])),payload:e[2],signature:e[3],data:e[1]+"."+e[2]};throw new Error("Incorrect format JWS")}function M(r){if(!r)throw new Error("no JWT passed into decodeJWT");try{var e=R(r);return Object.assign(e,{payload:JSON.parse(v(e.payload))})}catch(r){throw new Error("Incorrect format JWT")}}function G(r,e){var n=r.header,t=r.data,i=r.signature;return Array.isArray(e)||(e=[e]),V(n.alg)(t,i,e)}var Q="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function Y(r,e,n){if(!r.s){if(n instanceof rr){if(!n.s)return void(n.o=Y.bind(null,r,e));1&e&&(e=n.s),n=n.v}if(n&&n.then)return void n.then(Y.bind(null,r,e),Y.bind(null,r,2));r.s=e,r.v=n;var t=r.o;t&&t(r)}}var rr=function(){function r(){}return r.prototype.then=function(e,n){var t=new r,i=this.s;if(i){var o=1&i?e:n;if(o){try{Y(t,1,o(this.v))}catch(r){Y(t,2,r)}return t}return this}return this.o=function(r){try{var i=r.v;1&r.s?Y(t,1,e?e(i):i):n?Y(t,1,n(i)):Y(t,2,i)}catch(r){Y(t,2,r)}},t},r}();function er(r){return r instanceof rr&&1&r.s}function nr(r,e){var n=r.ciphertext,t=r.tag,i=r.recipient,o={protected:r.protectedHeader,iv:f(r.iv),ciphertext:f(n),tag:f(t)};return e&&(o.aad=f(e)),i&&(o.recipients=[i]),o}function tr(r){var e=new a.XChaCha20Poly1305(r);return function(r,n){var t=c.randomBytes(e.nonceLength),i=e.seal(t,r,n);return{ciphertext:i.subarray(0,i.length-e.tagLength),tag:i.subarray(i.length-e.tagLength),iv:t}}}function ir(r){var e=tr(r),n="XC20P";return{alg:"dir",enc:n,encrypt:function(r,t,i){void 0===t&&(t={});try{var o=d(JSON.stringify(Object.assign({alg:"dir"},t,{enc:n}))),a=new Uint8Array(Buffer.from(i?o+"."+f(i):o));return Promise.resolve(I({},e(r,a),{protectedHeader:o}))}catch(r){return Promise.reject(r)}}}}function or(r){var e=new a.XChaCha20Poly1305(r);return{alg:"dir",enc:"XC20P",decrypt:function(r,n,t){try{return Promise.resolve(e.open(n,r,t))}catch(r){return Promise.reject(r)}}}}function ar(r,e){var n=function(n){try{var a=u.generateKeyPair(),c=tr(J(u.sharedKey(a.secretKey,r),i,t))(n),s={encrypted_key:f(c.ciphertext),header:{alg:t,iv:f(c.iv),tag:f(c.tag),epk:{kty:"OKP",crv:o,x:f(a.publicKey)}}};return e&&(s.header.kid=e),Promise.resolve(s)}catch(r){return Promise.reject(r)}},t="ECDH-ES+XC20PKW",i=256,o="X25519";return{alg:t,enc:"XC20P",encrypt:function(r,e,t){void 0===e&&(e={});try{Object.assign(e,{alg:void 0});var i=c.randomBytes(32);return Promise.resolve(ir(i).encrypt(r,e,t)).then(function(r){return Promise.resolve(n(i)).then(function(e){return I({},r,{recipient:e,cek:i})})})}catch(r){return Promise.reject(r)}},encryptCek:n}}r.ES256KSigner=D,r.EdDSASigner=T,r.EllipticSigner=function(r){return D(r)},r.NaclSigner=function(r){return T(r)},r.SimpleSigner=function(r){var e=D(r,!0);return function(r){try{return Promise.resolve(e(r)).then(m)}catch(r){return Promise.reject(r)}}},r.createJWE=function(r,e,n,t){void 0===n&&(n={});try{if("dir"===e[0].alg){if(e.length>1)throw new Error('Can only do "dir" encryption to one key.');return Promise.resolve(e[0].encrypt(r,n,t)).then(function(r){return nr(r,t)})}var i,o,a=e[0].enc;if(!e.reduce(function(r,e){return r&&e.enc===a},!0))throw new Error("Incompatible encrypters passed");var u=function(r,e,n){if("function"==typeof r[Q]){var t,i,o,a=r[Q]();if(function r(n){try{for(;!(t=a.next()).done;)if((n=e(t.value))&&n.then){if(!er(n))return void n.then(r,o||(o=Y.bind(null,i=new rr,2)));n=n.v}i?Y(i,1,n):i=n}catch(r){Y(i||(i=new rr),2,r)}}(),a.return){var u=function(r){try{t.done||a.return()}catch(r){}return r};if(i&&i.then)return i.then(u,function(r){throw u(r)});u()}return i}if(!("length"in r))throw new TypeError("Object is not iterable");for(var c=[],f=0;f<r.length;f++)c.push(r[f]);return function(r,e,n){var t,i,o=-1;return function n(a){try{for(;++o<r.length;)if((a=e(o))&&a.then){if(!er(a))return void a.then(n,i||(i=Y.bind(null,t=new rr,2)));a=a.v}t?Y(t,1,a):t=a}catch(r){Y(t||(t=new rr),2,r)}}(),t}(c,function(r){return e(c[r])})}(e,function(e){var a=function(){if(i){var a=o.recipients,u=a.push;return Promise.resolve(e.encryptCek(i)).then(function(r){u.call(a,r)})}return Promise.resolve(e.encrypt(r,n,t)).then(function(r){i=r.cek,o=nr(r,t)})}();if(a&&a.then)return a.then(function(){})});return Promise.resolve(u&&u.then?u.then(function(){return o}):o)}catch(r){return Promise.reject(r)}},r.createJWS=Z,r.createJWT=function(r,e,n){var t=e.issuer,i=e.signer,o=e.alg,a=e.expiresIn;void 0===n&&(n={});try{if(!i)throw new Error("No Signer functionality has been configured");if(!t)throw new Error("No issuing DID has been configured");n.typ||(n.typ="JWT"),n.alg||(n.alg=o);var u={iat:Math.floor(Date.now()/1e3),exp:void 0};if(a){if("number"!=typeof a)throw new Error("JWT expiresIn is not a number");u.exp=(r.nbf||u.iat)+Math.floor(a)}var c=I({},u,r,{iss:t});return Z(c,i,n)}catch(r){return Promise.reject(r)}},r.decodeJWT=M,r.decryptJWE=function(r,e){try{var n=function(r){if(null===a)throw new Error("Failed to decrypt");return a};!function(r){if(!(r.protected&&r.iv&&r.ciphertext&&r.tag))throw new Error("Invalid JWE");r.recipients&&r.recipients.map(function(r){if(!r.header||!r.encrypted_key)throw new Error("Invalid JWE")})}(r);var t=JSON.parse(v(r.protected));if(t.enc!==e.enc)throw new Error("Decrypter does not support: '"+t.enc+"'");var i=w(r.ciphertext,r.tag),o=new Uint8Array(Buffer.from(r.aad?r.protected+"."+r.aad:r.protected)),a=null,u="dir"===t.alg&&"dir"===e.alg?Promise.resolve(e.decrypt(i,s(r.iv),o)).then(function(r){a=r}):function(){if(r.recipients&&0!==r.recipients.length){var n=0;return function(r,e,n){for(var t;;){var i=r();if(er(i)&&(i=i.v),!i)return o;if(i.then){t=0;break}var o=n();if(o&&o.then){if(!er(o)){t=1;break}o=o.s}if(e){var a=e();if(a&&a.then&&!er(a)){t=2;break}}}var u=new rr,c=Y.bind(null,u,2);return(0===t?i.then(s):1===t?o.then(f):a.then(l)).then(void 0,c),u;function f(t){o=t;do{if(e&&(a=e())&&a.then&&!er(a))return void a.then(l).then(void 0,c);if(!(i=r())||er(i)&&!i.v)return void Y(u,1,o);if(i.then)return void i.then(s).then(void 0,c);er(o=n())&&(o=o.v)}while(!o||!o.then);o.then(f).then(void 0,c)}function s(r){r?(o=n())&&o.then?o.then(f).then(void 0,c):f(o):Y(u,1,o)}function l(){(i=r())?i.then?i.then(s).then(void 0,c):s(i):Y(u,1,o)}}(function(){return!a&&n<r.recipients.length},function(){return n++},function(){var u=r.recipients[n];Object.assign(u.header,t);var c=function(){if(u.header.alg===e.alg)return Promise.resolve(e.decrypt(i,s(r.iv),o,u)).then(function(r){a=r})}();if(c&&c.then)return c.then(function(){})})}throw new Error("Invalid JWE")}();return Promise.resolve(u&&u.then?u.then(n):n())}catch(r){return Promise.reject(r)}},r.resolveX25519Encrypters=function(r,e){try{return Promise.all(r.map(function(r){try{return Promise.resolve(e.resolve(r)).then(function(e){var n;if(!e.keyAgreement)throw new Error("Could not find x25519 key for "+r);var t=(null==(n=e.keyAgreement)?void 0:n.map(function(r){return"string"==typeof r?e.publicKey.find(function(e){return e.id===r}):r})).find(function(r){return"X25519KeyAgreementKey2019"===r.type&&Boolean(r.publicKeyBase58)});if(!t)throw new Error("Could not find x25519 key for "+r);return ar(l(t.publicKeyBase58),t.id)})}catch(r){return Promise.reject(r)}}))}catch(r){return Promise.reject(r)}},r.toEthereumAddress=K,r.verifyJWS=function(r,e){return G(R(r),e)},r.verifyJWT=function(r,e){void 0===e&&(e={resolver:null,auth:null,audience:null,callbackUrl:null,skewTime:null});try{if(!e.resolver)throw new Error("No DID resolver has been configured");var n=M(r),t=n.payload,i=n.header,o=n.signature,a=n.data;return Promise.resolve(function(r,e,n,t){try{var i=F[e];if(!i||0===i.length)throw new Error("No supported signature types for algorithm "+e);return Promise.resolve(r.resolve(n)).then(function(r){if(!r)throw new Error("Unable to resolve DID document for "+n);var o=function(r,e){var n=r.publicKey.filter(function(r){return e===r.id});return n.length>0?n[0]:null},a=r.publicKey||[];t&&(a=(r.authentication||[]).map(function(e){return"string"==typeof e?o(r,e):"string"==typeof e.publicKey?o(r,e.publicKey):e}).filter(function(r){return null!=r}));var u=a.filter(function(r){var e=r.type;return i.find(function(r){return r===e})});if(t&&(!u||0===u.length))throw new Error("DID document for "+n+" does not have public keys suitable for authenticating user");if(!u||0===u.length)throw new Error("DID document for "+n+" does not have public keys for "+e);return{authenticators:u,issuer:n,doc:r}})}catch(r){return Promise.reject(r)}}(e.resolver,i.alg,t.iss,e.auth)).then(function(n){var u=n.doc,c=n.issuer;return Promise.resolve(G({header:i,data:a,signature:o},n.authenticators)).then(function(n){var i=Math.floor(Date.now()/1e3),o=e.skewTime>=0?e.skewTime:300;if(n){var a=i+o;if(t.nbf){if(t.nbf>a)throw new Error("JWT not valid before nbf: "+t.nbf)}else if(t.iat&&t.iat>a)throw new Error("JWT not valid yet (issued in the future) iat: "+t.iat);if(t.exp&&t.exp<=i-o)throw new Error("JWT has expired: exp: "+t.exp+" < now: "+i);if(t.aud){if(!e.audience&&!e.callbackUrl)throw new Error("JWT audience is required but your app address has not been configured");if(void 0===(Array.isArray(t.aud)?t.aud:[t.aud]).find(function(r){return e.audience===r||e.callbackUrl===r}))throw new Error("JWT audience does not match your DID or callback url")}return{payload:t,doc:u,issuer:c,signer:n,jwt:r}}})})}catch(r){return Promise.reject(r)}},r.x25519Decrypter=function(r){var e="ECDH-ES+XC20PKW";return{alg:e,enc:"XC20P",decrypt:function(n,t,i,o){try{if(function(r){if(!(r.epk&&r.iv&&r.tag))throw new Error("Invalid JWE")}(o.header),"X25519"!==o.header.epk.crv)return Promise.resolve(null);var a=s(o.header.epk.x),c=J(u.sharedKey(r,a),256,e),f=w(o.encrypted_key,o.header.tag);return Promise.resolve(or(c).decrypt(f,s(o.header.iv))).then(function(r){return null===r?null:or(r).decrypt(n,t,i)})}catch(r){return Promise.reject(r)}}}},r.x25519Encrypter=ar,r.xc20pDirDecrypter=or,r.xc20pDirEncrypter=ir});
//# sourceMappingURL=index.umd.js.map
import { EcdsaSignature } from './util';
import { DIDDocument, PublicKey } from 'did-resolver';
export declare type Signer = (data: string) => Promise<EcdsaSignature | string>;
export declare type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string>;
export declare type SignerAlgorithm = (payload: string, signer: Signer) => Promise<string>;

@@ -8,2 +8,5 @@ export interface JWTOptions {

signer: Signer;
/**
* @deprecated Please use `header.alg` to specify the JWT algorithm.
*/
alg?: string;

@@ -82,7 +85,7 @@ expiresIn?: number;

* @example
* const signer = SimpleSigner(process.env.PRIVATE_KEY)
* const signer = ES256KSigner(process.env.PRIVATE_KEY)
* const jws = await createJWS({ my: 'payload' }, signer)
*
* @param {Object} payload payload object
* @param {SimpleSigner} signer a signer, reference our SimpleSigner.js
* @param {Signer} signer a signer, see `ES256KSigner or `EdDSASigner`
* @param {Object} header optional object to specify or customize the JWS header

@@ -96,3 +99,3 @@ * @return {Promise<Object, Error>} a promise which resolves with a JWS string or rejects with an error

* @example
* const signer = SimpleSigner(process.env.PRIVATE_KEY)
* const signer = ES256KSigner(process.env.PRIVATE_KEY)
* createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {

@@ -103,7 +106,7 @@ * ...

* @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], Defaults to: ES256K.
* Please use `header.alg` to specify the algorithm
* @param {SimpleSigner} options.signer a signer, reference our SimpleSigner.js
* @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

@@ -110,0 +113,0 @@ * @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or rejects with an error

import { SignerAlgorithm } from './JWT';
export declare function ES256KSigner(recoverable?: boolean): SignerAlgorithm;
export declare function Ed25519Signer(): SignerAlgorithm;
export declare function ES256KSignerAlg(recoverable?: boolean): SignerAlgorithm;
export declare function Ed25519SignerAlg(): SignerAlgorithm;
declare function SignerAlgorithm(alg: string): SignerAlgorithm;
export default SignerAlgorithm;
//# sourceMappingURL=SignerAlgorithm.d.ts.map

@@ -0,1 +1,4 @@

/**
* @deprecated Signers will be expected to return base64url `string` signatures.
*/
export interface EcdsaSignature {

@@ -7,3 +10,2 @@ r: string;

export declare function bytesToBase64url(b: Uint8Array): string;
export declare function base64urlToBytes(s: string): Uint8Array;
export declare function base64ToBytes(s: string): Uint8Array;

@@ -18,3 +20,18 @@ export declare function bytesToBase64(b: Uint8Array): string;

export declare function toJose({ r, s, recoveryParam }: EcdsaSignature, recoverable?: boolean): string;
export declare function fromJose(signature: string): {
r: string;
s: string;
recoveryParam: number;
};
export declare function toSealed(ciphertext: string, tag: string): Uint8Array;
/**
* Parses a private key and returns the Uint8Array representation.
* This method uses an heuristic to determine the key encoding to then be able to parse it into 32 or 64 bytes.
*
* @param input a 32 or 64 byte key presented either as a Uint8Array or as a hex, base64, or base58btc encoded string
*
* @throws TypeError('Invalid private key format') if the key doesn't match any of the accepted formats or length
*/
export declare function parseKey(input: string | Uint8Array): Uint8Array;
export declare function leftpad(data: string, size?: number): string;
//# sourceMappingURL=util.d.ts.map
{
"name": "did-jwt",
"version": "4.8.1",
"version": "4.9.0",
"description": "Library for Signing and Verifying JWTs compatible uPort and DID standards",

@@ -65,5 +65,5 @@ "main": "lib/index.js",

"@types/elliptic": "6.4.12",
"@types/jest": "26.0.19",
"@types/jest": "26.0.20",
"codecov": "3.8.1",
"eslint": "7.15.0",
"eslint": "7.18.0",
"eslint-config-standard": "14.1.1",

@@ -78,3 +78,3 @@ "eslint-plugin-import": "2.22.1",

"jsontokens": "3.0.0",
"microbundle": "0.12.4",
"microbundle": "0.13.0",
"mockdate": "3.0.2",

@@ -84,4 +84,4 @@ "nacl-did": "1.0.1",

"regenerator-runtime": "0.13.7",
"semantic-release": "17.3.0",
"sinon": "9.2.2",
"semantic-release": "17.3.7",
"sinon": "9.2.4",
"standard": "14.3.4",

@@ -88,0 +88,0 @@ "ts-jest": "26.4.4",

# did-jwt
[![npm](https://img.shields.io/npm/dt/did-jwt.svg)](https://www.npmjs.com/package/did-jwt)

@@ -6,23 +7,13 @@ [![npm](https://img.shields.io/npm/v/did-jwt.svg)](https://www.npmjs.com/package/did-jwt)

[Algorithms supported](docs/guides/index.md#algorithms-supported) | [DID Public Key Types](docs/guides/index.md#did-publickey-types) | [Claim Specification](docs/guides/index.md#claims)
The did-JWT library allows you to sign and verify [JSON Web Tokens (JWT)](https://tools.ietf.org/html/rfc7519) using `ES256K` and `Ed25519` algorithms.
The non-standard `ES256K-R` is also supported for backward compatibility reasons.
The did-JWT library allows you to sign and verify [JSON Web Tokens (JWT)](https://tools.ietf.org/html/rfc7519) using ES256K, ES256K-R and Ed25519 algorithms.
Public keys are resolved using the [Decentralized ID (DID)](https://w3c-ccg.github.io/did-spec/#decentralized-identifiers-dids) of the signing identity of the token, which is passed as the `iss` attribute of the JWT payload.
Public keys are resolved using the [Decentralized ID (DID)](https://w3c-ccg.github.io/did-spec/#decentralized-identifiers-dids) of the signing identity of the claim, which is passed as the `iss` attribute of the encoded JWT.
## DID methods
We currently support the following DID methods:
- [`ethr`](https://github.com/uport-project/ethr-did-resolver)
- [`uport`](https://github.com/uport-project/uport-did-resolver)
- [`https`](https://github.com/uport-project/https-did-resolver)
- [`nacl`](https://github.com/uport-project/nacl-did)
- [`muport`](https://github.com/3box/muport-did-resolver)
All DID methods that can be resolved using the [`did-resolver'](https://github.com/uport-project/did-resolver) interface are supported for verification.
You will need to install each one you need to support. See each method for how to configure it.
If your DID method requires a different signing algorithm than what is already supported, please create an issue.
Support for other DID methods should be simple. Write a DID resolver supporting the [`did-resolver'](https://github.com/uport-project/did-resolver) interface. Once you've verified that it works, please add a PR adding it to the above list so people can find it.
If your DID method requires a different signing algorithm than what is already supported, please create a PR.
## Installation

@@ -44,19 +35,20 @@

[createJWT](docs/reference/index.md#did-jwtjwtcreatejwtpayload-config--promiseobject-error)
In practice, you must secure the key passed to ES256KSigner.
The key provided in code below is for informational purposes only.
In practice you should secure the key passed to SimpleSigner. The key provided in code below is for informational purposes; you will need to create an application identity at [My Apps](http://developer.uport.me/myapps) or use our uport-credentials library to [generate an ethereum key pair](https://github.com/uport-project/uport-credentials/blob/develop/docs/guides/index.md#generate-an-ethereum-keypair).
```js
const didJWT = require('did-jwt')
const signer = didJWT.SimpleSigner('278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f');
const signer = didJWT.ES256KSigner('278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f')
let jwt = await didJWT.createJWT({aud: 'did:ethr:0xf3beac30c498d9e26865f34fcaa57dbb935b0d74', exp: 1957463421, name: 'uPort Developer'},
{alg: 'ES256K', issuer: 'did:ethr:0xf3beac30c498d9e26865f34fcaa57dbb935b0d74', signer})
console.log(jwt);
let jwt = await didJWT.createJWT(
{ aud: 'did:ethr:0xf3beac30c498d9e26865f34fcaa57dbb935b0d74', exp: 1957463421, name: 'uPort Developer' },
{ issuer: 'did:ethr:0xf3beac30c498d9e26865f34fcaa57dbb935b0d74', signer },
{ alg: 'ES256K' }
)
console.log(jwt)
```
### 2. Decode a did-JWT
Try decoding the JWT. You can also do this using [jwt.io](jwt.io)
Try decoding the JWT. You can also do this using [jwt.io](https://jwt.io)

@@ -87,7 +79,8 @@ ```js

### 3. Verify a did-JWT
[verifyJWT](/docs/reference/index.md#did-jwtjwtverifyjwtjwt-config--promiseobject-error)
You need to provide a did-resolver for the verify function. For this example we will use ethr-did, but there are other methods available above. For more information on configuring the Resolver object please see [did-resolver](https://github.com/decentralized-identity/did-resolver#configure-resolver-object)
You need to provide a did-resolver for the verify function.
For this example we will use `did:ethr`, but there are other methods available.
For more information on configuring the Resolver object please see [did-resolver](https://github.com/decentralized-identity/did-resolver#configure-resolver-object)
``` bash
```bash
npm install ethr-did-resolver

@@ -98,12 +91,15 @@ ```

const Resolver = require('did-resolver')
const ethrDid = require('ethr-did-resolver').getResolver({rpcUrl: 'https://mainnet.infura.io/v3/...'})
const ethrDid = require('ethr-did-resolver').getResolver({ rpcUrl: 'https://mainnet.infura.io/v3/...' })
let resolver = new Resolver.Resolver(ethrDid)
// pass the JWT from step 1 & 2
let verifiedResponse = await didJWT.verifyJWT(jwt, {resolver: resolver, audience: 'did:ethr:0xf3beac30c498d9e26865f34fcaa57dbb935b0d74'})
console.log(verifiedResponse);
// pass the JWT from step 1
let verificationResponse = await didJWT.verifyJWT(jwt, {
resolver: resolver,
audience: 'did:ethr:0xf3beac30c498d9e26865f34fcaa57dbb935b0d74'
})
console.log(verificationResponse)
```
A verified did-JWT returns an object resembling:
A verification response is an object resembling:

@@ -110,0 +106,0 @@ ```js

@@ -1,2 +0,2 @@

import EllipticSigner from '../EllipticSigner'
import EllipticSigner from '../signers/EllipticSigner'

@@ -3,0 +3,0 @@ const privateKey = '278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f'

@@ -30,3 +30,3 @@ import { decryptJWE, createJWE, Encrypter } from '../JWE'

const decrypter = xc20pDirDecrypter(randomBytes(32))
await expect(decryptJWE(jwe, decrypter)).rejects.toThrow('Invalid JWE')
await expect(decryptJWE(jwe as any, decrypter)).rejects.toThrow('Invalid JWE')
})

@@ -38,3 +38,3 @@ })

const decrypter = x25519Decrypter(u8a.fromString(key, 'base64pad'))
const cleartextU8a = await decryptJWE(jwe, decrypter)
const cleartextU8a = await decryptJWE(jwe as any, decrypter)
expect(u8a.toString(cleartextU8a)).toEqual(cleartext)

@@ -45,3 +45,3 @@ })

const decrypter = x25519Decrypter(u8a.fromString(key, 'base64pad'))
await expect(decryptJWE(jwe, decrypter)).rejects.toThrow('Failed to decrypt')
await expect(decryptJWE(jwe as any, decrypter)).rejects.toThrow('Failed to decrypt')
})

@@ -51,3 +51,3 @@

const decrypter = x25519Decrypter(randomBytes(32))
await expect(decryptJWE(jwe, decrypter)).rejects.toThrow('Invalid JWE')
await expect(decryptJWE(jwe as any, decrypter)).rejects.toThrow('Invalid JWE')
})

@@ -54,0 +54,0 @@ })

import { createJWT, verifyJWT, decodeJWT, createJWS, verifyJWS, resolveAuthenticator, NBF_SKEW } from '../JWT'
import { TokenVerifier } from 'jsontokens'
import SimpleSigner from '../SimpleSigner'
import NaclSigner from '../NaclSigner'
import SimpleSigner from '../signers/SimpleSigner'
import NaclSigner from '../signers/NaclSigner'
import { bytesToBase64url, decodeBase64url } from '../util'

@@ -6,0 +6,0 @@ import { verifyJWT as naclVerifyJWT } from 'nacl-did'

@@ -1,2 +0,2 @@

import NaclSigner from '../NaclSigner'
import NaclSigner from '../signers/NaclSigner'

@@ -3,0 +3,0 @@ const privateKey = 'nlXR4aofRVuLqtn9+XVQNlX4s1nVQvp+TOhBBtYls1IG+sHyIkDP/WN+rWZHGIQp+v2pyct+rkM4asF/YRFQdQ=='

import SignerAlgorithm from '../SignerAlgorithm'
import { toSignatureObject } from '../VerifierAlgorithm'
import SimpleSigner from '../SimpleSigner'
import EllipticSigner from '../EllipticSigner'
import NaclSigner from '../NaclSigner'
import SimpleSigner from '../signers/SimpleSigner'
import EllipticSigner from '../signers/EllipticSigner'
import NaclSigner from '../signers/NaclSigner'
import { ec as EC } from 'elliptic'
import nacl from 'tweetnacl'
import { base64ToBytes, base64urlToBytes, stringToBytes } from '../util'
import { base64ToBytes, stringToBytes } from '../util'
import { sha256 } from '../Digest'
const secp256k1 = new EC('secp256k1')
const privateKey = '278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a241154cc1d25383f'
const privateKey = '0278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a241154cc1d25383f'
const ed25519PrivateKey = 'nlXR4aofRVuLqtn9+XVQNlX4s1nVQvp+TOhBBtYls1IG+sHyIkDP/WN+rWZHGIQp+v2pyct+rkM4asF/YRFQdQ=='

@@ -51,3 +51,3 @@ const kp = secp256k1.keyFromPrivate(privateKey)

const signature = await jwtSigner('hello', signer)
expect(base64urlToBytes(signature).length).toEqual(64)
expect(base64ToBytes(signature).length).toEqual(64)
})

@@ -79,3 +79,3 @@

const signature = await jwtSigner('hello', ecSigner)
expect(base64urlToBytes(signature).length).toEqual(64)
expect(base64ToBytes(signature).length).toEqual(64)
})

@@ -99,3 +99,3 @@

const signature = await jwtSigner('hello', signer)
expect(base64urlToBytes(signature).length).toEqual(65)
expect(base64ToBytes(signature).length).toEqual(65)
})

@@ -128,4 +128,4 @@

const signature = await jwtSigner('hello', edSigner)
expect(nacl.sign.detached.verify(stringToBytes('hello'), base64urlToBytes(signature), edKp.publicKey)).toBeTruthy()
expect(nacl.sign.detached.verify(stringToBytes('hello'), base64ToBytes(signature), edKp.publicKey)).toBeTruthy()
})
})

@@ -1,2 +0,2 @@

import SimpleSigner from '../SimpleSigner'
import SimpleSigner from '../signers/SimpleSigner'

@@ -3,0 +3,0 @@ const privateKey = '278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f'

import VerifierAlgorithm from '../VerifierAlgorithm'
import { createJWT } from '../JWT'
import SimpleSigner from '../SimpleSigner'
import NaclSigner from '../NaclSigner'
import SimpleSigner from '../signers/SimpleSigner'
import NaclSigner from '../signers/NaclSigner'
import { toEthereumAddress } from '../Digest'

@@ -6,0 +6,0 @@ import nacl from 'tweetnacl'

@@ -5,4 +5,5 @@ import { hash } from '@stablelib/sha256'

export function sha256(payload: string): Uint8Array {
return hash(u8a.fromString(payload))
export function sha256(payload: string | Uint8Array): Uint8Array {
const data = (typeof payload === 'string') ? u8a.fromString(payload) : payload
return hash(data)
}

@@ -9,0 +10,0 @@

@@ -1,4 +0,6 @@

import SimpleSigner from './SimpleSigner'
import EllipticSigner from './EllipticSigner'
import NaclSigner from './NaclSigner'
import SimpleSigner from './signers/SimpleSigner'
import EllipticSigner from './signers/EllipticSigner'
import NaclSigner from './signers/NaclSigner'
import { ES256KSigner } from './signers/ES256KSigner'
import { EdDSASigner } from './signers/EdDSASigner'
import {

@@ -30,2 +32,4 @@ verifyJWT,

NaclSigner,
ES256KSigner,
EdDSASigner,
verifyJWT,

@@ -32,0 +36,0 @@ createJWT,

@@ -1,2 +0,2 @@

import { base64urlToBytes, bytesToBase64url, encodeBase64url, decodeBase64url, toSealed } from './util'
import { base64ToBytes, bytesToBase64url, decodeBase64url, toSealed } from './util'

@@ -114,3 +114,3 @@ interface RecipientHeader {

if (protHeader.alg === 'dir' && decrypter.alg === 'dir') {
cleartext = await decrypter.decrypt(sealed, base64urlToBytes(jwe.iv), aad)
cleartext = await decrypter.decrypt(sealed, base64ToBytes(jwe.iv), aad)
} else if (!jwe.recipients || jwe.recipients.length === 0) {

@@ -123,3 +123,3 @@ throw new Error('Invalid JWE')

if (recipient.header.alg === decrypter.alg) {
cleartext = await decrypter.decrypt(sealed, base64urlToBytes(jwe.iv), aad, recipient)
cleartext = await decrypter.decrypt(sealed, base64ToBytes(jwe.iv), aad, recipient)
}

@@ -126,0 +126,0 @@ }

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

export type Signer = (data: string) => Promise<EcdsaSignature | string>
export type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string>
export type SignerAlgorithm = (payload: string, signer: Signer) => Promise<string>

@@ -13,2 +13,5 @@

signer: Signer
/**
* @deprecated Please use `header.alg` to specify the JWT algorithm.
*/
alg?: string

@@ -143,7 +146,7 @@ expiresIn?: number

* @example
* const signer = SimpleSigner(process.env.PRIVATE_KEY)
* const signer = ES256KSigner(process.env.PRIVATE_KEY)
* const jws = await createJWS({ my: 'payload' }, signer)
*
* @param {Object} payload payload object
* @param {SimpleSigner} signer a signer, reference our SimpleSigner.js
* @param {Signer} signer a signer, see `ES256KSigner or `EdDSASigner`
* @param {Object} header optional object to specify or customize the JWS header

@@ -170,3 +173,3 @@ * @return {Promise<Object, Error>} a promise which resolves with a JWS string or rejects with an error

* @example
* const signer = SimpleSigner(process.env.PRIVATE_KEY)
* const signer = ES256KSigner(process.env.PRIVATE_KEY)
* createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {

@@ -177,7 +180,7 @@ * ...

* @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], Defaults to: ES256K.
* Please use `header.alg` to specify the algorithm
* @param {SimpleSigner} options.signer a signer, reference our SimpleSigner.js
* @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

@@ -330,3 +333,3 @@ * @return {Promise<Object, Error>} a promise which resolves with a signed JSON Web Token or rejects with an error

let getPublicKeyById = (doc: DIDDocument, pubid: string): PublicKey | null => {
const getPublicKeyById = (doc: DIDDocument, pubid: string): PublicKey | null => {
const filtered = doc.publicKey.filter(({ id }) => pubid === id)

@@ -333,0 +336,0 @@ return filtered.length > 0 ? filtered[0] : null

import { Signer, SignerAlgorithm } from './JWT'
import { EcdsaSignature, toJose } from './util'
import { EcdsaSignature, fromJose, toJose } from './util'

@@ -8,3 +8,3 @@ function instanceOfEcdsaSignature(object: any): object is EcdsaSignature {

export function ES256KSigner(recoverable?: boolean): SignerAlgorithm {
export function ES256KSignerAlg(recoverable?: boolean): SignerAlgorithm {
return async function sign(payload: string, signer: Signer): Promise<string> {

@@ -15,3 +15,3 @@ const signature: EcdsaSignature | string = await signer(payload)

} else {
if (recoverable) throw new Error('ES256K-R not supported when signer function returns string')
if (recoverable && typeof fromJose(signature).recoveryParam === 'undefined') throw new Error(`ES256K-R not supported when signer doesn't provide a recovery param`)
return signature

@@ -22,3 +22,3 @@ }

export function Ed25519Signer(): SignerAlgorithm {
export function Ed25519SignerAlg(): SignerAlgorithm {
return async function sign(payload: string, signer: Signer): Promise<string> {

@@ -39,8 +39,10 @@ const signature: EcdsaSignature | string = await signer(payload)

const algorithms: SignerAlgorithms = {
ES256K: ES256KSigner(),
'ES256K-R': ES256KSigner(true),
ES256K: ES256KSignerAlg(),
// This is a non-standard algorithm but retained for backwards compatibility
// see https://github.com/decentralized-identity/did-jwt/issues/146
'ES256K-R': ES256KSignerAlg(true),
// This is actually incorrect but retained for backwards compatibility
// see https://github.com/decentralized-identity/did-jwt/issues/130
Ed25519: Ed25519Signer(),
EdDSA: Ed25519Signer()
Ed25519: Ed25519SignerAlg(),
EdDSA: Ed25519SignerAlg()
}

@@ -47,0 +49,0 @@

import * as u8a from 'uint8arrays'
/**
* @deprecated Signers will be expected to return base64url `string` signatures.
*/
export interface EcdsaSignature {

@@ -13,8 +16,5 @@ r: string

export function base64urlToBytes(s: string): Uint8Array {
return u8a.fromString(s, 'base64url')
}
export function base64ToBytes(s: string): Uint8Array {
return u8a.fromString(s, 'base64pad')
const inputBase64Url = s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
return u8a.fromString(inputBase64Url, 'base64url')
}

@@ -31,3 +31,4 @@

export function hexToBytes(s: string): Uint8Array {
return u8a.fromString(s, 'base16')
const input = s.startsWith('0x') ? s.substring(2) : s
return u8a.fromString(input.toLowerCase(), 'base16')
}

@@ -40,3 +41,3 @@

export function decodeBase64url(s: string): string {
return u8a.toString(base64urlToBytes(s))
return u8a.toString(base64ToBytes(s))
}

@@ -65,4 +66,50 @@

export function fromJose(signature: string): { r: string; s: string; recoveryParam: number } {
const signatureBytes: Uint8Array = base64ToBytes(signature)
if (signatureBytes.length < 64 || signatureBytes.length > 65) {
throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}`)
}
const r = bytesToHex(signatureBytes.slice(0, 32))
const s = bytesToHex(signatureBytes.slice(32, 64))
const recoveryParam = signatureBytes.length === 65 ? signatureBytes[64] : undefined
return { r, s, recoveryParam }
}
export function toSealed(ciphertext: string, tag: string): Uint8Array {
return u8a.concat([base64urlToBytes(ciphertext), base64urlToBytes(tag)])
return u8a.concat([base64ToBytes(ciphertext), base64ToBytes(tag)])
}
const hexMatcher = /^(0x)?([a-fA-F0-9]{64}|[a-fA-F0-9]{128})$/
const base58Matcher = /^([1-9A-HJ-NP-Za-km-z]{44}|[1-9A-HJ-NP-Za-km-z]{88})$/
const base64Matcher = /^([0-9a-zA-Z=\-_\+\/]{43}|[0-9a-zA-Z=\-_\+\/]{86})(={0,2})$/
/**
* Parses a private key and returns the Uint8Array representation.
* This method uses an heuristic to determine the key encoding to then be able to parse it into 32 or 64 bytes.
*
* @param input a 32 or 64 byte key presented either as a Uint8Array or as a hex, base64, or base58btc encoded string
*
* @throws TypeError('Invalid private key format') if the key doesn't match any of the accepted formats or length
*/
export function parseKey(input: string | Uint8Array): Uint8Array {
if (typeof input === 'string') {
if (hexMatcher.test(input)) {
return hexToBytes(input)
} else if (base58Matcher.test(input)) {
return base58ToBytes(input)
} else if (base64Matcher.test(input)) {
return base64ToBytes(input)
} else {
throw TypeError('Invalid private key format')
}
} else if (input instanceof Uint8Array) {
return input
} else {
throw TypeError('Invalid private key format')
}
}
export function leftpad(data: string, size = 64): string {
if (data.length === size) return data
return '0'.repeat(size - data.length) + data
}

@@ -5,3 +5,3 @@ import { ec as EC } from 'elliptic'

import { PublicKey } from 'did-resolver'
import { hexToBytes, base58ToBytes, base64ToBytes, base64urlToBytes, bytesToHex, EcdsaSignature, stringToBytes } from './util'
import { hexToBytes, base58ToBytes, base64ToBytes, bytesToHex, EcdsaSignature, stringToBytes } from './util'

@@ -12,3 +12,3 @@ const secp256k1 = new EC('secp256k1')

export function toSignatureObject(signature: string, recoverable = false): EcdsaSignature {
const rawsig: Uint8Array = base64urlToBytes(signature)
const rawsig: Uint8Array = base64ToBytes(signature)
if (rawsig.length !== (recoverable ? 65 : 64)) {

@@ -101,3 +101,3 @@ throw new Error('wrong signature length')

const clear: Uint8Array = stringToBytes(data)
const sig: Uint8Array = base64urlToBytes(signature)
const sig: Uint8Array = base64ToBytes(signature)
const signer: PublicKey = authenticators.find((pk: PublicKey) => {

@@ -117,2 +117,4 @@ return verify(extractPublicKeyBytes(pk), clear, sig)

ES256K: verifyES256K,
// This is a non-standard algorithm but retained for backwards compatibility
// see https://github.com/decentralized-identity/did-jwt/issues/146
'ES256K-R': verifyRecoverableES256K,

@@ -119,0 +121,0 @@ // This is actually incorrect but retained for backwards compatibility

@@ -5,3 +5,3 @@ import { XChaCha20Poly1305 } from '@stablelib/xchacha20poly1305'

import { concatKDF } from './Digest'
import { base64urlToBytes, bytesToBase64url, base58ToBytes, encodeBase64url, toSealed } from './util'
import { bytesToBase64url, base58ToBytes, encodeBase64url, toSealed, base64ToBytes } from './util'
import { Recipient, EncryptionResult, Encrypter, Decrypter } from './JWE'

@@ -119,3 +119,3 @@ import type { PublicKey, Resolver } from 'did-resolver'

if (recipient.header.epk.crv !== crv) return null
const publicKey = base64urlToBytes(recipient.header.epk.x)
const publicKey = base64ToBytes(recipient.header.epk.x)
const sharedSecret = sharedKey(secretKey, publicKey)

@@ -127,3 +127,3 @@

const sealedCek = toSealed(recipient.encrypted_key, recipient.header.tag)
const cek = await xc20pDirDecrypter(kek).decrypt(sealedCek, base64urlToBytes(recipient.header.iv))
const cek = await xc20pDirDecrypter(kek).decrypt(sealedCek, base64ToBytes(recipient.header.iv))
if (cek === null) return null

@@ -130,0 +130,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

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc