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 5.4.1 to 5.5.0

7

CHANGELOG.md

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

# [5.5.0](https://github.com/decentralized-identity/did-jwt/compare/5.4.1...5.5.0) (2021-05-31)
### Features
* Add support for authenticated encryption ([#177](https://github.com/decentralized-identity/did-jwt/issues/177)) ([9a71b07](https://github.com/decentralized-identity/did-jwt/commit/9a71b077b2f0f6ad548e60e3e0222a3bfaa6a404))
## [5.4.1](https://github.com/decentralized-identity/did-jwt/compare/5.4.0...5.4.1) (2021-05-19)

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

2

lib/Digest.d.ts
export declare function sha256(payload: string | Uint8Array): Uint8Array;
export declare function keccak(data: Uint8Array): Uint8Array;
export declare function toEthereumAddress(hexPublicKey: string): string;
export declare function concatKDF(secret: Uint8Array, keyLen: number, alg: string): Uint8Array;
export declare function concatKDF(secret: Uint8Array, keyLen: number, alg: string, producerInfo?: Uint8Array, consumerInfo?: Uint8Array): Uint8Array;
//# sourceMappingURL=Digest.d.ts.map

@@ -9,4 +9,4 @@ import SimpleSigner from './signers/SimpleSigner';

export { JWE, createJWE, decryptJWE, Encrypter, Decrypter } from './JWE';
export { xc20pDirEncrypter, xc20pDirDecrypter, x25519Encrypter, x25519Decrypter, resolveX25519Encrypters } from './xc20pEncryption';
export { xc20pDirEncrypter, xc20pDirDecrypter, x25519Encrypter, x25519Decrypter, resolveX25519Encrypters, createAuthEncrypter, createAnonEncrypter, createAuthDecrypter, createAnonDecrypter, xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2, xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2 } from './xc20pEncryption';
export { SimpleSigner, EllipticSigner, NaclSigner, ES256KSigner, EdDSASigner, verifyJWT, createJWT, decodeJWT, verifyJWS, createJWS, toEthereumAddress, Signer, JWTHeader, JWTPayload, JWTVerified };
//# sourceMappingURL=index.d.ts.map

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

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

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

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

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

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

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

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

@@ -7,2 +7,4 @@ interface RecipientHeader {

kid?: string;
apv?: string;
apu?: string;
}

@@ -9,0 +11,0 @@ export interface Recipient {

import { Encrypter, Decrypter } from './JWE';
import type { Resolvable } from 'did-resolver';
export declare type AuthEncryptParams = {
kid?: string;
skid?: string;
apu?: string;
apv?: string;
};
export declare type AnonEncryptParams = {
kid?: string;
};
/**
* Recommended encrypter for authenticated encryption (i.e. sender authentication and requires
* sender private key to encrypt the data).
* Uses ECDH-1PU [v3](https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03) and
* XC20PKW [v2](https://tools.ietf.org/html/draft-amringer-jose-chacha-02).
*
* NOTE: ECDH-1PU and XC20PKW are proposed drafts in IETF and not a standard yet and
* are subject to change as new revisions or until the offical CFRG specification are released.
*/
export declare function createAuthEncrypter(recipientPublicKey: Uint8Array, senderSecretKey: Uint8Array, options?: Partial<AuthEncryptParams>): Encrypter;
/**
* Recommended encrypter for anonymous encryption (i.e. no sender authentication).
* Uses ECDH-ES+XC20PKW [v2](https://tools.ietf.org/html/draft-amringer-jose-chacha-02).
*
* NOTE: ECDH-ES+XC20PKW is a proposed draft in IETF and not a standard yet and
* is subject to change as new revisions or until the offical CFRG specification is released.
*/
export declare function createAnonEncrypter(publicKey: Uint8Array, options?: Partial<AnonEncryptParams>): Encrypter;
/**
* Recommended decrypter for authenticated encryption (i.e. sender authentication and requires
* sender public key to decrypt the data).
* Uses ECDH-1PU [v3](https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03) and
* XC20PKW [v2](https://tools.ietf.org/html/draft-amringer-jose-chacha-02).
*
* NOTE: ECDH-1PU and XC20PKW are proposed drafts in IETF and not a standard yet and
* are subject to change as new revisions or until the offical CFRG specification are released.
*/
export declare function createAuthDecrypter(recipientSecretKey: Uint8Array, senderPublicKey: Uint8Array): Decrypter;
/**
* Recommended decrypter for anonymous encryption (i.e. no sender authentication).
* Uses ECDH-ES+XC20PKW [v2](https://tools.ietf.org/html/draft-amringer-jose-chacha-02).
*
* NOTE: ECDH-ES+XC20PKW is a proposed draft in IETF and not a standard yet and
* is subject to change as new revisions or until the offical CFRG specification is released.
*/
export declare function createAnonDecrypter(secretKey: Uint8Array): Decrypter;
export declare function xc20pDirEncrypter(key: Uint8Array): Encrypter;
export declare function xc20pDirDecrypter(key: Uint8Array): Decrypter;
export declare function x25519Encrypter(publicKey: Uint8Array, kid?: string): Encrypter;
/**
* Implements ECDH-1PU+XC20PKW with XChaCha20Poly1305 based on the following specs:
* - [XC20PKW](https://tools.ietf.org/html/draft-amringer-jose-chacha-02)
* - [ECDH-1PU](https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03)
*/
export declare function xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(recipientPublicKey: Uint8Array, senderSecretKey: Uint8Array, options?: Partial<AuthEncryptParams>): Encrypter;
export declare function resolveX25519Encrypters(dids: string[], resolver: Resolvable): Promise<Encrypter[]>;
export declare function x25519Decrypter(secretKey: Uint8Array): Decrypter;
/**
* Implements ECDH-1PU+XC20PKW with XChaCha20Poly1305 based on the following specs:
* - [XC20PKW](https://tools.ietf.org/html/draft-amringer-jose-chacha-02)
* - [ECDH-1PU](https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03)
*/
export declare function xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2(recipientSecretKey: Uint8Array, senderPublicKey: Uint8Array): Decrypter;
//# sourceMappingURL=xc20pEncryption.d.ts.map
{
"name": "did-jwt",
"version": "5.4.1",
"version": "5.5.0",
"description": "Library for Signing and Verifying JWTs compatible uPort and DID standards",

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

"codecov": "3.8.2",
"eslint": "7.26.0",
"eslint-config-standard": "16.0.2",
"eslint-plugin-import": "2.23.2",
"eslint": "7.27.0",
"eslint-config-standard": "16.0.3",
"eslint-plugin-import": "2.23.4",
"eslint-plugin-jest": "24.3.6",

@@ -68,5 +68,5 @@ "eslint-plugin-node": "11.1.0",

"eslint-plugin-standard": "5.0.0",
"jest": "26.6.3",
"jest": "27.0.3",
"jsontokens": "3.0.0",
"microbundle": "0.13.0",
"microbundle": "0.13.1",
"mockdate": "3.0.5",

@@ -76,5 +76,5 @@ "prettier": "2.3.0",

"semantic-release": "17.4.3",
"sinon": "10.0.0",
"sinon": "11.1.1",
"standard": "16.0.3",
"ts-jest": "26.5.6",
"ts-jest": "27.0.1",
"tslint": "6.1.3",

@@ -84,4 +84,4 @@ "tslint-config-prettier": "1.18.0",

"tweetnacl": "1.0.3",
"typescript": "4.2.4",
"webpack": "5.37.0",
"typescript": "4.3.2",
"webpack": "5.38.1",
"webpack-cli": "4.7.0"

@@ -88,0 +88,0 @@ },

@@ -34,4 +34,3 @@ import VerifierAlgorithm from '../VerifierAlgorithm'

{
id:
'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM#z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM',
id: 'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM#z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM',
type: 'Ed25519VerificationKey2018',

@@ -38,0 +37,0 @@ controller: 'did:key:z6MkoTHsgNNrby8JzCNQ1iRLyW5QQ6R8Xuu6AA8igGrMVPUM',

@@ -142,3 +142,102 @@ /* eslint-disable */

]
}
},
ecdh1PuV3Xc20PkwV2: {
pass: [
{
senderkey: 'Ga6k9NGzLLbyz4uDF/25rmxL6kcMpIUfAB6q4jyErEI=',
recipientkeys: [ 'eGftJuIHIOQ4pIhpdHGgqJAYGvNRQyL1UgbuHCJKrlw=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJlbmMiOiJYQzIwUCJ9","iv":"tqp15TShA-eDERy2qEgCLmDl1QJSDZ4j","ciphertext":"5jPbpy_tj3FVszRzrEHwc6J0o-KluNSa56zyN3D7EHiJ_hgQDwUN8B-U1AJ_1uaBuPBmV0e-zAE4iX9ils_POcvwdpEB0LVnJ6QPYoOdbMx94uLb6pd6xw","tag":"QAdzJ4M8bSqvvuYY9-H_tw","recipients":[{"encrypted_key":"R8CAGP5rj3IZsKHWnSKrb_Z5iFwtLvDIn_WqO3pIko0","header":{"alg":"ECDH-1PU+XC20PKW","iv":"uedotKy0c6EhJMrWZC8r4_60n-vqUdAK","tag":"BImFz89iFXrhX_OmwqZRPA","epk":{"kty":"OKP","crv":"X25519","x":"ZHdwr-bpjEIYvvmcVyTT-UvjJS1DxUOLMNo5CxjcQns"},"enc":"XC20P"}}]}
},
{
senderkey: '4pJFgMDsu0JqjFT9l2NnFv+/Q/1qUP9dzt0lFdu1+00=',
recipientkeys: [ 'G7MtaOo6BMsi8VoEgu4DEJmfgl088DIHLm6BbMFNnMk=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJza2lkIjoiZGlkOmV4YW1wbGU6c2VuZGVyI2tleS0xIiwiZW5jIjoiWEMyMFAifQ","iv":"4wcrBHUEBhhi1jYQWeGXzFSmf013CWjE","ciphertext":"nCCKJTjHI8IzNNC7OoCrKtXhkqzYUp2EeBkcSDy6rn4Z0oDc1-GAfJumQw83MO3aNKxEkF_iFEZiE6dlZKmvX5o9VDMk-pG8dd9gTlBS8Jx5V7GIotATkg","tag":"1U7BeQvvkGrK5idhUrwxOw","recipients":[{"encrypted_key":"2o2Ponu58YToFT1fi4jh6XADnLZK_2HV629zPB39FmY","header":{"alg":"ECDH-1PU+XC20PKW","iv":"DFTIc_GxomeBBNW0Ne5pYarqCFpCNEAQ","tag":"eGtKwjevonz39if11DIe3g","epk":{"kty":"OKP","crv":"X25519","x":"an9B9-jgsR53lrLIRVdgd2_AOglxnFv6JFmHhiBXniw"},"kid":"did:example:receiver#key-1","skid":"did:example:sender#key-1","enc":"XC20P"}}]}
},
{
senderkey: 'o9+nnB/a7L7OaHpDKV3ZNqO8kMxN87bTfc3PPHwdmAY=',
recipientkeys: [ 'aHCSf53GyAsi2NEPN7jSJCiBNPI6caFZSnTsARA2/JU=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJlbmMiOiJYQzIwUCJ9","iv":"Mv2AaWtIV9xKPkR0Z4YWwHbPWNYfkQUm","ciphertext":"bO4O_N4LDn0LXovMFr-YUIguYAOgRwEilWikeehEigMlHuRMhk9gXAxzgEXOVR3EeAY0rOiJBs3kM0lXbkibbq5jD7dkoTO8d4f9VwJTvjh1n5T7dIS_4g","tag":"Fp4irT84Ry261664HeDixQ","recipients":[{"encrypted_key":"xm_rMaWJbyi5d1Hy3DvGc-ShjBMmtBLBaBrgYbjbqqs","header":{"alg":"ECDH-1PU+XC20PKW","iv":"CfJBZwkmufgbkhH5RMmAGmnAO7_TeiEy","tag":"U1ffVZr8hhnAgJKmr9tgzA","epk":{"kty":"OKP","crv":"X25519","x":"ZtKE_n4apf8xJxPfrk_22fHeYz1oMVV-9Ilsjkt9GWQ"},"apu":"QWxpY2U","apv":"Qm9i","enc":"XC20P"}}]}
},
{
senderkey: 'gEBhMCE0zlLPTPY6TW/X1nFC+6Gn22KSuqdj8xuMDC8=',
recipientkeys: [ 'TnDUuo7hbVWYw/49HjZfWGDnDGZ/6tRdvwina0kYGwM=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJza2lkIjoiZGlkOmV4YW1wbGU6c2VuZGVyI2tleS0xIiwiZW5jIjoiWEMyMFAifQ","iv":"MDK1vppdO1fBhnWYBw5Vcj7OzXFoWLI6","ciphertext":"6orRa7wBlgRKsyaTxbHSEzphYRH_1HwC5FDJDsuBQ7Fv7XwAJ12gvkxSKx4HvFNRgcgsODmdjYGyQQFnkqswFyZwyNylYpJyh5bAaqV61Z7R79kYHuMRVg","tag":"NHflobCWt6lplerL8dj36w","recipients":[{"encrypted_key":"7swx_oZVz5Zwv1nfHx1ls8ZFaK2w-U-SbKN425GLrKQ","header":{"alg":"ECDH-1PU+XC20PKW","iv":"CgpZBwuh4UQMiE_ESRBdH7V9X4ZEo7cf","tag":"jm6l1jIaI8mOEn_wzTXHTQ","epk":{"kty":"OKP","crv":"X25519","x":"SGslzCO9UZ7p4jU3_jqgu-bHh7ojq0RxR3rswAhcvGo"},"kid":"did:example:receiver#key-1","apu":"QWxpY2U","apv":"Qm9i","skid":"did:example:sender#key-1","enc":"XC20P"}}]}
},
{
senderkey: 'winSRtxUQasfBLcd8HPmF85kS6HMa0RLRtA8PblTsFc=',
recipientkeys: [ '2EITYEbrM3CtbggjtIWb+XR1nXn33ak2f8x5U0+tUs8=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJtb3JlIjoicHJvdGVjdGVkIiwiZW5jIjoiWEMyMFAifQ","iv":"0AgTZOUg3yw0wayLySRVij8I7bDxQ0oZ","ciphertext":"3fYjaPgzawEdGbRir1dPzhTKNTtGlUvSkEFsW7wA3fpBrwN5qx3K_jyeixKkotOvn7kCG-NTgGAJ77ValW1Cl2X3fbb84YkYd1-UYr_qdBO_7-UELu145Q","tag":"H9h1pnOyWBpHUf76vnNobA","recipients":[{"encrypted_key":"mGqF1GmWGTzTQ1dtEHYuib1PEJs9bnezJBC0Qdw4Ih0","header":{"alg":"ECDH-1PU+XC20PKW","iv":"kQ9GZb3X3BGbf5KajtR7GhpW2Jneo1yp","tag":"cKZ6ilsGPmmA2X9rO3wOBQ","epk":{"kty":"OKP","crv":"X25519","x":"JhZV5gNSZ9LxoqKZ1tfkFUoisdqTUPpZXPThe-7pVnI"},"more":"protected","enc":"XC20P"}}]}
},
{
senderkey: 'Jec1EkYpuvVj2vKXIyMjSo2JS7KXwMA1rvVGj7umYlw=',
recipientkeys: [ 'L16P46IUqXyxbdG3vxq0HqwzBbMwkVU9/SKjRy7Nubo=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJtb3JlIjoicHJvdGVjdGVkIiwiZW5jIjoiWEMyMFAifQ","iv":"HtAxWrZXeFYQqhTX3VvTaPoo_iW78xhZ","ciphertext":"CPlGjk7prypqISuF0bMNgemNTG2JCLBrZbmsIAFBpqyUsJR9ZR6QA1osOb-ENZGqzem-TQvd8hn1EWtQiDBN_Sg8vt41GAfBvP3jYTxSvOMO4co2SZ864Q","tag":"6lvid-vUJHIIrTTdqtZWjQ","aad":"dGhpcyBkYXRhIGlzIGF1dGhlbnRpY2F0ZWQ","recipients":[{"encrypted_key":"-gFoPiUt1Ooqm6OfBxCS7zPntO_H13-a4fRah7OXNU4","header":{"alg":"ECDH-1PU+XC20PKW","iv":"WqVUpQgsjdkLeJ_9h3_cGq5F9bA49r84","tag":"OjXw26fPv6YYx0BAGK4r0w","epk":{"kty":"OKP","crv":"X25519","x":"yO4REF7yeuojtAgO7Zv4aBlopDhoId6RdKm4ByPYVG4"},"more":"protected","enc":"XC20P"}}]}
},
{
senderkey: 's1mmgl42lUYs/m9NFcZXsrejKxpu0wpmExmskyXWsUQ=',
recipientkeys: [ 'OG/mkqO2noX0/7E0I+HTHGMTpYxbPLG8X9ak7ADGOtY=', '0I452d/J7+xl5OB/4ZGXoRPKBwpJdvd7E20SGLy9IAQ=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJza2lkIjoiZGlkOmV4YW1wbGU6c2VuZGVyI2tleS0xIiwiZW5jIjoiWEMyMFAifQ","iv":"Hzl9pqbvncH10U6MFRpOZ7xyYqZTJkP_","ciphertext":"wvHImSFeFG6NpCEfpoAVe-DT8YgFPHt0dyPIS3nP3t6wY8A2GWf3z9-uzgX0ZVNr73_d0M_rhnPnBzlBiocsXrq7HLuBBucHoM2bC3NX2W_PoOoUHcf3zw","tag":"vDIWnftTdrkrHjiireD4aw","recipients":[{"encrypted_key":"DJYCzKQcf5heWMeOIcgVvCY99GVRMAcsrXsuElKK54s","header":{"alg":"ECDH-1PU+XC20PKW","iv":"XdcU-TJ2ZflgIDmQBJUDyDvHSCKdZpur","tag":"lGHm5Iofs-RZaGp3N4z0dQ","epk":{"kty":"OKP","crv":"X25519","x":"ZKI_CUgkKm2BSGZl61wCU8C94eiJMBYLZqZzFDTTJy4"},"kid":"did:example:receiver1#key-1","skid":"did:example:sender#key-1","enc":"XC20P"}},{"encrypted_key":"6hTnZ6Lw1PUtWXISFMTqI8BmQ9TQo3svwiC5CI8dhcg","header":{"alg":"ECDH-1PU+XC20PKW","iv":"ZgGZNiv_Zcm-dnoNl3keXAXMPO-ZSuAb","tag":"-zU7jiF-tNWdI7oDVzk52Q","epk":{"kty":"OKP","crv":"X25519","x":"oP9HpmTjYJpDvK1TJN0u9bZH70E7RLRVsx47-5zosUk"},"kid":"did:example:receiver2#key-1","skid":"did:example:sender#key-1","enc":"XC20P"}}]}
},
{
senderkey: 'L9q9/9Ja+sRXsgtaoJu4BKsU4tPShkD43q2q/J6QhS8=',
recipientkeys: [ 'NDj9lf1KGYV62+suEaV7eM9Jyf52IcNOgfk/gq2ZM88=', 'FjYBTXCaNXqOafuznKOiDsdza6seF6O1THL/aaOCoQ0=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJtb3JlIjoicHJvdGVjdGVkIiwic2tpZCI6ImRpZDpleGFtcGxlOnNlbmRlciNrZXktMSIsImVuYyI6IlhDMjBQIn0","iv":"BN5rEL2D8n6O4X5qFVD1NgspGtKABgXR","ciphertext":"lNbDB1MsqC654o5vuV2NlYjXp26WgPcYMWxU2xx1lTIuK1V3loF3vrRG7gItxWQp3KHJL4TZVYcGd29hFkB_Aw4JIp2t1-sLtjPsvs7P9hf0I-60Em3pFA","tag":"U2gFdvyJgTbhnt3WxIZv6A","recipients":[{"encrypted_key":"GoUONl8e-5lkG9nl4xgCmyGCJG6cR3l-PsTpWFAJ2-4","header":{"alg":"ECDH-1PU+XC20PKW","iv":"QHMSdRjuHQamlyiDG11xdI6ZRbMXxrd1","tag":"F7N6Gr_3kbS5uscGgrNEkg","epk":{"kty":"OKP","crv":"X25519","x":"4__NuoaZRG124GpJYReph2VsYSRYELNYiLIf6hXtVXQ"},"kid":"did:example:receiver1#key-1","more":"protected","skid":"did:example:sender#key-1","enc":"XC20P"}},{"encrypted_key":"H2GfRVKHOwdEsmvSoZWu7jP1Y--kwh3nKYMUtBiQzM8","header":{"alg":"ECDH-1PU+XC20PKW","iv":"gTF_tpp8FIOKqGItFwilpOhEhOErqa9j","tag":"mKP5Ey4c0CEt6R0inWhuRA","epk":{"kty":"OKP","crv":"X25519","x":"BGB0V4X_XJLVV5fXM-CbGyF6x7EQh4fWE6NxdAueXSE"},"kid":"did:example:receiver2#key-1"}}]}
},
{
senderkey: 'DMk0fWkt2Y8Y717xbUps8o+g9vXgqhIvUzG22u3YoVQ=',
recipientkeys: [ 'aK2tDSxuQB3wE0+pW2xhez+jd2Nlnlsn40TfmG/290A=', 'MBJmtMzmfH86xjiuFZ7yObzhUlWZyTSkXgNvClB7Nz8=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJtb3JlIjoicHJvdGVjdGVkIiwic2tpZCI6ImRpZDpleGFtcGxlOnNlbmRlciNrZXktMSIsImVuYyI6IlhDMjBQIn0","iv":"WEAjww6hpVW-q0qOHDtEEN-AwWVEkHgf","ciphertext":"OuSj8p9DJ2O4cOXRWHi3bLQbnsTRNuSKjgAr5ig1AcsXRj0olOOEK-gb5Qs7sNREUUBqUyK9SC2_cW2JD5BC-MKal08eriN7N2e-m5SS9OOIsZiyGtnI-A","tag":"MHAFgLIHcNS-m42OiVvNwQ","aad":"dGhpcyBkYXRhIGlzIGF1dGhlbnRpY2F0ZWQ","recipients":[{"encrypted_key":"puuKXBUXSBlRZCICaQnG-OLX_F_-GVE4lESLqZ4QDTk","header":{"alg":"ECDH-1PU+XC20PKW","iv":"zZqI4m9XO-aA6u2EVEZUGJexnMuSnxC4","tag":"HDZdndyMdRf77I2IO-zUow","epk":{"kty":"OKP","crv":"X25519","x":"KZfzLUZMwvlc7mItQyx0F9b1caC0SxiGuNemmYQ8nF8"},"kid":"did:example:receiver1#key-1","more":"protected","skid":"did:example:sender#key-1","enc":"XC20P"}},{"encrypted_key":"X85SlJ6WEJv4TFTxn2SYH1w0fEKH_HkI_oZZaK_VglE","header":{"alg":"ECDH-1PU+XC20PKW","iv":"HtBD10hnvYwqFB7BcHe9PPrOAV4qybHZ","tag":"p0ySr_KDlUWRAwSwE2ifNQ","epk":{"kty":"OKP","crv":"X25519","x":"zAkbzcZYPveVuE5nEiNGq4bN8Ja3ImJG_BI0UkTs_ys"},"kid":"did:example:receiver2#key-1","more":"protected","skid":"did:example:sender#key-1","enc":"XC20P"}}]}
}
],
fail: [
{
// wrong sender key
senderkey: 'DMk0fWkt2Y8Y717xbUps8o+g9vXgqhIvUzG22u3YoVQ=',
recipientkeys: [ 'eGftJuIHIOQ4pIhpdHGgqJAYGvNRQyL1UgbuHCJKrlw=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJlbmMiOiJYQzIwUCJ9","iv":"tqp15TShA-eDERy2qEgCLmDl1QJSDZ4j","ciphertext":"5jPbpy_tj3FVszRzrEHwc6J0o-KluNSa56zyN3D7EHiJ_hgQDwUN8B-U1AJ_1uaBuPBmV0e-zAE4iX9ils_POcvwdpEB0LVnJ6QPYoOdbMx94uLb6pd6xw","tag":"QAdzJ4M8bSqvvuYY9-H_tw","recipients":[{"encrypted_key":"R8CAGP5rj3IZsKHWnSKrb_Z5iFwtLvDIn_WqO3pIko0","header":{"alg":"ECDH-1PU+XC20PKW","iv":"uedotKy0c6EhJMrWZC8r4_60n-vqUdAK","tag":"BImFz89iFXrhX_OmwqZRPA","epk":{"kty":"OKP","crv":"X25519","x":"ZHdwr-bpjEIYvvmcVyTT-UvjJS1DxUOLMNo5CxjcQns"},"enc":"XC20P"}}]}
},
{
// wrong recipient keys
senderkey: 'Ga6k9NGzLLbyz4uDF/25rmxL6kcMpIUfAB6q4jyErEI=',
recipientkeys: [ 'aK2tDSxuQB3wE0+pW2xhez+jd2Nlnlsn40TfmG/290A=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJlbmMiOiJYQzIwUCJ9","iv":"tqp15TShA-eDERy2qEgCLmDl1QJSDZ4j","ciphertext":"5jPbpy_tj3FVszRzrEHwc6J0o-KluNSa56zyN3D7EHiJ_hgQDwUN8B-U1AJ_1uaBuPBmV0e-zAE4iX9ils_POcvwdpEB0LVnJ6QPYoOdbMx94uLb6pd6xw","tag":"QAdzJ4M8bSqvvuYY9-H_tw","recipients":[{"encrypted_key":"R8CAGP5rj3IZsKHWnSKrb_Z5iFwtLvDIn_WqO3pIko0","header":{"alg":"ECDH-1PU+XC20PKW","iv":"uedotKy0c6EhJMrWZC8r4_60n-vqUdAK","tag":"BImFz89iFXrhX_OmwqZRPA","epk":{"kty":"OKP","crv":"X25519","x":"ZHdwr-bpjEIYvvmcVyTT-UvjJS1DxUOLMNo5CxjcQns"},"enc":"XC20P"}}]}
},
{
// wrong sender key
senderkey: 'DMk0fWkt2Y8Y717xbUps8o+g9vXgqhIvUzG22u3YoVQ=',
recipientkeys: [ 'OG/mkqO2noX0/7E0I+HTHGMTpYxbPLG8X9ak7ADGOtY=', '0I452d/J7+xl5OB/4ZGXoRPKBwpJdvd7E20SGLy9IAQ=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJza2lkIjoiZGlkOmV4YW1wbGU6c2VuZGVyI2tleS0xIiwiZW5jIjoiWEMyMFAifQ","iv":"Hzl9pqbvncH10U6MFRpOZ7xyYqZTJkP_","ciphertext":"wvHImSFeFG6NpCEfpoAVe-DT8YgFPHt0dyPIS3nP3t6wY8A2GWf3z9-uzgX0ZVNr73_d0M_rhnPnBzlBiocsXrq7HLuBBucHoM2bC3NX2W_PoOoUHcf3zw","tag":"vDIWnftTdrkrHjiireD4aw","recipients":[{"encrypted_key":"DJYCzKQcf5heWMeOIcgVvCY99GVRMAcsrXsuElKK54s","header":{"alg":"ECDH-1PU+XC20PKW","iv":"XdcU-TJ2ZflgIDmQBJUDyDvHSCKdZpur","tag":"lGHm5Iofs-RZaGp3N4z0dQ","epk":{"kty":"OKP","crv":"X25519","x":"ZKI_CUgkKm2BSGZl61wCU8C94eiJMBYLZqZzFDTTJy4"},"kid":"did:example:receiver1#key-1","skid":"did:example:sender#key-1","enc":"XC20P"}},{"encrypted_key":"6hTnZ6Lw1PUtWXISFMTqI8BmQ9TQo3svwiC5CI8dhcg","header":{"alg":"ECDH-1PU+XC20PKW","iv":"ZgGZNiv_Zcm-dnoNl3keXAXMPO-ZSuAb","tag":"-zU7jiF-tNWdI7oDVzk52Q","epk":{"kty":"OKP","crv":"X25519","x":"oP9HpmTjYJpDvK1TJN0u9bZH70E7RLRVsx47-5zosUk"},"kid":"did:example:receiver2#key-1","skid":"did:example:sender#key-1","enc":"XC20P"}}]}
},
{
// wrong recipient keys
senderkey: 's1mmgl42lUYs/m9NFcZXsrejKxpu0wpmExmskyXWsUQ=',
recipientkeys: [ 'aK2tDSxuQB3wE0+pW2xhez+jd2Nlnlsn40TfmG/290A=', 'aK2tDSxuQB3wE0+pW2xhez+jd2Nlnlsn40TfmG/290A=' ],
cleartext: '/GOQlvtSg2V6m9L1IfjPpoyunkmjtvzZX5/gh+lo847Ys3oP+1wd0NmAsCGHiSTB58aAx6PG1+Vi4sXUtRP4kw==',
jwe: {"protected":"eyJza2lkIjoiZGlkOmV4YW1wbGU6c2VuZGVyI2tleS0xIiwiZW5jIjoiWEMyMFAifQ","iv":"Hzl9pqbvncH10U6MFRpOZ7xyYqZTJkP_","ciphertext":"wvHImSFeFG6NpCEfpoAVe-DT8YgFPHt0dyPIS3nP3t6wY8A2GWf3z9-uzgX0ZVNr73_d0M_rhnPnBzlBiocsXrq7HLuBBucHoM2bC3NX2W_PoOoUHcf3zw","tag":"vDIWnftTdrkrHjiireD4aw","recipients":[{"encrypted_key":"DJYCzKQcf5heWMeOIcgVvCY99GVRMAcsrXsuElKK54s","header":{"alg":"ECDH-1PU+XC20PKW","iv":"XdcU-TJ2ZflgIDmQBJUDyDvHSCKdZpur","tag":"lGHm5Iofs-RZaGp3N4z0dQ","epk":{"kty":"OKP","crv":"X25519","x":"ZKI_CUgkKm2BSGZl61wCU8C94eiJMBYLZqZzFDTTJy4"},"kid":"did:example:receiver1#key-1","skid":"did:example:sender#key-1","enc":"XC20P"}},{"encrypted_key":"6hTnZ6Lw1PUtWXISFMTqI8BmQ9TQo3svwiC5CI8dhcg","header":{"alg":"ECDH-1PU+XC20PKW","iv":"ZgGZNiv_Zcm-dnoNl3keXAXMPO-ZSuAb","tag":"-zU7jiF-tNWdI7oDVzk52Q","epk":{"kty":"OKP","crv":"X25519","x":"oP9HpmTjYJpDvK1TJN0u9bZH70E7RLRVsx47-5zosUk"},"kid":"did:example:receiver2#key-1","skid":"did:example:sender#key-1","enc":"XC20P"}}]}
}
],
invalid: [
{
jwe: {"protected":"eyJtb3JlIjoicHJvdGVjdGVkIiwic2tpZCI6ImRpZDpleGFtcGxlOnNlbmRlciNrZXktMSIsImVuYyI6IlhDMjBQIn0","ciphertext":"6DehIR6ps5yh5Mepwj6XluBSk5AS0d18Y27XTWvV5T0uCRtcxBGO1finKBqzgblJA7dPQ55TZuVd41UERiq9FhsPgp7ehR4bBoyHnm8ftnjSHVpyORxLBw","tag":"T2fKAQQgJGFpI0kfpGXFkg","aad":"dGhpcyBkYXRhIGlzIGF1dGhlbnRpY2F0ZWQ","recipients":[{"encrypted_key":"OKUxwt7G1VbLhl0K5yHGkEQe2Ii8CHblLREK304ub6M","header":{"alg":"ECDH-1PU+XC20PKW","iv":"Gnt5p0e8eG012SfLxh-uo9lKs8cYsYGy","tag":"XWZYufnclg_Ei4JsBMpYNA","epk":{"kty":"OKP","crv":"X25519","x":"u7j3sQuuUbDVFoujne22_1b9HcwHkbAUxRsyAmhGz14"},"kid":"did:example:receiver#key-1","apu":"ZGlkOmV4YW1wbGU6c2VuZGVyI2tleS0x","apv":"ZGlkOmV4YW1wbGU6cmVjZWl2ZXIja2V5LTE","more":"protected","skid":"did:example:sender#key-1","enc":"XC20P"}}]}
},
{
jwe: {"protected":"eyJtb3JlIjoicHJvdGVjdGVkIiwic2tpZCI6ImRpZDpleGFtcGxlOnNlbmRlciNrZXktMSIsImVuYyI6IlhDMjBQIn0","iv":"yZakU656sGJS9UKV5zyC1HV7cIhu0MPs","ciphertext":"6DehIR6ps5yh5Mepwj6XluBSk5AS0d18Y27XTWvV5T0uCRtcxBGO1finKBqzgblJA7dPQ55TZuVd41UERiq9FhsPgp7ehR4bBoyHnm8ftnjSHVpyORxLBw","tag":"T2fKAQQgJGFpI0kfpGXFkg","aad":"dGhpcyBkYXRhIGlzIGF1dGhlbnRpY2F0ZWQ","recipients":[]}
},
{
jwe: {"protected":"eyJtb3JlIjoicHJvdGVjdGVkIiwic2tpZCI6ImRpZDpleGFtcGxlOnNlbmRlciNrZXktMSIsImVuYyI6IlhDMjBQIn0","iv":"yZakU656sGJS9UKV5zyC1HV7cIhu0MPs","ciphertext":"6DehIR6ps5yh5Mepwj6XluBSk5AS0d18Y27XTWvV5T0uCRtcxBGO1finKBqzgblJA7dPQ55TZuVd41UERiq9FhsPgp7ehR4bBoyHnm8ftnjSHVpyORxLBw","aad":"dGhpcyBkYXRhIGlzIGF1dGhlbnRpY2F0ZWQ","recipients":[{"encrypted_key":"OKUxwt7G1VbLhl0K5yHGkEQe2Ii8CHblLREK304ub6M","header":{"alg":"ECDH-1PU+XC20PKW","iv":"Gnt5p0e8eG012SfLxh-uo9lKs8cYsYGy","tag":"XWZYufnclg_Ei4JsBMpYNA","epk":{"kty":"OKP","crv":"X25519","x":"u7j3sQuuUbDVFoujne22_1b9HcwHkbAUxRsyAmhGz14"},"kid":"did:example:receiver#key-1","apu":"ZGlkOmV4YW1wbGU6c2VuZGVyI2tleS0x","apv":"ZGlkOmV4YW1wbGU6cmVjZWl2ZXIja2V5LTE","more":"protected","skid":"did:example:sender#key-1","enc":"XC20P"}}]}
}
]
}
}
import { decryptJWE, createJWE, Encrypter } from '../JWE'
import vectors from './jwe-vectors.js'
import { xc20pDirEncrypter, xc20pDirDecrypter, x25519Encrypter, x25519Decrypter } from '../xc20pEncryption'
import { decodeBase64url } from '../util'
import {
xc20pDirEncrypter,
xc20pDirDecrypter,
x25519Encrypter,
x25519Decrypter,
xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2,
xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2
} from '../xc20pEncryption'
import { decodeBase64url, encodeBase64url } from '../util'
import * as u8a from 'uint8arrays'

@@ -52,2 +59,39 @@ import { randomBytes } from '@stablelib/random'

})
describe('ECDH-1PU+XC20PKW (X25519), Key Wrapping Mode with XC20P content encryption', () => {
test.each(vectors.ecdh1PuV3Xc20PkwV2.pass)(
'decrypts valid jwe',
async ({ senderkey, recipientkeys, cleartext, jwe }) => {
expect.assertions(recipientkeys.length)
for (let recipientkey of recipientkeys) {
const decrypter = xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2(
u8a.fromString(recipientkey, 'base64pad'),
u8a.fromString(senderkey, 'base64pad')
)
var cleartextU8a = await decryptJWE(jwe, decrypter)
expect(u8a.toString(cleartextU8a)).toEqual(cleartext)
}
}
)
test.each(vectors.ecdh1PuV3Xc20PkwV2.fail)(
'fails to decrypt bad jwe',
async ({ senderkey, recipientkeys, jwe }) => {
expect.assertions(recipientkeys.length)
for (let recipientkey of recipientkeys) {
const decrypter = xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2(
u8a.fromString(recipientkey, 'base64pad'),
u8a.fromString(senderkey, 'base64pad')
)
await expect(decryptJWE(jwe as any, decrypter)).rejects.toThrowError('Failed to decrypt')
}
}
)
test.each(vectors.ecdh1PuV3Xc20PkwV2.invalid)('throws on invalid jwe', async ({ jwe }) => {
expect.assertions(1)
const decrypter = xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2(randomBytes(32), randomBytes(32))
await expect(decryptJWE(jwe as any, decrypter)).rejects.toThrowError('Invalid JWE')
})
})
})

@@ -190,2 +234,188 @@

})
describe('ECDH-1PU+XC20PKW (X25519), Key Wrapping Mode with XC20P content encryption', () => {
describe('One recipient', () => {
let cleartext, recipientKey, senderKey, decrypter
beforeEach(() => {
recipientKey = generateKeyPairFromSeed(randomBytes(32))
senderKey = generateKeyPairFromSeed(randomBytes(32))
cleartext = u8a.fromString('my secret message')
decrypter = xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2(recipientKey.secretKey, senderKey.publicKey)
})
it('Creates with only ciphertext', async () => {
const encrypter = xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(recipientKey.publicKey, senderKey.secretKey)
expect.assertions(3)
const jwe = await createJWE(cleartext, [encrypter])
expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P' })
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)
})
it('Creates with skid, kid, no apu and no apv', async () => {
const kid = 'did:example:receiver#key-1'
const skid = 'did:example:sender#key-1'
const encrypter = xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(recipientKey.publicKey, senderKey.secretKey, {
kid,
skid
})
expect.assertions(6)
const jwe = await createJWE(cleartext, [encrypter])
expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P', skid: skid })
expect(jwe.recipients[0].header.kid).toEqual(kid)
expect(jwe.recipients[0].header.apu).toBeUndefined()
expect(jwe.recipients[0].header.apv).toBeUndefined()
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)
})
it('Creates with no skid, no kid, apu and apv', async () => {
const apu = encodeBase64url('Alice')
const apv = encodeBase64url('Bob')
const encrypter = xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(recipientKey.publicKey, senderKey.secretKey, {
apu,
apv
})
expect.assertions(6)
const jwe = await createJWE(cleartext, [encrypter])
expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P' })
expect(jwe.recipients[0].header.kid).toBeUndefined()
expect(jwe.recipients[0].header.apu).toEqual(apu)
expect(jwe.recipients[0].header.apv).toEqual(apv)
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)
})
it('Creates with skid, kid, apu and apv', async () => {
const kid = 'did:example:receiver#key-1'
const skid = 'did:example:sender#key-1'
const apu = encodeBase64url('Alice')
const apv = encodeBase64url('Bob')
const encrypter = xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(recipientKey.publicKey, senderKey.secretKey, {
kid,
skid,
apu,
apv
})
expect.assertions(6)
const jwe = await createJWE(cleartext, [encrypter])
expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P', skid: skid })
expect(jwe.recipients[0].header.kid).toEqual(kid)
expect(jwe.recipients[0].header.apu).toEqual(apu)
expect(jwe.recipients[0].header.apv).toEqual(apv)
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)
})
it('Creates with data in protected header', async () => {
const encrypter = xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(recipientKey.publicKey, senderKey.secretKey)
expect.assertions(3)
const jwe = await createJWE(cleartext, [encrypter], { more: 'protected' })
expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P', more: 'protected' })
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)
})
it('Creates with aad', async () => {
const encrypter = xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(recipientKey.publicKey, senderKey.secretKey)
expect.assertions(4)
const aad = u8a.fromString('this data is authenticated')
const jwe = await createJWE(cleartext, [encrypter], { more: 'protected' }, aad)
expect(u8a.fromString(jwe.aad, 'base64url')).toEqual(aad)
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P', more: 'protected' })
expect(await decryptJWE(jwe, decrypter)).toEqual(cleartext)
delete jwe.aad
await expect(decryptJWE(jwe, decrypter)).rejects.toThrowError('Failed to decrypt')
})
})
describe('Multiple recipients', () => {
let cleartext, senderkey
let recipients = []
let skid = 'did:example:sender#key-1'
beforeEach(() => {
senderkey = generateKeyPairFromSeed(randomBytes(32))
cleartext = u8a.fromString('my secret message')
recipients[0] = { kid: 'did:example:receiver1#key-1', recipientkey: generateKeyPairFromSeed(randomBytes(32)) }
recipients[0] = {
...recipients[0],
...{
encrypter: xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(
recipients[0].recipientkey.publicKey,
senderkey.secretKey,
{ kid: recipients[0].kid, skid }
),
decrypter: xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2(
recipients[0].recipientkey.secretKey,
senderkey.publicKey
)
}
}
recipients[1] = { kid: 'did:example:receiver2#key-1', recipientkey: generateKeyPairFromSeed(randomBytes(32)) }
recipients[1] = {
...recipients[1],
...{
encrypter: xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(
recipients[1].recipientkey.publicKey,
senderkey.secretKey,
{ kid: recipients[1].kid, skid }
),
decrypter: xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2(
recipients[1].recipientkey.secretKey,
senderkey.publicKey
)
}
}
})
it('Creates with only ciphertext', async () => {
expect.assertions(4)
const jwe = await createJWE(cleartext, [recipients[0].encrypter, recipients[1].encrypter])
expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P', skid: skid })
expect(await decryptJWE(jwe, recipients[0].decrypter)).toEqual(cleartext)
expect(await decryptJWE(jwe, recipients[1].decrypter)).toEqual(cleartext)
})
it('Creates with data in protected header', async () => {
expect.assertions(4)
const jwe = await createJWE(cleartext, [recipients[0].encrypter, recipients[1].encrypter], {
more: 'protected'
})
expect(jwe.aad).toBeUndefined()
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P', skid: skid, more: 'protected' })
expect(await decryptJWE(jwe, recipients[0].decrypter)).toEqual(cleartext)
expect(await decryptJWE(jwe, recipients[0].decrypter)).toEqual(cleartext)
})
it('Creates with aad', async () => {
expect.assertions(6)
const aad = u8a.fromString('this data is authenticated')
const jwe = await createJWE(
cleartext,
[recipients[0].encrypter, recipients[1].encrypter],
{ more: 'protected' },
aad
)
expect(u8a.fromString(jwe.aad, 'base64url')).toEqual(aad)
expect(JSON.parse(decodeBase64url(jwe.protected))).toEqual({ enc: 'XC20P', skid: skid, more: 'protected' })
expect(await decryptJWE(jwe, recipients[0].decrypter)).toEqual(cleartext)
expect(await decryptJWE(jwe, recipients[1].decrypter)).toEqual(cleartext)
delete jwe.aad
await expect(decryptJWE(jwe, recipients[0].decrypter)).rejects.toThrowError('Failed to decrypt')
await expect(decryptJWE(jwe, recipients[0].decrypter)).rejects.toThrowError('Failed to decrypt')
})
it('Incompatible encrypters throw', async () => {
expect.assertions(1)
const enc1 = { enc: 'cool enc alg1' } as Encrypter
const enc2 = { enc: 'cool enc alg2' } as Encrypter
await expect(createJWE(cleartext, [enc1, enc2])).rejects.toThrowError('Incompatible encrypters passed')
})
})
})
})

