@tinycloud/web-sdk 3.14.0-beta.2 → 3.14.0-beta.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -11
- package/dist/adapters/BrowserWasmBindings.d.ts +1 -0
- package/dist/delegations-issued.cjs +1 -1
- package/dist/delegations-issued.mjs +1 -1
- package/dist/delegations-renewal.cjs +1 -1
- package/dist/delegations-renewal.mjs +1 -1
- package/dist/encryption-keys.cjs +1 -1
- package/dist/encryption-keys.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/modals.cjs +1 -1
- package/dist/modals.mjs +1 -1
- package/dist/modules/Storage/tinycloud/types.schema.d.ts +8 -8
- package/dist/modules/WebSecretsService.d.ts +19 -4
- package/dist/modules/browserSessionPersistence.d.ts +2 -0
- package/dist/modules/openKeySignPresentation.d.ts +19 -0
- package/dist/modules/requestPermissionsCore.d.ts +2 -0
- package/dist/modules/runtimeGrantPersistence.d.ts +42 -2
- package/dist/modules/tcw.d.ts +80 -8
- package/dist/replica.cjs +1 -1
- package/dist/replica.mjs +1 -1
- package/dist/runtime-grants.cjs +1 -1
- package/dist/runtime-grants.mjs +1 -1
- package/dist/secret-read.cjs +1 -1
- package/dist/secret-read.mjs +1 -1
- package/dist/session-retire-entry.d.ts +3 -0
- package/dist/session-retire.cjs +1 -0
- package/dist/session-retire.mjs +1 -0
- package/package.json +6 -6
package/dist/encryption-keys.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! For license information please see encryption-keys.cjs.LICENSE.txt */
|
|
2
|
-
(()=>{"use strict";var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function n(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function r(t,...e){if(!n(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function i(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function o(t,e){r(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function s(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function c(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function a(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}t.r(e),t.d(e,{createNamedKeyClient:()=>ao});const u=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function d(t){if("string"==typeof t)t=function(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}(t);else{if(!n(t))throw new Error("Uint8Array expected, got "+typeof t);t=y(t)}return t}const f=(t,e)=>{function n(n,...i){if(r(n),!u)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==t.nonceLength){const e=i[0];if(!e)throw new Error("nonce / iv required");t.varSizeNonce?r(e):r(e,t.nonceLength)}const o=t.tagLength;o&&void 0!==i[1]&&r(i[1]);const s=e(n,...i),c=(t,e)=>{if(void 0!==e){if(2!==t)throw new Error("cipher output not supported");r(e)}};let a=!1;return{encrypt(t,e){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,r(t),c(s.encrypt.length,e),s.encrypt(t,e)},decrypt(t,e){if(r(t),o&&t.length<o)throw new Error("invalid ciphertext length: smaller than tagLength="+o);return c(s.decrypt.length,e),s.decrypt(t,e)}}}return Object.assign(n,t),n};function l(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),c=Number(n&o),a=r?4:0,u=r?0:4;t.setUint32(e+a,s,r),t.setUint32(e+u,c,r)}function h(t){return t.byteOffset%4==0}function y(t){return Uint8Array.from(t)}const p=16,w=new Uint8Array(16),g=s(w),b=(t,e,n,r)=>({s3:n<<31|r>>>1,s2:e<<31|n>>>1,s1:t<<31|e>>>1,s0:t>>>1^225<<24&-(1&r)}),m=t=>(t>>>0&255)<<24|(t>>>8&255)<<16|(t>>>16&255)<<8|t>>>24&255;class v{constructor(t,e){this.blockLen=p,this.outputLen=p,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,r(t=d(t),16);const n=a(t);let i=n.getUint32(0,!1),o=n.getUint32(4,!1),s=n.getUint32(8,!1),c=n.getUint32(12,!1);const u=[];for(let t=0;t<128;t++)u.push({s0:m(i),s1:m(o),s2:m(s),s3:m(c)}),({s0:i,s1:o,s2:s,s3:c}=b(i,o,s,c));const f=(l=e||1024)>65536?8:l>1024?4:2;var l;if(![1,2,4,8].includes(f))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=f;const h=128/f,y=this.windowSize=2**f,w=[];for(let t=0;t<h;t++)for(let e=0;e<y;e++){let n=0,r=0,i=0,o=0;for(let s=0;s<f;s++){if(!(e>>>f-s-1&1))continue;const{s0:c,s1:a,s2:d,s3:l}=u[f*t+s];n^=c,r^=a,i^=d,o^=l}w.push({s0:n,s1:r,s2:i,s3:o})}this.t=w}_updateBlock(t,e,n,r){t^=this.s0,e^=this.s1,n^=this.s2,r^=this.s3;const{W:i,t:o,windowSize:s}=this;let c=0,a=0,u=0,d=0;const f=(1<<i)-1;let l=0;for(const h of[t,e,n,r])for(let t=0;t<4;t++){const e=h>>>8*t&255;for(let t=8/i-1;t>=0;t--){const n=e>>>i*t&f,{s0:r,s1:h,s2:y,s3:p}=o[l*s+n];c^=r,a^=h,u^=y,d^=p,l+=1}}this.s0=c,this.s1=a,this.s2=u,this.s3=d}update(t){i(this),r(t=d(t));const e=s(t),n=Math.floor(t.length/p),o=t.length%p;for(let t=0;t<n;t++)this._updateBlock(e[4*t+0],e[4*t+1],e[4*t+2],e[4*t+3]);return o&&(w.set(t.subarray(n*p)),this._updateBlock(g[0],g[1],g[2],g[3]),c(g)),this}destroy(){const{t}=this;for(const e of t)e.s0=0,e.s1=0,e.s2=0,e.s3=0}digestInto(t){i(this),o(t,this),this.finished=!0;const{s0:e,s1:n,s2:r,s3:c}=this,a=s(t);return a[0]=e,a[1]=n,a[2]=r,a[3]=c,t}digest(){const t=new Uint8Array(p);return this.digestInto(t),this.destroy(),t}}class k extends v{constructor(t,e){r(t=d(t));const n=function(t){t.reverse();const e=1&t[15];let n=0;for(let e=0;e<t.length;e++){const r=t[e];t[e]=r>>>1|n,n=(1&r)<<7}return t[0]^=225&-e,t}(y(t));super(n,e),c(n)}update(t){t=d(t),i(this);const e=s(t),n=t.length%p,r=Math.floor(t.length/p);for(let t=0;t<r;t++)this._updateBlock(m(e[4*t+3]),m(e[4*t+2]),m(e[4*t+1]),m(e[4*t+0]));return n&&(w.set(t.subarray(r*p)),this._updateBlock(m(g[3]),m(g[2]),m(g[1]),m(g[0])),c(g)),this}digestInto(t){i(this),o(t,this),this.finished=!0;const{s0:e,s1:n,s2:r,s3:c}=this,a=s(t);return a[0]=e,a[1]=n,a[2]=r,a[3]=c,t.reverse()}}function E(t){const e=(e,n)=>t(n,e.length).update(d(e)).digest(),n=t(new Uint8Array(16),0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=(e,n)=>t(e,n),e}const I=E((t,e)=>new v(t,e)),x=(E((t,e)=>new k(t,e)),16),A=new Uint8Array(x);function N(t){return t<<1^283&-(t>>7)}function S(t,e){let n=0;for(;e>0;e>>=1)n^=t&-(1&e),t=N(t);return n}const B=t=>t<<24|t>>>8,O=t=>t<<8|t>>>24;function _(t,e){if(256!==t.length)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((n,r)=>e(t[r])),r=n.map(O),i=r.map(O),o=i.map(O),s=new Uint32Array(65536),c=new Uint32Array(65536),a=new Uint16Array(65536);for(let e=0;e<256;e++)for(let u=0;u<256;u++){const d=256*e+u;s[d]=n[e]^r[u],c[d]=i[e]^o[u],a[d]=t[e]<<8|t[u]}return{sbox:t,sbox2:a,T0:n,T1:r,T2:i,T3:o,T01:s,T23:c}}const P=_((()=>{const t=new Uint8Array(256);for(let e=0,n=1;e<256;e++,n^=N(n))t[e]=n;const e=new Uint8Array(256);e[0]=99;for(let n=0;n<255;n++){let r=t[255-n];r|=r<<8,e[t[n]]=255&(r^r>>4^r>>5^r>>6^r>>7^99)}return c(t),e})(),t=>S(t,3)<<24|t<<16|t<<8|S(t,2)),$=(()=>{const t=new Uint8Array(16);for(let e=0,n=1;e<16;e++,n=N(n))t[e]=n;return t})();function U(t,e,n,r,i,o){return t[n<<8&65280|r>>>8&255]^e[i>>>8&65280|o>>>24&255]}function R(t,e,n,r,i){return t[255&e|65280&n]|t[r>>>16&255|i>>>16&65280]<<16}function T(t,e,n,r,i){const{sbox2:o,T01:s,T23:c}=P;let a=0;e^=t[a++],n^=t[a++],r^=t[a++],i^=t[a++];const u=t.length/4-2;for(let o=0;o<u;o++){const o=t[a++]^U(s,c,e,n,r,i),u=t[a++]^U(s,c,n,r,i,e),d=t[a++]^U(s,c,r,i,e,n),f=t[a++]^U(s,c,i,e,n,r);e=o,n=u,r=d,i=f}return{s0:t[a++]^R(o,e,n,r,i),s1:t[a++]^R(o,n,r,i,e),s2:t[a++]^R(o,r,i,e,n),s3:t[a++]^R(o,i,e,n,r)}}function L(t,e,n,i,o){r(n,x),r(i),o=function(t,e,n=!0){if(void 0===e)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(n&&!h(e))throw new Error("invalid output, must be aligned");return e}(i.length,o);const u=n,d=s(u),f=a(u),l=s(i),y=s(o),p=e?0:12,w=i.length;let g=f.getUint32(p,e),{s0:b,s1:m,s2:v,s3:k}=T(t,d[0],d[1],d[2],d[3]);for(let n=0;n+4<=l.length;n+=4)y[n+0]=l[n+0]^b,y[n+1]=l[n+1]^m,y[n+2]=l[n+2]^v,y[n+3]=l[n+3]^k,g=g+1>>>0,f.setUint32(p,g,e),({s0:b,s1:m,s2:v,s3:k}=T(t,d[0],d[1],d[2],d[3]));const E=x*Math.floor(l.length/4);if(E<w){const t=new Uint32Array([b,m,v,k]),e=(I=t,new Uint8Array(I.buffer,I.byteOffset,I.byteLength));for(let t=E,n=0;t<w;t++,n++)o[t]=i[t]^e[n];c(t)}var I;return o}function D(t,e,n,r,i){const o=i?i.length:0,s=t.create(n,r.length+o);i&&s.update(i);const u=function(t,e,n){!function(t){if("boolean"!=typeof t)throw new Error(`boolean expected, not ${t}`)}(n);const r=new Uint8Array(16),i=a(r);return l(i,0,BigInt(e),n),l(i,8,BigInt(t),n),r}(8*r.length,8*o,e);s.update(r),s.update(u);const d=s.digest();return c(u),d}const K=f({blockSize:16,nonceLength:12,tagLength:16,varSizeNonce:!0},function(t,e,n){if(e.length<8)throw new Error("aes/gcm: invalid nonce length");function i(t,e,r){const i=D(I,!1,t,r,n);for(let t=0;t<e.length;t++)i[t]^=e[t];return i}function o(){const n=function(t){r(t);const e=t.length;if(![16,24,32].includes(e))throw new Error("aes: invalid key size, should be 16, 24 or 32, got "+e);const{sbox2:n}=P,i=[];h(t)||i.push(t=y(t));const o=s(t),a=o.length,u=t=>R(n,t,t,t,t),d=new Uint32Array(e+28);d.set(o);for(let t=a;t<d.length;t++){let e=d[t-1];t%a===0?e=u(B(e))^$[t/a-1]:a>6&&t%a===4&&(e=u(e)),d[t]=d[t-a]^e}return c(...i),d}(t),i=A.slice(),o=A.slice();if(L(n,!1,o,o,i),12===e.length)o.set(e);else{const t=A.slice();l(a(t),8,BigInt(8*e.length),!1);const n=I.create(i).update(e).update(t);n.digestInto(o),n.destroy()}return{xk:n,authKey:i,counter:o,tagMask:L(n,!1,o,A)}}return{encrypt(t){const{xk:e,authKey:n,counter:r,tagMask:s}=o(),a=new Uint8Array(t.length+16),u=[e,n,r,s];h(t)||u.push(t=y(t)),L(e,!1,r,t,a.subarray(0,t.length));const d=i(n,s,a.subarray(0,a.length-16));return u.push(d),a.set(d,t.length),c(...u),a},decrypt(t){const{xk:e,authKey:n,counter:r,tagMask:s}=o(),a=[e,n,s,r];h(t)||a.push(t=y(t));const u=t.subarray(0,-16),d=t.subarray(-16),f=i(n,s,u);if(a.push(f),!function(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}(f,d))throw new Error("aes/gcm: invalid ghash tag");const l=L(e,!1,r,u);return c(...a),l}}}),V=()=>"undefined"!=typeof globalThis&&globalThis.crypto?globalThis.crypto:"undefined"!=typeof window&&window.crypto?window.crypto:"undefined"!=typeof self&&self.crypto?self.crypto:void 0,z={web:V(),node:void 0,getRandomValues:function(t){const e=V();if(e&&e.getRandomValues)return e.getRandomValues(t);throw new Error("crypto.getRandomValues is unavailable")}};function C(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function H(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function q(t,...e){if(!C(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function F(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.createHasher");H(t.outputLen),H(t.blockLen)}function M(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function j(t,e){q(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function G(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Y(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function W(t,e){return t<<32-e|t>>>e}function Z(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const X=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?t=>t:function(t){for(let e=0;e<t.length;e++)t[e]=Z(t[e]);return t},J=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Q=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function tt(t){if(q(t),J)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Q[t[n]];return e}function et(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function nt(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);if(J)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let e=0,i=0;e<n;e++,i+=2){const n=et(t.charCodeAt(i)),o=et(t.charCodeAt(i+1));if(void 0===n||void 0===o){const e=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+e+'" at index '+i)}r[e]=16*n+o}return r}function rt(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}function it(t){return"string"==typeof t&&(t=rt(t)),q(t),t}function ot(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];q(r),e+=r.length}const n=new Uint8Array(e);for(let e=0,r=0;e<t.length;e++){const i=t[e];n.set(i,r),r+=i.length}return n}class st{}function ct(t){const e=e=>t().update(it(e)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function at(t=32){if(z&&"function"==typeof z.getRandomValues)return z.getRandomValues(new Uint8Array(t));if(z&&"function"==typeof z.randomBytes)return Uint8Array.from(z.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function ut(t,e,n){return t&e^~t&n}function dt(t,e,n){return t&e^t&n^e&n}class ft extends st{constructor(t,e,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(t),this.view=Y(this.buffer)}update(t){M(this),q(t=it(t));const{view:e,buffer:n,blockLen:r}=this,i=t.length;for(let o=0;o<i;){const s=Math.min(r-this.pos,i-o);if(s===r){const e=Y(t);for(;r<=i-o;o+=r)this.process(e,o);continue}n.set(t.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){M(this),j(t,this),this.finished=!0;const{buffer:e,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;e[o++]=128,G(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let t=o;t<r;t++)e[t]=0;!function(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),c=Number(n&o),a=r?4:0,u=r?0:4;t.setUint32(e+a,s,r),t.setUint32(e+u,c,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const s=Y(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const a=c/4,u=this.get();if(a>u.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t<a;t++)s.setUint32(4*t,u[t],i)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:e,buffer:n,length:r,finished:i,destroyed:o,pos:s}=this;return t.destroyed=o,t.finished=i,t.length=r,t.pos=s,r%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}}const lt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ht=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),yt=BigInt(2**32-1),pt=BigInt(32);function wt(t,e=!1){return e?{h:Number(t&yt),l:Number(t>>pt&yt)}:{h:0|Number(t>>pt&yt),l:0|Number(t&yt)}}function gt(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let o=0;o<n;o++){const{h:n,l:s}=wt(t[o],e);[r[o],i[o]]=[n,s]}return[r,i]}const bt=(t,e,n)=>t>>>n,mt=(t,e,n)=>t<<32-n|e>>>n,vt=(t,e,n)=>t>>>n|e<<32-n,kt=(t,e,n)=>t<<32-n|e>>>n,Et=(t,e,n)=>t<<64-n|e>>>n-32,It=(t,e,n)=>t>>>n-32|e<<64-n;function xt(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:0|i}}const At=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Nt=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,St=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Bt=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,Ot=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),_t=(t,e,n,r,i,o)=>e+n+r+i+o+(t/2**32|0)|0,Pt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$t=new Uint32Array(64);class Ut extends ft{constructor(t=32){super(64,t,8,!1),this.A=0|lt[0],this.B=0|lt[1],this.C=0|lt[2],this.D=0|lt[3],this.E=0|lt[4],this.F=0|lt[5],this.G=0|lt[6],this.H=0|lt[7]}get(){const{A:t,B:e,C:n,D:r,E:i,F:o,G:s,H:c}=this;return[t,e,n,r,i,o,s,c]}set(t,e,n,r,i,o,s,c){this.A=0|t,this.B=0|e,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|o,this.G=0|s,this.H=0|c}process(t,e){for(let n=0;n<16;n++,e+=4)$t[n]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=$t[t-15],n=$t[t-2],r=W(e,7)^W(e,18)^e>>>3,i=W(n,17)^W(n,19)^n>>>10;$t[t]=i+$t[t-7]+r+$t[t-16]|0}let{A:n,B:r,C:i,D:o,E:s,F:c,G:a,H:u}=this;for(let t=0;t<64;t++){const e=u+(W(s,6)^W(s,11)^W(s,25))+ut(s,c,a)+Pt[t]+$t[t]|0,d=(W(n,2)^W(n,13)^W(n,22))+dt(n,r,i)|0;u=a,a=c,c=s,s=o+e|0,o=i,i=r,r=n,n=e+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,c=c+this.F|0,a=a+this.G|0,u=u+this.H|0,this.set(n,r,i,o,s,c,a,u)}roundClean(){G($t)}destroy(){this.set(0,0,0,0,0,0,0,0),G(this.buffer)}}const Rt=(()=>gt(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))))(),Tt=(()=>Rt[0])(),Lt=(()=>Rt[1])(),Dt=new Uint32Array(80),Kt=new Uint32Array(80);class Vt extends ft{constructor(t=64){super(128,t,16,!1),this.Ah=0|ht[0],this.Al=0|ht[1],this.Bh=0|ht[2],this.Bl=0|ht[3],this.Ch=0|ht[4],this.Cl=0|ht[5],this.Dh=0|ht[6],this.Dl=0|ht[7],this.Eh=0|ht[8],this.El=0|ht[9],this.Fh=0|ht[10],this.Fl=0|ht[11],this.Gh=0|ht[12],this.Gl=0|ht[13],this.Hh=0|ht[14],this.Hl=0|ht[15]}get(){const{Ah:t,Al:e,Bh:n,Bl:r,Ch:i,Cl:o,Dh:s,Dl:c,Eh:a,El:u,Fh:d,Fl:f,Gh:l,Gl:h,Hh:y,Hl:p}=this;return[t,e,n,r,i,o,s,c,a,u,d,f,l,h,y,p]}set(t,e,n,r,i,o,s,c,a,u,d,f,l,h,y,p){this.Ah=0|t,this.Al=0|e,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|o,this.Dh=0|s,this.Dl=0|c,this.Eh=0|a,this.El=0|u,this.Fh=0|d,this.Fl=0|f,this.Gh=0|l,this.Gl=0|h,this.Hh=0|y,this.Hl=0|p}process(t,e){for(let n=0;n<16;n++,e+=4)Dt[n]=t.getUint32(e),Kt[n]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|Dt[t-15],n=0|Kt[t-15],r=vt(e,n,1)^vt(e,n,8)^bt(e,0,7),i=kt(e,n,1)^kt(e,n,8)^mt(e,n,7),o=0|Dt[t-2],s=0|Kt[t-2],c=vt(o,s,19)^Et(o,s,61)^bt(o,0,6),a=kt(o,s,19)^It(o,s,61)^mt(o,s,6),u=St(i,a,Kt[t-7],Kt[t-16]),d=Bt(u,r,c,Dt[t-7],Dt[t-16]);Dt[t]=0|d,Kt[t]=0|u}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:s,Cl:c,Dh:a,Dl:u,Eh:d,El:f,Fh:l,Fl:h,Gh:y,Gl:p,Hh:w,Hl:g}=this;for(let t=0;t<80;t++){const e=vt(d,f,14)^vt(d,f,18)^Et(d,f,41),b=kt(d,f,14)^kt(d,f,18)^It(d,f,41),m=d&l^~d&y,v=Ot(g,b,f&h^~f&p,Lt[t],Kt[t]),k=_t(v,w,e,m,Tt[t],Dt[t]),E=0|v,I=vt(n,r,28)^Et(n,r,34)^Et(n,r,39),x=kt(n,r,28)^It(n,r,34)^It(n,r,39),A=n&i^n&s^i&s,N=r&o^r&c^o&c;w=0|y,g=0|p,y=0|l,p=0|h,l=0|d,h=0|f,({h:d,l:f}=xt(0|a,0|u,0|k,0|E)),a=0|s,u=0|c,s=0|i,c=0|o,i=0|n,o=0|r;const S=At(E,x,N);n=Nt(S,k,I,A),r=0|S}({h:n,l:r}=xt(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:o}=xt(0|this.Bh,0|this.Bl,0|i,0|o)),({h:s,l:c}=xt(0|this.Ch,0|this.Cl,0|s,0|c)),({h:a,l:u}=xt(0|this.Dh,0|this.Dl,0|a,0|u)),({h:d,l:f}=xt(0|this.Eh,0|this.El,0|d,0|f)),({h:l,l:h}=xt(0|this.Fh,0|this.Fl,0|l,0|h)),({h:y,l:p}=xt(0|this.Gh,0|this.Gl,0|y,0|p)),({h:w,l:g}=xt(0|this.Hh,0|this.Hl,0|w,0|g)),this.set(n,r,i,o,s,c,a,u,d,f,l,h,y,p,w,g)}roundClean(){G(Dt,Kt)}destroy(){G(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const zt=ct(()=>new Ut),Ct=ct(()=>new Vt),Ht=BigInt(0),qt=BigInt(1);function Ft(t,e=""){if("boolean"!=typeof t)throw new Error((e&&`"${e}"`)+"expected boolean, got type="+typeof t);return t}function Mt(t,e,n=""){const r=C(t),i=t?.length,o=void 0!==e;if(!r||o&&i!==e)throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(o?` of length ${e}`:"")+", got "+(r?`length=${i}`:"type="+typeof t));return t}function jt(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);return""===t?Ht:BigInt("0x"+t)}function Gt(t){return q(t),jt(tt(Uint8Array.from(t).reverse()))}function Yt(t,e){return nt(t.toString(16).padStart(2*e,"0"))}function Wt(t,e){return Yt(t,e).reverse()}function Zt(t,e,n){let r;if("string"==typeof e)try{r=nt(e)}catch(e){throw new Error(t+" must be hex string or Uint8Array, cause: "+e)}else{if(!C(e))throw new Error(t+" must be hex string or Uint8Array");r=Uint8Array.from(e)}const i=r.length;if("number"==typeof n&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function Xt(t){return Uint8Array.from(t)}const Jt=t=>"bigint"==typeof t&&Ht<=t;function Qt(t,e,n,r){if(!function(t,e,n){return Jt(t)&&Jt(e)&&Jt(n)&&e<=t&&t<n}(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}const te=t=>(qt<<BigInt(t))-qt;function ee(t,e,n={}){if(!t||"object"!=typeof t)throw new Error("expected valid options object");function r(e,n,r){const i=t[e];if(r&&void 0===i)return;const o=typeof i;if(o!==n||null===i)throw new Error(`param "${e}" is invalid: expected ${n}, got ${o}`)}Object.entries(e).forEach(([t,e])=>r(t,e,!1)),Object.entries(n).forEach(([t,e])=>r(t,e,!0))}const ne=()=>{throw new Error("not implemented")};function re(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(void 0!==i)return i;const o=t(n,...r);return e.set(n,o),o}}const ie=BigInt(0),oe=BigInt(1),se=BigInt(2),ce=BigInt(3),ae=BigInt(4),ue=BigInt(5),de=BigInt(7),fe=BigInt(8),le=BigInt(9),he=BigInt(16);function ye(t,e){const n=t%e;return n>=ie?n:e+n}function pe(t,e,n){let r=t;for(;e-- >ie;)r*=r,r%=n;return r}function we(t,e){if(t===ie)throw new Error("invert: expected non-zero number");if(e<=ie)throw new Error("invert: expected positive modulus, got "+e);let n=ye(t,e),r=e,i=ie,o=oe,s=oe,c=ie;for(;n!==ie;){const t=r/n,e=r%n,a=i-s*t,u=o-c*t;r=n,n=e,i=s,o=c,s=a,c=u}if(r!==oe)throw new Error("invert: does not exist");return ye(i,e)}function ge(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function be(t,e){const n=(t.ORDER+oe)/ae,r=t.pow(e,n);return ge(t,r,e),r}function me(t,e){const n=(t.ORDER-ue)/fe,r=t.mul(e,se),i=t.pow(r,n),o=t.mul(e,i),s=t.mul(t.mul(o,se),i),c=t.mul(o,t.sub(s,t.ONE));return ge(t,c,e),c}function ve(t){if(t<ce)throw new Error("sqrt is not defined for small field");let e=t-oe,n=0;for(;e%se===ie;)e/=se,n++;let r=se;const i=Ae(t);for(;1===xe(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return be;let o=i.pow(r,e);const s=(e+oe)/se;return function(t,r){if(t.is0(r))return r;if(1!==xe(t,r))throw new Error("Cannot find square root");let i=n,c=t.mul(t.ONE,o),a=t.pow(r,e),u=t.pow(r,s);for(;!t.eql(a,t.ONE);){if(t.is0(a))return t.ZERO;let e=1,n=t.sqr(a);for(;!t.eql(n,t.ONE);)if(e++,n=t.sqr(n),e===i)throw new Error("Cannot find square root");const r=oe<<BigInt(i-e-1),o=t.pow(c,r);i=e,c=t.sqr(o),a=t.mul(a,c),u=t.mul(u,o)}return u}}const ke=(t,e)=>(ye(t,e)&oe)===oe,Ee=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ie(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((e,n,i)=>t.is0(n)?e:(r[i]=e,t.mul(e,n)),t.ONE),o=t.inv(i);return e.reduceRight((e,n,i)=>t.is0(n)?e:(r[i]=t.mul(e,r[i]),t.mul(e,n)),o),r}function xe(t,e){const n=(t.ORDER-oe)/se,r=t.pow(e,n),i=t.eql(r,t.ONE),o=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Ae(t,e,n=!1,r={}){if(t<=ie)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,o,s,c=!1;if("object"==typeof e&&null!=e){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const t=e;t.BITS&&(i=t.BITS),t.sqrt&&(o=t.sqrt),"boolean"==typeof t.isLE&&(n=t.isLE),"boolean"==typeof t.modFromBytes&&(c=t.modFromBytes),s=t.allowedLengths}else"number"==typeof e&&(i=e),r.sqrt&&(o=r.sqrt);const{nBitLength:a,nByteLength:u}=function(t,e){void 0!==e&&H(e);const n=void 0!==e?e:t.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const f=Object.freeze({ORDER:t,isLE:n,BITS:a,BYTES:u,MASK:te(a),ZERO:ie,ONE:oe,allowedLengths:s,create:e=>ye(e,t),isValid:e=>{if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return ie<=e&&e<t},is0:t=>t===ie,isValidNot0:t=>!f.is0(t)&&f.isValid(t),isOdd:t=>(t&oe)===oe,neg:e=>ye(-e,t),eql:(t,e)=>t===e,sqr:e=>ye(e*e,t),add:(e,n)=>ye(e+n,t),sub:(e,n)=>ye(e-n,t),mul:(e,n)=>ye(e*n,t),pow:(t,e)=>function(t,e,n){if(n<ie)throw new Error("invalid exponent, negatives unsupported");if(n===ie)return t.ONE;if(n===oe)return e;let r=t.ONE,i=e;for(;n>ie;)n&oe&&(r=t.mul(r,i)),i=t.sqr(i),n>>=oe;return r}(f,t,e),div:(e,n)=>ye(e*we(n,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>we(e,t),sqrt:o||(e=>{return d||(d=(n=t)%ae===ce?be:n%fe===ue?me:n%he===le?function(t){const e=Ae(t),n=ve(t),r=n(e,e.neg(e.ONE)),i=n(e,r),o=n(e,e.neg(r)),s=(t+de)/he;return(t,e)=>{let n=t.pow(e,s),c=t.mul(n,r);const a=t.mul(n,i),u=t.mul(n,o),d=t.eql(t.sqr(c),e),f=t.eql(t.sqr(a),e);n=t.cmov(n,c,d),c=t.cmov(u,a,f);const l=t.eql(t.sqr(c),e),h=t.cmov(n,c,l);return ge(t,h,e),h}}(n):ve(n)),d(f,e);var n}),toBytes:t=>n?Wt(t,u):Yt(t,u),fromBytes:(e,r=!0)=>{if(s){if(!s.includes(e.length)||e.length>u)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);const t=new Uint8Array(u);t.set(e,n?0:t.length-e.length),e=t}if(e.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+e.length);let i=n?Gt(e):function(t){return jt(tt(t))}(e);if(c&&(i=ye(i,t)),!r&&!f.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:t=>Ie(f,t),cmov:(t,e,n)=>n?e:t});return Object.freeze(f)}const Ne=BigInt(0),Se=BigInt(1);function Be(t,e){const n=e.negate();return t?n:e}function Oe(t,e){const n=Ie(t.Fp,e.map(t=>t.Z));return e.map((e,r)=>t.fromAffine(e.toAffine(n[r])))}function _e(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Pe(t,e){_e(t,e);const n=2**t;return{windows:Math.ceil(e/t)+1,windowSize:2**(t-1),mask:te(t),maxNumber:n,shiftBy:BigInt(t)}}function $e(t,e,n){const{windowSize:r,mask:i,maxNumber:o,shiftBy:s}=n;let c=Number(t&i),a=t>>s;c>r&&(c-=o,a+=Se);const u=e*r;return{nextN:a,offset:u+Math.abs(c)-1,isZero:0===c,isNeg:c<0,isNegF:e%2!=0,offsetF:u}}const Ue=new WeakMap,Re=new WeakMap;function Te(t){return Re.get(t)||1}function Le(t){if(t!==Ne)throw new Error("invalid wNAF")}class De{constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let r=t;for(;e>Ne;)e&Se&&(n=n.add(r)),r=r.double(),e>>=Se;return n}precomputeWindow(t,e){const{windows:n,windowSize:r}=Pe(e,this.bits),i=[];let o=t,s=o;for(let t=0;t<n;t++){s=o,i.push(s);for(let t=1;t<r;t++)s=s.add(o),i.push(s);o=s.double()}return i}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=Pe(t,this.bits);for(let t=0;t<o.windows;t++){const{nextN:s,offset:c,isZero:a,isNeg:u,isNegF:d,offsetF:f}=$e(n,t,o);n=s,a?i=i.add(Be(d,e[f])):r=r.add(Be(u,e[c]))}return Le(n),{p:r,f:i}}wNAFUnsafe(t,e,n,r=this.ZERO){const i=Pe(t,this.bits);for(let t=0;t<i.windows&&n!==Ne;t++){const{nextN:o,offset:s,isZero:c,isNeg:a}=$e(n,t,i);if(n=o,!c){const t=e[s];r=r.add(a?t.negate():t)}}return Le(n),r}getPrecomputes(t,e,n){let r=Ue.get(e);return r||(r=this.precomputeWindow(e,t),1!==t&&("function"==typeof n&&(r=n(r)),Ue.set(e,r))),r}cached(t,e,n){const r=Te(t);return this.wNAF(r,this.getPrecomputes(r,t,n),e)}unsafe(t,e,n,r){const i=Te(t);return 1===i?this._unsafeLadder(t,e,r):this.wNAFUnsafe(i,this.getPrecomputes(i,t,n),e,r)}createCache(t,e){_e(e,this.bits),Re.set(t,e),Ue.delete(t)}hasCache(t){return 1!==Te(t)}}function Ke(t,e,n,r){(function(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})})(n,t),function(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}(r,e);const i=n.length,o=r.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,c=function(t){let e;for(e=0;t>Ht;t>>=qt,e+=1);return e}(BigInt(i));let a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);const u=te(a),d=new Array(Number(u)+1).fill(s);let f=s;for(let t=Math.floor((e.BITS-1)/a)*a;t>=0;t-=a){d.fill(s);for(let e=0;e<o;e++){const i=r[e],o=Number(i>>BigInt(t)&u);d[o]=d[o].add(n[e])}let e=s;for(let t=d.length-1,n=s;t>0;t--)n=n.add(d[t]),e=e.add(n);if(f=f.add(e),0!==t)for(let t=0;t<a;t++)f=f.double()}return f}function Ve(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(t){ee(t,Ee.reduce((t,e)=>(t[e]="function",t),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(e),e}return Ae(t,{isLE:n})}const ze=BigInt(0),Ce=BigInt(1),He=BigInt(2),qe=BigInt(8);class Fe{constructor(t){this.ep=t}static fromBytes(t){ne()}static fromHex(t){ne()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return tt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}toRawBytes(){return this.toBytes()}}function Me(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:i}=function(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n={Fp:t.Fp,Fn:Ae(e.n,t.nBitLength,!0),uvRatio:t.uvRatio},r={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:n,hash:t.hash,eddsaOpts:r}}(t);return function(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}(t,function(t,e,n={}){if("function"!=typeof e)throw new Error('"hash" function param is required');ee(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:o,Fn:s}=t,c=n.randomBytes||at,a=n.adjustScalarBytes||(t=>t),u=n.domain||((t,e,n)=>{if(Ft(n,"phflag"),e.length||n)throw new Error("Contexts/pre-hash are not supported");return t});function d(t){return s.create(Gt(t))}function f(t){const{head:n,prefix:r,scalar:o}=function(t){const n=w.secretKey;t=Zt("private key",t,n);const r=Zt("hashed private key",e(t),2*n),i=a(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:d(i)}}(t),s=i.multiply(o),c=s.toBytes();return{head:n,prefix:r,scalar:o,point:s,pointBytes:c}}function l(t){return f(t).pointBytes}function h(t=Uint8Array.of(),...n){const i=ot(...n);return d(e(u(i,Zt("context",t),!!r)))}const y={zip215:!0},p=o.BYTES,w={secretKey:p,publicKey:p,signature:2*p,seed:p};function g(t=c(w.seed)){return Mt(t,w.seed,"seed")}const b={getExtendedPublicKey:f,randomSecretKey:g,isValidSecretKey:function(t){return C(t)&&t.length===s.BYTES},isValidPublicKey:function(e,n){try{return!!t.fromBytes(e,n)}catch(t){return!1}},toMontgomery(e){const{y:n}=t.fromBytes(e),r=w.publicKey,i=32===r;if(!i&&57!==r)throw new Error("only defined for 25519 and 448");const s=i?o.div(Ce+n,Ce-n):o.div(n-Ce,n+Ce);return o.toBytes(s)},toMontgomerySecret(t){const n=w.secretKey;Mt(t,n);const r=e(t.subarray(0,n));return a(r).subarray(0,n)},randomPrivateKey:g,precompute:(e=8,n=t.BASE)=>n.precompute(e,!1)};return Object.freeze({keygen:function(t){const e=b.randomSecretKey(t);return{secretKey:e,publicKey:l(e)}},getPublicKey:l,sign:function(t,e,n={}){t=Zt("message",t),r&&(t=r(t));const{prefix:o,scalar:c,pointBytes:a}=f(e),u=h(n.context,o,t),d=i.multiply(u).toBytes(),l=h(n.context,d,a,t),y=s.create(u+l*c);if(!s.isValid(y))throw new Error("sign failed: invalid s");return Mt(ot(d,s.toBytes(y)),w.signature,"result")},verify:function(e,n,o,s=y){const{context:c,zip215:a}=s,u=w.signature;e=Zt("signature",e,u),n=Zt("message",n),o=Zt("publicKey",o,w.publicKey),void 0!==a&&Ft(a,"zip215"),r&&(n=r(n));const d=u/2,f=e.subarray(0,d),l=Gt(e.subarray(d,u));let p,g,b;try{p=t.fromBytes(o,a),g=t.fromBytes(f,a),b=i.multiplyUnsafe(l)}catch(t){return!1}if(!a&&p.isSmallOrder())return!1;const m=h(c,g.toBytes(),p.toBytes(),n);return g.add(p.multiplyUnsafe(m)).subtract(b).clearCofactor().is0()},utils:b,Point:t,lengths:w})}(function(t,e={}){const n=function(t,e,n={},r){if(void 0===r&&(r="edwards"===t),!e||"object"!=typeof e)throw new Error(`expected valid ${t} CURVE object`);for(const t of["p","n","h"]){const n=e[t];if(!("bigint"==typeof n&&n>Ne))throw new Error(`CURVE.${t} must be positive bigint`)}const i=Ve(e.p,n.Fp,r),o=Ve(e.n,n.Fn,r),s=["Gx","Gy","a","weierstrass"===t?"b":"d"];for(const t of s)if(!i.isValid(e[t]))throw new Error(`CURVE.${t} must be valid field element of CURVE.Fp`);return{CURVE:e=Object.freeze(Object.assign({},e)),Fp:i,Fn:o}}("edwards",t,e,e.FpFnLE),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s}=o;ee(e,{},{uvRatio:"function"});const c=He<<BigInt(8*i.BYTES)-Ce,a=t=>r.create(t),u=e.uvRatio||((t,e)=>{try{return{isValid:!0,value:r.sqrt(r.div(t,e))}}catch(t){return{isValid:!1,value:ze}}});if(!function(t,e,n,r){const i=t.sqr(n),o=t.sqr(r),s=t.add(t.mul(e.a,i),o),c=t.add(t.ONE,t.mul(e.d,t.mul(i,o)));return t.eql(s,c)}(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function d(t,e,n=!1){return Qt("coordinate "+t,e,n?Ce:ze,c),e}function f(t){if(!(t instanceof y))throw new Error("ExtendedPoint expected")}const l=re((t,e)=>{const{X:n,Y:i,Z:o}=t,s=t.is0();null==e&&(e=s?qe:r.inv(o));const c=a(n*e),u=a(i*e),d=r.mul(o,e);if(s)return{x:ze,y:Ce};if(d!==Ce)throw new Error("invZ was invalid");return{x:c,y:u}}),h=re(t=>{const{a:e,d:n}=o;if(t.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:s,T:c}=t,u=a(r*r),d=a(i*i),f=a(s*s),l=a(f*f),h=a(u*e);if(a(f*a(h+d))!==a(l+a(n*a(u*d))))throw new Error("bad point: equation left != right (1)");if(a(r*i)!==a(s*c))throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(t,e,n,r){this.X=d("x",t),this.Y=d("y",e),this.Z=d("z",n,!0),this.T=d("t",r),Object.freeze(this)}static CURVE(){return o}static fromAffine(t){if(t instanceof y)throw new Error("extended point not allowed");const{x:e,y:n}=t||{};return d("x",e),d("y",n),new y(e,n,Ce,a(e*n))}static fromBytes(t,e=!1){const n=r.BYTES,{a:i,d:s}=o;t=Xt(Mt(t,n,"point")),Ft(e,"zip215");const d=Xt(t),f=t[n-1];d[n-1]=-129&f;const l=Gt(d),h=e?c:r.ORDER;Qt("point.y",l,ze,h);const p=a(l*l),w=a(p-Ce),g=a(s*p-i);let{isValid:b,value:m}=u(w,g);if(!b)throw new Error("bad point: invalid y coordinate");const v=(m&Ce)===Ce,k=!!(128&f);if(!e&&m===ze&&k)throw new Error("bad point: x=0 and x_0=1");return k!==v&&(m=a(-m)),y.fromAffine({x:m,y:l})}static fromHex(t,e=!1){return y.fromBytes(Zt("point",t),e)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return p.createCache(this,t),e||this.multiply(He),this}assertValidity(){h(this)}equals(t){f(t);const{X:e,Y:n,Z:r}=this,{X:i,Y:o,Z:s}=t,c=a(e*s),u=a(i*r),d=a(n*s),l=a(o*r);return c===u&&d===l}is0(){return this.equals(y.ZERO)}negate(){return new y(a(-this.X),this.Y,this.Z,a(-this.T))}double(){const{a:t}=o,{X:e,Y:n,Z:r}=this,i=a(e*e),s=a(n*n),c=a(He*a(r*r)),u=a(t*i),d=e+n,f=a(a(d*d)-i-s),l=u+s,h=l-c,p=u-s,w=a(f*h),g=a(l*p),b=a(f*p),m=a(h*l);return new y(w,g,m,b)}add(t){f(t);const{a:e,d:n}=o,{X:r,Y:i,Z:s,T:c}=this,{X:u,Y:d,Z:l,T:h}=t,p=a(r*u),w=a(i*d),g=a(c*n*h),b=a(s*l),m=a((r+i)*(u+d)-p-w),v=b-g,k=b+g,E=a(w-e*p),I=a(m*v),x=a(k*E),A=a(m*E),N=a(v*k);return new y(I,x,N,A)}subtract(t){return this.add(t.negate())}multiply(t){if(!i.isValidNot0(t))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:e,f:n}=p.cached(this,t,t=>Oe(y,t));return Oe(y,[e,n])[0]}multiplyUnsafe(t,e=y.ZERO){if(!i.isValid(t))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return t===ze?y.ZERO:this.is0()||t===Ce?this:p.unsafe(this,t,t=>Oe(y,t),e)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return p.unsafe(this,o.n).is0()}toAffine(t){return l(this,t)}clearCofactor(){return s===Ce?this:this.multiplyUnsafe(s)}toBytes(){const{x:t,y:e}=this.toAffine(),n=r.toBytes(e);return n[n.length-1]|=t&Ce?128:0,n}toHex(){return tt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(t){return Oe(y,t)}static msm(t,e){return Ke(y,i,t,e)}_setWindowSize(t){this.precompute(t)}toRawBytes(){return this.toBytes()}}y.BASE=new y(o.Gx,o.Gy,Ce,a(o.Gx*o.Gy)),y.ZERO=new y(ze,Ce,Ce,ze),y.Fp=r,y.Fn=i;const p=new De(y,i.BITS);return y.BASE.precompute(8),y}(e,n),r,i))}rt("HashToScalar-");const je=BigInt(0),Ge=BigInt(1),Ye=BigInt(2);const We=BigInt(0),Ze=BigInt(1),Xe=BigInt(2),Je=BigInt(3),Qe=BigInt(5),tn=BigInt(8),en=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),nn=(()=>({p:en,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:tn,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function rn(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),o=en,s=t*t%o*t%o,c=pe(s,Xe,o)*s%o,a=pe(c,Ze,o)*t%o,u=pe(a,Qe,o)*a%o,d=pe(u,e,o)*u%o,f=pe(d,n,o)*d%o,l=pe(f,r,o)*f%o,h=pe(l,i,o)*l%o,y=pe(h,i,o)*l%o,p=pe(y,e,o)*u%o;return{pow_p_5_8:pe(p,Xe,o)*t%o,b2:s}}function on(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const sn=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function cn(t,e){const n=en,r=ye(e*e*e,n),i=ye(r*r*e,n);let o=ye(t*r*rn(t*i).pow_p_5_8,n);const s=ye(e*o*o,n),c=o,a=ye(o*sn,n),u=s===t,d=s===ye(-t,n),f=s===ye(-t*sn,n);return u&&(o=c),(d||f)&&(o=a),ke(o,n)&&(o=ye(-o,n)),{isValid:u||d,value:o}}const an=(()=>Ae(nn.p,{isLE:!0}))(),un=(()=>Ae(nn.n,{isLE:!0}))(),dn=(()=>({...nn,Fp:an,hash:Ct,adjustScalarBytes:on,uvRatio:cn}))(),fn=(()=>Me(dn))(),ln=(()=>{const t=an.ORDER;return function(t){const e=(ee(n=t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...n}));var n;const{P:r,type:i,adjustScalarBytes:o,powPminus2:s,randomBytes:c}=e,a="x25519"===i;if(!a&&"x448"!==i)throw new Error("invalid type");const u=c||at,d=a?255:448,f=a?32:56,l=a?BigInt(9):BigInt(5),h=a?BigInt(121665):BigInt(39081),y=a?Ye**BigInt(254):Ye**BigInt(447),p=a?BigInt(8)*Ye**BigInt(251)-Ge:BigInt(4)*Ye**BigInt(445)-Ge,w=y+p+Ge,g=t=>ye(t,r),b=m(l);function m(t){return Wt(g(t),f)}function v(t,e){const n=function(t,e){Qt("u",t,je,r),Qt("scalar",e,y,w);const n=e,i=t;let o=Ge,c=je,a=t,u=Ge,f=je;for(let t=BigInt(d-1);t>=je;t--){const e=n>>t&Ge;f^=e,({x_2:o,x_3:a}=E(f,o,a)),({x_2:c,x_3:u}=E(f,c,u)),f=e;const r=o+c,s=g(r*r),d=o-c,l=g(d*d),y=s-l,p=a+u,w=g((a-u)*r),b=g(p*d),m=w+b,v=w-b;a=g(m*m),u=g(i*g(v*v)),o=g(s*l),c=g(y*(s+g(h*y)))}({x_2:o,x_3:a}=E(f,o,a)),({x_2:c,x_3:u}=E(f,c,u));const l=s(c);return g(o*l)}(function(t){const e=Zt("u coordinate",t,f);return a&&(e[31]&=127),g(Gt(e))}(e),function(t){return Gt(o(Zt("scalar",t,f)))}(t));if(n===je)throw new Error("invalid private or public key received");return m(n)}function k(t){return v(t,b)}function E(t,e,n){const r=g(t*(e-n));return{x_2:e=g(e-r),x_3:n=g(n+r)}}const I={secretKey:f,publicKey:f,seed:f},x=(t=u(f))=>(q(t,I.seed),t);return{keygen:function(t){const e=x(t);return{secretKey:e,publicKey:k(e)}},getSharedSecret:(t,e)=>v(t,e),getPublicKey:t=>k(t),scalarMult:v,scalarMultBase:k,utils:{randomSecretKey:x,randomPrivateKey:x},GuBytes:b.slice(),lengths:I}}({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=rn(e);return ye(pe(n,Je,t)*r,t)},adjustScalarBytes:on})})(),hn=sn,yn=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),pn=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),wn=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),gn=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),bn=t=>cn(Ze,t),mn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),vn=t=>fn.Point.Fp.create(Gt(t)&mn);function kn(t){const{d:e}=nn,n=en,r=t=>an.create(t),i=r(hn*t*t),o=r((i+Ze)*wn);let s=BigInt(-1);const c=r((s-e*i)*r(i+e));let{isValid:a,value:u}=cn(o,c),d=r(u*t);ke(d,n)||(d=r(-d)),a||(u=d),a||(s=i);const f=r(s*(i-Ze)*gn-c),l=u*u,h=r((u+u)*c),y=r(f*yn),p=r(Ze-l),w=r(Ze+l);return new fn.Point(r(h*w),r(p*y),r(y*w),r(h*p))}class En extends Fe{constructor(t){super(t)}static fromAffine(t){return new En(fn.Point.fromAffine(t))}assertSame(t){if(!(t instanceof En))throw new Error("RistrettoPoint expected")}init(t){return new En(t)}static hashToCurve(t){return function(t){q(t,64);const e=kn(vn(t.subarray(0,32))),n=kn(vn(t.subarray(32,64)));return new En(e.add(n))}(Zt("ristrettoHash",t,64))}static fromBytes(t){q(t,32);const{a:e,d:n}=nn,r=en,i=t=>an.create(t),o=vn(t);if(!function(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}(an.toBytes(o),t)||ke(o,r))throw new Error("invalid ristretto255 encoding 1");const s=i(o*o),c=i(Ze+e*s),a=i(Ze-e*s),u=i(c*c),d=i(a*a),f=i(e*n*u-d),{isValid:l,value:h}=bn(i(f*d)),y=i(h*a),p=i(h*y*f);let w=i((o+o)*y);ke(w,r)&&(w=i(-w));const g=i(c*p),b=i(w*g);if(!l||ke(b,r)||g===We)throw new Error("invalid ristretto255 encoding 2");return new En(new fn.Point(w,g,Ze,b))}static fromHex(t){return En.fromBytes(Zt("ristrettoHex",t,32))}static msm(t,e){return Ke(En,fn.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:r}=this.ep;const i=en,o=t=>an.create(t),s=o(o(n+e)*o(n-e)),c=o(t*e),a=o(c*c),{value:u}=bn(o(s*a)),d=o(u*s),f=o(u*c),l=o(d*f*r);let h;if(ke(r*l,i)){let n=o(e*hn),r=o(t*hn);t=n,e=r,h=o(d*pn)}else h=f;ke(t*l,i)&&(e=o(-e));let y=o((n-e)*h);return ke(y,i)&&(y=o(-y)),an.toBytes(y)}equals(t){this.assertSame(t);const{X:e,Y:n}=this.ep,{X:r,Y:i}=t.ep,o=t=>an.create(t),s=o(e*i)===o(n*r),c=o(n*i)===o(e*r);return s||c}is0(){return this.equals(En.ZERO)}}En.BASE=(()=>new En(fn.Point.BASE))(),En.ZERO=(()=>new En(fn.Point.ZERO))(),En.Fp=(()=>an)(),En.Fn=(()=>un)();class In extends st{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,F(t);const n=it(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?t.create().update(n).digest():n);for(let t=0;t<i.length;t++)i[t]^=54;this.iHash.update(i),this.oHash=t.create();for(let t=0;t<i.length;t++)i[t]^=106;this.oHash.update(i),G(i)}update(t){return M(this),this.iHash.update(t),this}digestInto(t){M(this),q(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:e,iHash:n,finished:r,destroyed:i,blockLen:o,outputLen:s}=this;return t.finished=r,t.destroyed=i,t.blockLen=o,t.outputLen=s,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const xn=(t,e,n)=>new In(t,e).update(n).digest();xn.create=(t,e)=>new In(t,e);const An=Uint8Array.from([0]),Nn=Uint8Array.of(),Sn=(t,e,n,r,i)=>function(t,e,n,r=32){F(t),H(r);const i=t.outputLen;if(r>255*i)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(r/i);void 0===n&&(n=Nn);const s=new Uint8Array(o*i),c=xn.create(t,e),a=c._cloneInto(),u=new Uint8Array(c.outputLen);for(let t=0;t<o;t++)An[0]=t+1,a.update(0===t?Nn:u).update(n).update(An).digestInto(u),s.set(u,i*t),c._cloneInto(a);return c.destroy(),a.destroy(),G(u,An),s.slice(0,r)}(t,function(t,e,n){return F(t),void 0===n&&(n=new Uint8Array(t.outputLen)),xn(t,it(n),it(e))}(t,e,n),r,i),Bn=zt;class On extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const e=super.get(t);return super.has(t)&&void 0!==e&&(this.delete(t),super.set(t,e)),e}set(t,e){if(super.set(t,e),this.maxSize&&this.size>this.maxSize){const t=this.keys().next().value;t&&this.delete(t)}return this}}const _n="2.45.1";let Pn=({docsBaseUrl:t,docsPath:e="",docsSlug:n})=>e?`${t??"https://viem.sh"}${e}${n?`#${n}`:""}`:void 0,$n=`viem@${_n}`;class Un extends Error{constructor(t,e={}){const n=e.cause instanceof Un?e.cause.details:e.cause?.message?e.cause.message:e.details,r=e.cause instanceof Un&&e.cause.docsPath||e.docsPath,i=Pn?.({...e,docsPath:r});super([t||"An error occurred.","",...e.metaMessages?[...e.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...$n?[`Version: ${$n}`]:[]].join("\n"),e.cause?{cause:e.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=r,this.metaMessages=e.metaMessages,this.name=e.name??this.name,this.shortMessage=t,this.version=_n}walk(t){return Rn(this,t)}}function Rn(t,e){return e?.(t)?t:t&&"object"==typeof t&&"cause"in t&&void 0!==t.cause?Rn(t.cause,e):e?null:t}class Tn extends Un{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}function Ln(t,{strict:e=!0}={}){return!!t&&"string"==typeof t&&(e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x"))}class Dn extends Un{constructor({size:t,targetSize:e,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${e}).`,{name:"SizeExceedsPaddingSizeError"})}}function Kn(t,{dir:e,size:n=32}={}){return"string"==typeof t?function(t,{dir:e,size:n=32}={}){if(null===n)return t;const r=t.replace("0x","");if(r.length>2*n)throw new Dn({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r["right"===e?"padEnd":"padStart"](2*n,"0")}`}(t,{dir:e,size:n}):function(t,{dir:e,size:n=32}={}){if(null===n)return t;if(t.length>n)throw new Dn({size:t.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const o="right"===e;r[o?i:n-i-1]=t[o?i:t.length-i-1]}return r}(t,{dir:e,size:n})}class Vn extends Un{constructor({max:t,min:e,signed:n,size:r,value:i}){super(`Number "${i}" is not in safe ${r?`${8*r}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${e} to ${t})`:`(above ${e})`}`,{name:"IntegerOutOfRangeError"})}}class zn extends Un{constructor({givenSize:t,maxSize:e}){super(`Size cannot exceed ${e} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}function Cn(t){return Ln(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}function Hn(t,{size:e}){if(Cn(t)>e)throw new zn({givenSize:Cn(t),maxSize:e})}function qn(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let o;r?o=n?(1n<<8n*BigInt(r)-1n)-1n:2n**(8n*BigInt(r))-1n:"number"==typeof t&&(o=BigInt(Number.MAX_SAFE_INTEGER));const s="bigint"==typeof o&&n?-o-1n:0;if(o&&i>o||i<s){const e="bigint"==typeof t?"n":"";throw new Vn({max:o?`${o}${e}`:void 0,min:`${s}${e}`,signed:n,size:r,value:`${t}${e}`})}const c=`0x${(n&&i<0?(1n<<BigInt(8*r))+BigInt(i):i).toString(16)}`;return r?Kn(c,{size:r}):c}const Fn=new TextEncoder;const Mn={zero:48,nine:57,A:65,F:70,a:97,f:102};function jn(t){return t>=Mn.zero&&t<=Mn.nine?t-Mn.zero:t>=Mn.A&&t<=Mn.F?t-(Mn.A-10):t>=Mn.a&&t<=Mn.f?t-(Mn.a-10):void 0}function Gn(t,e={}){let n=t;e.size&&(Hn(n,{size:e.size}),n=Kn(n,{dir:"right",size:e.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,o=new Uint8Array(i);for(let t=0,e=0;t<i;t++){const n=jn(r.charCodeAt(e++)),i=jn(r.charCodeAt(e++));if(void 0===n||void 0===i)throw new Un(`Invalid byte sequence ("${r[e-2]}${r[e-1]}" in "${r}").`);o[t]=16*n+i}return o}function Yn(t,e={}){const n=Fn.encode(t);return"number"==typeof e.size?(Hn(n,{size:e.size}),Kn(n,{dir:"right",size:e.size})):n}const Wn=BigInt(0),Zn=BigInt(1),Xn=BigInt(2),Jn=BigInt(7),Qn=BigInt(256),tr=BigInt(113),er=[],nr=[],rr=[];for(let t=0,e=Zn,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],er.push(2*(5*r+n)),nr.push((t+1)*(t+2)/2%64);let i=Wn;for(let t=0;t<7;t++)e=(e<<Zn^(e>>Jn)*tr)%Qn,e&Xn&&(i^=Zn<<(Zn<<BigInt(t))-Zn);rr.push(i)}const ir=gt(rr,!0),or=ir[0],sr=ir[1],cr=(t,e,n)=>n>32?((t,e,n)=>e<<n-32|t>>>64-n)(t,e,n):((t,e,n)=>t<<n|e>>>32-n)(t,e,n),ar=(t,e,n)=>n>32?((t,e,n)=>t<<n-32|e>>>64-n)(t,e,n):((t,e,n)=>e<<n|t>>>32-n)(t,e,n);class ur extends st{constructor(t,e,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=e,this.outputLen=n,this.enableXOF=r,this.rounds=i,H(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");var o;this.state=new Uint8Array(200),this.state32=(o=this.state,new Uint32Array(o.buffer,o.byteOffset,Math.floor(o.byteLength/4)))}clone(){return this._cloneInto()}keccak(){X(this.state32),function(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let e=0;e<10;e++)n[e]=t[e]^t[e+10]^t[e+20]^t[e+30]^t[e+40];for(let e=0;e<10;e+=2){const r=(e+8)%10,i=(e+2)%10,o=n[i],s=n[i+1],c=cr(o,s,1)^n[r],a=ar(o,s,1)^n[r+1];for(let n=0;n<50;n+=10)t[e+n]^=c,t[e+n+1]^=a}let e=t[2],i=t[3];for(let n=0;n<24;n++){const r=nr[n],o=cr(e,i,r),s=ar(e,i,r),c=er[n];e=t[c],i=t[c+1],t[c]=o,t[c+1]=s}for(let e=0;e<50;e+=10){for(let r=0;r<10;r++)n[r]=t[e+r];for(let r=0;r<10;r++)t[e+r]^=~n[(r+2)%10]&n[(r+4)%10]}t[0]^=or[r],t[1]^=sr[r]}G(n)}(this.state32,this.rounds),X(this.state32),this.posOut=0,this.pos=0}update(t){M(this),q(t=it(t));const{blockLen:e,state:n}=this,r=t.length;for(let i=0;i<r;){const o=Math.min(e-this.pos,r-i);for(let e=0;e<o;e++)n[this.pos++]^=t[i++];this.pos===e&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:e,pos:n,blockLen:r}=this;t[n]^=e,128&e&&n===r-1&&this.keccak(),t[r-1]^=128,this.keccak()}writeInto(t){M(this,!1),q(t),this.finish();const e=this.state,{blockLen:n}=this;for(let r=0,i=t.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);t.set(e.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return H(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(j(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,G(this.state)}_cloneInto(t){const{blockLen:e,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return t||(t=new ur(e,n,r,o,i)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=n,t.outputLen=r,t.enableXOF=o,t.destroyed=this.destroyed,t}}const dr=(()=>{return t=1,e=136,n=32,ct(()=>new ur(e,t,n));var t,e,n})(),fr=new On(8192);function lr(t,e){if(fr.has(`${t}.${e}`))return fr.get(`${t}.${e}`);const n=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),r=function(t){const e=dr(Ln(t,{strict:!1})?function(t,e={}){return"number"==typeof t||"bigint"==typeof t?function(t,e){return Gn(qn(t,e))}(t,e):"boolean"==typeof t?function(t,e={}){const n=new Uint8Array(1);return n[0]=Number(t),"number"==typeof e.size?(Hn(n,{size:e.size}),Kn(n,{size:e.size})):n}(t,e):Ln(t)?Gn(t,e):Yn(t,e)}(t):t);return e}(Yn(n)),i=(e?n.substring(`${e}0x`.length):n).split("");for(let t=0;t<40;t+=2)r[t>>1]>>4>=8&&i[t]&&(i[t]=i[t].toUpperCase()),(15&r[t>>1])>=8&&i[t+1]&&(i[t+1]=i[t+1].toUpperCase());const o=`0x${i.join("")}`;return fr.set(`${t}.${e}`,o),o}const hr=/^0x[a-fA-F0-9]{40}$/,yr=new On(8192);function pr(t,e){const{strict:n=!0}=e??{},r=`${t}.${n}`;if(yr.has(r))return yr.get(r);const i=!(!hr.test(t)||t.toLowerCase()!==t&&n&&lr(t)!==t);return yr.set(r,i),i}var wr=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function gr(t){return"*"===t?"ALL":t.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function br(t){return t.slice(10,t.indexOf("/"))}function mr(t){return t.slice(t.indexOf("/")+1)}function vr(t){const e={};for(const n of wr)br(n.urn)===t&&(e[gr(mr(n.urn))]=n.urn);return e}var kr=vr("kv"),Er={...vr("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},Ir=(vr("duckdb"),vr("capabilities")),xr=(vr("hooks"),vr("encryption")),Ar=vr("space");["tinychat-4jq","share-2fz","tinycloud-secrets","openkey-tinycloud-demo"].map(t=>new RegExp(`^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)?${t}\\.pages\\.dev$`));var Nr="applications",Sr="account",Br="applications/",Or="secrets",_r="default",Pr="public",$r="agents",Ur="tinycloud.encryption",Rr=xr.NETWORK_CREATE,Tr=[_r,Nr,Sr,Or,Pr,$r],Lr={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:_r,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:_r,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:_r,path:"",actions:["read","write"]}]},Dr={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:Nr,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Nr,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:Nr,path:"",actions:["read","write"]}]},Kr={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:Sr,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Sr,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:Sr,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:Sr,path:"account",actions:["read","write","schema"]}]},Vr={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:Or,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:Or,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:Or,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:Or,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:Or,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:Or,path:"",actions:["read"],skipPrefix:!0}]},zr={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:Pr,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Pr,path:"",actions:["get","list","metadata"]}]},Cr={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:$r,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:$r,path:"",actions:["get","put","del","list","metadata"]}]},Hr={[_r]:Lr,[Nr]:Dr,[Sr]:Kr,[Or]:Vr,[Pr]:zr,[$r]:Cr};function qr(t,e=1){return function(t){if(!Number.isSafeInteger(t)||t<=0)throw new Error(`Invalid EIP-155 chain ID: ${t}`)}(e),`did:pkh:eip155:${e}:${function(t){if(!pr(t,{strict:!1}))throw new Error(`Invalid EVM address: ${t}`);return function(t){if(!pr(t,{strict:!1}))throw new Tn({address:t});return lr(t,void 0)}(t)}(t)}`}function Fr(t){return{...t,permissions:t.permissions?.map(t=>({...t,actions:[...t.actions]}))}}function Mr(t,e,n){return!0===n||""===t||""===e?e:"/"===e?`${t}/`:`${t.endsWith("/")?t.slice(0,-1):t}/${e.startsWith("/")?e.slice(1):e}`}function jr(t,e,n){if("tinycloud.vault"===t.service)return function(t){return t.actions.map(e=>{const n=e.startsWith("tinycloud.vault/")?e.slice(16):e.startsWith("tinycloud.kv/")?e.slice(13):e,r="read"===n||"get"===n?kr.GET:"write"===n||"put"===n?kr.PUT:"delete"===n||"del"===n?kr.DEL:"list"===n?kr.LIST:"metadata"===n?kr.METADATA:void 0;if(void 0===r)throw new Error(`unknown vault action ${JSON.stringify(e)}`);const i=t.path.startsWith("/")?t.path.slice(1):t.path;return{...t,service:"tinycloud.kv",path:`vault/${i}`,actions:[r],skipPrefix:!0}})}(t).flatMap(t=>jr(t,e,n));const r=!0===t.skipPrefix||t.service===Ur;return[{service:t.service,space:t.service===Ur?"encryption":t.space??n,path:Mr(e,t.path,r),actions:t.actions.map(e=>function(t,e){return e.includes("/")?e:`${t}/${e}`}(t.service,e)),...void 0!==t.description?{description:t.description}:{}}]}function Gr(t){const e=new Set(t.filter(t=>t.service!==Ur).map(t=>t.space));return function(t){const e=new Map;for(const n of t){const t=`${n.service}\0${n.space}\0${n.path}`,r=e.get(t);if(r)for(const t of n.actions)r.actions.includes(t)||r.actions.push(t);else e.set(t,{...n,actions:[...n.actions]})}return[...e.values()]}([...t,...[...e].map(t=>({service:"tinycloud.capabilities",space:t,path:"",actions:[Ir.READ]}))])}function Yr(t){return function(t,e={}){if(!Array.isArray(t)||0===t.length)throw new Error("composeManifestRequest requires at least one manifest");const n=e.includeAccountRegistryPermissions??!0,r=t.map(Fr),i=r.flatMap(t=>{const e=t.prefix??t.app_id,n=t.space??Nr;return(t.permissions??[]).flatMap(t=>jr(t,e,n))});n&&i.push(...Wr.map(t=>({...t,actions:[...t.actions]})));const o=new Map;for(const t of r){const e=o.get(t.app_id)??[];e.push(Fr(t)),o.set(t.app_id,e)}return{manifests:r,resources:Gr(i),delegationTargets:[],registryRecords:n?[...o.entries()].map(([t,e])=>({key:`${Br}${t}`,app_id:t,manifests:e})):[],expiryMs:2592e6,includePublicSpace:r.some(t=>t.includePublicSpace??!0)}}([Hr[t]],{includeAccountRegistryPermissions:!1})}Tr.map(t=>({name:t,manifest:Hr[t],persistedAsApplication:t===Or}));var Wr=Object.freeze([{service:"tinycloud.kv",space:Sr,path:Br,actions:[kr.GET,kr.PUT,kr.LIST]},{service:"tinycloud.kv",space:Sr,path:"spaces/",actions:[kr.GET,kr.PUT,kr.LIST]},{service:"tinycloud.kv",space:Sr,path:"system/bootstrap/complete",actions:[kr.GET,kr.PUT]},{service:"tinycloud.delegation",space:Sr,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:Sr,path:"account",actions:[Er.READ,Er.WRITE,Er.SCHEMA]},{service:"tinycloud.capabilities",space:Sr,path:"",actions:[Ir.READ]}]),Zr=Yr(_r),Xr={...Zr,resources:[...Zr.resources,...Wr.map(t=>({...t,actions:[...t.actions]}))]},Jr=Object.freeze(Object.fromEntries(Tr.map(t=>[t,t===_r?Xr:Yr(t)]))),Qr=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[Rr]}]);function ti(t){return void 0===t?"":ei(t)}function ei(t){if(null===t)return"null";switch(typeof t){case"boolean":case"number":case"string":return JSON.stringify(t);case"object":{if(Array.isArray(t))return`[${t.map(ei).join(",")}]`;const e=Object.keys(t).sort(),n=[];for(const r of e){const e=t[r];void 0!==e&&n.push(`${JSON.stringify(r)}:${ei(e)}`)}return`{${n.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof t)}}Object.freeze(Tr.flatMap(t=>[{kind:"session",service:"tinycloud.session",space:t,actions:["siwe"],resources:Jr[t].resources,...t===Sr?{rawAbilities:Qr}:{}},{kind:"space/host",service:"tinycloud.space",space:t,actions:[Ar.HOST]}]));var ni="0123456789abcdef";function ri(t){let e="";for(let n=0;n<t.length;n++){const r=t[n];e+=ni[r>>4&15]+ni[15&r]}return e}function ii(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let n="";for(let r=0;r<t.length;r+=3){const i=t[r],o=r+1<t.length?t[r+1]:0,s=r+2<t.length?t[r+2]:0;n+=e[i>>2&63],n+=e[63&(i<<4|o>>4)],n+=r+1<t.length?e[63&(o<<2|s>>6)]:"=",n+=r+2<t.length?e[63&s]:"="}return n}function oi(t){const e=t.replace(/[^A-Za-z0-9+/=]/g,""),n=e.length;if(n%4!=0)throw new Error("invalid base64 input");const r=n/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0),i=new Uint8Array(r),o={};for(let t=0;t<64;t++)o["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[t]]=t;let s=0;for(let t=0;t<n;t+=4){const n=o[e[t]]??0,c=o[e[t+1]]??0,a="="===e[t+2]?0:o[e[t+2]]??0,u=n<<2|c>>4,d=(15&c)<<4|a>>2,f=(3&a)<<6|("="===e[t+3]?0:o[e[t+3]]??0);s<r&&(i[s++]=u),s<r&&(i[s++]=d),s<r&&(i[s++]=f)}return i}function si(t){return(new TextEncoder).encode(t)}function ci(t,e){return ri(t(si(ti(e))))}var ai="urn:tinycloud:encryption:",ui=/^[a-z0-9][a-z0-9-]*$/,di=class extends Error{constructor(t){super(t),this.name="NetworkIdError"}};function fi(t){if("string"!=typeof t||0===t.length)throw new di("networkId must be a non-empty string");if(!t.startsWith(ai))throw new di(`networkId must start with ${ai} (got ${JSON.stringify(t)})`);const e=t.slice(25),n=e.lastIndexOf(":");if(n<=0||n===e.length-1)throw new di(`networkId missing ownerDid or name segment (got ${JSON.stringify(t)})`);const r=e.slice(0,n),i=e.slice(n+1);if(!r.startsWith("did:"))throw new di(`networkId ownerDid must be a DID (got ${JSON.stringify(r)})`);const o=r.split(":");if(o.length<3||o.some(t=>0===t.length))throw new di(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(r)})`);if(!ui.test(i))throw new di(`networkId name ${JSON.stringify(i)} must match ${ui.source}`);return{networkId:t,ownerDid:r,name:i}}var li=ai,hi="tinycloud.encryption.decrypt/v1",yi="tinycloud.encryption.decrypt-result/v1",pi="tinycloud.encryption/decrypt";function wi(t){switch(t.code){case"NETWORK_NOT_FOUND":return t.message??`Network not found: ${t.networkId??t.name??"<unknown>"}`;case"NETWORK_NOT_ACTIVE":return t.message??`Network not active (state=${t.state})`;case"INVALID_NETWORK_ID":case"INVALID_ENVELOPE":case"DECRYPT_DENIED":case"INVALID_RESPONSE":case"INVALID_INPUT":return t.message;case"RESPONSE_SIGNATURE_INVALID":return t.message??"Node response signature failed to verify";case"RESPONSE_BINDING_MISMATCH":return t.message??`Node response binding mismatch on field ${JSON.stringify(t.field)}`;case"TRANSPORT_ERROR":return t.message??t.cause.message;default:return t.message??t.code}}function gi(t){return{...t,service:"encryption",message:wi(t)}}var bi="x25519-hkdf-aes256gcm/v2",mi=si("TCW2"),vi=si("tinycloud.encryption.key-wrap/v2");function ki(...t){const e=new Uint8Array(t.reduce((t,e)=>t+e.length,0));let n=0;for(const r of t)e.set(r,n),n+=r.length;return e}function Ei(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}function Ii(t){if("string"!=typeof t)throw new Error("Invalid key wrap encoding");const e=oi(t);if(32!==e.length||ii(e)!==t)throw new Error("Invalid key wrap encoding");return e}function xi(t){for(let e=0;e<t.length;e++){const n=t.charCodeAt(e);if(n>=55296&&n<=56319){const n=t.charCodeAt(++e);if(!(n>=56320&&n<=57343))return!1}else if(n>=56320&&n<=57343)return!1}return!0}function Ai(t){if("network-key"!==t.purpose&&"receiver-key"!==t.purpose||"string"!=typeof t.networkId||"string"!=typeof t.keyPath||!xi(t.networkId)||!xi(t.keyPath)||!Number.isSafeInteger(t.keyVersion)||t.keyVersion<=0||!t.metadata||"object"!=typeof t.metadata||Array.isArray(t.metadata)||Object.entries(t.metadata).some(([t,e])=>!xi(t)||"string"!=typeof e||!xi(e)))throw new Error("Invalid key wrap context");if(""!==t.networkId){const e=function(t){const e=t.lastIndexOf(":"),n=t.slice(e+1),r=n.indexOf("/"),i=-1===r?n:n.slice(0,r),o=fi(-1===r?t:`${t.slice(0,e+1)}${i}`);if(-1===r)return o;const s=n.slice(r+1),c=s.split("/"),a=s.endsWith("/");if(0===s.length||/[\u0000-\u001f\u007f\\]/.test(s)||c.some((t,e)=>"."===t||".."===t||0===t.length&&!(a&&e===c.length-1)))throw new di(`encryption resource has an invalid keyPath (got ${JSON.stringify(t)})`);return{...o,keyPath:s}}(""===t.keyPath?t.networkId:`${t.networkId}/${t.keyPath}`);if(e.networkId!==t.networkId||(e.keyPath??"")!==t.keyPath||t.keyPath.endsWith("/"))throw new Error("Invalid key wrap resource")}}function Ni(t){return t.length>=4&&mi.every((e,n)=>t[n]===e)}function Si(t){if(!Ni(t)||t.length<8)throw new Error("Invalid v2 key wrap frame");const e=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(4);if(0===e||e>65536||t.length<8+e+12+16)throw new Error("Invalid v2 key wrap length");const n=t.subarray(8,8+e),r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)),i=["v","alg","kdf","aead","salt","ephemeralPublicKey","recipientPublicKey","purpose","networkId","keyPath","keyVersion","metadata"].sort();if(!r||"object"!=typeof r||Array.isArray(r)||Object.keys(r).sort().join(",")!==i.join(",")||2!==r.v||r.alg!==bi||"hkdf-sha256"!==r.kdf||"aes-256-gcm"!==r.aead)throw new Error("Invalid v2 key wrap header");if(Ai(r),Ii(r.salt),Ii(r.ephemeralPublicKey),Ii(r.recipientPublicKey),!Ei(n,si(ti({...r}))))throw new Error("Non-canonical v2 key wrap header");const o=8+e;return{header:r,aad:t.subarray(0,o),nonce:t.subarray(o,o+12),ciphertext:t.subarray(o+12)}}function Bi(t,e){Ai(e);for(const n of["purpose","networkId","keyPath","keyVersion"])if(t[n]!==e[n])throw new Error("Key wrap context mismatch");if(ti(t.metadata)!==ti(e.metadata))throw new Error("Key wrap metadata mismatch")}function Oi(t,e,n=!1){if("x25519-aes256gcm/v1"!==e&&e!==bi)throw new Error("Unsupported key wrap algorithm");if(n&&e!==bi)throw new Error("V2 network key wrap required");if(Ni(t)!==(e===bi))throw new Error("Key wrap algorithm mismatch");e===bi&&Si(t)}function _i(t,e=!1){const n=oi(t.encryptedSymmetricKey);Oi(n,t.alg,e),t.alg===bi&&Bi(Si(n).header,{purpose:"network-key",networkId:t.networkId,keyPath:t.keyPath??"",keyVersion:t.keyVersion,metadata:t.metadata??{}})}var Pi="[a-z0-9][a-z0-9._-]{0,63}",$i=new RegExp(`^${Pi}(?:/${Pi}){0,7}$`),Ui=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ri=/^(did:[a-z0-9]+:[A-Za-z0-9._:-]+):([^:/]+)(?:\/(.*))?$/s,Ti="did:pkh:eip155:",Li="tinycloud.encryption/key.create",Di="tinycloud.encryption/key.block",Ki="tinycloud.encryption/key.unblock",Vi=(Object.freeze([pi,Li,Di,Ki]),class extends Error{constructor(t,e){super(e),this.name="EncryptionResourceError",this.code=t}});function zi(t){if(!t.startsWith(Ti))return t;const e=t.slice(15),n=e.indexOf(":"),r=-1===n?"":e.slice(0,n),i=-1===n?"":e.slice(n+1);if(!/^\d+$/.test(r)||!/^0x[a-fA-F0-9]{40}$/.test(i))throw new Vi("bad_owner",`owner DID is not a valid did:pkh:eip155 (got ${JSON.stringify(t)})`);const o=BigInt(r);if(0n===o||o>18446744073709551615n)throw new Vi("bad_owner",`did:pkh:eip155 chain id must be a positive u64 (got ${JSON.stringify(r)})`);const s=qr(i,1).slice(17);return`${Ti}${o}:${s}`}function Ci(t){const e=zi(t);if(e!==t)throw new Vi("non_canonical_owner",`owner DID is not canonical (expected ${e})`)}function Hi(t,e){if(0===t.length)throw new Vi("empty_path",`${e} must not be empty`);if((new TextEncoder).encode(t).length>255)throw new Vi("path_too_long",`${e} exceeds 255 bytes`);if(!$i.test(t))throw new Vi("bad_path",`${e} ${JSON.stringify(t)} must match ${$i.source}`);const n=t.split("/");if("apps"===n[0]&&n.length<("key path"===e?3:2))throw new Vi("bad_path",`${e} ${JSON.stringify(t)} under apps/ needs ${"key path"===e?"apps/<id>/<name>":"apps/<id>/"}`)}function qi(t){if("string"!=typeof t||!t.startsWith(li))throw new Vi("not_encryption_urn",`resource must start with ${li}`);const e=t.slice(25),n=Ri.exec(e);if(null===n)throw new Vi("malformed",`resource is not <ownerDid>:<network>[/<path>] (got ${JSON.stringify(t)})`);const r=n[1],i=n[2],o=n[3];if(void 0===o){const t=zi(r),e=`${li}${t}:${i}`;try{fi(e)}catch(t){if(t instanceof di)throw new Vi("bad_network",t.message);throw t}return{kind:"network",ownerDid:t,network:i,networkId:e}}if(!Ui.test(i))throw new Vi("bad_network",`network ${JSON.stringify(i)} must match ${Ui.source}`);Ci(r);const s=`${li}${r}:${i}`;if(o.endsWith("/")){const t=o.slice(0,-1);return Hi(t,"prefix"),{kind:"prefix",ownerDid:r,network:i,networkId:s,prefix:t}}return Hi(o,"key path"),{kind:"key",ownerDid:r,network:i,networkId:s,path:o}}function Fi(t){let e="";for(const n of t){const t=n.codePointAt(0);e+=t>=32&&t<=126?n:`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`}return e}function Mi(t){const e="string"==typeof t?t:String(t),n=Array.from(e);return Fi(n.length>120?`${n.slice(0,120).join("")}...`:e)}var ji=class extends Error{constructor(t,e,n={}){super(Fi(e),void 0===n.cause?void 0:{cause:n.cause}),this.name="NamedKeyError",this.code=t,void 0!==n.status&&(this.status=n.status),void 0!==n.nodeCode&&(this.nodeCode=n.nodeCode),void 0!==n.detail&&(this.detail=n.detail),void 0!==n.rawState&&(this.rawState=n.rawState),void 0!==n.kind&&(this.kind=n.kind),void 0!==n.input&&(this.input=n.input)}},Gi=Object.assign(Object.create(null),{key_blocked:"KEY_BLOCKED",key_not_found:"KEY_NOT_FOUND",key_exists:"KEY_EXISTS",network_not_found:"NETWORK_NOT_FOUND",network_not_active:"NETWORK_NOT_ACTIVE",key_limit_exceeded:"KEY_LIMIT_EXCEEDED",deletable_unavailable:"DELETABLE_UNAVAILABLE",key_not_deletable:"KEY_NOT_DELETABLE",key_path_invalid:"KEY_PATH_INVALID",key_unwrap_failed:"KEY_UNWRAP_FAILED",receiver_key_invalid:"RECEIVER_KEY_INVALID"}),Yi=Object.assign(Object.create(null),{key_deleted:!0}),Wi=/^([a-z][a-z0-9_]*):\s?([\s\S]*)$/;function Zi(t,e,n){const r=Wi.exec(e.trim()),i=r?.[1]?.slice(0,64),o=r?.[2]?.trim(),s={status:t,...void 0===i?{}:{nodeCode:i},...void 0===o||0===o.length?{}:{detail:o}};if(void 0!==i){const t=Gi[i];if(void 0!==t)return new ji(t,`${n}: ${i}`,s);if(!0===Yi[i])return new ji("KEY_UNAVAILABLE",`${n}: key unavailable (${i})`,{...s,rawState:i})}return new ji("NODE_ERROR",`${n}: node responded ${t}`,s)}function Xi(t){let e;try{e=qi(t)}catch(e){throw new ji("INVALID_KEY_TARGET",`not a valid encryption key resource: ${Mi(e instanceof Error?e.message:e)}`,{cause:e,input:t})}if("key"!==e.kind)throw new ji("INVALID_KEY_TARGET",`a ${e.kind} resource cannot be an invocation target; an exact key is required`,{input:t});return e}function Ji(t){const e=Xi(t.keyResource);return{type:"tinycloud.encryption.key-admin/v1",targetNode:t.targetNode,networkId:e.networkId,keyPath:e.path,action:t.action,bodyHash:ci(t.crypto.sha256,t.body)}}function Qi(t){const e=Xi(t.keyResource);return{type:"tinycloud.encryption.key-describe/v1",targetNode:t.targetNode,networkId:e.networkId,keyPath:e.path}}var to={[pi]:!0,[Li]:!0,[Di]:!0,[Ki]:!0};function eo(t){return new ji("INVALID_RESPONSE",`node returned an invalid ${t}`)}function no(t,e,n){const r="object"==typeof t&&null!==t?t:{};if("string"!=typeof r.alg||"number"!=typeof r.keyVersion||!Number.isInteger(r.keyVersion)||"string"!=typeof r.publicEncryptionKey||0===r.publicEncryptionKey.length)throw eo("key descriptor");if(r.networkId!==e||r.keyPath!==n)throw new ji("INVALID_RESPONSE","node returned a descriptor for a different network or key");return{networkId:e,keyPath:n,alg:r.alg,keyVersion:r.keyVersion,publicEncryptionKey:r.publicEncryptionKey}}function ro(t,e,n){const r=no(t,e,n),i=t;if("string"!=typeof i.state||"string"!=typeof i.kind)throw eo("key descriptor (state/kind missing)");return{...r,state:i.state,kind:i.kind,..."string"==typeof i.createdAt?{createdAt:i.createdAt}:{},..."string"==typeof i.updatedAt?{updatedAt:i.updatedAt}:{}}}function io(t){return t.startsWith("apps/")}var oo=["alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"],so=class{constructor(t){this.config=t,this.nodeInfo=new Map}networkFor(t){return t?.networkId??this.config.defaultNetworkId()}keyUrn(t,e){try{return function(t,e){const n=function(t){let e;try{e=fi(t)}catch(t){if(t instanceof di)throw new Vi("bad_network",t.message);throw t}return Ci(e.ownerDid),e.networkId}(t);Hi(e,"key path");const r=`${n}/${e}`;return function(t,e){if(qi(t).networkId!==e)throw new Vi("malformed",`built resource does not round-trip (got ${JSON.stringify(t)})`)}(r,n),r}(t,e)}catch(n){throw new ji("INVALID_KEY_TARGET",Mi(n instanceof Error?n.message:n),{cause:n,input:`${t}/${e}`})}}async requireNode(t){const e=void 0===this.config.resolveNode?void 0:await this.config.resolveNode(t),n=e?.url??this.config.host,r=`${n} ${e?.nodeDid??""}`;let i=this.nodeInfo.get(r);if(void 0===i){const t=this.readNodeInfo(n,e?.nodeDid);i=t,this.nodeInfo.set(r,t),t.catch(()=>{this.nodeInfo.get(r)===t&&this.nodeInfo.delete(r)})}return{url:n,nodeDid:await i}}refreshNodeInfo(){this.nodeInfo.clear()}async readNodeInfo(t,e){const n=await this.config.fetch(`${t}/info`);if(!n.ok)throw Zi(n.status,await co(n),"failed to read node info");const r=await n.json();if(!function(t){const e=t?.features;return Array.isArray(e)&&e.includes("encryption-named-keys-v1")}(r))throw new ji("NAMED_KEYS_UNSUPPORTED","this node does not support named encryption keys");if("string"!=typeof r.nodeId||0===r.nodeId.length)throw eo("/info response (nodeId missing)");if(void 0!==e&&r.nodeId!==e)throw new ji("NODE_IDENTITY_MISMATCH","the node's /info identity does not match its verified identity");return r.nodeId}keysUrl(t,e,n){return`${t}/encryption/networks/${e}/keys/${n}`}async getPublicKey(t,e){const n=this.networkFor(e);this.keyUrn(n,t);const r=await this.requireNode(n),i=await this.config.fetch(this.keysUrl(r.url,n,t),{method:"GET"});if(!i.ok)throw Zi(i.status,await co(i),"failed to read key");return no(await i.json(),n,t)}async describeKey(t,e){const n=this.networkFor(e),r=await this.describeBody(t,e);return null===r?null:ro(r,n,t)}async describePublic(t,e){const n=this.networkFor(e),r=await this.describeBody(t,e);if(null===r)throw new ji("KEY_NOT_FOUND",`key ${Mi(t)} does not exist`,{status:404});return no(r,n,t)}async describeBody(t,e){const n=this.networkFor(e),r=this.keyUrn(n,t),i=e?.ability??pi;if(!0!==to[i])throw new ji("INVALID_KEY_TARGET",`${Mi(i)} cannot describe a key`,{input:i});const{url:o,nodeDid:s}=await this.requireNode(n),c=await this.config.signInvocation({targetNode:s,resource:r,action:i,facts:Qi({targetNode:s,keyResource:r})}),a=await this.config.fetch(this.keysUrl(o,n,t),{method:"GET",headers:{Authorization:c.authorization}});if(404===a.status){const t=Zi(404,await co(a),"failed to describe key");if("KEY_NOT_FOUND"===t.code)return null;throw t}if(!a.ok)throw Zi(a.status,await co(a),"failed to describe key");return a.json()}async admin(t,e,n,r){const i=this.networkFor(r),o=this.keyUrn(i,n),s="keys"===t?{keyPath:n,deletable:io(n)}:{keyPath:n},{url:c,nodeDid:a}=await this.requireNode(i),u=await this.config.signInvocation({targetNode:a,resource:o,action:e,facts:Ji({crypto:this.config.crypto,targetNode:a,keyResource:o,action:e,body:s})}),d=await this.config.fetch(`${c}/encryption/networks/${i}/${t}`,{method:"POST",headers:{Authorization:u.authorization,"Content-Type":"application/json"},body:ti(s)});if(!d.ok)throw Zi(d.status,await co(d),`failed to ${e}`);return ro(function(t){const e="object"==typeof t&&null!==t?t:{};return"object"==typeof e.descriptor&&null!==e.descriptor?e.descriptor:t}(await d.json()),i,n)}createKey(t,e){return this.admin("keys",Li,t,e)}blockKey(t,e){return this.admin("key-actions/block",Di,t,e)}unblockKey(t,e){return this.admin("key-actions/unblock",Ki,t,e)}async ensureKey(t,e){const n=()=>this.describeKey(t,{...e,ability:Li});let r=await n();if(null===r)try{r=await this.createKey(t,e)}catch(e){if(!(e instanceof ji)||"KEY_EXISTS"!==e.code)throw e;if(r=await n(),null===r)throw new ji("KEY_NOT_FOUND",`key ${Mi(t)} reported as existing but could not be read back`)}return function(t,e){if("blocked"===t.state)throw new ji("KEY_BLOCKED",`key ${Mi(t.keyPath)} is blocked`,{rawState:t.state});if("active"!==t.state)throw new ji("KEY_UNAVAILABLE",`key ${Mi(t.keyPath)} is unavailable (state ${Mi(t.state)})`,{rawState:t.state});if(t.kind!==e)throw new ji("KEY_KIND_MISMATCH",`key ${Mi(t.keyPath)} exists with kind ${Mi(t.kind)}, not ${e}`,{kind:t.kind});return t}(r,io(t)?"deletable":"deterministic")}async encrypt(t,e,n){const r=io(t)?await this.describePublic(t,n):await this.getPublicKey(t,n),{crypto:i}=this.config,o=i.randomBytes(32),s=i.authEncrypt(o,e,n?.aad),c=n?.keyWrapV2??this.config.keyWrapV2??!1,a=oi(r.publicEncryptionKey),u=c?function(t,e,n){if(Ai(n),32!==t.length)throw new Error("Invalid recipient public key");const r=at(32),i=ln.getPublicKey(r),o=at(32),s=si(ti({...{...n,v:2,alg:bi,kdf:"hkdf-sha256",aead:"aes-256-gcm",salt:ii(o),ephemeralPublicKey:ii(i),recipientPublicKey:ii(t)}}));if(s.length>65536)throw new Error("Key wrap header too large");const c=new Uint8Array(8);c.set(mi),new DataView(c.buffer).setUint32(4,s.length);const a=ki(c,s),u=at(12);let d;try{const n=ln.getSharedSecret(r,t);try{if(n.every(t=>0===t))throw new Error("Invalid key agreement");d=Sn(Bn,n,o,ki(vi,i,t),32)}finally{n.fill(0)}return ki(a,u,K(d,u,a).encrypt(e))}finally{r.fill(0),d?.fill(0)}}(a,o,{purpose:"network-key",networkId:r.networkId,keyPath:r.keyPath,keyVersion:r.keyVersion,metadata:n?.metadata??{}}):i.sealToNetworkKey(a,o),d=ii(u);return{v:2,networkId:r.networkId,keyPath:r.keyPath,alg:c?bi:"x25519-aes256gcm/v1",keyVersion:r.keyVersion,encryptedSymmetricKey:d,encryptedSymmetricKeyHash:ci(i.sha256,d),ciphertext:ii(s),...void 0!==n?.aad?{aad:ii(n.aad)}:{},...void 0!==n?.metadata?{metadata:n.metadata}:{}}}async decrypt(t){const e="object"==typeof t&&null!==t?t:{};if(1===e.v&&void 0===e.keyPath)return this.decryptRoot(e);if(2===e.v&&"string"==typeof e.keyPath)return this.decryptKey(this.validateKeyEnvelope(e));throw new ji("INVALID_ENVELOPE","envelope must be v1 without keyPath or v2 with keyPath")}async decryptMany(t){const e=[];for(const n of t)try{e.push({ok:!0,data:await this.decrypt(n)})}catch(t){e.push({ok:!1,error:t instanceof ji?t:new ji("DECRYPT_FAILED","decrypt failed",{cause:t})})}return e}async decryptRoot(t){if(this.config.requireKeyWrapV2)try{_i(t,!0)}catch(t){throw new ji("INVALID_ENVELOPE","Envelope key wrap context is invalid",{cause:t})}if(void 0===this.config.decryptRoot)throw new ji("DECRYPT_FAILED","no root-key decrypt path is configured");const e=await this.config.decryptRoot(t);if(!e.ok)throw new ji("DECRYPT_FAILED",Mi(e.error.message),{cause:e.error});return e.data}validateKeyEnvelope(t){for(const e of oo)if("string"!=typeof t[e]||0===t[e].length)throw new ji("INVALID_ENVELOPE",`envelope.${e} must be a non-empty string`);if("number"!=typeof t.keyVersion||!Number.isInteger(t.keyVersion))throw new ji("INVALID_ENVELOPE","envelope.keyVersion must be an integer");if("string"!=typeof t.networkId)throw new ji("INVALID_ENVELOPE","envelope.networkId must be a string");try{fi(t.networkId)}catch(t){throw new ji("INVALID_ENVELOPE","envelope.networkId is malformed",{cause:t})}if(ci(this.config.crypto.sha256,t.encryptedSymmetricKey)!==t.encryptedSymmetricKeyHash)throw new ji("INVALID_ENVELOPE","envelope.encryptedSymmetricKeyHash does not match encryptedSymmetricKey");try{_i(t,this.config.requireKeyWrapV2??!1)}catch(t){throw new ji("INVALID_ENVELOPE","Envelope key wrap context is invalid",{cause:t})}return t}async decryptKey(t){const{crypto:e}=this.config,n=this.keyUrn(t.networkId,t.keyPath),{url:r,nodeDid:i}=await this.requireNode(t.networkId),o=function(t){const e=t.crypto.randomBytes(32);return t.crypto.x25519FromSeed(e)}({crypto:e}),s=ii(o.publicKey),c=ci(e.sha256,s),a={type:hi,targetNode:i,networkId:t.networkId,keyPath:t.keyPath,alg:t.alg,keyVersion:t.keyVersion,encryptedSymmetricKey:t.encryptedSymmetricKey,encryptedSymmetricKeyHash:t.encryptedSymmetricKeyHash,receiverPublicKey:s,receiverPublicKeyHash:c},u=ti(a),d={type:hi,targetNode:i,networkId:t.networkId,keyPath:t.keyPath,bodyHash:ci(e.sha256,a),encryptedSymmetricKeyHash:t.encryptedSymmetricKeyHash,receiverPublicKeyHash:c,alg:t.alg,keyVersion:t.keyVersion},f=await this.config.signInvocation({targetNode:i,resource:n,action:pi,facts:d}),l=await this.config.fetch(`${r}/invoke`,{method:"POST",headers:{Authorization:f.authorization,"Content-Type":"application/json"},body:u});if(!l.ok)throw Zi(l.status,await co(l),"failed to decrypt");const h=function(t){const{crypto:e,request:n,facts:r,invocationCid:i,requestBodyHash:o,response:s}=t;if(s.type!==yi)return{ok:!1,error:gi({code:"INVALID_RESPONSE",message:`response.type must be ${yi}`})};if(s.targetNode!==n.targetNode)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(s.networkId!==n.networkId)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(s.nodeId!==n.targetNode)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if("x25519-aes256gcm/v1"!==s.alg&&s.alg!==bi)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(s.keyVersion!==n.keyVersion)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(s.encryptedSymmetricKeyHash!==n.encryptedSymmetricKeyHash)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(s.receiverPublicKeyHash!==n.receiverPublicKeyHash)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(s.invocationCid!==i)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const c=ri(e.sha256(si(`${i}${o}`)));if(s.requestHash!==c)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(r.encryptedSymmetricKeyHash!==s.encryptedSymmetricKeyHash||r.receiverPublicKeyHash!==s.receiverPublicKeyHash||r.networkId!==s.networkId||r.targetNode!==s.targetNode||r.alg!==n.alg||r.keyVersion!==s.keyVersion)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const a=(new TextEncoder).encode(function(t){const{nodeSignature:e,...n}=t;return ti(n)}(s)),u=oi(s.nodeSignature);return e.verifyNodeSignature(s.nodeId,a,u)?{ok:!0,data:s}:{ok:!1,error:gi({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:e,request:a,facts:d,invocationCid:f.invocationCid,requestBodyHash:d.bodyHash,response:await l.json()});if(!h.ok)throw new ji("INVALID_RESPONSE",Mi(h.error.message),{cause:h.error});const y=function(t,e,n,r){const i=oi(n.wrappedKey);if(Oi(i,n.alg),n.alg===bi){if(!r)throw new Error("V2 response requires expected key context");return function(t,e,n){const{header:r,aad:i,nonce:o,ciphertext:s}=Si(e);Bi(r,n);const c=ln.getPublicKey(t);if(!Ei(c,Ii(r.recipientPublicKey)))throw new Error("Key wrap recipient mismatch");const a=function(t,e,n,r){const i=ln.getSharedSecret(t,e);if(i.every(t=>0===t))throw new Error("Invalid key agreement");try{return Sn(Bn,i,r,ki(vi,e,n),32)}finally{i.fill(0)}}(t,Ii(r.ephemeralPublicKey),c,Ii(r.salt));try{return K(a,o,i).decrypt(s)}finally{a.fill(0)}}(e,i,r)}return t.openWithReceiverKey(e,i)}(e,o.privateKey,h.data,{purpose:"receiver-key",networkId:a.networkId,keyPath:a.keyPath,keyVersion:a.keyVersion,metadata:{}});try{return e.authDecrypt(y,oi(t.ciphertext),void 0!==t.aad?oi(t.aad):void 0)}catch(t){throw new ji("DECRYPT_FAILED","local decryption failed",{cause:t})}}};async function co(t){try{return await t.text()}catch{return""}}function ao(t,e={}){const n=t;for(const t of["signRawNetworkAuthorization","createEncryptionCrypto","encryptionDestination"])if("function"!=typeof n[t])throw new ji("NODE_HOOK_MISSING",`TinyCloudNode.${t} is not available; named keys cannot sign invocations`);const r=n,i=t.hosts[0];if(void 0===i)throw new Error("TinyCloud node host has not been resolved");const o=e.fetch??globalThis.fetch.bind(globalThis),s=Object.assign((t,e)=>o(t,{...e,redirect:"error"}),{preconnect:()=>{}}),c={keyWrapV2:e.keyWrapV2??r.config?.keyWrapV2??!1,requireKeyWrapV2:e.requireKeyWrapV2??r.config?.requireKeyWrapV2??!1,host:i,resolveNode:async t=>{const{url:e,nodeDid:n}=await r.encryptionDestination(t);return{url:e,nodeDid:n}},crypto:r.createEncryptionCrypto(),fetch:s,defaultNetworkId:()=>e.networkId??t.getDefaultEncryptionNetworkId(),signInvocation:t=>r.signRawNetworkAuthorization({targetNode:t.targetNode,networkId:t.resource,action:t.action,facts:t.facts}),decryptRoot:e=>{const n=t.session?.delegationCid;return void 0===n?Promise.reject(new Error("Not signed in. Call signIn() first.")):t.encryption.decryptEnvelope(e,{proofs:[n]})}};return new so(c)}module.exports=e})();
|
|
2
|
+
(()=>{"use strict";var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function n(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function r(t,...e){if(!n(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function i(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function o(t,e){r(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function s(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function c(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function a(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}t.r(e),t.d(e,{createNamedKeyClient:()=>uo});const u=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function d(t){if("string"==typeof t)t=function(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}(t);else{if(!n(t))throw new Error("Uint8Array expected, got "+typeof t);t=y(t)}return t}const f=(t,e)=>{function n(n,...i){if(r(n),!u)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==t.nonceLength){const e=i[0];if(!e)throw new Error("nonce / iv required");t.varSizeNonce?r(e):r(e,t.nonceLength)}const o=t.tagLength;o&&void 0!==i[1]&&r(i[1]);const s=e(n,...i),c=(t,e)=>{if(void 0!==e){if(2!==t)throw new Error("cipher output not supported");r(e)}};let a=!1;return{encrypt(t,e){if(a)throw new Error("cannot encrypt() twice with same key + nonce");return a=!0,r(t),c(s.encrypt.length,e),s.encrypt(t,e)},decrypt(t,e){if(r(t),o&&t.length<o)throw new Error("invalid ciphertext length: smaller than tagLength="+o);return c(s.decrypt.length,e),s.decrypt(t,e)}}}return Object.assign(n,t),n};function l(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),c=Number(n&o),a=r?4:0,u=r?0:4;t.setUint32(e+a,s,r),t.setUint32(e+u,c,r)}function h(t){return t.byteOffset%4==0}function y(t){return Uint8Array.from(t)}const p=16,w=new Uint8Array(16),g=s(w),b=(t,e,n,r)=>({s3:n<<31|r>>>1,s2:e<<31|n>>>1,s1:t<<31|e>>>1,s0:t>>>1^225<<24&-(1&r)}),m=t=>(t>>>0&255)<<24|(t>>>8&255)<<16|(t>>>16&255)<<8|t>>>24&255;class v{constructor(t,e){this.blockLen=p,this.outputLen=p,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,r(t=d(t),16);const n=a(t);let i=n.getUint32(0,!1),o=n.getUint32(4,!1),s=n.getUint32(8,!1),c=n.getUint32(12,!1);const u=[];for(let t=0;t<128;t++)u.push({s0:m(i),s1:m(o),s2:m(s),s3:m(c)}),({s0:i,s1:o,s2:s,s3:c}=b(i,o,s,c));const f=(l=e||1024)>65536?8:l>1024?4:2;var l;if(![1,2,4,8].includes(f))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=f;const h=128/f,y=this.windowSize=2**f,w=[];for(let t=0;t<h;t++)for(let e=0;e<y;e++){let n=0,r=0,i=0,o=0;for(let s=0;s<f;s++){if(!(e>>>f-s-1&1))continue;const{s0:c,s1:a,s2:d,s3:l}=u[f*t+s];n^=c,r^=a,i^=d,o^=l}w.push({s0:n,s1:r,s2:i,s3:o})}this.t=w}_updateBlock(t,e,n,r){t^=this.s0,e^=this.s1,n^=this.s2,r^=this.s3;const{W:i,t:o,windowSize:s}=this;let c=0,a=0,u=0,d=0;const f=(1<<i)-1;let l=0;for(const h of[t,e,n,r])for(let t=0;t<4;t++){const e=h>>>8*t&255;for(let t=8/i-1;t>=0;t--){const n=e>>>i*t&f,{s0:r,s1:h,s2:y,s3:p}=o[l*s+n];c^=r,a^=h,u^=y,d^=p,l+=1}}this.s0=c,this.s1=a,this.s2=u,this.s3=d}update(t){i(this),r(t=d(t));const e=s(t),n=Math.floor(t.length/p),o=t.length%p;for(let t=0;t<n;t++)this._updateBlock(e[4*t+0],e[4*t+1],e[4*t+2],e[4*t+3]);return o&&(w.set(t.subarray(n*p)),this._updateBlock(g[0],g[1],g[2],g[3]),c(g)),this}destroy(){const{t}=this;for(const e of t)e.s0=0,e.s1=0,e.s2=0,e.s3=0}digestInto(t){i(this),o(t,this),this.finished=!0;const{s0:e,s1:n,s2:r,s3:c}=this,a=s(t);return a[0]=e,a[1]=n,a[2]=r,a[3]=c,t}digest(){const t=new Uint8Array(p);return this.digestInto(t),this.destroy(),t}}class k extends v{constructor(t,e){r(t=d(t));const n=function(t){t.reverse();const e=1&t[15];let n=0;for(let e=0;e<t.length;e++){const r=t[e];t[e]=r>>>1|n,n=(1&r)<<7}return t[0]^=225&-e,t}(y(t));super(n,e),c(n)}update(t){t=d(t),i(this);const e=s(t),n=t.length%p,r=Math.floor(t.length/p);for(let t=0;t<r;t++)this._updateBlock(m(e[4*t+3]),m(e[4*t+2]),m(e[4*t+1]),m(e[4*t+0]));return n&&(w.set(t.subarray(r*p)),this._updateBlock(m(g[3]),m(g[2]),m(g[1]),m(g[0])),c(g)),this}digestInto(t){i(this),o(t,this),this.finished=!0;const{s0:e,s1:n,s2:r,s3:c}=this,a=s(t);return a[0]=e,a[1]=n,a[2]=r,a[3]=c,t.reverse()}}function E(t){const e=(e,n)=>t(n,e.length).update(d(e)).digest(),n=t(new Uint8Array(16),0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=(e,n)=>t(e,n),e}const I=E((t,e)=>new v(t,e)),x=(E((t,e)=>new k(t,e)),16),A=new Uint8Array(x);function N(t){return t<<1^283&-(t>>7)}function S(t,e){let n=0;for(;e>0;e>>=1)n^=t&-(1&e),t=N(t);return n}const B=t=>t<<24|t>>>8,O=t=>t<<8|t>>>24;function _(t,e){if(256!==t.length)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((n,r)=>e(t[r])),r=n.map(O),i=r.map(O),o=i.map(O),s=new Uint32Array(65536),c=new Uint32Array(65536),a=new Uint16Array(65536);for(let e=0;e<256;e++)for(let u=0;u<256;u++){const d=256*e+u;s[d]=n[e]^r[u],c[d]=i[e]^o[u],a[d]=t[e]<<8|t[u]}return{sbox:t,sbox2:a,T0:n,T1:r,T2:i,T3:o,T01:s,T23:c}}const P=_((()=>{const t=new Uint8Array(256);for(let e=0,n=1;e<256;e++,n^=N(n))t[e]=n;const e=new Uint8Array(256);e[0]=99;for(let n=0;n<255;n++){let r=t[255-n];r|=r<<8,e[t[n]]=255&(r^r>>4^r>>5^r>>6^r>>7^99)}return c(t),e})(),t=>S(t,3)<<24|t<<16|t<<8|S(t,2)),$=(()=>{const t=new Uint8Array(16);for(let e=0,n=1;e<16;e++,n=N(n))t[e]=n;return t})();function U(t,e,n,r,i,o){return t[n<<8&65280|r>>>8&255]^e[i>>>8&65280|o>>>24&255]}function R(t,e,n,r,i){return t[255&e|65280&n]|t[r>>>16&255|i>>>16&65280]<<16}function T(t,e,n,r,i){const{sbox2:o,T01:s,T23:c}=P;let a=0;e^=t[a++],n^=t[a++],r^=t[a++],i^=t[a++];const u=t.length/4-2;for(let o=0;o<u;o++){const o=t[a++]^U(s,c,e,n,r,i),u=t[a++]^U(s,c,n,r,i,e),d=t[a++]^U(s,c,r,i,e,n),f=t[a++]^U(s,c,i,e,n,r);e=o,n=u,r=d,i=f}return{s0:t[a++]^R(o,e,n,r,i),s1:t[a++]^R(o,n,r,i,e),s2:t[a++]^R(o,r,i,e,n),s3:t[a++]^R(o,i,e,n,r)}}function L(t,e,n,i,o){r(n,x),r(i),o=function(t,e,n=!0){if(void 0===e)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(n&&!h(e))throw new Error("invalid output, must be aligned");return e}(i.length,o);const u=n,d=s(u),f=a(u),l=s(i),y=s(o),p=e?0:12,w=i.length;let g=f.getUint32(p,e),{s0:b,s1:m,s2:v,s3:k}=T(t,d[0],d[1],d[2],d[3]);for(let n=0;n+4<=l.length;n+=4)y[n+0]=l[n+0]^b,y[n+1]=l[n+1]^m,y[n+2]=l[n+2]^v,y[n+3]=l[n+3]^k,g=g+1>>>0,f.setUint32(p,g,e),({s0:b,s1:m,s2:v,s3:k}=T(t,d[0],d[1],d[2],d[3]));const E=x*Math.floor(l.length/4);if(E<w){const t=new Uint32Array([b,m,v,k]),e=(I=t,new Uint8Array(I.buffer,I.byteOffset,I.byteLength));for(let t=E,n=0;t<w;t++,n++)o[t]=i[t]^e[n];c(t)}var I;return o}function D(t,e,n,r,i){const o=i?i.length:0,s=t.create(n,r.length+o);i&&s.update(i);const u=function(t,e,n){!function(t){if("boolean"!=typeof t)throw new Error(`boolean expected, not ${t}`)}(n);const r=new Uint8Array(16),i=a(r);return l(i,0,BigInt(e),n),l(i,8,BigInt(t),n),r}(8*r.length,8*o,e);s.update(r),s.update(u);const d=s.digest();return c(u),d}const K=f({blockSize:16,nonceLength:12,tagLength:16,varSizeNonce:!0},function(t,e,n){if(e.length<8)throw new Error("aes/gcm: invalid nonce length");function i(t,e,r){const i=D(I,!1,t,r,n);for(let t=0;t<e.length;t++)i[t]^=e[t];return i}function o(){const n=function(t){r(t);const e=t.length;if(![16,24,32].includes(e))throw new Error("aes: invalid key size, should be 16, 24 or 32, got "+e);const{sbox2:n}=P,i=[];h(t)||i.push(t=y(t));const o=s(t),a=o.length,u=t=>R(n,t,t,t,t),d=new Uint32Array(e+28);d.set(o);for(let t=a;t<d.length;t++){let e=d[t-1];t%a===0?e=u(B(e))^$[t/a-1]:a>6&&t%a===4&&(e=u(e)),d[t]=d[t-a]^e}return c(...i),d}(t),i=A.slice(),o=A.slice();if(L(n,!1,o,o,i),12===e.length)o.set(e);else{const t=A.slice();l(a(t),8,BigInt(8*e.length),!1);const n=I.create(i).update(e).update(t);n.digestInto(o),n.destroy()}return{xk:n,authKey:i,counter:o,tagMask:L(n,!1,o,A)}}return{encrypt(t){const{xk:e,authKey:n,counter:r,tagMask:s}=o(),a=new Uint8Array(t.length+16),u=[e,n,r,s];h(t)||u.push(t=y(t)),L(e,!1,r,t,a.subarray(0,t.length));const d=i(n,s,a.subarray(0,a.length-16));return u.push(d),a.set(d,t.length),c(...u),a},decrypt(t){const{xk:e,authKey:n,counter:r,tagMask:s}=o(),a=[e,n,s,r];h(t)||a.push(t=y(t));const u=t.subarray(0,-16),d=t.subarray(-16),f=i(n,s,u);if(a.push(f),!function(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}(f,d))throw new Error("aes/gcm: invalid ghash tag");const l=L(e,!1,r,u);return c(...a),l}}}),V=()=>"undefined"!=typeof globalThis&&globalThis.crypto?globalThis.crypto:"undefined"!=typeof window&&window.crypto?window.crypto:"undefined"!=typeof self&&self.crypto?self.crypto:void 0,z={web:V(),node:void 0,getRandomValues:function(t){const e=V();if(e&&e.getRandomValues)return e.getRandomValues(t);throw new Error("crypto.getRandomValues is unavailable")}};function C(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function H(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function q(t,...e){if(!C(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function F(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.createHasher");H(t.outputLen),H(t.blockLen)}function M(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function j(t,e){q(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function G(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Y(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function W(t,e){return t<<32-e|t>>>e}function Z(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const X=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?t=>t:function(t){for(let e=0;e<t.length;e++)t[e]=Z(t[e]);return t},J=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Q=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function tt(t){if(q(t),J)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Q[t[n]];return e}function et(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function nt(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);if(J)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let e=0,i=0;e<n;e++,i+=2){const n=et(t.charCodeAt(i)),o=et(t.charCodeAt(i+1));if(void 0===n||void 0===o){const e=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+e+'" at index '+i)}r[e]=16*n+o}return r}function rt(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}function it(t){return"string"==typeof t&&(t=rt(t)),q(t),t}function ot(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];q(r),e+=r.length}const n=new Uint8Array(e);for(let e=0,r=0;e<t.length;e++){const i=t[e];n.set(i,r),r+=i.length}return n}class st{}function ct(t){const e=e=>t().update(it(e)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function at(t=32){if(z&&"function"==typeof z.getRandomValues)return z.getRandomValues(new Uint8Array(t));if(z&&"function"==typeof z.randomBytes)return Uint8Array.from(z.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function ut(t,e,n){return t&e^~t&n}function dt(t,e,n){return t&e^t&n^e&n}class ft extends st{constructor(t,e,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(t),this.view=Y(this.buffer)}update(t){M(this),q(t=it(t));const{view:e,buffer:n,blockLen:r}=this,i=t.length;for(let o=0;o<i;){const s=Math.min(r-this.pos,i-o);if(s===r){const e=Y(t);for(;r<=i-o;o+=r)this.process(e,o);continue}n.set(t.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){M(this),j(t,this),this.finished=!0;const{buffer:e,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;e[o++]=128,G(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let t=o;t<r;t++)e[t]=0;!function(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),c=Number(n&o),a=r?4:0,u=r?0:4;t.setUint32(e+a,s,r),t.setUint32(e+u,c,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const s=Y(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const a=c/4,u=this.get();if(a>u.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t<a;t++)s.setUint32(4*t,u[t],i)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:e,buffer:n,length:r,finished:i,destroyed:o,pos:s}=this;return t.destroyed=o,t.finished=i,t.length=r,t.pos=s,r%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}}const lt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ht=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),yt=BigInt(2**32-1),pt=BigInt(32);function wt(t,e=!1){return e?{h:Number(t&yt),l:Number(t>>pt&yt)}:{h:0|Number(t>>pt&yt),l:0|Number(t&yt)}}function gt(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let o=0;o<n;o++){const{h:n,l:s}=wt(t[o],e);[r[o],i[o]]=[n,s]}return[r,i]}const bt=(t,e,n)=>t>>>n,mt=(t,e,n)=>t<<32-n|e>>>n,vt=(t,e,n)=>t>>>n|e<<32-n,kt=(t,e,n)=>t<<32-n|e>>>n,Et=(t,e,n)=>t<<64-n|e>>>n-32,It=(t,e,n)=>t>>>n-32|e<<64-n;function xt(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:0|i}}const At=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Nt=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,St=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Bt=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,Ot=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),_t=(t,e,n,r,i,o)=>e+n+r+i+o+(t/2**32|0)|0,Pt=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),$t=new Uint32Array(64);class Ut extends ft{constructor(t=32){super(64,t,8,!1),this.A=0|lt[0],this.B=0|lt[1],this.C=0|lt[2],this.D=0|lt[3],this.E=0|lt[4],this.F=0|lt[5],this.G=0|lt[6],this.H=0|lt[7]}get(){const{A:t,B:e,C:n,D:r,E:i,F:o,G:s,H:c}=this;return[t,e,n,r,i,o,s,c]}set(t,e,n,r,i,o,s,c){this.A=0|t,this.B=0|e,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|o,this.G=0|s,this.H=0|c}process(t,e){for(let n=0;n<16;n++,e+=4)$t[n]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=$t[t-15],n=$t[t-2],r=W(e,7)^W(e,18)^e>>>3,i=W(n,17)^W(n,19)^n>>>10;$t[t]=i+$t[t-7]+r+$t[t-16]|0}let{A:n,B:r,C:i,D:o,E:s,F:c,G:a,H:u}=this;for(let t=0;t<64;t++){const e=u+(W(s,6)^W(s,11)^W(s,25))+ut(s,c,a)+Pt[t]+$t[t]|0,d=(W(n,2)^W(n,13)^W(n,22))+dt(n,r,i)|0;u=a,a=c,c=s,s=o+e|0,o=i,i=r,r=n,n=e+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,c=c+this.F|0,a=a+this.G|0,u=u+this.H|0,this.set(n,r,i,o,s,c,a,u)}roundClean(){G($t)}destroy(){this.set(0,0,0,0,0,0,0,0),G(this.buffer)}}const Rt=(()=>gt(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))))(),Tt=(()=>Rt[0])(),Lt=(()=>Rt[1])(),Dt=new Uint32Array(80),Kt=new Uint32Array(80);class Vt extends ft{constructor(t=64){super(128,t,16,!1),this.Ah=0|ht[0],this.Al=0|ht[1],this.Bh=0|ht[2],this.Bl=0|ht[3],this.Ch=0|ht[4],this.Cl=0|ht[5],this.Dh=0|ht[6],this.Dl=0|ht[7],this.Eh=0|ht[8],this.El=0|ht[9],this.Fh=0|ht[10],this.Fl=0|ht[11],this.Gh=0|ht[12],this.Gl=0|ht[13],this.Hh=0|ht[14],this.Hl=0|ht[15]}get(){const{Ah:t,Al:e,Bh:n,Bl:r,Ch:i,Cl:o,Dh:s,Dl:c,Eh:a,El:u,Fh:d,Fl:f,Gh:l,Gl:h,Hh:y,Hl:p}=this;return[t,e,n,r,i,o,s,c,a,u,d,f,l,h,y,p]}set(t,e,n,r,i,o,s,c,a,u,d,f,l,h,y,p){this.Ah=0|t,this.Al=0|e,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|o,this.Dh=0|s,this.Dl=0|c,this.Eh=0|a,this.El=0|u,this.Fh=0|d,this.Fl=0|f,this.Gh=0|l,this.Gl=0|h,this.Hh=0|y,this.Hl=0|p}process(t,e){for(let n=0;n<16;n++,e+=4)Dt[n]=t.getUint32(e),Kt[n]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|Dt[t-15],n=0|Kt[t-15],r=vt(e,n,1)^vt(e,n,8)^bt(e,0,7),i=kt(e,n,1)^kt(e,n,8)^mt(e,n,7),o=0|Dt[t-2],s=0|Kt[t-2],c=vt(o,s,19)^Et(o,s,61)^bt(o,0,6),a=kt(o,s,19)^It(o,s,61)^mt(o,s,6),u=St(i,a,Kt[t-7],Kt[t-16]),d=Bt(u,r,c,Dt[t-7],Dt[t-16]);Dt[t]=0|d,Kt[t]=0|u}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:s,Cl:c,Dh:a,Dl:u,Eh:d,El:f,Fh:l,Fl:h,Gh:y,Gl:p,Hh:w,Hl:g}=this;for(let t=0;t<80;t++){const e=vt(d,f,14)^vt(d,f,18)^Et(d,f,41),b=kt(d,f,14)^kt(d,f,18)^It(d,f,41),m=d&l^~d&y,v=Ot(g,b,f&h^~f&p,Lt[t],Kt[t]),k=_t(v,w,e,m,Tt[t],Dt[t]),E=0|v,I=vt(n,r,28)^Et(n,r,34)^Et(n,r,39),x=kt(n,r,28)^It(n,r,34)^It(n,r,39),A=n&i^n&s^i&s,N=r&o^r&c^o&c;w=0|y,g=0|p,y=0|l,p=0|h,l=0|d,h=0|f,({h:d,l:f}=xt(0|a,0|u,0|k,0|E)),a=0|s,u=0|c,s=0|i,c=0|o,i=0|n,o=0|r;const S=At(E,x,N);n=Nt(S,k,I,A),r=0|S}({h:n,l:r}=xt(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:o}=xt(0|this.Bh,0|this.Bl,0|i,0|o)),({h:s,l:c}=xt(0|this.Ch,0|this.Cl,0|s,0|c)),({h:a,l:u}=xt(0|this.Dh,0|this.Dl,0|a,0|u)),({h:d,l:f}=xt(0|this.Eh,0|this.El,0|d,0|f)),({h:l,l:h}=xt(0|this.Fh,0|this.Fl,0|l,0|h)),({h:y,l:p}=xt(0|this.Gh,0|this.Gl,0|y,0|p)),({h:w,l:g}=xt(0|this.Hh,0|this.Hl,0|w,0|g)),this.set(n,r,i,o,s,c,a,u,d,f,l,h,y,p,w,g)}roundClean(){G(Dt,Kt)}destroy(){G(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const zt=ct(()=>new Ut),Ct=ct(()=>new Vt),Ht=BigInt(0),qt=BigInt(1);function Ft(t,e=""){if("boolean"!=typeof t)throw new Error((e&&`"${e}"`)+"expected boolean, got type="+typeof t);return t}function Mt(t,e,n=""){const r=C(t),i=t?.length,o=void 0!==e;if(!r||o&&i!==e)throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(o?` of length ${e}`:"")+", got "+(r?`length=${i}`:"type="+typeof t));return t}function jt(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);return""===t?Ht:BigInt("0x"+t)}function Gt(t){return q(t),jt(tt(Uint8Array.from(t).reverse()))}function Yt(t,e){return nt(t.toString(16).padStart(2*e,"0"))}function Wt(t,e){return Yt(t,e).reverse()}function Zt(t,e,n){let r;if("string"==typeof e)try{r=nt(e)}catch(e){throw new Error(t+" must be hex string or Uint8Array, cause: "+e)}else{if(!C(e))throw new Error(t+" must be hex string or Uint8Array");r=Uint8Array.from(e)}const i=r.length;if("number"==typeof n&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function Xt(t){return Uint8Array.from(t)}const Jt=t=>"bigint"==typeof t&&Ht<=t;function Qt(t,e,n,r){if(!function(t,e,n){return Jt(t)&&Jt(e)&&Jt(n)&&e<=t&&t<n}(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}const te=t=>(qt<<BigInt(t))-qt;function ee(t,e,n={}){if(!t||"object"!=typeof t)throw new Error("expected valid options object");function r(e,n,r){const i=t[e];if(r&&void 0===i)return;const o=typeof i;if(o!==n||null===i)throw new Error(`param "${e}" is invalid: expected ${n}, got ${o}`)}Object.entries(e).forEach(([t,e])=>r(t,e,!1)),Object.entries(n).forEach(([t,e])=>r(t,e,!0))}const ne=()=>{throw new Error("not implemented")};function re(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(void 0!==i)return i;const o=t(n,...r);return e.set(n,o),o}}const ie=BigInt(0),oe=BigInt(1),se=BigInt(2),ce=BigInt(3),ae=BigInt(4),ue=BigInt(5),de=BigInt(7),fe=BigInt(8),le=BigInt(9),he=BigInt(16);function ye(t,e){const n=t%e;return n>=ie?n:e+n}function pe(t,e,n){let r=t;for(;e-- >ie;)r*=r,r%=n;return r}function we(t,e){if(t===ie)throw new Error("invert: expected non-zero number");if(e<=ie)throw new Error("invert: expected positive modulus, got "+e);let n=ye(t,e),r=e,i=ie,o=oe,s=oe,c=ie;for(;n!==ie;){const t=r/n,e=r%n,a=i-s*t,u=o-c*t;r=n,n=e,i=s,o=c,s=a,c=u}if(r!==oe)throw new Error("invert: does not exist");return ye(i,e)}function ge(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function be(t,e){const n=(t.ORDER+oe)/ae,r=t.pow(e,n);return ge(t,r,e),r}function me(t,e){const n=(t.ORDER-ue)/fe,r=t.mul(e,se),i=t.pow(r,n),o=t.mul(e,i),s=t.mul(t.mul(o,se),i),c=t.mul(o,t.sub(s,t.ONE));return ge(t,c,e),c}function ve(t){if(t<ce)throw new Error("sqrt is not defined for small field");let e=t-oe,n=0;for(;e%se===ie;)e/=se,n++;let r=se;const i=Ae(t);for(;1===xe(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return be;let o=i.pow(r,e);const s=(e+oe)/se;return function(t,r){if(t.is0(r))return r;if(1!==xe(t,r))throw new Error("Cannot find square root");let i=n,c=t.mul(t.ONE,o),a=t.pow(r,e),u=t.pow(r,s);for(;!t.eql(a,t.ONE);){if(t.is0(a))return t.ZERO;let e=1,n=t.sqr(a);for(;!t.eql(n,t.ONE);)if(e++,n=t.sqr(n),e===i)throw new Error("Cannot find square root");const r=oe<<BigInt(i-e-1),o=t.pow(c,r);i=e,c=t.sqr(o),a=t.mul(a,c),u=t.mul(u,o)}return u}}const ke=(t,e)=>(ye(t,e)&oe)===oe,Ee=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ie(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((e,n,i)=>t.is0(n)?e:(r[i]=e,t.mul(e,n)),t.ONE),o=t.inv(i);return e.reduceRight((e,n,i)=>t.is0(n)?e:(r[i]=t.mul(e,r[i]),t.mul(e,n)),o),r}function xe(t,e){const n=(t.ORDER-oe)/se,r=t.pow(e,n),i=t.eql(r,t.ONE),o=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Ae(t,e,n=!1,r={}){if(t<=ie)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,o,s,c=!1;if("object"==typeof e&&null!=e){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const t=e;t.BITS&&(i=t.BITS),t.sqrt&&(o=t.sqrt),"boolean"==typeof t.isLE&&(n=t.isLE),"boolean"==typeof t.modFromBytes&&(c=t.modFromBytes),s=t.allowedLengths}else"number"==typeof e&&(i=e),r.sqrt&&(o=r.sqrt);const{nBitLength:a,nByteLength:u}=function(t,e){void 0!==e&&H(e);const n=void 0!==e?e:t.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const f=Object.freeze({ORDER:t,isLE:n,BITS:a,BYTES:u,MASK:te(a),ZERO:ie,ONE:oe,allowedLengths:s,create:e=>ye(e,t),isValid:e=>{if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return ie<=e&&e<t},is0:t=>t===ie,isValidNot0:t=>!f.is0(t)&&f.isValid(t),isOdd:t=>(t&oe)===oe,neg:e=>ye(-e,t),eql:(t,e)=>t===e,sqr:e=>ye(e*e,t),add:(e,n)=>ye(e+n,t),sub:(e,n)=>ye(e-n,t),mul:(e,n)=>ye(e*n,t),pow:(t,e)=>function(t,e,n){if(n<ie)throw new Error("invalid exponent, negatives unsupported");if(n===ie)return t.ONE;if(n===oe)return e;let r=t.ONE,i=e;for(;n>ie;)n&oe&&(r=t.mul(r,i)),i=t.sqr(i),n>>=oe;return r}(f,t,e),div:(e,n)=>ye(e*we(n,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>we(e,t),sqrt:o||(e=>{return d||(d=(n=t)%ae===ce?be:n%fe===ue?me:n%he===le?function(t){const e=Ae(t),n=ve(t),r=n(e,e.neg(e.ONE)),i=n(e,r),o=n(e,e.neg(r)),s=(t+de)/he;return(t,e)=>{let n=t.pow(e,s),c=t.mul(n,r);const a=t.mul(n,i),u=t.mul(n,o),d=t.eql(t.sqr(c),e),f=t.eql(t.sqr(a),e);n=t.cmov(n,c,d),c=t.cmov(u,a,f);const l=t.eql(t.sqr(c),e),h=t.cmov(n,c,l);return ge(t,h,e),h}}(n):ve(n)),d(f,e);var n}),toBytes:t=>n?Wt(t,u):Yt(t,u),fromBytes:(e,r=!0)=>{if(s){if(!s.includes(e.length)||e.length>u)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);const t=new Uint8Array(u);t.set(e,n?0:t.length-e.length),e=t}if(e.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+e.length);let i=n?Gt(e):function(t){return jt(tt(t))}(e);if(c&&(i=ye(i,t)),!r&&!f.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:t=>Ie(f,t),cmov:(t,e,n)=>n?e:t});return Object.freeze(f)}const Ne=BigInt(0),Se=BigInt(1);function Be(t,e){const n=e.negate();return t?n:e}function Oe(t,e){const n=Ie(t.Fp,e.map(t=>t.Z));return e.map((e,r)=>t.fromAffine(e.toAffine(n[r])))}function _e(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Pe(t,e){_e(t,e);const n=2**t;return{windows:Math.ceil(e/t)+1,windowSize:2**(t-1),mask:te(t),maxNumber:n,shiftBy:BigInt(t)}}function $e(t,e,n){const{windowSize:r,mask:i,maxNumber:o,shiftBy:s}=n;let c=Number(t&i),a=t>>s;c>r&&(c-=o,a+=Se);const u=e*r;return{nextN:a,offset:u+Math.abs(c)-1,isZero:0===c,isNeg:c<0,isNegF:e%2!=0,offsetF:u}}const Ue=new WeakMap,Re=new WeakMap;function Te(t){return Re.get(t)||1}function Le(t){if(t!==Ne)throw new Error("invalid wNAF")}class De{constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let r=t;for(;e>Ne;)e&Se&&(n=n.add(r)),r=r.double(),e>>=Se;return n}precomputeWindow(t,e){const{windows:n,windowSize:r}=Pe(e,this.bits),i=[];let o=t,s=o;for(let t=0;t<n;t++){s=o,i.push(s);for(let t=1;t<r;t++)s=s.add(o),i.push(s);o=s.double()}return i}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=Pe(t,this.bits);for(let t=0;t<o.windows;t++){const{nextN:s,offset:c,isZero:a,isNeg:u,isNegF:d,offsetF:f}=$e(n,t,o);n=s,a?i=i.add(Be(d,e[f])):r=r.add(Be(u,e[c]))}return Le(n),{p:r,f:i}}wNAFUnsafe(t,e,n,r=this.ZERO){const i=Pe(t,this.bits);for(let t=0;t<i.windows&&n!==Ne;t++){const{nextN:o,offset:s,isZero:c,isNeg:a}=$e(n,t,i);if(n=o,!c){const t=e[s];r=r.add(a?t.negate():t)}}return Le(n),r}getPrecomputes(t,e,n){let r=Ue.get(e);return r||(r=this.precomputeWindow(e,t),1!==t&&("function"==typeof n&&(r=n(r)),Ue.set(e,r))),r}cached(t,e,n){const r=Te(t);return this.wNAF(r,this.getPrecomputes(r,t,n),e)}unsafe(t,e,n,r){const i=Te(t);return 1===i?this._unsafeLadder(t,e,r):this.wNAFUnsafe(i,this.getPrecomputes(i,t,n),e,r)}createCache(t,e){_e(e,this.bits),Re.set(t,e),Ue.delete(t)}hasCache(t){return 1!==Te(t)}}function Ke(t,e,n,r){(function(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})})(n,t),function(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}(r,e);const i=n.length,o=r.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,c=function(t){let e;for(e=0;t>Ht;t>>=qt,e+=1);return e}(BigInt(i));let a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);const u=te(a),d=new Array(Number(u)+1).fill(s);let f=s;for(let t=Math.floor((e.BITS-1)/a)*a;t>=0;t-=a){d.fill(s);for(let e=0;e<o;e++){const i=r[e],o=Number(i>>BigInt(t)&u);d[o]=d[o].add(n[e])}let e=s;for(let t=d.length-1,n=s;t>0;t--)n=n.add(d[t]),e=e.add(n);if(f=f.add(e),0!==t)for(let t=0;t<a;t++)f=f.double()}return f}function Ve(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(t){ee(t,Ee.reduce((t,e)=>(t[e]="function",t),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(e),e}return Ae(t,{isLE:n})}const ze=BigInt(0),Ce=BigInt(1),He=BigInt(2),qe=BigInt(8);class Fe{constructor(t){this.ep=t}static fromBytes(t){ne()}static fromHex(t){ne()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return tt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}toRawBytes(){return this.toBytes()}}function Me(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:i}=function(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n={Fp:t.Fp,Fn:Ae(e.n,t.nBitLength,!0),uvRatio:t.uvRatio},r={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:n,hash:t.hash,eddsaOpts:r}}(t);return function(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}(t,function(t,e,n={}){if("function"!=typeof e)throw new Error('"hash" function param is required');ee(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:o,Fn:s}=t,c=n.randomBytes||at,a=n.adjustScalarBytes||(t=>t),u=n.domain||((t,e,n)=>{if(Ft(n,"phflag"),e.length||n)throw new Error("Contexts/pre-hash are not supported");return t});function d(t){return s.create(Gt(t))}function f(t){const{head:n,prefix:r,scalar:o}=function(t){const n=w.secretKey;t=Zt("private key",t,n);const r=Zt("hashed private key",e(t),2*n),i=a(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:d(i)}}(t),s=i.multiply(o),c=s.toBytes();return{head:n,prefix:r,scalar:o,point:s,pointBytes:c}}function l(t){return f(t).pointBytes}function h(t=Uint8Array.of(),...n){const i=ot(...n);return d(e(u(i,Zt("context",t),!!r)))}const y={zip215:!0},p=o.BYTES,w={secretKey:p,publicKey:p,signature:2*p,seed:p};function g(t=c(w.seed)){return Mt(t,w.seed,"seed")}const b={getExtendedPublicKey:f,randomSecretKey:g,isValidSecretKey:function(t){return C(t)&&t.length===s.BYTES},isValidPublicKey:function(e,n){try{return!!t.fromBytes(e,n)}catch(t){return!1}},toMontgomery(e){const{y:n}=t.fromBytes(e),r=w.publicKey,i=32===r;if(!i&&57!==r)throw new Error("only defined for 25519 and 448");const s=i?o.div(Ce+n,Ce-n):o.div(n-Ce,n+Ce);return o.toBytes(s)},toMontgomerySecret(t){const n=w.secretKey;Mt(t,n);const r=e(t.subarray(0,n));return a(r).subarray(0,n)},randomPrivateKey:g,precompute:(e=8,n=t.BASE)=>n.precompute(e,!1)};return Object.freeze({keygen:function(t){const e=b.randomSecretKey(t);return{secretKey:e,publicKey:l(e)}},getPublicKey:l,sign:function(t,e,n={}){t=Zt("message",t),r&&(t=r(t));const{prefix:o,scalar:c,pointBytes:a}=f(e),u=h(n.context,o,t),d=i.multiply(u).toBytes(),l=h(n.context,d,a,t),y=s.create(u+l*c);if(!s.isValid(y))throw new Error("sign failed: invalid s");return Mt(ot(d,s.toBytes(y)),w.signature,"result")},verify:function(e,n,o,s=y){const{context:c,zip215:a}=s,u=w.signature;e=Zt("signature",e,u),n=Zt("message",n),o=Zt("publicKey",o,w.publicKey),void 0!==a&&Ft(a,"zip215"),r&&(n=r(n));const d=u/2,f=e.subarray(0,d),l=Gt(e.subarray(d,u));let p,g,b;try{p=t.fromBytes(o,a),g=t.fromBytes(f,a),b=i.multiplyUnsafe(l)}catch(t){return!1}if(!a&&p.isSmallOrder())return!1;const m=h(c,g.toBytes(),p.toBytes(),n);return g.add(p.multiplyUnsafe(m)).subtract(b).clearCofactor().is0()},utils:b,Point:t,lengths:w})}(function(t,e={}){const n=function(t,e,n={},r){if(void 0===r&&(r="edwards"===t),!e||"object"!=typeof e)throw new Error(`expected valid ${t} CURVE object`);for(const t of["p","n","h"]){const n=e[t];if(!("bigint"==typeof n&&n>Ne))throw new Error(`CURVE.${t} must be positive bigint`)}const i=Ve(e.p,n.Fp,r),o=Ve(e.n,n.Fn,r),s=["Gx","Gy","a","weierstrass"===t?"b":"d"];for(const t of s)if(!i.isValid(e[t]))throw new Error(`CURVE.${t} must be valid field element of CURVE.Fp`);return{CURVE:e=Object.freeze(Object.assign({},e)),Fp:i,Fn:o}}("edwards",t,e,e.FpFnLE),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s}=o;ee(e,{},{uvRatio:"function"});const c=He<<BigInt(8*i.BYTES)-Ce,a=t=>r.create(t),u=e.uvRatio||((t,e)=>{try{return{isValid:!0,value:r.sqrt(r.div(t,e))}}catch(t){return{isValid:!1,value:ze}}});if(!function(t,e,n,r){const i=t.sqr(n),o=t.sqr(r),s=t.add(t.mul(e.a,i),o),c=t.add(t.ONE,t.mul(e.d,t.mul(i,o)));return t.eql(s,c)}(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function d(t,e,n=!1){return Qt("coordinate "+t,e,n?Ce:ze,c),e}function f(t){if(!(t instanceof y))throw new Error("ExtendedPoint expected")}const l=re((t,e)=>{const{X:n,Y:i,Z:o}=t,s=t.is0();null==e&&(e=s?qe:r.inv(o));const c=a(n*e),u=a(i*e),d=r.mul(o,e);if(s)return{x:ze,y:Ce};if(d!==Ce)throw new Error("invZ was invalid");return{x:c,y:u}}),h=re(t=>{const{a:e,d:n}=o;if(t.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:s,T:c}=t,u=a(r*r),d=a(i*i),f=a(s*s),l=a(f*f),h=a(u*e);if(a(f*a(h+d))!==a(l+a(n*a(u*d))))throw new Error("bad point: equation left != right (1)");if(a(r*i)!==a(s*c))throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(t,e,n,r){this.X=d("x",t),this.Y=d("y",e),this.Z=d("z",n,!0),this.T=d("t",r),Object.freeze(this)}static CURVE(){return o}static fromAffine(t){if(t instanceof y)throw new Error("extended point not allowed");const{x:e,y:n}=t||{};return d("x",e),d("y",n),new y(e,n,Ce,a(e*n))}static fromBytes(t,e=!1){const n=r.BYTES,{a:i,d:s}=o;t=Xt(Mt(t,n,"point")),Ft(e,"zip215");const d=Xt(t),f=t[n-1];d[n-1]=-129&f;const l=Gt(d),h=e?c:r.ORDER;Qt("point.y",l,ze,h);const p=a(l*l),w=a(p-Ce),g=a(s*p-i);let{isValid:b,value:m}=u(w,g);if(!b)throw new Error("bad point: invalid y coordinate");const v=(m&Ce)===Ce,k=!!(128&f);if(!e&&m===ze&&k)throw new Error("bad point: x=0 and x_0=1");return k!==v&&(m=a(-m)),y.fromAffine({x:m,y:l})}static fromHex(t,e=!1){return y.fromBytes(Zt("point",t),e)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return p.createCache(this,t),e||this.multiply(He),this}assertValidity(){h(this)}equals(t){f(t);const{X:e,Y:n,Z:r}=this,{X:i,Y:o,Z:s}=t,c=a(e*s),u=a(i*r),d=a(n*s),l=a(o*r);return c===u&&d===l}is0(){return this.equals(y.ZERO)}negate(){return new y(a(-this.X),this.Y,this.Z,a(-this.T))}double(){const{a:t}=o,{X:e,Y:n,Z:r}=this,i=a(e*e),s=a(n*n),c=a(He*a(r*r)),u=a(t*i),d=e+n,f=a(a(d*d)-i-s),l=u+s,h=l-c,p=u-s,w=a(f*h),g=a(l*p),b=a(f*p),m=a(h*l);return new y(w,g,m,b)}add(t){f(t);const{a:e,d:n}=o,{X:r,Y:i,Z:s,T:c}=this,{X:u,Y:d,Z:l,T:h}=t,p=a(r*u),w=a(i*d),g=a(c*n*h),b=a(s*l),m=a((r+i)*(u+d)-p-w),v=b-g,k=b+g,E=a(w-e*p),I=a(m*v),x=a(k*E),A=a(m*E),N=a(v*k);return new y(I,x,N,A)}subtract(t){return this.add(t.negate())}multiply(t){if(!i.isValidNot0(t))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:e,f:n}=p.cached(this,t,t=>Oe(y,t));return Oe(y,[e,n])[0]}multiplyUnsafe(t,e=y.ZERO){if(!i.isValid(t))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return t===ze?y.ZERO:this.is0()||t===Ce?this:p.unsafe(this,t,t=>Oe(y,t),e)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return p.unsafe(this,o.n).is0()}toAffine(t){return l(this,t)}clearCofactor(){return s===Ce?this:this.multiplyUnsafe(s)}toBytes(){const{x:t,y:e}=this.toAffine(),n=r.toBytes(e);return n[n.length-1]|=t&Ce?128:0,n}toHex(){return tt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(t){return Oe(y,t)}static msm(t,e){return Ke(y,i,t,e)}_setWindowSize(t){this.precompute(t)}toRawBytes(){return this.toBytes()}}y.BASE=new y(o.Gx,o.Gy,Ce,a(o.Gx*o.Gy)),y.ZERO=new y(ze,Ce,Ce,ze),y.Fp=r,y.Fn=i;const p=new De(y,i.BITS);return y.BASE.precompute(8),y}(e,n),r,i))}rt("HashToScalar-");const je=BigInt(0),Ge=BigInt(1),Ye=BigInt(2);const We=BigInt(0),Ze=BigInt(1),Xe=BigInt(2),Je=BigInt(3),Qe=BigInt(5),tn=BigInt(8),en=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),nn=(()=>({p:en,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:tn,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function rn(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),o=en,s=t*t%o*t%o,c=pe(s,Xe,o)*s%o,a=pe(c,Ze,o)*t%o,u=pe(a,Qe,o)*a%o,d=pe(u,e,o)*u%o,f=pe(d,n,o)*d%o,l=pe(f,r,o)*f%o,h=pe(l,i,o)*l%o,y=pe(h,i,o)*l%o,p=pe(y,e,o)*u%o;return{pow_p_5_8:pe(p,Xe,o)*t%o,b2:s}}function on(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const sn=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function cn(t,e){const n=en,r=ye(e*e*e,n),i=ye(r*r*e,n);let o=ye(t*r*rn(t*i).pow_p_5_8,n);const s=ye(e*o*o,n),c=o,a=ye(o*sn,n),u=s===t,d=s===ye(-t,n),f=s===ye(-t*sn,n);return u&&(o=c),(d||f)&&(o=a),ke(o,n)&&(o=ye(-o,n)),{isValid:u||d,value:o}}const an=(()=>Ae(nn.p,{isLE:!0}))(),un=(()=>Ae(nn.n,{isLE:!0}))(),dn=(()=>({...nn,Fp:an,hash:Ct,adjustScalarBytes:on,uvRatio:cn}))(),fn=(()=>Me(dn))(),ln=(()=>{const t=an.ORDER;return function(t){const e=(ee(n=t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...n}));var n;const{P:r,type:i,adjustScalarBytes:o,powPminus2:s,randomBytes:c}=e,a="x25519"===i;if(!a&&"x448"!==i)throw new Error("invalid type");const u=c||at,d=a?255:448,f=a?32:56,l=a?BigInt(9):BigInt(5),h=a?BigInt(121665):BigInt(39081),y=a?Ye**BigInt(254):Ye**BigInt(447),p=a?BigInt(8)*Ye**BigInt(251)-Ge:BigInt(4)*Ye**BigInt(445)-Ge,w=y+p+Ge,g=t=>ye(t,r),b=m(l);function m(t){return Wt(g(t),f)}function v(t,e){const n=function(t,e){Qt("u",t,je,r),Qt("scalar",e,y,w);const n=e,i=t;let o=Ge,c=je,a=t,u=Ge,f=je;for(let t=BigInt(d-1);t>=je;t--){const e=n>>t&Ge;f^=e,({x_2:o,x_3:a}=E(f,o,a)),({x_2:c,x_3:u}=E(f,c,u)),f=e;const r=o+c,s=g(r*r),d=o-c,l=g(d*d),y=s-l,p=a+u,w=g((a-u)*r),b=g(p*d),m=w+b,v=w-b;a=g(m*m),u=g(i*g(v*v)),o=g(s*l),c=g(y*(s+g(h*y)))}({x_2:o,x_3:a}=E(f,o,a)),({x_2:c,x_3:u}=E(f,c,u));const l=s(c);return g(o*l)}(function(t){const e=Zt("u coordinate",t,f);return a&&(e[31]&=127),g(Gt(e))}(e),function(t){return Gt(o(Zt("scalar",t,f)))}(t));if(n===je)throw new Error("invalid private or public key received");return m(n)}function k(t){return v(t,b)}function E(t,e,n){const r=g(t*(e-n));return{x_2:e=g(e-r),x_3:n=g(n+r)}}const I={secretKey:f,publicKey:f,seed:f},x=(t=u(f))=>(q(t,I.seed),t);return{keygen:function(t){const e=x(t);return{secretKey:e,publicKey:k(e)}},getSharedSecret:(t,e)=>v(t,e),getPublicKey:t=>k(t),scalarMult:v,scalarMultBase:k,utils:{randomSecretKey:x,randomPrivateKey:x},GuBytes:b.slice(),lengths:I}}({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=rn(e);return ye(pe(n,Je,t)*r,t)},adjustScalarBytes:on})})(),hn=sn,yn=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),pn=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),wn=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),gn=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),bn=t=>cn(Ze,t),mn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),vn=t=>fn.Point.Fp.create(Gt(t)&mn);function kn(t){const{d:e}=nn,n=en,r=t=>an.create(t),i=r(hn*t*t),o=r((i+Ze)*wn);let s=BigInt(-1);const c=r((s-e*i)*r(i+e));let{isValid:a,value:u}=cn(o,c),d=r(u*t);ke(d,n)||(d=r(-d)),a||(u=d),a||(s=i);const f=r(s*(i-Ze)*gn-c),l=u*u,h=r((u+u)*c),y=r(f*yn),p=r(Ze-l),w=r(Ze+l);return new fn.Point(r(h*w),r(p*y),r(y*w),r(h*p))}class En extends Fe{constructor(t){super(t)}static fromAffine(t){return new En(fn.Point.fromAffine(t))}assertSame(t){if(!(t instanceof En))throw new Error("RistrettoPoint expected")}init(t){return new En(t)}static hashToCurve(t){return function(t){q(t,64);const e=kn(vn(t.subarray(0,32))),n=kn(vn(t.subarray(32,64)));return new En(e.add(n))}(Zt("ristrettoHash",t,64))}static fromBytes(t){q(t,32);const{a:e,d:n}=nn,r=en,i=t=>an.create(t),o=vn(t);if(!function(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}(an.toBytes(o),t)||ke(o,r))throw new Error("invalid ristretto255 encoding 1");const s=i(o*o),c=i(Ze+e*s),a=i(Ze-e*s),u=i(c*c),d=i(a*a),f=i(e*n*u-d),{isValid:l,value:h}=bn(i(f*d)),y=i(h*a),p=i(h*y*f);let w=i((o+o)*y);ke(w,r)&&(w=i(-w));const g=i(c*p),b=i(w*g);if(!l||ke(b,r)||g===We)throw new Error("invalid ristretto255 encoding 2");return new En(new fn.Point(w,g,Ze,b))}static fromHex(t){return En.fromBytes(Zt("ristrettoHex",t,32))}static msm(t,e){return Ke(En,fn.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:r}=this.ep;const i=en,o=t=>an.create(t),s=o(o(n+e)*o(n-e)),c=o(t*e),a=o(c*c),{value:u}=bn(o(s*a)),d=o(u*s),f=o(u*c),l=o(d*f*r);let h;if(ke(r*l,i)){let n=o(e*hn),r=o(t*hn);t=n,e=r,h=o(d*pn)}else h=f;ke(t*l,i)&&(e=o(-e));let y=o((n-e)*h);return ke(y,i)&&(y=o(-y)),an.toBytes(y)}equals(t){this.assertSame(t);const{X:e,Y:n}=this.ep,{X:r,Y:i}=t.ep,o=t=>an.create(t),s=o(e*i)===o(n*r),c=o(n*i)===o(e*r);return s||c}is0(){return this.equals(En.ZERO)}}En.BASE=(()=>new En(fn.Point.BASE))(),En.ZERO=(()=>new En(fn.Point.ZERO))(),En.Fp=(()=>an)(),En.Fn=(()=>un)();class In extends st{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,F(t);const n=it(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?t.create().update(n).digest():n);for(let t=0;t<i.length;t++)i[t]^=54;this.iHash.update(i),this.oHash=t.create();for(let t=0;t<i.length;t++)i[t]^=106;this.oHash.update(i),G(i)}update(t){return M(this),this.iHash.update(t),this}digestInto(t){M(this),q(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:e,iHash:n,finished:r,destroyed:i,blockLen:o,outputLen:s}=this;return t.finished=r,t.destroyed=i,t.blockLen=o,t.outputLen=s,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const xn=(t,e,n)=>new In(t,e).update(n).digest();xn.create=(t,e)=>new In(t,e);const An=Uint8Array.from([0]),Nn=Uint8Array.of(),Sn=(t,e,n,r,i)=>function(t,e,n,r=32){F(t),H(r);const i=t.outputLen;if(r>255*i)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(r/i);void 0===n&&(n=Nn);const s=new Uint8Array(o*i),c=xn.create(t,e),a=c._cloneInto(),u=new Uint8Array(c.outputLen);for(let t=0;t<o;t++)An[0]=t+1,a.update(0===t?Nn:u).update(n).update(An).digestInto(u),s.set(u,i*t),c._cloneInto(a);return c.destroy(),a.destroy(),G(u,An),s.slice(0,r)}(t,function(t,e,n){return F(t),void 0===n&&(n=new Uint8Array(t.outputLen)),xn(t,it(n),it(e))}(t,e,n),r,i),Bn=zt;class On extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const e=super.get(t);return super.has(t)&&void 0!==e&&(this.delete(t),super.set(t,e)),e}set(t,e){if(super.set(t,e),this.maxSize&&this.size>this.maxSize){const t=this.keys().next().value;t&&this.delete(t)}return this}}const _n="2.45.1";let Pn=({docsBaseUrl:t,docsPath:e="",docsSlug:n})=>e?`${t??"https://viem.sh"}${e}${n?`#${n}`:""}`:void 0,$n=`viem@${_n}`;class Un extends Error{constructor(t,e={}){const n=e.cause instanceof Un?e.cause.details:e.cause?.message?e.cause.message:e.details,r=e.cause instanceof Un&&e.cause.docsPath||e.docsPath,i=Pn?.({...e,docsPath:r});super([t||"An error occurred.","",...e.metaMessages?[...e.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...$n?[`Version: ${$n}`]:[]].join("\n"),e.cause?{cause:e.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=r,this.metaMessages=e.metaMessages,this.name=e.name??this.name,this.shortMessage=t,this.version=_n}walk(t){return Rn(this,t)}}function Rn(t,e){return e?.(t)?t:t&&"object"==typeof t&&"cause"in t&&void 0!==t.cause?Rn(t.cause,e):e?null:t}class Tn extends Un{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}function Ln(t,{strict:e=!0}={}){return!!t&&"string"==typeof t&&(e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x"))}class Dn extends Un{constructor({size:t,targetSize:e,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${e}).`,{name:"SizeExceedsPaddingSizeError"})}}function Kn(t,{dir:e,size:n=32}={}){return"string"==typeof t?function(t,{dir:e,size:n=32}={}){if(null===n)return t;const r=t.replace("0x","");if(r.length>2*n)throw new Dn({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r["right"===e?"padEnd":"padStart"](2*n,"0")}`}(t,{dir:e,size:n}):function(t,{dir:e,size:n=32}={}){if(null===n)return t;if(t.length>n)throw new Dn({size:t.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const o="right"===e;r[o?i:n-i-1]=t[o?i:t.length-i-1]}return r}(t,{dir:e,size:n})}class Vn extends Un{constructor({max:t,min:e,signed:n,size:r,value:i}){super(`Number "${i}" is not in safe ${r?`${8*r}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${e} to ${t})`:`(above ${e})`}`,{name:"IntegerOutOfRangeError"})}}class zn extends Un{constructor({givenSize:t,maxSize:e}){super(`Size cannot exceed ${e} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}function Cn(t){return Ln(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}function Hn(t,{size:e}){if(Cn(t)>e)throw new zn({givenSize:Cn(t),maxSize:e})}function qn(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let o;r?o=n?(1n<<8n*BigInt(r)-1n)-1n:2n**(8n*BigInt(r))-1n:"number"==typeof t&&(o=BigInt(Number.MAX_SAFE_INTEGER));const s="bigint"==typeof o&&n?-o-1n:0;if(o&&i>o||i<s){const e="bigint"==typeof t?"n":"";throw new Vn({max:o?`${o}${e}`:void 0,min:`${s}${e}`,signed:n,size:r,value:`${t}${e}`})}const c=`0x${(n&&i<0?(1n<<BigInt(8*r))+BigInt(i):i).toString(16)}`;return r?Kn(c,{size:r}):c}const Fn=new TextEncoder;const Mn={zero:48,nine:57,A:65,F:70,a:97,f:102};function jn(t){return t>=Mn.zero&&t<=Mn.nine?t-Mn.zero:t>=Mn.A&&t<=Mn.F?t-(Mn.A-10):t>=Mn.a&&t<=Mn.f?t-(Mn.a-10):void 0}function Gn(t,e={}){let n=t;e.size&&(Hn(n,{size:e.size}),n=Kn(n,{dir:"right",size:e.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,o=new Uint8Array(i);for(let t=0,e=0;t<i;t++){const n=jn(r.charCodeAt(e++)),i=jn(r.charCodeAt(e++));if(void 0===n||void 0===i)throw new Un(`Invalid byte sequence ("${r[e-2]}${r[e-1]}" in "${r}").`);o[t]=16*n+i}return o}function Yn(t,e={}){const n=Fn.encode(t);return"number"==typeof e.size?(Hn(n,{size:e.size}),Kn(n,{dir:"right",size:e.size})):n}const Wn=BigInt(0),Zn=BigInt(1),Xn=BigInt(2),Jn=BigInt(7),Qn=BigInt(256),tr=BigInt(113),er=[],nr=[],rr=[];for(let t=0,e=Zn,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],er.push(2*(5*r+n)),nr.push((t+1)*(t+2)/2%64);let i=Wn;for(let t=0;t<7;t++)e=(e<<Zn^(e>>Jn)*tr)%Qn,e&Xn&&(i^=Zn<<(Zn<<BigInt(t))-Zn);rr.push(i)}const ir=gt(rr,!0),or=ir[0],sr=ir[1],cr=(t,e,n)=>n>32?((t,e,n)=>e<<n-32|t>>>64-n)(t,e,n):((t,e,n)=>t<<n|e>>>32-n)(t,e,n),ar=(t,e,n)=>n>32?((t,e,n)=>t<<n-32|e>>>64-n)(t,e,n):((t,e,n)=>e<<n|t>>>32-n)(t,e,n);class ur extends st{constructor(t,e,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=e,this.outputLen=n,this.enableXOF=r,this.rounds=i,H(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");var o;this.state=new Uint8Array(200),this.state32=(o=this.state,new Uint32Array(o.buffer,o.byteOffset,Math.floor(o.byteLength/4)))}clone(){return this._cloneInto()}keccak(){X(this.state32),function(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let e=0;e<10;e++)n[e]=t[e]^t[e+10]^t[e+20]^t[e+30]^t[e+40];for(let e=0;e<10;e+=2){const r=(e+8)%10,i=(e+2)%10,o=n[i],s=n[i+1],c=cr(o,s,1)^n[r],a=ar(o,s,1)^n[r+1];for(let n=0;n<50;n+=10)t[e+n]^=c,t[e+n+1]^=a}let e=t[2],i=t[3];for(let n=0;n<24;n++){const r=nr[n],o=cr(e,i,r),s=ar(e,i,r),c=er[n];e=t[c],i=t[c+1],t[c]=o,t[c+1]=s}for(let e=0;e<50;e+=10){for(let r=0;r<10;r++)n[r]=t[e+r];for(let r=0;r<10;r++)t[e+r]^=~n[(r+2)%10]&n[(r+4)%10]}t[0]^=or[r],t[1]^=sr[r]}G(n)}(this.state32,this.rounds),X(this.state32),this.posOut=0,this.pos=0}update(t){M(this),q(t=it(t));const{blockLen:e,state:n}=this,r=t.length;for(let i=0;i<r;){const o=Math.min(e-this.pos,r-i);for(let e=0;e<o;e++)n[this.pos++]^=t[i++];this.pos===e&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:e,pos:n,blockLen:r}=this;t[n]^=e,128&e&&n===r-1&&this.keccak(),t[r-1]^=128,this.keccak()}writeInto(t){M(this,!1),q(t),this.finish();const e=this.state,{blockLen:n}=this;for(let r=0,i=t.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);t.set(e.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return H(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(j(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,G(this.state)}_cloneInto(t){const{blockLen:e,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return t||(t=new ur(e,n,r,o,i)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=n,t.outputLen=r,t.enableXOF=o,t.destroyed=this.destroyed,t}}const dr=(()=>{return t=1,e=136,n=32,ct(()=>new ur(e,t,n));var t,e,n})(),fr=new On(8192);function lr(t,e){if(fr.has(`${t}.${e}`))return fr.get(`${t}.${e}`);const n=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),r=function(t){const e=dr(Ln(t,{strict:!1})?function(t,e={}){return"number"==typeof t||"bigint"==typeof t?function(t,e){return Gn(qn(t,e))}(t,e):"boolean"==typeof t?function(t,e={}){const n=new Uint8Array(1);return n[0]=Number(t),"number"==typeof e.size?(Hn(n,{size:e.size}),Kn(n,{size:e.size})):n}(t,e):Ln(t)?Gn(t,e):Yn(t,e)}(t):t);return e}(Yn(n)),i=(e?n.substring(`${e}0x`.length):n).split("");for(let t=0;t<40;t+=2)r[t>>1]>>4>=8&&i[t]&&(i[t]=i[t].toUpperCase()),(15&r[t>>1])>=8&&i[t+1]&&(i[t+1]=i[t+1].toUpperCase());const o=`0x${i.join("")}`;return fr.set(`${t}.${e}`,o),o}const hr=/^0x[a-fA-F0-9]{40}$/,yr=new On(8192);function pr(t,e){const{strict:n=!0}=e??{},r=`${t}.${n}`;if(yr.has(r))return yr.get(r);const i=!(!hr.test(t)||t.toLowerCase()!==t&&n&&lr(t)!==t);return yr.set(r,i),i}var wr=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function gr(t){return"*"===t?"ALL":t.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function br(t){return t.slice(10,t.indexOf("/"))}function mr(t){return t.slice(t.indexOf("/")+1)}function vr(t){const e={};for(const n of wr)br(n.urn)===t&&(e[gr(mr(n.urn))]=n.urn);return e}var kr=vr("kv"),Er={...vr("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},Ir=(vr("duckdb"),vr("capabilities")),xr=(vr("hooks"),vr("encryption")),Ar=vr("space");["tinychat-4jq","share-2fz","tinycloud-secrets","openkey-tinycloud-demo"].map(t=>new RegExp(`^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)?${t}\\.pages\\.dev$`));var Nr="applications",Sr="account",Br="applications/",Or="secrets",_r="default",Pr="public",$r="agents",Ur="tinycloud.encryption",Rr=xr.NETWORK_CREATE,Tr=[_r,Nr,Sr,Or,Pr,$r],Lr={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:_r,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:_r,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:_r,path:"",actions:["read","write"]}]},Dr={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:Nr,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Nr,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:Nr,path:"",actions:["read","write"]}]},Kr={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:Sr,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Sr,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:Sr,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:Sr,path:"account",actions:["read","write","schema"]}]},Vr={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:Or,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:Or,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:Or,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:Or,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:Or,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:Or,path:"",actions:["read"],skipPrefix:!0}]},zr={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:Pr,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Pr,path:"",actions:["get","list","metadata"]}]},Cr={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:$r,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:$r,path:"",actions:["get","put","del","list","metadata"]}]},Hr={[_r]:Lr,[Nr]:Dr,[Sr]:Kr,[Or]:Vr,[Pr]:zr,[$r]:Cr};function qr(t,e=1){return function(t){if(!Number.isSafeInteger(t)||t<=0)throw new Error(`Invalid EIP-155 chain ID: ${t}`)}(e),`did:pkh:eip155:${e}:${function(t){if(!pr(t,{strict:!1}))throw new Error(`Invalid EVM address: ${t}`);return function(t){if(!pr(t,{strict:!1}))throw new Tn({address:t});return lr(t,void 0)}(t)}(t)}`}function Fr(t){return{...t,permissions:t.permissions?.map(t=>({...t,actions:[...t.actions]}))}}function Mr(t,e,n){return!0===n||""===t||""===e?e:"/"===e?`${t}/`:`${t.endsWith("/")?t.slice(0,-1):t}/${e.startsWith("/")?e.slice(1):e}`}function jr(t,e,n){if("tinycloud.vault"===t.service)return function(t){return t.actions.map(e=>{const n=e.startsWith("tinycloud.vault/")?e.slice(16):e.startsWith("tinycloud.kv/")?e.slice(13):e,r="read"===n||"get"===n?kr.GET:"write"===n||"put"===n?kr.PUT:"delete"===n||"del"===n?kr.DEL:"list"===n?kr.LIST:"metadata"===n?kr.METADATA:void 0;if(void 0===r)throw new Error(`unknown vault action ${JSON.stringify(e)}`);const i=t.path.startsWith("/")?t.path.slice(1):t.path;return{...t,service:"tinycloud.kv",path:`vault/${i}`,actions:[r],skipPrefix:!0}})}(t).flatMap(t=>jr(t,e,n));const r=!0===t.skipPrefix||t.service===Ur;return[{service:t.service,space:t.service===Ur?"encryption":t.space??n,path:Mr(e,t.path,r),actions:t.actions.map(e=>function(t,e){return e.includes("/")?e:`${t}/${e}`}(t.service,e)),...void 0!==t.description?{description:t.description}:{}}]}function Gr(t){const e=new Set(t.filter(t=>t.service!==Ur).map(t=>t.space));return function(t){const e=new Map;for(const n of t){const t=`${n.service}\0${n.space}\0${n.path}`,r=e.get(t);if(r)for(const t of n.actions)r.actions.includes(t)||r.actions.push(t);else e.set(t,{...n,actions:[...n.actions]})}return[...e.values()]}([...t,...[...e].map(t=>({service:"tinycloud.capabilities",space:t,path:"",actions:[Ir.READ]}))])}function Yr(t){return function(t,e={}){if(!Array.isArray(t)||0===t.length)throw new Error("composeManifestRequest requires at least one manifest");const n=e.includeAccountRegistryPermissions??!0,r=t.map(Fr),i=r.flatMap(t=>{const e=t.prefix??t.app_id,n=t.space??Nr;return(t.permissions??[]).flatMap(t=>jr(t,e,n))});n&&i.push(...Wr.map(t=>({...t,actions:[...t.actions]})));const o=new Map;for(const t of r){const e=o.get(t.app_id)??[];e.push(Fr(t)),o.set(t.app_id,e)}return{manifests:r,resources:Gr(i),delegationTargets:[],registryRecords:n?[...o.entries()].map(([t,e])=>({key:`${Br}${t}`,app_id:t,manifests:e})):[],expiryMs:6048e5,includePublicSpace:r.some(t=>t.includePublicSpace??!0)}}([Hr[t]],{includeAccountRegistryPermissions:!1})}Tr.map(t=>({name:t,manifest:Hr[t],persistedAsApplication:t===Or}));var Wr=Object.freeze([{service:"tinycloud.kv",space:Sr,path:Br,actions:[kr.GET,kr.PUT,kr.LIST]},{service:"tinycloud.kv",space:Sr,path:"spaces/",actions:[kr.GET,kr.PUT,kr.LIST]},{service:"tinycloud.kv",space:Sr,path:"system/bootstrap/complete",actions:[kr.GET,kr.PUT]},{service:"tinycloud.delegation",space:Sr,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:Sr,path:"account",actions:[Er.READ,Er.WRITE,Er.SCHEMA]},{service:"tinycloud.capabilities",space:Sr,path:"",actions:[Ir.READ]}]),Zr=Yr(_r),Xr={...Zr,resources:[...Zr.resources,...Wr.map(t=>({...t,actions:[...t.actions]}))]},Jr=Object.freeze(Object.fromEntries(Tr.map(t=>[t,t===_r?Xr:Yr(t)]))),Qr=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[Rr]}]);function ti(t){return void 0===t?"":ei(t)}function ei(t){if(null===t)return"null";switch(typeof t){case"boolean":case"number":case"string":return JSON.stringify(t);case"object":{if(Array.isArray(t))return`[${t.map(ei).join(",")}]`;const e=Object.keys(t).sort(),n=[];for(const r of e){const e=t[r];void 0!==e&&n.push(`${JSON.stringify(r)}:${ei(e)}`)}return`{${n.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof t)}}Object.freeze(Tr.flatMap(t=>[{kind:"session",service:"tinycloud.session",space:t,actions:["siwe"],resources:Jr[t].resources,...t===Sr?{rawAbilities:Qr}:{}},{kind:"space/host",service:"tinycloud.space",space:t,actions:[Ar.HOST]}]));var ni="0123456789abcdef";function ri(t){let e="";for(let n=0;n<t.length;n++){const r=t[n];e+=ni[r>>4&15]+ni[15&r]}return e}function ii(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let n="";for(let r=0;r<t.length;r+=3){const i=t[r],o=r+1<t.length?t[r+1]:0,s=r+2<t.length?t[r+2]:0;n+=e[i>>2&63],n+=e[63&(i<<4|o>>4)],n+=r+1<t.length?e[63&(o<<2|s>>6)]:"=",n+=r+2<t.length?e[63&s]:"="}return n}function oi(t){const e=t.replace(/[^A-Za-z0-9+/=]/g,""),n=e.length;if(n%4!=0)throw new Error("invalid base64 input");const r=n/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0),i=new Uint8Array(r),o={};for(let t=0;t<64;t++)o["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[t]]=t;let s=0;for(let t=0;t<n;t+=4){const n=o[e[t]]??0,c=o[e[t+1]]??0,a="="===e[t+2]?0:o[e[t+2]]??0,u=n<<2|c>>4,d=(15&c)<<4|a>>2,f=(3&a)<<6|("="===e[t+3]?0:o[e[t+3]]??0);s<r&&(i[s++]=u),s<r&&(i[s++]=d),s<r&&(i[s++]=f)}return i}function si(t){return(new TextEncoder).encode(t)}function ci(t,e){return ri(t(si(ti(e))))}var ai="urn:tinycloud:encryption:",ui=/^[a-z0-9][a-z0-9-]*$/,di=class extends Error{constructor(t){super(t),this.name="NetworkIdError"}};function fi(t){if("string"!=typeof t||0===t.length)throw new di("networkId must be a non-empty string");if(!t.startsWith(ai))throw new di(`networkId must start with ${ai} (got ${JSON.stringify(t)})`);const e=t.slice(25),n=e.lastIndexOf(":");if(n<=0||n===e.length-1)throw new di(`networkId missing ownerDid or name segment (got ${JSON.stringify(t)})`);const r=e.slice(0,n),i=e.slice(n+1);if(!r.startsWith("did:"))throw new di(`networkId ownerDid must be a DID (got ${JSON.stringify(r)})`);const o=r.split(":");if(o.length<3||o.some(t=>0===t.length))throw new di(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(r)})`);if(!ui.test(i))throw new di(`networkId name ${JSON.stringify(i)} must match ${ui.source}`);return{networkId:t,ownerDid:r,name:i}}var li=ai,hi="tinycloud.encryption.decrypt/v1",yi="tinycloud.encryption.decrypt-result/v1",pi="tinycloud.encryption/decrypt";function wi(t){switch(t.code){case"NETWORK_NOT_FOUND":return t.message??`Network not found: ${t.networkId??t.name??"<unknown>"}`;case"NETWORK_NOT_ACTIVE":return t.message??`Network not active (state=${t.state})`;case"INVALID_NETWORK_ID":case"INVALID_ENVELOPE":case"DECRYPT_DENIED":case"INVALID_RESPONSE":case"INVALID_INPUT":return t.message;case"RESPONSE_SIGNATURE_INVALID":return t.message??"Node response signature failed to verify";case"RESPONSE_BINDING_MISMATCH":return t.message??`Node response binding mismatch on field ${JSON.stringify(t.field)}`;case"TRANSPORT_ERROR":return t.message??t.cause.message;default:return t.message??t.code}}function gi(t){return{...t,service:"encryption",message:wi(t)}}var bi="x25519-hkdf-aes256gcm/v2",mi=si("TCW2"),vi=si("tinycloud.encryption.key-wrap/v2");function ki(...t){const e=new Uint8Array(t.reduce((t,e)=>t+e.length,0));let n=0;for(const r of t)e.set(r,n),n+=r.length;return e}function Ei(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}function Ii(t){if("string"!=typeof t)throw new Error("Invalid key wrap encoding");const e=oi(t);if(32!==e.length||ii(e)!==t)throw new Error("Invalid key wrap encoding");return e}function xi(t){for(let e=0;e<t.length;e++){const n=t.charCodeAt(e);if(n>=55296&&n<=56319){const n=t.charCodeAt(++e);if(!(n>=56320&&n<=57343))return!1}else if(n>=56320&&n<=57343)return!1}return!0}function Ai(t){if("network-key"!==t.purpose&&"receiver-key"!==t.purpose||"string"!=typeof t.networkId||"string"!=typeof t.keyPath||!xi(t.networkId)||!xi(t.keyPath)||!Number.isSafeInteger(t.keyVersion)||t.keyVersion<=0||!t.metadata||"object"!=typeof t.metadata||Array.isArray(t.metadata)||Object.entries(t.metadata).some(([t,e])=>!xi(t)||"string"!=typeof e||!xi(e)))throw new Error("Invalid key wrap context");if(""!==t.networkId){const e=function(t){const e=t.lastIndexOf(":"),n=t.slice(e+1),r=n.indexOf("/"),i=-1===r?n:n.slice(0,r),o=fi(-1===r?t:`${t.slice(0,e+1)}${i}`);if(-1===r)return o;const s=n.slice(r+1),c=s.split("/"),a=s.endsWith("/");if(0===s.length||/[\u0000-\u001f\u007f\\]/.test(s)||c.some((t,e)=>"."===t||".."===t||0===t.length&&!(a&&e===c.length-1)))throw new di(`encryption resource has an invalid keyPath (got ${JSON.stringify(t)})`);return{...o,keyPath:s}}(""===t.keyPath?t.networkId:`${t.networkId}/${t.keyPath}`);if(e.networkId!==t.networkId||(e.keyPath??"")!==t.keyPath||t.keyPath.endsWith("/"))throw new Error("Invalid key wrap resource")}}function Ni(t){return t.length>=4&&mi.every((e,n)=>t[n]===e)}function Si(t){if(!Ni(t)||t.length<8)throw new Error("Invalid v2 key wrap frame");const e=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(4);if(0===e||e>65536||t.length<8+e+12+16)throw new Error("Invalid v2 key wrap length");const n=t.subarray(8,8+e),r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)),i=["v","alg","kdf","aead","salt","ephemeralPublicKey","recipientPublicKey","purpose","networkId","keyPath","keyVersion","metadata"].sort();if(!r||"object"!=typeof r||Array.isArray(r)||Object.keys(r).sort().join(",")!==i.join(",")||2!==r.v||r.alg!==bi||"hkdf-sha256"!==r.kdf||"aes-256-gcm"!==r.aead)throw new Error("Invalid v2 key wrap header");if(Ai(r),Ii(r.salt),Ii(r.ephemeralPublicKey),Ii(r.recipientPublicKey),!Ei(n,si(ti({...r}))))throw new Error("Non-canonical v2 key wrap header");const o=8+e;return{header:r,aad:t.subarray(0,o),nonce:t.subarray(o,o+12),ciphertext:t.subarray(o+12)}}function Bi(t,e){Ai(e);for(const n of["purpose","networkId","keyPath","keyVersion"])if(t[n]!==e[n])throw new Error("Key wrap context mismatch");if(ti(t.metadata)!==ti(e.metadata))throw new Error("Key wrap metadata mismatch")}function Oi(t,e,n=!1){if("x25519-aes256gcm/v1"!==e&&e!==bi)throw new Error("Unsupported key wrap algorithm");if(n&&e!==bi)throw new Error("V2 network key wrap required");if(Ni(t)!==(e===bi))throw new Error("Key wrap algorithm mismatch");e===bi&&Si(t)}function _i(t,e=!1){const n=oi(t.encryptedSymmetricKey);Oi(n,t.alg,e),t.alg===bi&&Bi(Si(n).header,{purpose:"network-key",networkId:t.networkId,keyPath:t.keyPath??"",keyVersion:t.keyVersion,metadata:t.metadata??{}})}var Pi="[a-z0-9][a-z0-9._-]{0,63}",$i=new RegExp(`^${Pi}(?:/${Pi}){0,7}$`),Ui=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ri=/^(did:[a-z0-9]+:[A-Za-z0-9._:-]+):([^:/]+)(?:\/(.*))?$/s,Ti="did:pkh:eip155:",Li="tinycloud.encryption/key.create",Di="tinycloud.encryption/key.block",Ki="tinycloud.encryption/key.unblock",Vi=(Object.freeze([pi,Li,Di,Ki]),class extends Error{constructor(t,e){super(e),this.name="EncryptionResourceError",this.code=t}});function zi(t){if(!t.startsWith(Ti))return t;const e=t.slice(15),n=e.indexOf(":"),r=-1===n?"":e.slice(0,n),i=-1===n?"":e.slice(n+1);if(!/^\d+$/.test(r)||!/^0x[a-fA-F0-9]{40}$/.test(i))throw new Vi("bad_owner",`owner DID is not a valid did:pkh:eip155 (got ${JSON.stringify(t)})`);const o=BigInt(r);if(0n===o||o>18446744073709551615n)throw new Vi("bad_owner",`did:pkh:eip155 chain id must be a positive u64 (got ${JSON.stringify(r)})`);const s=qr(i,1).slice(17);return`${Ti}${o}:${s}`}function Ci(t){const e=zi(t);if(e!==t)throw new Vi("non_canonical_owner",`owner DID is not canonical (expected ${e})`)}function Hi(t,e){if(0===t.length)throw new Vi("empty_path",`${e} must not be empty`);if((new TextEncoder).encode(t).length>255)throw new Vi("path_too_long",`${e} exceeds 255 bytes`);if(!$i.test(t))throw new Vi("bad_path",`${e} ${JSON.stringify(t)} must match ${$i.source}`);const n=t.split("/");if("apps"===n[0]&&n.length<("key path"===e?3:2))throw new Vi("bad_path",`${e} ${JSON.stringify(t)} under apps/ needs ${"key path"===e?"apps/<id>/<name>":"apps/<id>/"}`)}function qi(t){if("string"!=typeof t||!t.startsWith(li))throw new Vi("not_encryption_urn",`resource must start with ${li}`);const e=t.slice(25),n=Ri.exec(e);if(null===n)throw new Vi("malformed",`resource is not <ownerDid>:<network>[/<path>] (got ${JSON.stringify(t)})`);const r=n[1],i=n[2],o=n[3];if(void 0===o){const t=zi(r),e=`${li}${t}:${i}`;try{fi(e)}catch(t){if(t instanceof di)throw new Vi("bad_network",t.message);throw t}return{kind:"network",ownerDid:t,network:i,networkId:e}}if(!Ui.test(i))throw new Vi("bad_network",`network ${JSON.stringify(i)} must match ${Ui.source}`);Ci(r);const s=`${li}${r}:${i}`;if(o.endsWith("/")){const t=o.slice(0,-1);return Hi(t,"prefix"),{kind:"prefix",ownerDid:r,network:i,networkId:s,prefix:t}}return Hi(o,"key path"),{kind:"key",ownerDid:r,network:i,networkId:s,path:o}}function Fi(t){let e="";for(const n of t){const t=n.codePointAt(0);e+=t>=32&&t<=126?n:`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`}return e}function Mi(t){const e="string"==typeof t?t:String(t),n=Array.from(e);return Fi(n.length>120?`${n.slice(0,120).join("")}...`:e)}var ji=class extends Error{constructor(t,e,n={}){super(Fi(e),void 0===n.cause?void 0:{cause:n.cause}),this.name="NamedKeyError",this.code=t,void 0!==n.status&&(this.status=n.status),void 0!==n.nodeCode&&(this.nodeCode=n.nodeCode),void 0!==n.detail&&(this.detail=n.detail),void 0!==n.rawState&&(this.rawState=n.rawState),void 0!==n.kind&&(this.kind=n.kind),void 0!==n.input&&(this.input=n.input)}},Gi=Object.assign(Object.create(null),{key_blocked:"KEY_BLOCKED",key_not_found:"KEY_NOT_FOUND",key_exists:"KEY_EXISTS",network_not_found:"NETWORK_NOT_FOUND",network_not_active:"NETWORK_NOT_ACTIVE",key_limit_exceeded:"KEY_LIMIT_EXCEEDED",deletable_unavailable:"DELETABLE_UNAVAILABLE",key_not_deletable:"KEY_NOT_DELETABLE",key_path_invalid:"KEY_PATH_INVALID",key_unwrap_failed:"KEY_UNWRAP_FAILED",receiver_key_invalid:"RECEIVER_KEY_INVALID"}),Yi=Object.assign(Object.create(null),{key_deleted:!0}),Wi=/^([a-z][a-z0-9_]*):\s?([\s\S]*)$/;function Zi(t,e,n){const r=Wi.exec(e.trim()),i=r?.[1]?.slice(0,64),o=r?.[2]?.trim(),s={status:t,...void 0===i?{}:{nodeCode:i},...void 0===o||0===o.length?{}:{detail:o}};if(void 0!==i){const t=Gi[i];if(void 0!==t)return new ji(t,`${n}: ${i}`,s);if(!0===Yi[i])return new ji("KEY_UNAVAILABLE",`${n}: key unavailable (${i})`,{...s,rawState:i})}return new ji("NODE_ERROR",`${n}: node responded ${t}`,s)}function Xi(t){let e;try{e=qi(t)}catch(e){throw new ji("INVALID_KEY_TARGET",`not a valid encryption key resource: ${Mi(e instanceof Error?e.message:e)}`,{cause:e,input:t})}if("key"!==e.kind)throw new ji("INVALID_KEY_TARGET",`a ${e.kind} resource cannot be an invocation target; an exact key is required`,{input:t});return e}function Ji(t){const e=Xi(t.keyResource);return{type:"tinycloud.encryption.key-admin/v1",targetNode:t.targetNode,networkId:e.networkId,keyPath:e.path,action:t.action,bodyHash:ci(t.crypto.sha256,t.body)}}function Qi(t){const e=Xi(t.keyResource);return{type:"tinycloud.encryption.key-describe/v1",targetNode:t.targetNode,networkId:e.networkId,keyPath:e.path}}var to={[pi]:!0,[Li]:!0,[Di]:!0,[Ki]:!0};function eo(t){return new ji("INVALID_RESPONSE",`node returned an invalid ${t}`)}function no(t,e,n){const r="object"==typeof t&&null!==t?t:{};if("string"!=typeof r.alg||"number"!=typeof r.keyVersion||!Number.isInteger(r.keyVersion)||"string"!=typeof r.publicEncryptionKey||0===r.publicEncryptionKey.length)throw eo("key descriptor");if(r.networkId!==e||r.keyPath!==n)throw new ji("INVALID_RESPONSE","node returned a descriptor for a different network or key");return{networkId:e,keyPath:n,alg:r.alg,keyVersion:r.keyVersion,publicEncryptionKey:r.publicEncryptionKey}}function ro(t,e,n){const r=no(t,e,n),i=t;if("string"!=typeof i.state||"string"!=typeof i.kind)throw eo("key descriptor (state/kind missing)");return{...r,state:i.state,kind:i.kind,..."string"==typeof i.createdAt?{createdAt:i.createdAt}:{},..."string"==typeof i.updatedAt?{updatedAt:i.updatedAt}:{}}}function io(t,e){if("blocked"===t.state)throw new ji("KEY_BLOCKED",`key ${Mi(t.keyPath)} is blocked`,{rawState:t.state});if("active"!==t.state)throw new ji("KEY_UNAVAILABLE",`key ${Mi(t.keyPath)} is unavailable (state ${Mi(t.state)})`,{rawState:t.state});if(t.kind!==e)throw new ji("KEY_KIND_MISMATCH",`key ${Mi(t.keyPath)} exists with kind ${Mi(t.kind)}, not ${e}`,{kind:t.kind});return t}function oo(t){return/^(?:apps|secrets)(?:\/|$)/.test(t)}var so=["alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"],co=class{constructor(t){this.config=t,this.nodeInfo=new Map}networkFor(t){return t?.networkId??this.config.defaultNetworkId()}keyUrn(t,e){try{return function(t,e){const n=function(t){let e;try{e=fi(t)}catch(t){if(t instanceof di)throw new Vi("bad_network",t.message);throw t}return Ci(e.ownerDid),e.networkId}(t);Hi(e,"key path");const r=`${n}/${e}`;return function(t,e){if(qi(t).networkId!==e)throw new Vi("malformed",`built resource does not round-trip (got ${JSON.stringify(t)})`)}(r,n),r}(t,e)}catch(n){throw new ji("INVALID_KEY_TARGET",Mi(n instanceof Error?n.message:n),{cause:n,input:`${t}/${e}`})}}async requireNode(t){const e=void 0===this.config.resolveNode?void 0:await this.config.resolveNode(t),n=e?.url??this.config.host,r=`${n} ${e?.nodeDid??""}`;let i=this.nodeInfo.get(r);if(void 0===i){const t=this.readNodeInfo(n,e?.nodeDid);i=t,this.nodeInfo.set(r,t),t.catch(()=>{this.nodeInfo.get(r)===t&&this.nodeInfo.delete(r)})}return{url:n,nodeDid:await i}}refreshNodeInfo(){this.nodeInfo.clear()}async readNodeInfo(t,e){const n=await this.config.fetch(`${t}/info`);if(!n.ok)throw Zi(n.status,await ao(n),"failed to read node info");const r=await n.json();if(!function(t){const e=t?.features;return Array.isArray(e)&&e.includes("encryption-named-keys-v1")}(r))throw new ji("NAMED_KEYS_UNSUPPORTED","this node does not support named encryption keys");if("string"!=typeof r.nodeId||0===r.nodeId.length)throw eo("/info response (nodeId missing)");if(void 0!==e&&r.nodeId!==e)throw new ji("NODE_IDENTITY_MISMATCH","the node's /info identity does not match its verified identity");return r.nodeId}keysUrl(t,e,n){return`${t}/encryption/networks/${e}/keys/${n}`}async getPublicKey(t,e){const n=this.networkFor(e);this.keyUrn(n,t);const r=await this.requireNode(n),i=await this.config.fetch(this.keysUrl(r.url,n,t),{method:"GET"});if(!i.ok)throw Zi(i.status,await ao(i),"failed to read key");return no(await i.json(),n,t)}async describeKey(t,e){const n=this.networkFor(e),r=await this.describeBody(t,e);return null===r?null:ro(r,n,t)}async describePublic(t,e){const n=this.networkFor(e),r=await this.describeBody(t,e);if(null===r)throw new ji("KEY_NOT_FOUND",`key ${Mi(t)} does not exist`,{status:404});return no(r,n,t)}async describeBody(t,e){const n=this.networkFor(e),r=this.keyUrn(n,t),i=e?.ability??pi;if(!0!==to[i])throw new ji("INVALID_KEY_TARGET",`${Mi(i)} cannot describe a key`,{input:i});const{url:o,nodeDid:s}=await this.requireNode(n),c=await this.config.signInvocation({targetNode:s,resource:r,action:i,facts:Qi({targetNode:s,keyResource:r})}),a=await this.config.fetch(this.keysUrl(o,n,t),{method:"GET",headers:{Authorization:c.authorization}});if(404===a.status){const t=Zi(404,await ao(a),"failed to describe key");if("KEY_NOT_FOUND"===t.code)return null;throw t}if(!a.ok)throw Zi(a.status,await ao(a),"failed to describe key");return a.json()}async admin(t,e,n,r){const i=this.networkFor(r),o=this.keyUrn(i,n),s="keys"===t?{keyPath:n,deletable:oo(n)}:{keyPath:n},{url:c,nodeDid:a}=await this.requireNode(i),u=await this.config.signInvocation({targetNode:a,resource:o,action:e,facts:Ji({crypto:this.config.crypto,targetNode:a,keyResource:o,action:e,body:s})}),d=await this.config.fetch(`${c}/encryption/networks/${i}/${t}`,{method:"POST",headers:{Authorization:u.authorization,"Content-Type":"application/json"},body:ti(s)});if(!d.ok)throw Zi(d.status,await ao(d),`failed to ${e}`);return ro(function(t){const e="object"==typeof t&&null!==t?t:{};return"object"==typeof e.descriptor&&null!==e.descriptor?e.descriptor:t}(await d.json()),i,n)}createKey(t,e){return this.admin("keys",Li,t,e)}blockKey(t,e){return this.admin("key-actions/block",Di,t,e)}unblockKey(t,e){return this.admin("key-actions/unblock",Ki,t,e)}async ensureKey(t,e){const n=()=>this.describeKey(t,{...e,ability:Li});let r=await n();if(null===r)try{r=await this.createKey(t,e)}catch(e){if(!(e instanceof ji)||"KEY_EXISTS"!==e.code)throw e;if(r=await n(),null===r)throw new ji("KEY_NOT_FOUND",`key ${Mi(t)} reported as existing but could not be read back`)}return io(r,oo(t)?"deletable":"deterministic")}async encrypt(t,e,n){let r;const i=n?.descriptor;if(void 0!==i){if(!0===n?.ensureKey)throw new ji("INVALID_KEY_TARGET","a pinned descriptor cannot be combined with ensureKey");const e=this.networkFor(n);this.keyUrn(e,t);const o=oo(t);r=o||"object"==typeof i&&null!==i&&("state"in i||"kind"in i)?io(ro(i,e,t),o?"deletable":"deterministic"):no(i,e,t);const s=r.publicEncryptionKey;if(!r.alg||!Number.isSafeInteger(r.keyVersion)||r.keyVersion<1||44!==s.length||!/^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/.test(s))throw new ji("INVALID_RESPONSE","invalid pinned key descriptor")}else r=n?.ensureKey?await this.ensureKey(t,n):oo(t)?await this.describePublic(t,n):await this.getPublicKey(t,n);const{crypto:o}=this.config,s=o.randomBytes(32),c=o.authEncrypt(s,e,n?.aad),a=n?.keyWrapV2??this.config.keyWrapV2??!1,u=oi(r.publicEncryptionKey),d=a?function(t,e,n){if(Ai(n),32!==t.length)throw new Error("Invalid recipient public key");const r=at(32),i=ln.getPublicKey(r),o=at(32),s=si(ti({...{...n,v:2,alg:bi,kdf:"hkdf-sha256",aead:"aes-256-gcm",salt:ii(o),ephemeralPublicKey:ii(i),recipientPublicKey:ii(t)}}));if(s.length>65536)throw new Error("Key wrap header too large");const c=new Uint8Array(8);c.set(mi),new DataView(c.buffer).setUint32(4,s.length);const a=ki(c,s),u=at(12);let d;try{const n=ln.getSharedSecret(r,t);try{if(n.every(t=>0===t))throw new Error("Invalid key agreement");d=Sn(Bn,n,o,ki(vi,i,t),32)}finally{n.fill(0)}return ki(a,u,K(d,u,a).encrypt(e))}finally{r.fill(0),d?.fill(0)}}(u,s,{purpose:"network-key",networkId:r.networkId,keyPath:r.keyPath,keyVersion:r.keyVersion,metadata:n?.metadata??{}}):o.sealToNetworkKey(u,s),f=ii(d);return{v:2,networkId:r.networkId,keyPath:r.keyPath,alg:a?bi:"x25519-aes256gcm/v1",keyVersion:r.keyVersion,encryptedSymmetricKey:f,encryptedSymmetricKeyHash:ci(o.sha256,f),ciphertext:ii(c),...void 0!==n?.aad?{aad:ii(n.aad)}:{},...void 0!==n?.metadata?{metadata:n.metadata}:{}}}async decrypt(t){const e="object"==typeof t&&null!==t?t:{};if(1===e.v&&void 0===e.keyPath)return this.decryptRoot(e);if(2===e.v&&"string"==typeof e.keyPath)return this.decryptKey(this.validateKeyEnvelope(e));throw new ji("INVALID_ENVELOPE","envelope must be v1 without keyPath or v2 with keyPath")}async decryptMany(t){const e=[];for(const n of t)try{e.push({ok:!0,data:await this.decrypt(n)})}catch(t){e.push({ok:!1,error:t instanceof ji?t:new ji("DECRYPT_FAILED","decrypt failed",{cause:t})})}return e}async decryptRoot(t){if(this.config.requireKeyWrapV2)try{_i(t,!0)}catch(t){throw new ji("INVALID_ENVELOPE","Envelope key wrap context is invalid",{cause:t})}if(void 0===this.config.decryptRoot)throw new ji("DECRYPT_FAILED","no root-key decrypt path is configured");const e=await this.config.decryptRoot(t);if(!e.ok)throw new ji("DECRYPT_FAILED",Mi(e.error.message),{cause:e.error});return e.data}validateKeyEnvelope(t){for(const e of so)if("string"!=typeof t[e]||0===t[e].length)throw new ji("INVALID_ENVELOPE",`envelope.${e} must be a non-empty string`);if("number"!=typeof t.keyVersion||!Number.isInteger(t.keyVersion))throw new ji("INVALID_ENVELOPE","envelope.keyVersion must be an integer");if("string"!=typeof t.networkId)throw new ji("INVALID_ENVELOPE","envelope.networkId must be a string");try{fi(t.networkId)}catch(t){throw new ji("INVALID_ENVELOPE","envelope.networkId is malformed",{cause:t})}if(ci(this.config.crypto.sha256,t.encryptedSymmetricKey)!==t.encryptedSymmetricKeyHash)throw new ji("INVALID_ENVELOPE","envelope.encryptedSymmetricKeyHash does not match encryptedSymmetricKey");try{_i(t,this.config.requireKeyWrapV2??!1)}catch(t){throw new ji("INVALID_ENVELOPE","Envelope key wrap context is invalid",{cause:t})}return t}async decryptKey(t){const{crypto:e}=this.config,n=this.keyUrn(t.networkId,t.keyPath),{url:r,nodeDid:i}=await this.requireNode(t.networkId),o=function(t){const e=t.crypto.randomBytes(32);return t.crypto.x25519FromSeed(e)}({crypto:e}),s=ii(o.publicKey),c=ci(e.sha256,s),a={type:hi,targetNode:i,networkId:t.networkId,keyPath:t.keyPath,alg:t.alg,keyVersion:t.keyVersion,encryptedSymmetricKey:t.encryptedSymmetricKey,encryptedSymmetricKeyHash:t.encryptedSymmetricKeyHash,receiverPublicKey:s,receiverPublicKeyHash:c},u=ti(a),d={type:hi,targetNode:i,networkId:t.networkId,keyPath:t.keyPath,bodyHash:ci(e.sha256,a),encryptedSymmetricKeyHash:t.encryptedSymmetricKeyHash,receiverPublicKeyHash:c,alg:t.alg,keyVersion:t.keyVersion},f=await this.config.signInvocation({targetNode:i,resource:n,action:pi,facts:d}),l=await this.config.fetch(`${r}/invoke`,{method:"POST",headers:{Authorization:f.authorization,"Content-Type":"application/json"},body:u});if(!l.ok)throw Zi(l.status,await ao(l),"failed to decrypt");const h=function(t){const{crypto:e,request:n,facts:r,invocationCid:i,requestBodyHash:o,response:s}=t;if(s.type!==yi)return{ok:!1,error:gi({code:"INVALID_RESPONSE",message:`response.type must be ${yi}`})};if(s.targetNode!==n.targetNode)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(s.networkId!==n.networkId)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(s.nodeId!==n.targetNode)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if("x25519-aes256gcm/v1"!==s.alg&&s.alg!==bi)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(s.keyVersion!==n.keyVersion)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(s.encryptedSymmetricKeyHash!==n.encryptedSymmetricKeyHash)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(s.receiverPublicKeyHash!==n.receiverPublicKeyHash)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(s.invocationCid!==i)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const c=ri(e.sha256(si(`${i}${o}`)));if(s.requestHash!==c)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(r.encryptedSymmetricKeyHash!==s.encryptedSymmetricKeyHash||r.receiverPublicKeyHash!==s.receiverPublicKeyHash||r.networkId!==s.networkId||r.targetNode!==s.targetNode||r.alg!==n.alg||r.keyVersion!==s.keyVersion)return{ok:!1,error:gi({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const a=(new TextEncoder).encode(function(t){const{nodeSignature:e,...n}=t;return ti(n)}(s)),u=oi(s.nodeSignature);return e.verifyNodeSignature(s.nodeId,a,u)?{ok:!0,data:s}:{ok:!1,error:gi({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:e,request:a,facts:d,invocationCid:f.invocationCid,requestBodyHash:d.bodyHash,response:await l.json()});if(!h.ok)throw new ji("INVALID_RESPONSE",Mi(h.error.message),{cause:h.error});const y=function(t,e,n,r){const i=oi(n.wrappedKey);if(Oi(i,n.alg),n.alg===bi){if(!r)throw new Error("V2 response requires expected key context");return function(t,e,n){const{header:r,aad:i,nonce:o,ciphertext:s}=Si(e);Bi(r,n);const c=ln.getPublicKey(t);if(!Ei(c,Ii(r.recipientPublicKey)))throw new Error("Key wrap recipient mismatch");const a=function(t,e,n,r){const i=ln.getSharedSecret(t,e);if(i.every(t=>0===t))throw new Error("Invalid key agreement");try{return Sn(Bn,i,r,ki(vi,e,n),32)}finally{i.fill(0)}}(t,Ii(r.ephemeralPublicKey),c,Ii(r.salt));try{return K(a,o,i).decrypt(s)}finally{a.fill(0)}}(e,i,r)}return t.openWithReceiverKey(e,i)}(e,o.privateKey,h.data,{purpose:"receiver-key",networkId:a.networkId,keyPath:a.keyPath,keyVersion:a.keyVersion,metadata:{}});try{return e.authDecrypt(y,oi(t.ciphertext),void 0!==t.aad?oi(t.aad):void 0)}catch(t){throw new ji("DECRYPT_FAILED","local decryption failed",{cause:t})}}};async function ao(t){try{return await t.text()}catch{return""}}function uo(t,e={}){const n=t;for(const t of["signRawNetworkAuthorization","createEncryptionCrypto","encryptionDestination"])if("function"!=typeof n[t])throw new ji("NODE_HOOK_MISSING",`TinyCloudNode.${t} is not available; named keys cannot sign invocations`);const r=n,i=t.hosts[0];if(void 0===i)throw new Error("TinyCloud node host has not been resolved");const o=e.fetch??globalThis.fetch.bind(globalThis),s=Object.assign((t,e)=>o(t,{...e,redirect:"error"}),{preconnect:()=>{}}),c={keyWrapV2:e.keyWrapV2??r.config?.keyWrapV2??!1,requireKeyWrapV2:e.requireKeyWrapV2??r.config?.requireKeyWrapV2??!1,host:i,resolveNode:async t=>{const{url:e,nodeDid:n}=await r.encryptionDestination(t);return{url:e,nodeDid:n}},crypto:r.createEncryptionCrypto(),fetch:s,defaultNetworkId:()=>e.networkId??t.getDefaultEncryptionNetworkId(),signInvocation:t=>r.signRawNetworkAuthorization({targetNode:t.targetNode,networkId:t.resource,action:t.action,facts:t.facts},e.binding),decryptRoot:n=>{const r=t.session?.delegationCid;return void 0!==e.binding||void 0===r?Promise.reject(new Error(void 0===e.binding?"Not signed in. Call signIn() first.":"A delegated named-key client never opens the network root key")):t.encryption.decryptEnvelope(n,{proofs:[r]})}};return new co(c)}module.exports=e})();
|