@konemono/nostr-login 1.14.0 → 1.14.1
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 +1 -0
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/modules/Nip46.d.ts +1 -0
- package/dist/unpkg.js +1 -1
- package/package.json +2 -2
- package/src/modules/Nip46.ts +19 -2
package/README.md
CHANGED
|
@@ -7,6 +7,7 @@ This library is a powerful `window.nostr` provider with NIP-46 (Nostr Connect) s
|
|
|
7
7
|
|
|
8
8
|
### Fork Enhancements
|
|
9
9
|
|
|
10
|
+
- **rx-nostr based relay management** — Replaced raw WebSocket handling with [rx-nostr](https://github.com/penpenpng/rx-nostr) v3: automatic reconnection with exponential backoff, lazy-keep connection strategy, reactive connection monitoring via `createConnectionStateObservable()`, and `cast()` for best-effort event publishing
|
|
10
11
|
- **Multiple NIP-46 relay support** — Add/remove/reset relays from the UI
|
|
11
12
|
- **QR code scanning** — Scan `bunker://` or `nostrconnect://` QR codes with camera
|
|
12
13
|
- **NIP-46 signing retry** — Auto-retry (up to 3 times) with forced reconnection on relay disconnect/timeout
|
package/dist/index.esm.js
CHANGED
|
@@ -18,7 +18,7 @@ new Uint8Array(new Uint32Array([287454020]).buffer)[0];var me$1=function(e,t){re
|
|
|
18
18
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */}function bn(e){const t=Be(e);bt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:o}=t;if(n){if(!r.eql(o,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if("object"!=typeof n||"bigint"!=typeof n.beta||"function"!=typeof n.splitScalar)throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:En,hexToBytes:mn}=on,st={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(e){const{Err:t}=st;if(e.length<2||2!==e[0])throw new t("Invalid signature integer tag");const n=e[1],r=e.subarray(2,n+2);if(!n||r.length!==n)throw new t("Invalid signature integer: wrong length");if(128&r[0])throw new t("Invalid signature integer: negative");if(0===r[0]&&!(128&r[1]))throw new t("Invalid signature integer: unnecessary leading zero");return{d:En(r),l:e.subarray(n+2)}},toSig(e){const{Err:t}=st,n="string"==typeof e?mn(e):e;pt(n);let r=n.length;if(r<2||48!=n[0])throw new t("Invalid signature tag");if(n[1]!==r-2)throw new t("Invalid signature: incorrect length");const{d:o,l:s}=st._parseInt(n.subarray(2)),{d:i,l:a}=st._parseInt(s);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(e){const t=e=>8&Number.parseInt(e[0],16)?"00"+e:e,n=e=>{const t=e.toString(16);return 1&t.length?`0${t}`:t},r=t(n(e.s)),o=t(n(e.r)),s=r.length/2,i=o.length/2,a=n(s),c=n(i);return`30${n(i+s+4)}02${c}${o}02${a}${r}`}},D=BigInt(0),K=BigInt(1);BigInt(2);const ce=BigInt(3);function xn(e){const t=bn(e),{Fp:n}=t,r=t.toBytes||((e,t,r)=>{const o=t.toAffine();return ct(Uint8Array.from([4]),n.toBytes(o.x),n.toBytes(o.y))}),o=t.fromBytes||(e=>{const t=e.subarray(1);return{x:n.fromBytes(t.subarray(0,n.BYTES)),y:n.fromBytes(t.subarray(n.BYTES,2*n.BYTES))}});function s(e){const{a:r,b:o}=t,s=n.sqr(e),i=n.mul(s,e);return n.add(n.add(i,n.mul(e,r)),o)}if(!n.eql(n.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function i(e){return"bigint"==typeof e&&D<e&&e<t.n}function a(e){if(!i(e))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(e){const{allowedPrivateKeyLengths:n,nByteLength:r,wrapPrivateKey:o,n:s}=t;if(n&&"bigint"!=typeof e){if(it(e)&&(e=lt(e)),"string"!=typeof e||!n.includes(e.length))throw new Error("Invalid key");e=e.padStart(2*r,"0")}let i;try{i="bigint"==typeof e?e:V(C("private key",e,r))}catch{throw new Error(`private key must be ${r} bytes, hex or bigint, not ${typeof e}`)}return o&&(i=T(i,s)),a(i),i}const l=new Map;function d(e){if(!(e instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(e,t,r){if(this.px=e,this.py=t,this.pz=r,null==e||!n.isValid(e))throw new Error("x required");if(null==t||!n.isValid(t))throw new Error("y required");if(null==r||!n.isValid(r))throw new Error("z required")}static fromAffine(e){const{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw new Error("invalid affine point");if(e instanceof u)throw new Error("projective point not allowed");const o=e=>n.eql(e,n.ZERO);return o(t)&&o(r)?u.ZERO:new u(t,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=n.invertBatch(e.map((e=>e.pz)));return e.map(((e,n)=>e.toAffine(t[n]))).map(u.fromAffine)}static fromHex(e){const t=u.fromAffine(o(C("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return u.BASE.multiply(c(e))}_setWindowSize(e){this._WINDOW_SIZE=e,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:e,y:r}=this.toAffine();if(!n.isValid(e)||!n.isValid(r))throw new Error("bad point: x or y not FE");const o=n.sqr(r),i=s(e);if(!n.eql(o,i))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:e}=this.toAffine();if(n.isOdd)return!n.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){d(e);const{px:t,py:r,pz:o}=this,{px:s,py:i,pz:a}=e,c=n.eql(n.mul(t,a),n.mul(s,o)),l=n.eql(n.mul(r,a),n.mul(i,o));return c&&l}negate(){return new u(this.px,n.neg(this.py),this.pz)}double(){const{a:e,b:r}=t,o=n.mul(r,ce),{px:s,py:i,pz:a}=this;let c=n.ZERO,l=n.ZERO,d=n.ZERO,h=n.mul(s,s),f=n.mul(i,i),p=n.mul(a,a),g=n.mul(s,i);return g=n.add(g,g),d=n.mul(s,a),d=n.add(d,d),c=n.mul(e,d),l=n.mul(o,p),l=n.add(c,l),c=n.sub(f,l),l=n.add(f,l),l=n.mul(c,l),c=n.mul(g,c),d=n.mul(o,d),p=n.mul(e,p),g=n.sub(h,p),g=n.mul(e,g),g=n.add(g,d),d=n.add(h,h),h=n.add(d,h),h=n.add(h,p),h=n.mul(h,g),l=n.add(l,h),p=n.mul(i,a),p=n.add(p,p),h=n.mul(p,g),c=n.sub(c,h),d=n.mul(p,f),d=n.add(d,d),d=n.add(d,d),new u(c,l,d)}add(e){d(e);const{px:r,py:o,pz:s}=this,{px:i,py:a,pz:c}=e;let l=n.ZERO,h=n.ZERO,f=n.ZERO;const p=t.a,g=n.mul(t.b,ce);let m=n.mul(r,i),b=n.mul(o,a),y=n.mul(s,c),w=n.add(r,o),v=n.add(i,a);w=n.mul(w,v),v=n.add(m,b),w=n.sub(w,v),v=n.add(r,s);let k=n.add(i,c);return v=n.mul(v,k),k=n.add(m,y),v=n.sub(v,k),k=n.add(o,s),l=n.add(a,c),k=n.mul(k,l),l=n.add(b,y),k=n.sub(k,l),f=n.mul(p,v),l=n.mul(g,y),f=n.add(l,f),l=n.sub(b,f),f=n.add(b,f),h=n.mul(l,f),b=n.add(m,m),b=n.add(b,m),y=n.mul(p,y),v=n.mul(g,v),b=n.add(b,y),y=n.sub(m,y),y=n.mul(p,y),v=n.add(v,y),m=n.mul(b,v),h=n.add(h,m),m=n.mul(k,v),l=n.mul(w,l),l=n.sub(l,m),m=n.mul(w,b),f=n.mul(k,f),f=n.add(f,m),new u(l,h,f)}subtract(e){return this.add(e.negate())}is0(){return this.equals(u.ZERO)}wNAF(e){return f.wNAFCached(this,l,e,(e=>{const t=n.invertBatch(e.map((e=>e.pz)));return e.map(((e,n)=>e.toAffine(t[n]))).map(u.fromAffine)}))}multiplyUnsafe(e){const r=u.ZERO;if(e===D)return r;if(a(e),e===K)return this;const{endo:o}=t;if(!o)return f.unsafeLadder(this,e);let{k1neg:s,k1:i,k2neg:c,k2:l}=o.splitScalar(e),d=r,h=r,p=this;for(;i>D||l>D;)i&K&&(d=d.add(p)),l&K&&(h=h.add(p)),p=p.double(),i>>=K,l>>=K;return s&&(d=d.negate()),c&&(h=h.negate()),h=new u(n.mul(h.px,o.beta),h.py,h.pz),d.add(h)}multiply(e){a(e);let r,o,s=e;const{endo:i}=t;if(i){const{k1neg:e,k1:t,k2neg:a,k2:c}=i.splitScalar(s);let{p:l,f:d}=this.wNAF(t),{p:h,f:p}=this.wNAF(c);l=f.constTimeNegate(e,l),h=f.constTimeNegate(a,h),h=new u(n.mul(h.px,i.beta),h.py,h.pz),r=l.add(h),o=d.add(p)}else{const{p:e,f:t}=this.wNAF(s);r=e,o=t}return u.normalizeZ([r,o])[0]}multiplyAndAddUnsafe(e,t,n){const r=u.BASE,o=(e,t)=>t!==D&&t!==K&&e.equals(r)?e.multiply(t):e.multiplyUnsafe(t),s=o(this,t).add(o(e,n));return s.is0()?void 0:s}toAffine(e){const{px:t,py:r,pz:o}=this,s=this.is0();null==e&&(e=s?n.ONE:n.inv(o));const i=n.mul(t,e),a=n.mul(r,e),c=n.mul(o,e);if(s)return{x:n.ZERO,y:n.ZERO};if(!n.eql(c,n.ONE))throw new Error("invZ was invalid");return{x:i,y:a}}isTorsionFree(){const{h:e,isTorsionFree:n}=t;if(e===K)return!0;if(n)return n(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:n}=t;return e===K?this:n?n(u,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return this.assertValidity(),r(u,this,e)}toHex(e=!0){return lt(this.toRawBytes(e))}}u.BASE=new u(t.Gx,t.Gy,n.ONE),u.ZERO=new u(n.ZERO,n.ONE,n.ZERO);const h=t.nBitLength,f=pn(u,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:u,normPrivateKeyToScalar:c,weierstrassEquation:s,isWithinCurveOrder:i}}function Bn(e){const t=Be(e);return bt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function An(e){const t=Bn(e),{Fp:n,n:r}=t,o=n.BYTES+1,s=2*n.BYTES+1;function i(e){return T(e,r)}function a(e){return Rt(e,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:d,isWithinCurveOrder:u}=xn({...t,toBytes(e,t,r){const o=t.toAffine(),s=n.toBytes(o.x),i=ct;return r?i(Uint8Array.from([t.hasEvenY()?2:3]),s):i(Uint8Array.from([4]),s,n.toBytes(o.y))},fromBytes(e){const t=e.length,r=e[0],i=e.subarray(1);if(t!==o||2!==r&&3!==r){if(t===s&&4===r){return{x:n.fromBytes(i.subarray(0,n.BYTES)),y:n.fromBytes(i.subarray(n.BYTES,2*n.BYTES))}}throw new Error(`Point of length ${t} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}{const e=V(i);if(!function(e){return D<e&&e<n.ORDER}(e))throw new Error("Point is not on curve");const t=d(e);let o;try{o=n.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return!(1&~r)!==((o&K)===K)&&(o=n.neg(o)),{x:e,y:o}}}}),h=e=>lt(nt(e,t.nByteLength));function f(e){return e>r>>K}const p=(e,t,n)=>V(e.slice(t,n));class g{constructor(e,t,n){this.r=e,this.s=t,this.recovery=n,this.assertValidity()}static fromCompact(e){const n=t.nByteLength;return e=C("compactSignature",e,2*n),new g(p(e,0,n),p(e,n,2*n))}static fromDER(e){const{r:t,s:n}=st.toSig(C("DER",e));return new g(t,n)}assertValidity(){if(!u(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!u(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(e){return new g(this.r,this.s,e)}recoverPublicKey(e){const{r:r,s:o,recovery:s}=this,l=w(C("msgHash",e));if(null==s||![0,1,2,3].includes(s))throw new Error("recovery id invalid");const d=2===s||3===s?r+t.n:r;if(d>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const u=1&s?"03":"02",f=c.fromHex(u+h(d)),p=a(d),g=i(-l*p),m=i(o*p),b=c.BASE.multiplyAndAddUnsafe(f,g,m);if(!b)throw new Error("point at infinify");return b.assertValidity(),b}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return dt(this.toDERHex())}toDERHex(){return st.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return dt(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}const m={isValidPrivateKey(e){try{return l(e),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=xe(t.n);return wn(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function b(e){const t=it(e),n="string"==typeof e,r=(t||n)&&e.length;return t?r===o||r===s:n?r===2*o||r===2*s:e instanceof c}const y=t.bits2int||function(e){const n=V(e),r=8*e.length-t.nBitLength;return r>0?n>>BigInt(r):n},w=t.bits2int_modN||function(e){return i(y(e))},v=Yt(t.nBitLength);function k(e){if("bigint"!=typeof e)throw new Error("bigint expected");if(!(D<=e&&e<v))throw new Error(`bigint expected < 2^${t.nBitLength}`);return nt(e,t.nByteLength)}function E(e,r,o=x){if(["recovered","canonical"].some((e=>e in o)))throw new Error("sign() legacy options not supported");const{hash:s,randomBytes:d}=t;let{lowS:h,prehash:p,extraEntropy:m}=o;null==h&&(h=!0),e=C("msgHash",e),p&&(e=C("prehashed msgHash",s(e)));const b=w(e),v=l(r),E=[k(v),k(b)];if(null!=m&&!1!==m){const e=!0===m?d(n.BYTES):m;E.push(C("extraEntropy",e))}const $=ct(...E),B=b;return{seed:$,k2sig:function(e){const t=y(e);if(!u(t))return;const n=a(t),r=c.BASE.multiply(t).toAffine(),o=i(r.x);if(o===D)return;const s=i(n*i(B+o*v));if(s===D)return;let l=(r.x===o?0:2)|Number(r.y&K),d=s;return h&&f(s)&&(d=function(e){return f(e)?i(-e):e}(s),l^=1),new g(o,d,l)}}}const x={lowS:t.lowS,prehash:!1},$={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,n=!0){if(b(e))throw new Error("first arg must be private key");if(!b(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(l(e)).toRawBytes(n)},sign:function(e,n,r=x){const{seed:o,k2sig:s}=E(e,n,r),i=t;return be(i.hash.outputLen,i.nByteLength,i.hmac)(o,s)},verify:function(e,n,r,o=$){var s;const l=e;if(n=C("msgHash",n),r=C("publicKey",r),"strict"in o)throw new Error("options.strict was renamed to lowS");const{lowS:d,prehash:u}=o;let h,f;try{if("string"==typeof l||it(l))try{h=g.fromDER(l)}catch(e){if(!(e instanceof st.Err))throw e;h=g.fromCompact(l)}else{if("object"!=typeof l||"bigint"!=typeof l.r||"bigint"!=typeof l.s)throw new Error("PARSE");{const{r:e,s:t}=l;h=new g(e,t)}}f=c.fromHex(r)}catch(e){if("PARSE"===e.message)throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(d&&h.hasHighS())return!1;u&&(n=t.hash(n));const{r:p,s:m}=h,b=w(n),y=a(m),v=i(b*y),k=i(p*y),E=null==(s=c.BASE.multiplyAndAddUnsafe(f,v,k))?void 0:s.toAffine();return!!E&&i(E.x)===p},ProjectivePoint:c,Signature:g,utils:m}}BigInt(4);class Ae extends ge{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ke(e);const n=Kt(t);if(this.iHash=e.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,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<o.length;e++)o[e]^=54;this.iHash.update(o),this.oHash=e.create();for(let e=0;e<o.length;e++)o[e]^=106;this.oHash.update(o),o.fill(0)}update(e){return mt(this),this.iHash.update(e),this}digestInto(e){mt(this),yt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:o,blockLen:s,outputLen:i}=this;return e.finished=r,e.destroyed=o,e.blockLen=s,e.outputLen=i,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ve=(e,t,n)=>new Ae(e,t).update(n).digest();
|
|
19
19
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
20
20
|
function vn(e){return{hash:e,hmac:(t,...n)=>ve(e,t,je(...n)),randomBytes:we}}function In(e,t){const n=t=>An({...e,...vn(t)});return Object.freeze({...n(t),create:n})}
|
|
21
|
-
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ve.create=(e,t)=>new Ae(e,t);const Nt=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),At=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ie=BigInt(1),vt=BigInt(2),fe=(e,t)=>(e+t/vt)/t;function Se(e){const t=Nt,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,d=l*l*e%t,u=z(d,n,t)*d%t,h=z(u,n,t)*d%t,f=z(h,vt,t)*l%t,p=z(f,o,t)*f%t,g=z(p,s,t)*p%t,m=z(g,a,t)*g%t,b=z(m,c,t)*m%t,y=z(b,a,t)*g%t,w=z(y,n,t)*d%t,v=z(w,i,t)*p%t,k=z(v,r,t)*l%t,E=z(k,vt,t);if(!Vt.eql(Vt.sqr(E),e))throw new Error("Cannot find square root");return E}const Vt=gn(Nt,void 0,void 0,{sqrt:Se}),Dt=In({a:BigInt(0),b:BigInt(7),Fp:Vt,n:At,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=At,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Ie*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,i=BigInt("0x100000000000000000000000000000000"),a=fe(s*e,t),c=fe(-r*e,t);let l=T(e-a*n-c*o,t),d=T(-a*r-c*s,t);const u=l>i,h=d>i;if(u&&(l=t-l),h&&(d=t-d),l>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:l,k2neg:h,k2:d}}}},Bt),_t=BigInt(0),$e=e=>"bigint"==typeof e&&_t<e&&e<Nt,Sn=e=>"bigint"==typeof e&&_t<e&&e<At,ae={};function It(e,...t){let n=ae[e];if(void 0===n){const t=Bt(Uint8Array.from(e,(e=>e.charCodeAt(0))));n=ct(t,t),ae[e]=n}return Bt(ct(n,...t))}const Ft=e=>e.toRawBytes(!0).slice(1),Pt=e=>nt(e,32),Tt=e=>T(e,Nt),wt=e=>T(e,At),Xt=Dt.ProjectivePoint,$n=(e,t,n)=>Xt.BASE.multiplyAndAddUnsafe(e,t,n);function jt(e){let t=Dt.utils.normPrivateKeyToScalar(e),n=Xt.fromPrivateKey(t);return{scalar:n.hasEvenY()?t:wt(-t),bytes:Ft(n)}}function Ne(e){if(!$e(e))throw new Error("bad x: need 0 < x < p");const t=Tt(e*e);let n=Se(Tt(t*e+BigInt(7)));n%vt!==_t&&(n=Tt(-n));const r=new Xt(e,n,Ie);return r.assertValidity(),r}function _e(...e){return wt(V(It("BIP0340/challenge",...e)))}function Nn(e){return jt(e).bytes}function _n(e,t,n=we(32)){const r=C("message",e),{bytes:o,scalar:s}=jt(t),i=C("auxRand",n,32),a=Pt(s^V(It("BIP0340/aux",i))),c=It("BIP0340/nonce",a,o,r),l=wt(V(c));if(l===_t)throw new Error("sign failed: k is zero");const{bytes:d,scalar:u}=jt(l),h=_e(d,o,r),f=new Uint8Array(64);if(f.set(d,0),f.set(Pt(wt(u+h*s)),32),!Le(f,r,o))throw new Error("sign: Invalid signature produced");return f}function Le(e,t,n){const r=C("signature",e,64),o=C("message",t),s=C("publicKey",n,32);try{const e=Ne(V(s)),t=V(r.subarray(0,32));if(!$e(t))return!1;const n=V(r.subarray(32,64));if(!Sn(n))return!1;const i=_e(Pt(t),Ft(e),o),a=$n(e,n,wt(-i));return!(!a||!a.hasEvenY()||a.toAffine().x!==t)}catch{return!1}}const Ct={getPublicKey:Nn,sign:_n,verify:Le,utils:{randomPrivateKey:Dt.utils.randomPrivateKey,lift_x:Ne,pointToBytes:Ft,numberToBytesBE:nt,bytesToNumberBE:V,taggedHash:It,mod:T}},Cn=new TextEncoder;function kn(e){return xt(Bt(Cn.encode(e)))}const Qt={sign:(e,t)=>xt(Ct.sign(e,t)),verify:Ct.verify,getPublicKey:e=>xt(Ct.getPublicKey(e))};function He(e){return kn(JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]))}function Pn(e){try{return Qt.verify(e.sig,He(e),e.pubkey)}catch(e){return console.warn("The following error occurred during verify():",e),!1}}const Ue=async e=>Pn(e);var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},extendStatics(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function __awaiter(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))}function __generator(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function __values(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,s=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)i.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(o)throw o.error}}return i}function __spreadArray(e,t,n){if(n||2===arguments.length)for(var r,o=0,s=t.length;o<s;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}function __await(e){return this instanceof __await?(this.v=e,this):new __await(e)}function __asyncGenerator(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,o=n.apply(e,t||[]),s=[];return r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r;function i(e){o[e]&&(r[e]=function(t){return new Promise((function(n,r){s.push([e,t,n,r])>1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof __await?Promise.resolve(n.value.v).then(c,l):d(s[0][2],n)}catch(e){d(s[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function d(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function __asyncValues(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,o){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,o,(t=e[n](t)).done,t.value)}))}}}function isFunction(e){return"function"==typeof e}function createErrorClass(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}"function"==typeof SuppressedError&&SuppressedError;var UnsubscriptionError=createErrorClass((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function arrRemove(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var Subscription=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,r,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var i=__values(s),a=i.next();!a.done;a=i.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(isFunction(c))try{c()}catch(e){o=e instanceof UnsubscriptionError?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var d=__values(l),u=d.next();!u.done;u=d.next()){var h=u.value;try{execFinalizer(h)}catch(e){o=null!=o?o:[],e instanceof UnsubscriptionError?o=__spreadArray(__spreadArray([],__read(o)),__read(e.errors)):o.push(e)}}}catch(e){n={error:e}}finally{try{u&&!u.done&&(r=d.return)&&r.call(d)}finally{if(n)throw n.error}}}if(o)throw new UnsubscriptionError(o)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)execFinalizer(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&arrRemove(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&arrRemove(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function isSubscription(e){return e instanceof Subscription||e&&"closed"in e&&isFunction(e.remove)&&isFunction(e.add)&&isFunction(e.unsubscribe)}function execFinalizer(e){isFunction(e)?e():e.unsubscribe()}Subscription.EMPTY;var config={Promise:void 0},timeoutProvider={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,__spreadArray([e,t],__read(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function reportUnhandledError(e){timeoutProvider.setTimeout((function(){throw e}))}function noop(){}function errorContext(e){e()}var Subscriber=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,isSubscription(t)&&t.add(n)):n.destination=EMPTY_OBSERVER,n}return __extends(t,e),t.create=function(e,t,n){return new SafeSubscriber(e,t,n)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(Subscription),ConsumerObserver=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){handleUnhandledError(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){handleUnhandledError(e)}else handleUnhandledError(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){handleUnhandledError(e)}},e}(),SafeSubscriber=function(e){function t(t,n,r){var o,s=e.call(this)||this;return o=isFunction(t)||!t?{next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:t,s.destination=new ConsumerObserver(o),s}return __extends(t,e),t}(Subscriber);function handleUnhandledError(e){reportUnhandledError(e)}function defaultErrorHandler(e){throw e}var EMPTY_OBSERVER={closed:!0,next:noop,error:defaultErrorHandler,complete:noop},observable="function"==typeof Symbol&&Symbol.observable||"@@observable";function identity(e){return e}function pipeFromArray(e){return 0===e.length?identity:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var Observable=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r=this,o=isSubscriber(e)?e:new SafeSubscriber(e,t,n);return errorContext((function(){var e=r,t=e.operator,n=e.source;o.add(t?t.call(o,n):n?r._subscribe(o):r._trySubscribe(o))})),o},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=getPromiseCtor(t))((function(t,r){var o=new SafeSubscriber({next:function(t){try{e(t)}catch(e){r(e),o.unsubscribe()}},error:r,complete:t});n.subscribe(o)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[observable]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pipeFromArray(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=getPromiseCtor(e))((function(e,n){var r;t.subscribe((function(e){return r=e}),(function(e){return n(e)}),(function(){return e(r)}))}))},e.create=function(t){return new e(t)},e}();function getPromiseCtor(e){var t;return null!==(t=null!=e?e:config.Promise)&&void 0!==t?t:Promise}function isObserver(e){return e&&isFunction(e.next)&&isFunction(e.error)&&isFunction(e.complete)}function isSubscriber(e){return e&&e instanceof Subscriber||isObserver(e)&&isSubscription(e)}function hasLift(e){return isFunction(null==e?void 0:e.lift)}function operate(e){return function(t){if(hasLift(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}function createOperatorSubscriber(e,t,n,r,o){return new OperatorSubscriber(e,t,n,r,o)}var OperatorSubscriber=function(e){function t(t,n,r,o,s,i){var a=e.call(this,t)||this;return a.onFinalize=s,a.shouldUnsubscribe=i,a._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=o?function(e){try{o(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return __extends(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(Subscriber),dateTimestampProvider={now:function(){return Date.now()}},Action=function(e){function t(t,n){return e.call(this)||this}return __extends(t,e),t.prototype.schedule=function(e,t){return this},t}(Subscription),intervalProvider={setInterval:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,__spreadArray([e,t],__read(n)))},clearInterval:function(e){return clearInterval(e)},delegate:void 0},AsyncAction=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.scheduler=t,r.work=n,r.pending=!1,r}return __extends(t,e),t.prototype.schedule=function(e,t){var n;if(void 0===t&&(t=0),this.closed)return this;this.state=e;var r=this.id,o=this.scheduler;return null!=r&&(this.id=this.recycleAsyncId(o,r,t)),this.pending=!0,this.delay=t,this.id=null!==(n=this.id)&&void 0!==n?n:this.requestAsyncId(o,this.id,t),this},t.prototype.requestAsyncId=function(e,t,n){return void 0===n&&(n=0),intervalProvider.setInterval(e.flush.bind(e,this),n)},t.prototype.recycleAsyncId=function(e,t,n){if(void 0===n&&(n=0),null!=n&&this.delay===n&&!1===this.pending)return t;null!=t&&intervalProvider.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(e,t);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var n,r=!1;try{this.work(e)}catch(e){r=!0,n=e||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),n},t.prototype.unsubscribe=function(){if(!this.closed){var t=this.id,n=this.scheduler,r=n.actions;this.work=this.state=this.scheduler=null,this.pending=!1,arrRemove(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(Action),Scheduler=function(){function e(t,n){void 0===n&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},e.now=dateTimestampProvider.now,e}(),AsyncScheduler=function(e){function t(t,n){void 0===n&&(n=Scheduler.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r}return __extends(t,e),t.prototype.flush=function(e){var t=this.actions;if(this._active)t.push(e);else{var n;this._active=!0;do{if(n=e.execute(e.state,e.delay))break}while(e=t.shift());if(this._active=!1,n){for(;e=t.shift();)e.unsubscribe();throw n}}},t}(Scheduler),asyncScheduler=new AsyncScheduler(AsyncAction),async=asyncScheduler,EMPTY=new Observable((function(e){return e.complete()}));function isScheduler(e){return e&&isFunction(e.schedule)}var isArrayLike=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function isPromise(e){return isFunction(null==e?void 0:e.then)}function isInteropObservable(e){return isFunction(e[observable])}function isAsyncIterable(e){return Symbol.asyncIterator&&isFunction(null==e?void 0:e[Symbol.asyncIterator])}function createInvalidObservableTypeError(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function getSymbolIterator(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var iterator=getSymbolIterator();function isIterable(e){return isFunction(null==e?void 0:e[iterator])}function readableStreamLikeToAsyncGenerator(e){return __asyncGenerator(this,arguments,(function(){var t,n,r;return __generator(this,(function(o){switch(o.label){case 0:t=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,__await(t.read())];case 3:return n=o.sent(),r=n.value,n.done?[4,__await(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,__await(r)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}function isReadableStreamLike(e){return isFunction(null==e?void 0:e.getReader)}function innerFrom(e){if(e instanceof Observable)return e;if(null!=e){if(isInteropObservable(e))return fromInteropObservable(e);if(isArrayLike(e))return fromArrayLike(e);if(isPromise(e))return fromPromise(e);if(isAsyncIterable(e))return fromAsyncIterable(e);if(isIterable(e))return fromIterable(e);if(isReadableStreamLike(e))return fromReadableStreamLike(e)}throw createInvalidObservableTypeError(e)}function fromInteropObservable(e){return new Observable((function(t){var n=e[observable]();if(isFunction(n.subscribe))return n.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")}))}function fromArrayLike(e){return new Observable((function(t){for(var n=0;n<e.length&&!t.closed;n++)t.next(e[n]);t.complete()}))}function fromPromise(e){return new Observable((function(t){e.then((function(e){t.closed||(t.next(e),t.complete())}),(function(e){return t.error(e)})).then(null,reportUnhandledError)}))}function fromIterable(e){return new Observable((function(t){var n,r;try{for(var o=__values(e),s=o.next();!s.done;s=o.next()){var i=s.value;if(t.next(i),t.closed)return}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}t.complete()}))}function fromAsyncIterable(e){return new Observable((function(t){process(e,t).catch((function(e){return t.error(e)}))}))}function fromReadableStreamLike(e){return fromAsyncIterable(readableStreamLikeToAsyncGenerator(e))}function process(e,t){var n,r,o,s;return __awaiter(this,void 0,void 0,(function(){var i,a;return __generator(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=__asyncValues(e),c.label=1;case 1:return[4,n.next()];case 2:if((r=c.sent()).done)return[3,4];if(i=r.value,t.next(i),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),o={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))}function executeSchedule(e,t,n,r,o){void 0===r&&(r=0),void 0===o&&(o=!1);var s=t.schedule((function(){n(),o?e.add(this.schedule(null,r)):this.unsubscribe()}),r);if(e.add(s),!o)return s}function isValidDate(e){return e instanceof Date&&!isNaN(e)}function map(e,t){return operate((function(n,r){var o=0;n.subscribe(createOperatorSubscriber(r,(function(n){r.next(e.call(t,n,o++))})))}))}function mergeInternals(e,t,n,r,o,s,i,a){var c=[],l=0,d=0,u=!1,h=function(){!u||c.length||l||t.complete()},f=function(e){l++;var o=!1;innerFrom(n(e,d++)).subscribe(createOperatorSubscriber(t,(function(e){t.next(e)}),(function(){o=!0}),void 0,(function(){if(o)try{l--;for(;c.length&&l<r;)e=void 0,e=c.shift(),i||f(e);h()}catch(e){t.error(e)}var e})))};return e.subscribe(createOperatorSubscriber(t,(function(e){return l<r?f(e):c.push(e)}),(function(){u=!0,h()}))),function(){}}function mergeMap(e,t,n){return void 0===n&&(n=1/0),isFunction(t)?mergeMap((function(n,r){return map((function(e,o){return t(n,e,r,o)}))(innerFrom(e(n,r)))}),n):("number"==typeof t&&(n=t),operate((function(t,r){return mergeInternals(t,r,e,n)})))}function timer(e,t,n){void 0===n&&(n=async);var r=-1;return null!=t&&(isScheduler(t)?n=t:r=t),new Observable((function(t){var o=isValidDate(e)?+e-n.now():e;o<0&&(o=0);var s=0;return n.schedule((function(){t.closed||(t.next(s++),0<=r?this.schedule(void 0,r):t.complete())}),o)}))}function filter(e,t){return operate((function(n,r){var o=0;n.subscribe(createOperatorSubscriber(r,(function(n){return e.call(t,n,o++)&&r.next(n)})))}))}function take(e){return e<=0?function(){return EMPTY}:operate((function(t,n){var r=0;t.subscribe(createOperatorSubscriber(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function mapTo(e){return map((function(){return e}))}function delayWhen(e,t){return mergeMap((function(t,n){return innerFrom(e(t,n)).pipe(take(1),mapTo(t))}))}function delay(e,t){void 0===t&&(t=asyncScheduler);var n=timer(e,t);return delayWhen((function(){return n}))}const CALL_TIMEOUT=5e3,AUTH_URL_CALL_TIMEOUT=12e4,DEFAULT_NIP46_RELAYS=["wss://relay.nsec.app/","wss://ephemeral.snowflare.cc/"],NIP46_REQUEST_TIMEOUT=3e4;class Nip46Error extends Error{code;constructor(e,t){super(e),this.name="Nip46Error",this.code=t}get retryable(){return"TIMEOUT"===this.code||"RELAY_DISCONNECTED"===this.code}}class RelayPool{rxNostr;_relayUrls=[];_owned;_connStateSub;constructor(e){e?(this.rxNostr=e,this._owned=!1):(this.rxNostr=Wr({verifier:Ue,connectionStrategy:"lazy-keep",retry:{strategy:"exponential",maxCount:5,initialDelay:1e3},eoseTimeout:1e4,okTimeout:1e4,skipFetchNip11:!0}),this._owned=!0),this._connStateSub=this.rxNostr.createConnectionStateObservable().pipe(filter((e=>"error"===e.state)),delay(3e4)).subscribe((e=>{console.log("RelayPool: auto-reconnecting error relay:",e.from);try{this.rxNostr.reconnect(e.from)}catch(t){console.warn("RelayPool: auto-reconnect failed",e.from,t)}}))}addRelay(e){this._relayUrls.includes(e)||(this._relayUrls.push(e),this._syncRelays())}removeRelay(e){this._relayUrls=this._relayUrls.filter((t=>t!==e)),this._syncRelays()}removeAllRelays(){this._relayUrls=[],this.rxNostr.setDefaultRelays([])}_syncRelays(){this.rxNostr.setDefaultRelays(this._relayUrls)}async connect(e=1e4){if(this._syncRelays(),!this.isAnyConnected())return new Promise((t=>{const n=setTimeout((()=>{r.unsubscribe(),t()}),e),r=this.rxNostr.createConnectionStateObservable().subscribe((e=>{"connected"===e.state&&(clearTimeout(n),r.unsubscribe(),t())}))}))}disconnectAll(){this.rxNostr.setDefaultRelays([])}dispose(){this._connStateSub?.unsubscribe(),this._owned&&this.rxNostr.dispose()}isAnyConnected(){const e=this.rxNostr.getAllRelayStatus();return Object.values(e).some((e=>"connected"===e.connection))}get relayUrls(){return[...this._relayUrls]}async publish(e){await this.rxNostr.cast(e)}async publishToRelays(e,t){await this.rxNostr.cast(e,{on:{relays:t}})}subscribe(e,t){const n=Kr(),r=this.rxNostr.use(n).subscribe({next:e=>{t(e.event)}});return n.emit(e),()=>{r.unsubscribe()}}subscribeOnce(e,t,n){const r=zr(),o=n?{on:{relays:n}}:void 0,s=this.rxNostr.use(r,o).subscribe({next:e=>{t(e.event)}});return r.emit(e),r.over(),()=>{s.unsubscribe()}}reconnect(e){this.rxNostr.reconnect(e)}waitForConnection(e){return this.isAnyConnected()?Promise.resolve():new Promise(((t,n)=>{const r=setTimeout((()=>{o.unsubscribe(),n(new Nip46Error("Failed to connect to any relay","RELAY_DISCONNECTED"))}),e),o=this.rxNostr.createConnectionStateObservable().subscribe((e=>{"connected"===e.state&&(clearTimeout(r),o.unsubscribe(),t())}))}))}}class NostrRpc extends lib.EventEmitter{pool;_signer;requests=new Set;unsub;lastSubscribeFilter;requestTimers=new Map;_useNip44=!1;constructor(e,t){super(),this.pool=e,this._signer=t}subscribe(e){e.kinds=e.kinds?.filter((e=>24133===e)),this.lastSubscribeFilter={...e},this.unsub=this.pool.subscribe(e,(async e=>{try{const t=await this.parseEvent(e);t.method?this.emit("request",t):this.emit("response-"+t.id,t)}catch(e){console.error("error parsing event in subscription",e)}}))}ensureSubscription(){if(this.unsub)return;const e=this._signer.pubkey;console.log("ensureSubscription: subscribing for",e),this.subscribe({kinds:[24133],"#p":[e]})}stop(){this.unsub&&(this.unsub(),this.unsub=void 0)}resubscribe(){this.lastSubscribeFilter?(console.log("resubscribe: re-subscribing with filter",this.lastSubscribeFilter),this.stop(),this.subscribe(this.lastSubscribeFilter)):console.warn("resubscribe: no previous filter to resubscribe with")}isSubscriptionActive(){return!this.lastSubscribeFilter||!!this.unsub}clearPendingRequests(){for(const[e,t]of this.requestTimers.entries())clearTimeout(t),this.requestTimers.delete(e);this.requests.clear(),console.log("clearPendingRequests: all pending requests cleared")}setUseNip44(e){this._useNip44=e}isNip04(e){const t=e.length;return!(t<28)&&("?"===e[t-28]&&"i"===e[t-27]&&"v"===e[t-26]&&"="===e[t-25])}async parseEvent(e){const t=e.pubkey,n=this.isNip04(e.content)?this._signer.decrypt:this._signer.decryptNip44,r=await n.call(this._signer,{pubkey:t},e.content),o=JSON.parse(r),{id:s,method:i,params:a,result:c,error:l}=o;return i?{id:s,pubkey:e.pubkey,method:i,params:a,event:e}:{id:s,result:c,error:l,event:e}}async parseNostrConnectReply(e,t){const n=e,r=await this.parseEvent(n);if(console.log("nostr connect parsedEvent",r),r.method)throw new Error("Bad nostr connect reply");{const e=r;if(e.result!==t)throw new Error(e.error||"Invalid secret in reply");return n.pubkey}}async listen(e){const t=this._signer.pubkey;return console.log("nostr-login listening for conn to",t,"expecting secret:",e),new Promise(((n,r)=>{const o=setTimeout((()=>{r(new Error("Connection timeout: no response from signer"))}),6e4),s={kinds:[24133],"#p":[t]};this.stop(),this.lastSubscribeFilter=s,this.unsub=this.pool.subscribe(s,(async t=>{try{const s=await this.parseEvent(t);if(s.method?this.emit("request",s):this.emit("response-"+s.id,s),!s.method){const i=s;if("auth_url"===i.result)return void console.log("Ignoring auth_url response in listen");i.result===e?(clearTimeout(o),console.log("Connection established with signer:",t.pubkey),n(t.pubkey)):"ack"===i.result?(console.warn('Received "ack" instead of secret.'),clearTimeout(o),n(t.pubkey)):(console.error("Invalid response:",i),clearTimeout(o),r(new Error(i.error||"Invalid connection response")))}}catch(e){console.error("Error parsing event in listen",e)}}))}))}async connect(e,t,n){return console.log("Sending connect request to",e,"with perms:",n),this.ensureSubscription(),new Promise(((r,o)=>{const s=setTimeout((()=>{o(new Error("Connect timeout: no response from signer"))}),3e4),i=[e,t||"",n||""];this.sendRequest(e,"connect",i,24133,(e=>{clearTimeout(s),"ack"===e.result?(console.log("Connect acknowledged by signer"),r()):(console.error("Connect failed:",e.error),o(new Error(e.error||"Connection rejected by signer")))}))}))}getId(){return Math.random().toString(36).substring(7)}async sendRequest(e,t,n=[],r=24133,o){const s=this.getId();this.setResponseHandler(s,o);const i=await this.createRequestEvent(s,e,t,n,r);console.log("sendRequest",{event:i,method:t,remotePubkey:e,params:n}),await this.pool.publish(i)}setResponseHandler(e,t){let n=!1,r=!1;const o=Date.now(),s=()=>{const t=this.requestTimers.get(e);t&&(clearTimeout(t),this.requestTimers.delete(e)),this.requests.delete(e)},i=()=>{const n=this.requestTimers.get(e);n&&clearTimeout(n);const i=setTimeout((()=>{console.warn("nip46 request "+e+" timed out after "+(Date.now()-o)+"ms (authUrl="+r+")"),s(),t&&t({id:e,result:"",error:"Request timeout",event:void 0})}),r?4*NIP46_REQUEST_TIMEOUT:NIP46_REQUEST_TIMEOUT);this.requestTimers.set(e,i)};return i(),new Promise((()=>{const a=c=>{"auth_url"===c.result?(this.once("response-"+e,a),n||(n=!0,r=!0,this.emit("authUrl",c.error),i())):t&&this.requests.has(e)&&(s(),console.log("nostr-login processed nip46 request in",Date.now()-o,"ms"),t(c))};this.once("response-"+e,a)}))}async createRequestEvent(e,t,n,r=[],o=24133){this.requests.add(e);const s={id:e,method:n,params:r},i=JSON.stringify(s),a=this._useNip44&&"create_account"!==n?this._signer.encryptNip44:this._signer.encrypt,c=await a.call(this._signer,{pubkey:t},i),l={kind:o,created_at:Math.floor(Date.now()/1e3),tags:[["p",t]],content:c};return finalizeEvent(l,this._signer.secretKey)}}class IframeNostrRpc extends NostrRpc{peerOrigin;iframePort;iframeRequests=new Map;pingInterval;constructor(e,t,n){super(e,t),this.peerOrigin=n}subscribe(e){this.peerOrigin||super.subscribe(e)}setWorkerIframePort(e){if(!this.peerOrigin)throw new Error("Unexpected iframe port");this.iframePort=e,this.pingInterval&&clearInterval(this.pingInterval),this.pingInterval=setInterval((()=>{console.log("iframe-nip46 ping"),this.iframePort.postMessage("ping")}),5e3),e.onmessage=async e=>{if(console.log("iframe-nip46 got response",e.data),"string"==typeof e.data&&e.data.startsWith("errorNoKey")){const t=e.data.split(":")[1],{id:n="",pubkey:r=""}=this.iframeRequests.get(t)||{};n&&r&&this.requests.has(n)&&this.emit("iframeRestart-"+r)}else try{const t=e.data;if(!validateEvent(t))throw new Error("Invalid event from iframe");if(!verifyEvent(t))throw new Error("Invalid event signature from iframe");const n=await this.parseEvent(t);n.method||(console.log("parsed response",n),this.emit("response-"+n.id,n))}catch(t){console.log("error parsing event",t,e.data)}}}async sendRequest(e,t,n=[],r=24133,o){const s=this.getId(),i=await this.createRequestEvent(s,e,t,n,r);this.setResponseHandler(s,o),this.iframePort?(this.iframeRequests.set(i.id||"",{id:s,pubkey:e}),console.log("iframe-nip46 sending request to",this.peerOrigin,i),this.iframePort.postMessage(i)):await this.pool.publish(i)}stop(){super.stop(),this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=void 0)}}class ReadyListener{origin;messages;promise;constructor(e,t){this.origin=t,this.messages=e,this.promise=new Promise((e=>{console.log(new Date,"started listener for",this.messages);const n=async r=>{const o=new URL(t).hostname,s=new URL(r.origin).hostname;(s===o||s.endsWith("."+o))&&Array.isArray(r.data)&&r.data.length&&this.messages.includes(r.data[0])&&(console.log(new Date,"got ready message from",r.origin,r.data),window.removeEventListener("message",n),e(r.data))};window.addEventListener("message",n)}))}async wait(){console.log(new Date,"waiting for",this.messages);const e=await this.promise;return console.log(new Date,"finished waiting for",this.messages,e),e}}class Nip46Signer extends lib.EventEmitter{rpc;bunkerPubkey;userPubkey="";constructor(e,t,n,r){super(),this.bunkerPubkey=n,this.rpc=new IframeNostrRpc(e,t,r),this.rpc.setUseNip44(!0),this.rpc.on("authUrl",(e=>{this.emit("authUrl",e)}))}async setSignerPubkey(e,t=!1){console.log("setSignerPubkey",e),this.bunkerPubkey=e,this.rpc.on("iframeRestart-"+e,(()=>{this.emit("iframeRestart")})),await this.initUserPubkey(t?e:"")}async initUserPubkey(e){if(this.userPubkey)console.warn("initUserPubkey already called, pubkey:",this.userPubkey);else{if(e)return this.userPubkey=e,void console.log("User pubkey set from hint:",this.userPubkey);console.log("Requesting user pubkey from signer:",this.bunkerPubkey),this.userPubkey=await new Promise(((e,t)=>{if(!this.bunkerPubkey)throw new Error("Signer pubkey not set");const n=setTimeout((()=>{t(new Error("Timeout getting user pubkey"))}),3e4);console.log("get_public_key",this.bunkerPubkey),this.rpc.sendRequest(this.bunkerPubkey,"get_public_key",[],24133,(r=>{clearTimeout(n),r.error?t(new Error(r.error)):(console.log("User pubkey received:",r.result),e(r.result))}))}))}}async listen(e){const t=await this.rpc.listen(e);await this.setSignerPubkey(t)}async connect(e,t){if(!this.bunkerPubkey)throw new Error("No signer pubkey");await this.rpc.connect(this.bunkerPubkey,e,t),await this.setSignerPubkey(this.bunkerPubkey)}async setListenReply(e,t){const n=await this.rpc.parseNostrConnectReply(e,t);await this.setSignerPubkey(n,!0)}async sign(e){return new Promise(((t,n)=>{const r=JSON.stringify(e);this.rpc.sendRequest(this.bunkerPubkey,"sign_event",[r],24133,(e=>{if(e.error)e.error.includes("timeout")||"Request timeout"===e.error?n(new Nip46Error(e.error,"TIMEOUT")):n(new Nip46Error(e.error,"SIGNER_REJECTED"));else try{const n=JSON.parse(e.result);n.sig&&n.pubkey&&n.id?t(n):n.sig?t(n.sig):t(e.result)}catch{t(e.result)}}))}))}async encrypt(e,t){return new Promise(((n,r)=>{this.rpc.sendRequest(this.bunkerPubkey,"nip04_encrypt",[e,t],24133,(e=>{e.error?r(new Nip46Error(e.error,"SIGNER_REJECTED")):n(e.result)}))}))}async decrypt(e,t){return new Promise(((n,r)=>{this.rpc.sendRequest(this.bunkerPubkey,"nip04_decrypt",[e,t],24133,(e=>{e.error?r(new Nip46Error(e.error,"SIGNER_REJECTED")):n(e.result)}))}))}async createAccount2({bunkerPubkey:e,name:t,domain:n,perms:r=""}){const o=[t,n,"",r],s=await new Promise(((t,n)=>{const r=setTimeout((()=>{n(new Error("Timeout creating account"))}),6e4);this.rpc.sendRequest(e,"create_account",o,void 0,(e=>{clearTimeout(r),t(e)}))}));if(console.log("create_account response",s),"error"===s.result||s.error)throw new Error(s.error||"Failed to create account");return s.result}}class BannerManager extends lib.EventEmitter{banner=null;iframeReady;params;constructor(e){super(),this.params=e}onAuthUrl(e,t){this.banner&&(this.banner.notify=e?{mode:t?"iframeAuthUrl":"authUrl",url:e}:{mode:""})}onIframeRestart(e){this.banner&&(this.iframeReady=new ReadyListener(["rebinderDone","rebinderError"],new URL(e).origin),this.banner.notify={mode:"rebind",url:e})}onUserInfo(e){this.banner&&(this.banner.userInfo=e)}onCallTimeout(){this.banner&&(this.banner.notify={mode:"timeout"})}onCallStart(){this.banner&&(this.banner.isLoading=!0)}async onCallEnd(){this.banner&&(this.iframeReady&&(await this.iframeReady.wait(),this.iframeReady=void 0),this.banner.isLoading=!1,this.banner.notify={mode:""})}onUpdateAccounts(e){this.banner&&(this.banner.accounts=e)}onDarkMode(e){this.banner&&(this.banner.darkMode=e)}launchAuthBanner(e){this.banner=document.createElement("nl-banner"),this.banner.setAttribute("dark-mode",String(getDarkMode(e))),e.theme&&this.banner.setAttribute("theme",e.theme),e.noBanner&&this.banner.setAttribute("hidden-mode","true"),this.banner.addEventListener("handleLoginBanner",(e=>{this.emit("launch",e.detail)})),this.banner.addEventListener("handleConfirmLogout",(()=>{this.emit("onConfirmLogout")})),this.banner.addEventListener("handleLogoutBanner",(async()=>{this.emit("logout")})),this.banner.addEventListener("handleImportModal",(e=>{this.emit("import")})),this.banner.addEventListener("handleNotifyConfirmBanner",(e=>{this.emit("onAuthUrlClick",e.detail)})),this.banner.addEventListener("handleNotifyConfirmBannerIframe",(e=>{this.emit("onIframeAuthUrlClick",e.detail)})),this.banner.addEventListener("handleSwitchAccount",(e=>{this.emit("onSwitchAccount",e.detail)})),this.banner.addEventListener("handleOpenWelcomeModal",(()=>{this.emit("launch"),this.banner&&(this.banner.isOpen=!1)})),this.banner.addEventListener("handleCancelTimeout",(()=>{this.emit("cancelTimeout")})),document.body.appendChild(this.banner)}}function setBigUint64(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const o=BigInt(32),s=BigInt(4294967295),i=Number(n>>o&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+l,a,r)}function Chi(e,t,n){return e&t^~e&n}function Maj(e,t,n){return e&t^e&n^t&n}class HashMD extends Hash{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=createView(this.buffer)}update(e){aexists(this),abytes$1(e=toBytes(e));const{view:t,buffer:n,blockLen:r}=this,o=e.length;for(let s=0;s<o;){const i=Math.min(r-this.pos,o-s);if(i!==r)n.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=createView(e);for(;r<=o-s;s+=r)this.process(t,s)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){aexists(this),aoutput(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:o}=this;let{pos:s}=this;t[s++]=128,clean(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;setBigUint64(n,r-8,BigInt(8*this.length),o),this.process(n,0);const i=createView(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)i.setUint32(4*e,l[e],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_K=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]),SHA256_W=new Uint32Array(64);class SHA256 extends HashMD{constructor(e=32){super(64,e,8,!1),this.A=0|SHA256_IV[0],this.B=0|SHA256_IV[1],this.C=0|SHA256_IV[2],this.D=0|SHA256_IV[3],this.E=0|SHA256_IV[4],this.F=0|SHA256_IV[5],this.G=0|SHA256_IV[6],this.H=0|SHA256_IV[7]}get(){const{A:e,B:t,C:n,D:r,E:o,F:s,G:i,H:a}=this;return[e,t,n,r,o,s,i,a]}set(e,t,n,r,o,s,i,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|o,this.F=0|s,this.G=0|i,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)SHA256_W[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=SHA256_W[e-15],n=SHA256_W[e-2],r=rotr(t,7)^rotr(t,18)^t>>>3,o=rotr(n,17)^rotr(n,19)^n>>>10;SHA256_W[e]=o+SHA256_W[e-7]+r+SHA256_W[e-16]|0}let{A:n,B:r,C:o,D:s,E:i,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(rotr(i,6)^rotr(i,11)^rotr(i,25))+Chi(i,a,c)+SHA256_K[e]+SHA256_W[e]|0,d=(rotr(n,2)^rotr(n,13)^rotr(n,22))+Maj(n,r,o)|0;l=c,c=a,a=i,i=s+t|0,s=o,o=r,r=n,n=t+d|0}n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,s=s+this.D|0,i=i+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,o,s,i,a,c,l)}roundClean(){clean(SHA256_W)}destroy(){this.set(0,0,0,0,0,0,0,0),clean(this.buffer)}}const sha256$1=createHasher((()=>new SHA256));class HMAC extends Hash{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ahash(e);const n=toBytes(t);if(this.iHash=e.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,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<o.length;e++)o[e]^=54;this.iHash.update(o),this.oHash=e.create();for(let e=0;e<o.length;e++)o[e]^=106;this.oHash.update(o),clean(o)}update(e){return aexists(this),this.iHash.update(e),this}digestInto(e){aexists(this),abytes$1(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:o,blockLen:s,outputLen:i}=this;return e.finished=r,e.destroyed=o,e.blockLen=s,e.outputLen=i,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(e,t,n)=>new HMAC(e,t).update(n).digest();hmac.create=(e,t)=>new HMAC(e,t)
|
|
21
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ve.create=(e,t)=>new Ae(e,t);const Nt=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),At=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ie=BigInt(1),vt=BigInt(2),fe=(e,t)=>(e+t/vt)/t;function Se(e){const t=Nt,n=BigInt(3),r=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,d=l*l*e%t,u=z(d,n,t)*d%t,h=z(u,n,t)*d%t,f=z(h,vt,t)*l%t,p=z(f,o,t)*f%t,g=z(p,s,t)*p%t,m=z(g,a,t)*g%t,b=z(m,c,t)*m%t,y=z(b,a,t)*g%t,w=z(y,n,t)*d%t,v=z(w,i,t)*p%t,k=z(v,r,t)*l%t,E=z(k,vt,t);if(!Vt.eql(Vt.sqr(E),e))throw new Error("Cannot find square root");return E}const Vt=gn(Nt,void 0,void 0,{sqrt:Se}),Dt=In({a:BigInt(0),b:BigInt(7),Fp:Vt,n:At,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=At,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Ie*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,i=BigInt("0x100000000000000000000000000000000"),a=fe(s*e,t),c=fe(-r*e,t);let l=T(e-a*n-c*o,t),d=T(-a*r-c*s,t);const u=l>i,h=d>i;if(u&&(l=t-l),h&&(d=t-d),l>i||d>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:u,k1:l,k2neg:h,k2:d}}}},Bt),_t=BigInt(0),$e=e=>"bigint"==typeof e&&_t<e&&e<Nt,Sn=e=>"bigint"==typeof e&&_t<e&&e<At,ae={};function It(e,...t){let n=ae[e];if(void 0===n){const t=Bt(Uint8Array.from(e,(e=>e.charCodeAt(0))));n=ct(t,t),ae[e]=n}return Bt(ct(n,...t))}const Ft=e=>e.toRawBytes(!0).slice(1),Pt=e=>nt(e,32),Tt=e=>T(e,Nt),wt=e=>T(e,At),Xt=Dt.ProjectivePoint,$n=(e,t,n)=>Xt.BASE.multiplyAndAddUnsafe(e,t,n);function jt(e){let t=Dt.utils.normPrivateKeyToScalar(e),n=Xt.fromPrivateKey(t);return{scalar:n.hasEvenY()?t:wt(-t),bytes:Ft(n)}}function Ne(e){if(!$e(e))throw new Error("bad x: need 0 < x < p");const t=Tt(e*e);let n=Se(Tt(t*e+BigInt(7)));n%vt!==_t&&(n=Tt(-n));const r=new Xt(e,n,Ie);return r.assertValidity(),r}function _e(...e){return wt(V(It("BIP0340/challenge",...e)))}function Nn(e){return jt(e).bytes}function _n(e,t,n=we(32)){const r=C("message",e),{bytes:o,scalar:s}=jt(t),i=C("auxRand",n,32),a=Pt(s^V(It("BIP0340/aux",i))),c=It("BIP0340/nonce",a,o,r),l=wt(V(c));if(l===_t)throw new Error("sign failed: k is zero");const{bytes:d,scalar:u}=jt(l),h=_e(d,o,r),f=new Uint8Array(64);if(f.set(d,0),f.set(Pt(wt(u+h*s)),32),!Le(f,r,o))throw new Error("sign: Invalid signature produced");return f}function Le(e,t,n){const r=C("signature",e,64),o=C("message",t),s=C("publicKey",n,32);try{const e=Ne(V(s)),t=V(r.subarray(0,32));if(!$e(t))return!1;const n=V(r.subarray(32,64));if(!Sn(n))return!1;const i=_e(Pt(t),Ft(e),o),a=$n(e,n,wt(-i));return!(!a||!a.hasEvenY()||a.toAffine().x!==t)}catch{return!1}}const Ct={getPublicKey:Nn,sign:_n,verify:Le,utils:{randomPrivateKey:Dt.utils.randomPrivateKey,lift_x:Ne,pointToBytes:Ft,numberToBytesBE:nt,bytesToNumberBE:V,taggedHash:It,mod:T}},Cn=new TextEncoder;function kn(e){return xt(Bt(Cn.encode(e)))}const Qt={sign:(e,t)=>xt(Ct.sign(e,t)),verify:Ct.verify,getPublicKey:e=>xt(Ct.getPublicKey(e))};function He(e){return kn(JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]))}function Pn(e){try{return Qt.verify(e.sig,He(e),e.pubkey)}catch(e){return console.warn("The following error occurred during verify():",e),!1}}const Ue=async e=>Pn(e);var extendStatics=function(e,t){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},extendStatics(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function __awaiter(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}c((r=r.apply(e,t||[])).next())}))}function __generator(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}function __values(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,s=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)i.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(o)throw o.error}}return i}function __spreadArray(e,t,n){if(n||2===arguments.length)for(var r,o=0,s=t.length;o<s;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}function __await(e){return this instanceof __await?(this.v=e,this):new __await(e)}function __asyncGenerator(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,o=n.apply(e,t||[]),s=[];return r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r;function i(e){o[e]&&(r[e]=function(t){return new Promise((function(n,r){s.push([e,t,n,r])>1||a(e,t)}))})}function a(e,t){try{(n=o[e](t)).value instanceof __await?Promise.resolve(n.value.v).then(c,l):d(s[0][2],n)}catch(e){d(s[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function d(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function __asyncValues(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,o){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,o,(t=e[n](t)).done,t.value)}))}}}function isFunction(e){return"function"==typeof e}function createErrorClass(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}"function"==typeof SuppressedError&&SuppressedError;var UnsubscriptionError=createErrorClass((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function arrRemove(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var Subscription=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,r,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var i=__values(s),a=i.next();!a.done;a=i.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(isFunction(c))try{c()}catch(e){o=e instanceof UnsubscriptionError?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var d=__values(l),u=d.next();!u.done;u=d.next()){var h=u.value;try{execFinalizer(h)}catch(e){o=null!=o?o:[],e instanceof UnsubscriptionError?o=__spreadArray(__spreadArray([],__read(o)),__read(e.errors)):o.push(e)}}}catch(e){n={error:e}}finally{try{u&&!u.done&&(r=d.return)&&r.call(d)}finally{if(n)throw n.error}}}if(o)throw new UnsubscriptionError(o)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)execFinalizer(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&arrRemove(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&arrRemove(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function isSubscription(e){return e instanceof Subscription||e&&"closed"in e&&isFunction(e.remove)&&isFunction(e.add)&&isFunction(e.unsubscribe)}function execFinalizer(e){isFunction(e)?e():e.unsubscribe()}Subscription.EMPTY;var config={Promise:void 0},timeoutProvider={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setTimeout.apply(void 0,__spreadArray([e,t],__read(n)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function reportUnhandledError(e){timeoutProvider.setTimeout((function(){throw e}))}function noop(){}function errorContext(e){e()}var Subscriber=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,isSubscription(t)&&t.add(n)):n.destination=EMPTY_OBSERVER,n}return __extends(t,e),t.create=function(e,t,n){return new SafeSubscriber(e,t,n)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(Subscription),ConsumerObserver=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){handleUnhandledError(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){handleUnhandledError(e)}else handleUnhandledError(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){handleUnhandledError(e)}},e}(),SafeSubscriber=function(e){function t(t,n,r){var o,s=e.call(this)||this;return o=isFunction(t)||!t?{next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:t,s.destination=new ConsumerObserver(o),s}return __extends(t,e),t}(Subscriber);function handleUnhandledError(e){reportUnhandledError(e)}function defaultErrorHandler(e){throw e}var EMPTY_OBSERVER={closed:!0,next:noop,error:defaultErrorHandler,complete:noop},observable="function"==typeof Symbol&&Symbol.observable||"@@observable";function identity(e){return e}function pipeFromArray(e){return 0===e.length?identity:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var Observable=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r=this,o=isSubscriber(e)?e:new SafeSubscriber(e,t,n);return errorContext((function(){var e=r,t=e.operator,n=e.source;o.add(t?t.call(o,n):n?r._subscribe(o):r._trySubscribe(o))})),o},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=getPromiseCtor(t))((function(t,r){var o=new SafeSubscriber({next:function(t){try{e(t)}catch(e){r(e),o.unsubscribe()}},error:r,complete:t});n.subscribe(o)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[observable]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return pipeFromArray(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=getPromiseCtor(e))((function(e,n){var r;t.subscribe((function(e){return r=e}),(function(e){return n(e)}),(function(){return e(r)}))}))},e.create=function(t){return new e(t)},e}();function getPromiseCtor(e){var t;return null!==(t=null!=e?e:config.Promise)&&void 0!==t?t:Promise}function isObserver(e){return e&&isFunction(e.next)&&isFunction(e.error)&&isFunction(e.complete)}function isSubscriber(e){return e&&e instanceof Subscriber||isObserver(e)&&isSubscription(e)}function hasLift(e){return isFunction(null==e?void 0:e.lift)}function operate(e){return function(t){if(hasLift(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}function createOperatorSubscriber(e,t,n,r,o){return new OperatorSubscriber(e,t,n,r,o)}var OperatorSubscriber=function(e){function t(t,n,r,o,s,i){var a=e.call(this,t)||this;return a.onFinalize=s,a.shouldUnsubscribe=i,a._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=o?function(e){try{o(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return __extends(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(Subscriber),dateTimestampProvider={now:function(){return Date.now()}},Action=function(e){function t(t,n){return e.call(this)||this}return __extends(t,e),t.prototype.schedule=function(e,t){return this},t}(Subscription),intervalProvider={setInterval:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];return setInterval.apply(void 0,__spreadArray([e,t],__read(n)))},clearInterval:function(e){return clearInterval(e)},delegate:void 0},AsyncAction=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.scheduler=t,r.work=n,r.pending=!1,r}return __extends(t,e),t.prototype.schedule=function(e,t){var n;if(void 0===t&&(t=0),this.closed)return this;this.state=e;var r=this.id,o=this.scheduler;return null!=r&&(this.id=this.recycleAsyncId(o,r,t)),this.pending=!0,this.delay=t,this.id=null!==(n=this.id)&&void 0!==n?n:this.requestAsyncId(o,this.id,t),this},t.prototype.requestAsyncId=function(e,t,n){return void 0===n&&(n=0),intervalProvider.setInterval(e.flush.bind(e,this),n)},t.prototype.recycleAsyncId=function(e,t,n){if(void 0===n&&(n=0),null!=n&&this.delay===n&&!1===this.pending)return t;null!=t&&intervalProvider.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(e,t);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var n,r=!1;try{this.work(e)}catch(e){r=!0,n=e||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),n},t.prototype.unsubscribe=function(){if(!this.closed){var t=this.id,n=this.scheduler,r=n.actions;this.work=this.state=this.scheduler=null,this.pending=!1,arrRemove(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(Action),Scheduler=function(){function e(t,n){void 0===n&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},e.now=dateTimestampProvider.now,e}(),AsyncScheduler=function(e){function t(t,n){void 0===n&&(n=Scheduler.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r}return __extends(t,e),t.prototype.flush=function(e){var t=this.actions;if(this._active)t.push(e);else{var n;this._active=!0;do{if(n=e.execute(e.state,e.delay))break}while(e=t.shift());if(this._active=!1,n){for(;e=t.shift();)e.unsubscribe();throw n}}},t}(Scheduler),asyncScheduler=new AsyncScheduler(AsyncAction),async=asyncScheduler,EMPTY=new Observable((function(e){return e.complete()}));function isScheduler(e){return e&&isFunction(e.schedule)}var isArrayLike=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function isPromise(e){return isFunction(null==e?void 0:e.then)}function isInteropObservable(e){return isFunction(e[observable])}function isAsyncIterable(e){return Symbol.asyncIterator&&isFunction(null==e?void 0:e[Symbol.asyncIterator])}function createInvalidObservableTypeError(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function getSymbolIterator(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var iterator=getSymbolIterator();function isIterable(e){return isFunction(null==e?void 0:e[iterator])}function readableStreamLikeToAsyncGenerator(e){return __asyncGenerator(this,arguments,(function(){var t,n,r;return __generator(this,(function(o){switch(o.label){case 0:t=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,__await(t.read())];case 3:return n=o.sent(),r=n.value,n.done?[4,__await(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,__await(r)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}function isReadableStreamLike(e){return isFunction(null==e?void 0:e.getReader)}function innerFrom(e){if(e instanceof Observable)return e;if(null!=e){if(isInteropObservable(e))return fromInteropObservable(e);if(isArrayLike(e))return fromArrayLike(e);if(isPromise(e))return fromPromise(e);if(isAsyncIterable(e))return fromAsyncIterable(e);if(isIterable(e))return fromIterable(e);if(isReadableStreamLike(e))return fromReadableStreamLike(e)}throw createInvalidObservableTypeError(e)}function fromInteropObservable(e){return new Observable((function(t){var n=e[observable]();if(isFunction(n.subscribe))return n.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")}))}function fromArrayLike(e){return new Observable((function(t){for(var n=0;n<e.length&&!t.closed;n++)t.next(e[n]);t.complete()}))}function fromPromise(e){return new Observable((function(t){e.then((function(e){t.closed||(t.next(e),t.complete())}),(function(e){return t.error(e)})).then(null,reportUnhandledError)}))}function fromIterable(e){return new Observable((function(t){var n,r;try{for(var o=__values(e),s=o.next();!s.done;s=o.next()){var i=s.value;if(t.next(i),t.closed)return}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}t.complete()}))}function fromAsyncIterable(e){return new Observable((function(t){process(e,t).catch((function(e){return t.error(e)}))}))}function fromReadableStreamLike(e){return fromAsyncIterable(readableStreamLikeToAsyncGenerator(e))}function process(e,t){var n,r,o,s;return __awaiter(this,void 0,void 0,(function(){var i,a;return __generator(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=__asyncValues(e),c.label=1;case 1:return[4,n.next()];case 2:if((r=c.sent()).done)return[3,4];if(i=r.value,t.next(i),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),o={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))}function executeSchedule(e,t,n,r,o){void 0===r&&(r=0),void 0===o&&(o=!1);var s=t.schedule((function(){n(),o?e.add(this.schedule(null,r)):this.unsubscribe()}),r);if(e.add(s),!o)return s}function isValidDate(e){return e instanceof Date&&!isNaN(e)}function map(e,t){return operate((function(n,r){var o=0;n.subscribe(createOperatorSubscriber(r,(function(n){r.next(e.call(t,n,o++))})))}))}function mergeInternals(e,t,n,r,o,s,i,a){var c=[],l=0,d=0,u=!1,h=function(){!u||c.length||l||t.complete()},f=function(e){l++;var o=!1;innerFrom(n(e,d++)).subscribe(createOperatorSubscriber(t,(function(e){t.next(e)}),(function(){o=!0}),void 0,(function(){if(o)try{l--;for(;c.length&&l<r;)e=void 0,e=c.shift(),i||f(e);h()}catch(e){t.error(e)}var e})))};return e.subscribe(createOperatorSubscriber(t,(function(e){return l<r?f(e):c.push(e)}),(function(){u=!0,h()}))),function(){}}function mergeMap(e,t,n){return void 0===n&&(n=1/0),isFunction(t)?mergeMap((function(n,r){return map((function(e,o){return t(n,e,r,o)}))(innerFrom(e(n,r)))}),n):("number"==typeof t&&(n=t),operate((function(t,r){return mergeInternals(t,r,e,n)})))}function timer(e,t,n){void 0===n&&(n=async);var r=-1;return null!=t&&(isScheduler(t)?n=t:r=t),new Observable((function(t){var o=isValidDate(e)?+e-n.now():e;o<0&&(o=0);var s=0;return n.schedule((function(){t.closed||(t.next(s++),0<=r?this.schedule(void 0,r):t.complete())}),o)}))}function filter(e,t){return operate((function(n,r){var o=0;n.subscribe(createOperatorSubscriber(r,(function(n){return e.call(t,n,o++)&&r.next(n)})))}))}function take(e){return e<=0?function(){return EMPTY}:operate((function(t,n){var r=0;t.subscribe(createOperatorSubscriber(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function mapTo(e){return map((function(){return e}))}function delayWhen(e,t){return mergeMap((function(t,n){return innerFrom(e(t,n)).pipe(take(1),mapTo(t))}))}function delay(e,t){void 0===t&&(t=asyncScheduler);var n=timer(e,t);return delayWhen((function(){return n}))}const CALL_TIMEOUT=5e3,AUTH_URL_CALL_TIMEOUT=12e4,DEFAULT_NIP46_RELAYS=["wss://relay.nsec.app/","wss://ephemeral.snowflare.cc/"],NIP46_REQUEST_TIMEOUT=3e4;class Nip46Error extends Error{code;constructor(e,t){super(e),this.name="Nip46Error",this.code=t}get retryable(){return"TIMEOUT"===this.code||"RELAY_DISCONNECTED"===this.code}}class RelayPool{rxNostr;_relayUrls=[];_owned;_connStateSub;constructor(e){e?(this.rxNostr=e,this._owned=!1):(this.rxNostr=Wr({verifier:Ue,connectionStrategy:"lazy-keep",retry:{strategy:"exponential",maxCount:5,initialDelay:1e3},eoseTimeout:1e4,okTimeout:1e4,skipFetchNip11:!0}),this._owned=!0),this._connStateSub=this.rxNostr.createConnectionStateObservable().pipe(filter((e=>"error"===e.state)),delay(3e4)).subscribe((e=>{console.log("RelayPool: auto-reconnecting error relay:",e.from);try{this.rxNostr.reconnect(e.from)}catch(t){console.warn("RelayPool: auto-reconnect failed",e.from,t)}}))}addRelay(e){this._relayUrls.includes(e)||(this._relayUrls.push(e),this._syncRelays())}removeRelay(e){this._relayUrls=this._relayUrls.filter((t=>t!==e)),this._syncRelays()}removeAllRelays(){this._relayUrls=[],this.rxNostr.setDefaultRelays([])}_syncRelays(){this.rxNostr.setDefaultRelays(this._relayUrls)}async connect(e=1e4){if(this._syncRelays(),!this.isAnyConnected())return new Promise((t=>{const n=setTimeout((()=>{r.unsubscribe(),t()}),e),r=this.rxNostr.createConnectionStateObservable().subscribe((e=>{"connected"===e.state&&(clearTimeout(n),r.unsubscribe(),t())}))}))}disconnectAll(){this.rxNostr.setDefaultRelays([])}dispose(){this._connStateSub?.unsubscribe(),this._owned&&this.rxNostr.dispose()}isAnyConnected(){const e=this.rxNostr.getAllRelayStatus();return Object.values(e).some((e=>"connected"===e.connection))}get relayUrls(){return[...this._relayUrls]}async publish(e){try{await this.rxNostr.cast(e)}catch(e){if("EmptyError"!==e?.name)throw e;console.warn("RelayPool: publish - no connected relays, event may not have been sent")}}async publishToRelays(e,t){try{await this.rxNostr.cast(e,{on:{relays:t}})}catch(e){if("EmptyError"!==e?.name)throw e;console.warn("RelayPool: publishToRelays - no connected relays, event may not have been sent")}}subscribe(e,t){const n=Kr(),r=this.rxNostr.use(n).subscribe({next:e=>{t(e.event)}});return n.emit(e),()=>{r.unsubscribe()}}subscribeOnce(e,t,n){const r=zr(),o=n?{on:{relays:n}}:void 0,s=this.rxNostr.use(r,o).subscribe({next:e=>{t(e.event)}});return r.emit(e),r.over(),()=>{s.unsubscribe()}}reconnect(e){this.rxNostr.reconnect(e)}waitForConnection(e){return this.isAnyConnected()?Promise.resolve():new Promise(((t,n)=>{const r=setTimeout((()=>{o.unsubscribe(),n(new Nip46Error("Failed to connect to any relay","RELAY_DISCONNECTED"))}),e),o=this.rxNostr.createConnectionStateObservable().subscribe((e=>{"connected"===e.state&&(clearTimeout(r),o.unsubscribe(),t())}))}))}}class NostrRpc extends lib.EventEmitter{pool;_signer;requests=new Set;unsub;lastSubscribeFilter;requestTimers=new Map;_useNip44=!1;constructor(e,t){super(),this.pool=e,this._signer=t}subscribe(e){e.kinds=e.kinds?.filter((e=>24133===e)),this.lastSubscribeFilter={...e},this.unsub=this.pool.subscribe(e,(async e=>{try{const t=await this.parseEvent(e);t.method?this.emit("request",t):this.emit("response-"+t.id,t)}catch(e){console.error("error parsing event in subscription",e)}}))}ensureSubscription(){if(this.unsub)return;const e=this._signer.pubkey;console.log("ensureSubscription: subscribing for",e),this.subscribe({kinds:[24133],"#p":[e]})}stop(){this.unsub&&(this.unsub(),this.unsub=void 0)}resubscribe(){this.lastSubscribeFilter?(console.log("resubscribe: re-subscribing with filter",this.lastSubscribeFilter),this.stop(),this.subscribe(this.lastSubscribeFilter)):console.warn("resubscribe: no previous filter to resubscribe with")}isSubscriptionActive(){return!this.lastSubscribeFilter||!!this.unsub}clearPendingRequests(){for(const[e,t]of this.requestTimers.entries())clearTimeout(t),this.requestTimers.delete(e);this.requests.clear(),console.log("clearPendingRequests: all pending requests cleared")}setUseNip44(e){this._useNip44=e}isNip04(e){const t=e.length;return!(t<28)&&("?"===e[t-28]&&"i"===e[t-27]&&"v"===e[t-26]&&"="===e[t-25])}async parseEvent(e){const t=e.pubkey,n=this.isNip04(e.content)?this._signer.decrypt:this._signer.decryptNip44,r=await n.call(this._signer,{pubkey:t},e.content),o=JSON.parse(r),{id:s,method:i,params:a,result:c,error:l}=o;return i?{id:s,pubkey:e.pubkey,method:i,params:a,event:e}:{id:s,result:c,error:l,event:e}}async parseNostrConnectReply(e,t){const n=e,r=await this.parseEvent(n);if(console.log("nostr connect parsedEvent",r),r.method)throw new Error("Bad nostr connect reply");{const e=r;if(e.result!==t)throw new Error(e.error||"Invalid secret in reply");return n.pubkey}}async listen(e){const t=this._signer.pubkey;return console.log("nostr-login listening for conn to",t,"expecting secret:",e),new Promise(((n,r)=>{const o=setTimeout((()=>{r(new Error("Connection timeout: no response from signer"))}),6e4),s={kinds:[24133],"#p":[t]};this.stop(),this.lastSubscribeFilter=s,this.unsub=this.pool.subscribe(s,(async t=>{try{const s=await this.parseEvent(t);if(s.method?this.emit("request",s):this.emit("response-"+s.id,s),!s.method){const i=s;if("auth_url"===i.result)return void console.log("Ignoring auth_url response in listen");i.result===e?(clearTimeout(o),console.log("Connection established with signer:",t.pubkey),n(t.pubkey)):"ack"===i.result?(console.warn('Received "ack" instead of secret.'),clearTimeout(o),n(t.pubkey)):(console.error("Invalid response:",i),clearTimeout(o),r(new Error(i.error||"Invalid connection response")))}}catch(e){console.error("Error parsing event in listen",e)}}))}))}async connect(e,t,n){return console.log("Sending connect request to",e,"with perms:",n),this.ensureSubscription(),new Promise(((r,o)=>{const s=setTimeout((()=>{o(new Error("Connect timeout: no response from signer"))}),3e4),i=[e,t||"",n||""];this.sendRequest(e,"connect",i,24133,(e=>{clearTimeout(s),"ack"===e.result?(console.log("Connect acknowledged by signer"),r()):(console.error("Connect failed:",e.error),o(new Error(e.error||"Connection rejected by signer")))}))}))}getId(){return Math.random().toString(36).substring(7)}async sendRequest(e,t,n=[],r=24133,o){const s=this.getId();this.setResponseHandler(s,o);const i=await this.createRequestEvent(s,e,t,n,r);console.log("sendRequest",{event:i,method:t,remotePubkey:e,params:n}),await this.pool.publish(i)}setResponseHandler(e,t){let n=!1,r=!1;const o=Date.now(),s=()=>{const t=this.requestTimers.get(e);t&&(clearTimeout(t),this.requestTimers.delete(e)),this.requests.delete(e)},i=()=>{const n=this.requestTimers.get(e);n&&clearTimeout(n);const i=setTimeout((()=>{console.warn("nip46 request "+e+" timed out after "+(Date.now()-o)+"ms (authUrl="+r+")"),s(),t&&t({id:e,result:"",error:"Request timeout",event:void 0})}),r?4*NIP46_REQUEST_TIMEOUT:NIP46_REQUEST_TIMEOUT);this.requestTimers.set(e,i)};return i(),new Promise((()=>{const a=c=>{"auth_url"===c.result?(this.once("response-"+e,a),n||(n=!0,r=!0,this.emit("authUrl",c.error),i())):t&&this.requests.has(e)&&(s(),console.log("nostr-login processed nip46 request in",Date.now()-o,"ms"),t(c))};this.once("response-"+e,a)}))}async createRequestEvent(e,t,n,r=[],o=24133){this.requests.add(e);const s={id:e,method:n,params:r},i=JSON.stringify(s),a=this._useNip44&&"create_account"!==n?this._signer.encryptNip44:this._signer.encrypt,c=await a.call(this._signer,{pubkey:t},i),l={kind:o,created_at:Math.floor(Date.now()/1e3),tags:[["p",t]],content:c};return finalizeEvent(l,this._signer.secretKey)}}class IframeNostrRpc extends NostrRpc{peerOrigin;iframePort;iframeRequests=new Map;pingInterval;constructor(e,t,n){super(e,t),this.peerOrigin=n}subscribe(e){this.peerOrigin||super.subscribe(e)}setWorkerIframePort(e){if(!this.peerOrigin)throw new Error("Unexpected iframe port");this.iframePort=e,this.pingInterval&&clearInterval(this.pingInterval),this.pingInterval=setInterval((()=>{console.log("iframe-nip46 ping"),this.iframePort.postMessage("ping")}),5e3),e.onmessage=async e=>{if(console.log("iframe-nip46 got response",e.data),"string"==typeof e.data&&e.data.startsWith("errorNoKey")){const t=e.data.split(":")[1],{id:n="",pubkey:r=""}=this.iframeRequests.get(t)||{};n&&r&&this.requests.has(n)&&this.emit("iframeRestart-"+r)}else try{const t=e.data;if(!validateEvent(t))throw new Error("Invalid event from iframe");if(!verifyEvent(t))throw new Error("Invalid event signature from iframe");const n=await this.parseEvent(t);n.method||(console.log("parsed response",n),this.emit("response-"+n.id,n))}catch(t){console.log("error parsing event",t,e.data)}}}async sendRequest(e,t,n=[],r=24133,o){const s=this.getId(),i=await this.createRequestEvent(s,e,t,n,r);this.setResponseHandler(s,o),this.iframePort?(this.iframeRequests.set(i.id||"",{id:s,pubkey:e}),console.log("iframe-nip46 sending request to",this.peerOrigin,i),this.iframePort.postMessage(i)):await this.pool.publish(i)}stop(){super.stop(),this.pingInterval&&(clearInterval(this.pingInterval),this.pingInterval=void 0)}}class ReadyListener{origin;messages;promise;constructor(e,t){this.origin=t,this.messages=e,this.promise=new Promise((e=>{console.log(new Date,"started listener for",this.messages);const n=async r=>{const o=new URL(t).hostname,s=new URL(r.origin).hostname;(s===o||s.endsWith("."+o))&&Array.isArray(r.data)&&r.data.length&&this.messages.includes(r.data[0])&&(console.log(new Date,"got ready message from",r.origin,r.data),window.removeEventListener("message",n),e(r.data))};window.addEventListener("message",n)}))}async wait(){console.log(new Date,"waiting for",this.messages);const e=await this.promise;return console.log(new Date,"finished waiting for",this.messages,e),e}}class Nip46Signer extends lib.EventEmitter{rpc;bunkerPubkey;userPubkey="";constructor(e,t,n,r){super(),this.bunkerPubkey=n,this.rpc=new IframeNostrRpc(e,t,r),this.rpc.setUseNip44(!0),this.rpc.on("authUrl",(e=>{this.emit("authUrl",e)}))}async setSignerPubkey(e,t=!1){console.log("setSignerPubkey",e),this.bunkerPubkey=e,this.rpc.on("iframeRestart-"+e,(()=>{this.emit("iframeRestart")})),await this.initUserPubkey(t?e:"")}async initUserPubkey(e){if(this.userPubkey)console.warn("initUserPubkey already called, pubkey:",this.userPubkey);else{if(e)return this.userPubkey=e,void console.log("User pubkey set from hint:",this.userPubkey);console.log("Requesting user pubkey from signer:",this.bunkerPubkey),this.userPubkey=await new Promise(((e,t)=>{if(!this.bunkerPubkey)throw new Error("Signer pubkey not set");const n=setTimeout((()=>{t(new Error("Timeout getting user pubkey"))}),3e4);console.log("get_public_key",this.bunkerPubkey),this.rpc.sendRequest(this.bunkerPubkey,"get_public_key",[],24133,(r=>{clearTimeout(n),r.error?t(new Error(r.error)):(console.log("User pubkey received:",r.result),e(r.result))}))}))}}async listen(e){const t=await this.rpc.listen(e);await this.setSignerPubkey(t)}async connect(e,t){if(!this.bunkerPubkey)throw new Error("No signer pubkey");await this.rpc.connect(this.bunkerPubkey,e,t),await this.setSignerPubkey(this.bunkerPubkey)}async setListenReply(e,t){const n=await this.rpc.parseNostrConnectReply(e,t);await this.setSignerPubkey(n,!0)}async sign(e){return new Promise(((t,n)=>{const r=JSON.stringify(e);this.rpc.sendRequest(this.bunkerPubkey,"sign_event",[r],24133,(e=>{if(e.error)e.error.includes("timeout")||"Request timeout"===e.error?n(new Nip46Error(e.error,"TIMEOUT")):n(new Nip46Error(e.error,"SIGNER_REJECTED"));else try{const n=JSON.parse(e.result);n.sig&&n.pubkey&&n.id?t(n):n.sig?t(n.sig):t(e.result)}catch{t(e.result)}}))}))}async encrypt(e,t){return new Promise(((n,r)=>{this.rpc.sendRequest(this.bunkerPubkey,"nip04_encrypt",[e,t],24133,(e=>{e.error?r(new Nip46Error(e.error,"SIGNER_REJECTED")):n(e.result)}))}))}async decrypt(e,t){return new Promise(((n,r)=>{this.rpc.sendRequest(this.bunkerPubkey,"nip04_decrypt",[e,t],24133,(e=>{e.error?r(new Nip46Error(e.error,"SIGNER_REJECTED")):n(e.result)}))}))}async createAccount2({bunkerPubkey:e,name:t,domain:n,perms:r=""}){const o=[t,n,"",r],s=await new Promise(((t,n)=>{const r=setTimeout((()=>{n(new Error("Timeout creating account"))}),6e4);this.rpc.sendRequest(e,"create_account",o,void 0,(e=>{clearTimeout(r),t(e)}))}));if(console.log("create_account response",s),"error"===s.result||s.error)throw new Error(s.error||"Failed to create account");return s.result}}class BannerManager extends lib.EventEmitter{banner=null;iframeReady;params;constructor(e){super(),this.params=e}onAuthUrl(e,t){this.banner&&(this.banner.notify=e?{mode:t?"iframeAuthUrl":"authUrl",url:e}:{mode:""})}onIframeRestart(e){this.banner&&(this.iframeReady=new ReadyListener(["rebinderDone","rebinderError"],new URL(e).origin),this.banner.notify={mode:"rebind",url:e})}onUserInfo(e){this.banner&&(this.banner.userInfo=e)}onCallTimeout(){this.banner&&(this.banner.notify={mode:"timeout"})}onCallStart(){this.banner&&(this.banner.isLoading=!0)}async onCallEnd(){this.banner&&(this.iframeReady&&(await this.iframeReady.wait(),this.iframeReady=void 0),this.banner.isLoading=!1,this.banner.notify={mode:""})}onUpdateAccounts(e){this.banner&&(this.banner.accounts=e)}onDarkMode(e){this.banner&&(this.banner.darkMode=e)}launchAuthBanner(e){this.banner=document.createElement("nl-banner"),this.banner.setAttribute("dark-mode",String(getDarkMode(e))),e.theme&&this.banner.setAttribute("theme",e.theme),e.noBanner&&this.banner.setAttribute("hidden-mode","true"),this.banner.addEventListener("handleLoginBanner",(e=>{this.emit("launch",e.detail)})),this.banner.addEventListener("handleConfirmLogout",(()=>{this.emit("onConfirmLogout")})),this.banner.addEventListener("handleLogoutBanner",(async()=>{this.emit("logout")})),this.banner.addEventListener("handleImportModal",(e=>{this.emit("import")})),this.banner.addEventListener("handleNotifyConfirmBanner",(e=>{this.emit("onAuthUrlClick",e.detail)})),this.banner.addEventListener("handleNotifyConfirmBannerIframe",(e=>{this.emit("onIframeAuthUrlClick",e.detail)})),this.banner.addEventListener("handleSwitchAccount",(e=>{this.emit("onSwitchAccount",e.detail)})),this.banner.addEventListener("handleOpenWelcomeModal",(()=>{this.emit("launch"),this.banner&&(this.banner.isOpen=!1)})),this.banner.addEventListener("handleCancelTimeout",(()=>{this.emit("cancelTimeout")})),document.body.appendChild(this.banner)}}function setBigUint64(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const o=BigInt(32),s=BigInt(4294967295),i=Number(n>>o&s),a=Number(n&s),c=r?4:0,l=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+l,a,r)}function Chi(e,t,n){return e&t^~e&n}function Maj(e,t,n){return e&t^e&n^t&n}class HashMD extends Hash{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=createView(this.buffer)}update(e){aexists(this),abytes$1(e=toBytes(e));const{view:t,buffer:n,blockLen:r}=this,o=e.length;for(let s=0;s<o;){const i=Math.min(r-this.pos,o-s);if(i!==r)n.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(t,0),this.pos=0);else{const t=createView(e);for(;r<=o-s;s+=r)this.process(t,s)}}return this.length+=e.length,this.roundClean(),this}digestInto(e){aexists(this),aoutput(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:o}=this;let{pos:s}=this;t[s++]=128,clean(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;setBigUint64(n,r-8,BigInt(8*this.length),o),this.process(n,0);const i=createView(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)i.setUint32(4*e,l[e],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:o,destroyed:s,pos:i}=this;return e.destroyed=s,e.finished=o,e.length=r,e.pos=i,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_K=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]),SHA256_W=new Uint32Array(64);class SHA256 extends HashMD{constructor(e=32){super(64,e,8,!1),this.A=0|SHA256_IV[0],this.B=0|SHA256_IV[1],this.C=0|SHA256_IV[2],this.D=0|SHA256_IV[3],this.E=0|SHA256_IV[4],this.F=0|SHA256_IV[5],this.G=0|SHA256_IV[6],this.H=0|SHA256_IV[7]}get(){const{A:e,B:t,C:n,D:r,E:o,F:s,G:i,H:a}=this;return[e,t,n,r,o,s,i,a]}set(e,t,n,r,o,s,i,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|o,this.F=0|s,this.G=0|i,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)SHA256_W[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=SHA256_W[e-15],n=SHA256_W[e-2],r=rotr(t,7)^rotr(t,18)^t>>>3,o=rotr(n,17)^rotr(n,19)^n>>>10;SHA256_W[e]=o+SHA256_W[e-7]+r+SHA256_W[e-16]|0}let{A:n,B:r,C:o,D:s,E:i,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(rotr(i,6)^rotr(i,11)^rotr(i,25))+Chi(i,a,c)+SHA256_K[e]+SHA256_W[e]|0,d=(rotr(n,2)^rotr(n,13)^rotr(n,22))+Maj(n,r,o)|0;l=c,c=a,a=i,i=s+t|0,s=o,o=r,r=n,n=t+d|0}n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,s=s+this.D|0,i=i+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,o,s,i,a,c,l)}roundClean(){clean(SHA256_W)}destroy(){this.set(0,0,0,0,0,0,0,0),clean(this.buffer)}}const sha256$1=createHasher((()=>new SHA256));class HMAC extends Hash{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ahash(e);const n=toBytes(t);if(this.iHash=e.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,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<o.length;e++)o[e]^=54;this.iHash.update(o),this.oHash=e.create();for(let e=0;e<o.length;e++)o[e]^=106;this.oHash.update(o),clean(o)}update(e){return aexists(this),this.iHash.update(e),this}digestInto(e){aexists(this),abytes$1(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:n,finished:r,destroyed:o,blockLen:s,outputLen:i}=this;return e.finished=r,e.destroyed=o,e.blockLen=s,e.outputLen=i,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(e,t,n)=>new HMAC(e,t).update(n).digest();hmac.create=(e,t)=>new HMAC(e,t)
|
|
22
22
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */;const _0n$3=BigInt(0),_1n$3=BigInt(1);function _abool2(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function _abytes2(e,t,n=""){const r=isBytes$1(e),o=e?.length,s=void 0!==t;if(!r||s&&o!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${o}`:"type="+typeof e))}return e}function numberToHexUnpadded(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function hexToNumber(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?_0n$3:BigInt("0x"+e)}function bytesToNumberBE(e){return hexToNumber(bytesToHex(e))}function bytesToNumberLE(e){return abytes$1(e),hexToNumber(bytesToHex(Uint8Array.from(e).reverse()))}function numberToBytesBE(e,t){return hexToBytes(e.toString(16).padStart(2*t,"0"))}function numberToBytesLE(e,t){return numberToBytesBE(e,t).reverse()}function ensureBytes(e,t,n){let r;if("string"==typeof t)try{r=hexToBytes(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!isBytes$1(t))throw new Error(e+" must be hex string or Uint8Array");r=Uint8Array.from(t)}return r.length,r}const isPosBig=e=>"bigint"==typeof e&&_0n$3<=e;function inRange(e,t,n){return isPosBig(e)&&isPosBig(t)&&isPosBig(n)&&t<=e&&e<n}function aInRange(e,t,n,r){if(!inRange(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function bitLen(e){let t;for(t=0;e>_0n$3;e>>=_1n$3,t+=1);return t}const bitMask=e=>(_1n$3<<BigInt(e))-_1n$3;function createHmacDrbg(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const r=e=>new Uint8Array(e),o=e=>Uint8Array.of(e);let s=r(e),i=r(e),a=0;const c=()=>{s.fill(1),i.fill(0),a=0},l=(...e)=>n(i,s,...e),d=(e=r(0))=>{i=l(o(0),e),s=l(),0!==e.length&&(i=l(o(1),e),s=l())},u=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){s=l();const t=s.slice();n.push(t),e+=s.length}return concatBytes(...n)};return(e,t)=>{let n;for(c(),d(e);!(n=t(u()));)d();return c(),n}}function _validateObject(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function r(t,n,r){const o=e[t];if(r&&void 0===o)return;const s=typeof o;if(s!==n||null===o)throw new Error(`param "${t}" is invalid: expected ${n}, got ${s}`)}Object.entries(t).forEach((([e,t])=>r(e,t,!1))),Object.entries(n).forEach((([e,t])=>r(e,t,!0)))}function memoized(e){const t=new WeakMap;return(n,...r)=>{const o=t.get(n);if(void 0!==o)return o;const s=e(n,...r);return t.set(n,s),s}}
|
|
23
23
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$2=BigInt(1),_2n$2=BigInt(2),_3n$1=BigInt(3),_4n$1=BigInt(4),_5n=BigInt(5),_7n=BigInt(7),_8n=BigInt(8),_9n=BigInt(9),_16n=BigInt(16);function mod(e,t){const n=e%t;return n>=_0n$2?n:t+n}function pow2(e,t,n){let r=e;for(;t-- >_0n$2;)r*=r,r%=n;return r}function invert(e,t){if(e===_0n$2)throw new Error("invert: expected non-zero number");if(t<=_0n$2)throw new Error("invert: expected positive modulus, got "+t);let n=mod(e,t),r=t,o=_0n$2,s=_1n$2;for(;n!==_0n$2;){const e=r%n,t=o-s*(r/n);r=n,n=e,o=s,s=t}if(r!==_1n$2)throw new Error("invert: does not exist");return mod(o,t)}function assertIsSquare(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function sqrt3mod4(e,t){const n=(e.ORDER+_1n$2)/_4n$1,r=e.pow(t,n);return assertIsSquare(e,r,t),r}function sqrt5mod8(e,t){const n=(e.ORDER-_5n)/_8n,r=e.mul(t,_2n$2),o=e.pow(r,n),s=e.mul(t,o),i=e.mul(e.mul(s,_2n$2),o),a=e.mul(s,e.sub(i,e.ONE));return assertIsSquare(e,a,t),a}function sqrt9mod16(e){const t=Field(e),n=tonelliShanks(e),r=n(t,t.neg(t.ONE)),o=n(t,r),s=n(t,t.neg(r)),i=(e+_7n)/_16n;return(e,t)=>{let n=e.pow(t,i),a=e.mul(n,r);const c=e.mul(n,o),l=e.mul(n,s),d=e.eql(e.sqr(a),t),u=e.eql(e.sqr(c),t);n=e.cmov(n,a,d),a=e.cmov(l,c,u);const h=e.eql(e.sqr(a),t),f=e.cmov(n,a,h);return assertIsSquare(e,f,t),f}}function tonelliShanks(e){if(e<_3n$1)throw new Error("sqrt is not defined for small field");let t=e-_1n$2,n=0;for(;t%_2n$2===_0n$2;)t/=_2n$2,n++;let r=_2n$2;const o=Field(e);for(;1===FpLegendre(o,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return sqrt3mod4;let s=o.pow(r,t);const i=(t+_1n$2)/_2n$2;return function(e,r){if(e.is0(r))return r;if(1!==FpLegendre(e,r))throw new Error("Cannot find square root");let o=n,a=e.mul(e.ONE,s),c=e.pow(r,t),l=e.pow(r,i);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===o)throw new Error("Cannot find square root");const r=_1n$2<<BigInt(o-t-1),s=e.pow(a,r);o=t,a=e.sqr(s),c=e.mul(c,a),l=e.mul(l,s)}return l}}function FpSqrt(e){return e%_4n$1===_3n$1?sqrt3mod4:e%_8n===_5n?sqrt5mod8:e%_16n===_9n?sqrt9mod16(e):tonelliShanks(e)}const FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(e){const t=FIELD_FIELDS.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"});return _validateObject(e,t),e}function FpPow(e,t,n){if(n<_0n$2)throw new Error("invalid exponent, negatives unsupported");if(n===_0n$2)return e.ONE;if(n===_1n$2)return t;let r=e.ONE,o=t;for(;n>_0n$2;)n&_1n$2&&(r=e.mul(r,o)),o=e.sqr(o),n>>=_1n$2;return r}function FpInvertBatch(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),o=t.reduce(((t,n,o)=>e.is0(n)?t:(r[o]=t,e.mul(t,n))),e.ONE),s=e.inv(o);return t.reduceRight(((t,n,o)=>e.is0(n)?t:(r[o]=e.mul(t,r[o]),e.mul(t,n))),s),r}function FpLegendre(e,t){const n=(e.ORDER-_1n$2)/_2n$2,r=e.pow(t,n),o=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),i=e.eql(r,e.neg(e.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function nLength(e,t){void 0!==t&&anumber$1(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Field(e,t,n=!1,r={}){if(e<=_0n$2)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,s,i,a=!1;if("object"==typeof t&&null!=t){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(o=e.BITS),e.sqrt&&(s=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),i=e.allowedLengths}else"number"==typeof t&&(o=t),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=nLength(e,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const u=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:bitMask(c),ZERO:_0n$2,ONE:_1n$2,allowedLengths:i,create:t=>mod(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return _0n$2<=t&&t<e},is0:e=>e===_0n$2,isValidNot0:e=>!u.is0(e)&&u.isValid(e),isOdd:e=>(e&_1n$2)===_1n$2,neg:t=>mod(-t,e),eql:(e,t)=>e===t,sqr:t=>mod(t*t,e),add:(t,n)=>mod(t+n,e),sub:(t,n)=>mod(t-n,e),mul:(t,n)=>mod(t*n,e),pow:(e,t)=>FpPow(u,e,t),div:(t,n)=>mod(t*invert(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>invert(t,e),sqrt:s||(t=>(d||(d=FpSqrt(e)),d(u,t))),toBytes:e=>n?numberToBytesLE(e,l):numberToBytesBE(e,l),fromBytes:(t,r=!0)=>{if(i){if(!i.includes(t.length)||t.length>l)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let o=n?bytesToNumberLE(t):bytesToNumberBE(t);if(a&&(o=mod(o,e)),!r&&!u.isValid(o))throw new Error("invalid field element: outside of range 0..ORDER");return o},invertBatch:e=>FpInvertBatch(u,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(u)}function getFieldBytesLength(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function getMinHashLength(e){const t=getFieldBytesLength(e);return t+Math.ceil(t/2)}function mapHashToField(e,t,n=!1){const r=e.length,o=getFieldBytesLength(t),s=getMinHashLength(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const i=mod(n?bytesToNumberLE(e):bytesToNumberBE(e),t-_1n$2)+_1n$2;return n?numberToBytesLE(i,o):numberToBytesBE(i,o)}
|
|
24
24
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$1=BigInt(0),_1n$1=BigInt(1);function negateCt(e,t){const n=t.negate();return e?n:t}function normalizeZ(e,t){const n=FpInvertBatch(e.Fp,t.map((e=>e.Z)));return t.map(((t,r)=>e.fromAffine(t.toAffine(n[r]))))}function validateW(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function calcWOpts(e,t){validateW(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:bitMask(e),maxNumber:n,shiftBy:BigInt(e)}}function calcOffsets(e,t,n){const{windowSize:r,mask:o,maxNumber:s,shiftBy:i}=n;let a=Number(e&o),c=e>>i;a>r&&(a-=s,c+=_1n$1);const l=t*r;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}function validateMSMPoints(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)}))}function validateMSMScalars(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)}))}const pointPrecomputes=new WeakMap,pointWindowSizes=new WeakMap;function getW(e){return pointWindowSizes.get(e)||1}function assert0(e){if(e!==_0n$1)throw new Error("invalid wNAF")}class wNAF{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>_0n$1;)t&_1n$1&&(n=n.add(r)),r=r.double(),t>>=_1n$1;return n}precomputeWindow(e,t){const{windows:n,windowSize:r}=calcWOpts(t,this.bits),o=[];let s=e,i=s;for(let e=0;e<n;e++){i=s,o.push(i);for(let e=1;e<r;e++)i=i.add(s),o.push(i);s=i.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,o=this.BASE;const s=calcWOpts(e,this.bits);for(let e=0;e<s.windows;e++){const{nextN:i,offset:a,isZero:c,isNeg:l,isNegF:d,offsetF:u}=calcOffsets(n,e,s);n=i,c?o=o.add(negateCt(d,t[u])):r=r.add(negateCt(l,t[a]))}return assert0(n),{p:r,f:o}}wNAFUnsafe(e,t,n,r=this.ZERO){const o=calcWOpts(e,this.bits);for(let e=0;e<o.windows&&n!==_0n$1;e++){const{nextN:s,offset:i,isZero:a,isNeg:c}=calcOffsets(n,e,o);if(n=s,!a){const e=t[i];r=r.add(c?e.negate():e)}}return assert0(n),r}getPrecomputes(e,t,n){let r=pointPrecomputes.get(t);return r||(r=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(r=n(r)),pointPrecomputes.set(t,r))),r}cached(e,t,n){const r=getW(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){const o=getW(e);return 1===o?this._unsafeLadder(e,t,r):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,r)}createCache(e,t){validateW(t,this.bits),pointWindowSizes.set(e,t),pointPrecomputes.delete(e)}hasCache(e){return 1!==getW(e)}}function mulEndoUnsafe(e,t,n,r){let o=t,s=e.ZERO,i=e.ZERO;for(;n>_0n$1||r>_0n$1;)n&_1n$1&&(s=s.add(o)),r&_1n$1&&(i=i.add(o)),o=o.double(),n>>=_1n$1,r>>=_1n$1;return{p1:s,p2:i}}function pippenger(e,t,n,r){validateMSMPoints(n,e),validateMSMScalars(r,t);const o=n.length,s=r.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");const i=e.ZERO,a=bitLen(BigInt(o));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=bitMask(c),d=new Array(Number(l)+1).fill(i);let u=i;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){d.fill(i);for(let t=0;t<s;t++){const o=r[t],s=Number(o>>BigInt(e)&l);d[s]=d[s].add(n[t])}let t=i;for(let e=d.length-1,n=i;e>0;e--)n=n.add(d[e]),t=t.add(n);if(u=u.add(t),0!==e)for(let e=0;e<c;e++)u=u.double()}return u}function createField(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return validateField(t),t}return Field(e,{isLE:n})}function _createCurveFields(e,t,n={},r){if(void 0===r&&(r="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>_0n$1))throw new Error(`CURVE.${e} must be positive bigint`)}const o=createField(t.p,n.Fp,r),s=createField(t.n,n.Fn,r),i=["Gx","Gy","a","b"];for(const e of i)if(!o.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:o,Fn:s}}
|