@@ -30,10 +30,17 @@ import { hash } from '@stablelib/sha256'

// https://github.com/panva/jose/blob/master/lib/jwa/ecdh/derive.js
export function concatKDF(secret: Uint8Array, keyLen: number, alg: string): Uint8Array {
export function concatKDF(
secret: Uint8Array,
keyLen: number,
alg: string,
producerInfo?: Uint8Array,
consumerInfo?: Uint8Array
): Uint8Array {
if (keyLen !== 256) throw new Error(`Unsupported key length: ${keyLen}`)
const value = u8a.concat([
lengthAndInput(u8a.fromString(alg)),
lengthAndInput(new Uint8Array(0)), // apu
lengthAndInput(new Uint8Array(0)), // apv
lengthAndInput(typeof producerInfo === 'undefined' ? new Uint8Array(0) : producerInfo), // apu
lengthAndInput(typeof consumerInfo === 'undefined' ? new Uint8Array(0) : consumerInfo), // apv
writeUint32BE(keyLen)
])
// since our key lenght is 256 we only have to do one round

@@ -40,0 +47,0 @@ const roundNumber = 1

@@ -24,3 +24,9 @@ import SimpleSigner from './signers/SimpleSigner'

x25519Decrypter,
resolveX25519Encrypters
resolveX25519Encrypters,
createAuthEncrypter,
createAnonEncrypter,
createAuthDecrypter,
createAnonDecrypter,
xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2,
xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2
} from './xc20pEncryption'

@@ -27,0 +33,0 @@

@@ -9,2 +9,4 @@ import { base64ToBytes, bytesToBase64url, decodeBase64url, toSealed } from './util'

kid?: string
apv?: string
apu?: string
}

@@ -11,0 +13,0 @@

@@ -12,2 +12,67 @@ import { XChaCha20Poly1305 } from '@stablelib/xchacha20poly1305'

export type AuthEncryptParams = {
kid?: string
skid?: string
// base64url encoded
apu?: string
// base64url encoded
apv?: string
}
export type AnonEncryptParams = {
kid?: string
}
/**
* Recommended encrypter for authenticated encryption (i.e. sender authentication and requires
* sender private key to encrypt the data).
* Uses ECDH-1PU [v3](https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03) and
* XC20PKW [v2](https://tools.ietf.org/html/draft-amringer-jose-chacha-02).
*
* NOTE: ECDH-1PU and XC20PKW are proposed drafts in IETF and not a standard yet and
* are subject to change as new revisions or until the offical CFRG specification are released.
*/
export function createAuthEncrypter(
recipientPublicKey: Uint8Array,
senderSecretKey: Uint8Array,
options: Partial<AuthEncryptParams> = {}
): Encrypter {
return xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(recipientPublicKey, senderSecretKey, options)
}
/**
* Recommended encrypter for anonymous encryption (i.e. no sender authentication).
* Uses ECDH-ES+XC20PKW [v2](https://tools.ietf.org/html/draft-amringer-jose-chacha-02).
*
* NOTE: ECDH-ES+XC20PKW is a proposed draft in IETF and not a standard yet and
* is subject to change as new revisions or until the offical CFRG specification is released.
*/
export function createAnonEncrypter(publicKey: Uint8Array, options: Partial<AnonEncryptParams> = {}): Encrypter {
return options !== undefined ? x25519Encrypter(publicKey, options.kid) : x25519Encrypter(publicKey)
}
/**
* Recommended decrypter for authenticated encryption (i.e. sender authentication and requires
* sender public key to decrypt the data).
* Uses ECDH-1PU [v3](https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03) and
* XC20PKW [v2](https://tools.ietf.org/html/draft-amringer-jose-chacha-02).
*
* NOTE: ECDH-1PU and XC20PKW are proposed drafts in IETF and not a standard yet and
* are subject to change as new revisions or until the offical CFRG specification are released.
*/
export function createAuthDecrypter(recipientSecretKey: Uint8Array, senderPublicKey: Uint8Array): Decrypter {
return xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2(recipientSecretKey, senderPublicKey)
}
/**
* Recommended decrypter for anonymous encryption (i.e. no sender authentication).
* Uses ECDH-ES+XC20PKW [v2](https://tools.ietf.org/html/draft-amringer-jose-chacha-02).
*
* NOTE: ECDH-ES+XC20PKW is a proposed draft in IETF and not a standard yet and
* is subject to change as new revisions or until the offical CFRG specification is released.
*/
export function createAnonDecrypter(secretKey: Uint8Array): Decrypter {
return x25519Decrypter(secretKey)
}
function xc20pEncrypter(key: Uint8Array): (cleartext: Uint8Array, aad?: Uint8Array) => EncryptionResult {

@@ -85,2 +150,66 @@ const cipher = new XChaCha20Poly1305(key)

/**
* Implements ECDH-1PU+XC20PKW with XChaCha20Poly1305 based on the following specs:
* - [XC20PKW](https://tools.ietf.org/html/draft-amringer-jose-chacha-02)
* - [ECDH-1PU](https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03)
*/
export function xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(
recipientPublicKey: Uint8Array,
senderSecretKey: Uint8Array,
options: Partial<AuthEncryptParams> = {}
): Encrypter {
const alg = 'ECDH-1PU+XC20PKW'
const keyLen = 256
const crv = 'X25519'
let partyUInfo
let partyVInfo
if (options.apu !== undefined) partyUInfo = base64ToBytes(options.apu)
if (options.apv !== undefined) partyVInfo = base64ToBytes(options.apv)
async function encryptCek(cek): Promise<Recipient> {
const epk = generateKeyPair()
const zE = sharedKey(epk.secretKey, recipientPublicKey)
// ECDH-1PU requires additional shared secret between
// static key of sender and static key of recipient
const zS = sharedKey(senderSecretKey, recipientPublicKey)
const sharedSecret = new Uint8Array(zE.length + zS.length)
sharedSecret.set(zE)
sharedSecret.set(zS, zE.length)
// Key Encryption Key
const kek = concatKDF(sharedSecret, keyLen, alg, partyUInfo, partyVInfo)
const res = xc20pEncrypter(kek)(cek)
const recipient: Recipient = {
encrypted_key: bytesToBase64url(res.ciphertext),
header: {
alg,
iv: bytesToBase64url(res.iv),
tag: bytesToBase64url(res.tag),
epk: { kty: 'OKP', crv, x: bytesToBase64url(epk.publicKey) }
}
}
if (options.kid) recipient.header.kid = options.kid
if (options.apu) recipient.header.apu = options.apu
if (options.apv) recipient.header.apv = options.apv
return recipient
}
async function encrypt(cleartext, protectedHeader = {}, aad?): Promise<EncryptionResult> {
// we won't want alg to be set to dir from xc20pDirEncrypter
Object.assign(protectedHeader, { alg: undefined, skid: options.skid })
// Content Encryption Key
const cek = randomBytes(32)
return {
...(await xc20pDirEncrypter(cek).encrypt(cleartext, protectedHeader, aad)),
recipient: await encryptCek(cek),
cek
}
}
return { alg, enc: 'XC20P', encrypt, encryptCek }
}
export async function resolveX25519Encrypters(dids: string[], resolver: Resolvable): Promise<Encrypter[]> {

@@ -141,1 +270,43 @@ const encryptersForDID = async (did): Promise<Encrypter[]> => {

}
/**
* Implements ECDH-1PU+XC20PKW with XChaCha20Poly1305 based on the following specs:
* - [XC20PKW](https://tools.ietf.org/html/draft-amringer-jose-chacha-02)
* - [ECDH-1PU](https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03)
*/
export function xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2(
recipientSecretKey: Uint8Array,
senderPublicKey: Uint8Array
): Decrypter {
const alg = 'ECDH-1PU+XC20PKW'
const keyLen = 256
const crv = 'X25519'
async function decrypt(sealed, iv, aad, recipient): Promise<Uint8Array> {
validateHeader(recipient.header)
if (recipient.header.epk.crv !== crv) return null
// ECDH-1PU requires additional shared secret between
// static key of sender and static key of recipient
const publicKey = base64ToBytes(recipient.header.epk.x)
const zE = sharedKey(recipientSecretKey, publicKey)
const zS = sharedKey(recipientSecretKey, senderPublicKey)
const sharedSecret = new Uint8Array(zE.length + zS.length)
sharedSecret.set(zE)
sharedSecret.set(zS, zE.length)
// Key Encryption Key
let producerInfo
let consumerInfo
if (recipient.header.apu) producerInfo = base64ToBytes(recipient.header.apu)
if (recipient.header.apv) consumerInfo = base64ToBytes(recipient.header.apv)
const kek = concatKDF(sharedSecret, keyLen, alg, producerInfo, consumerInfo)
// Content Encryption Key
const sealedCek = toSealed(recipient.encrypted_key, recipient.header.tag)
const cek = await xc20pDirDecrypter(kek).decrypt(sealedCek, base64ToBytes(recipient.header.iv))
if (cek === null) return null
return xc20pDirDecrypter(cek).decrypt(sealed, iv, aad)
}
return { alg, enc: 'XC20P', decrypt }
}

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

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