shogun-core 1.3.0 → 1.3.2

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.
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ShogunCore=t():e.ShogunCore=t()}(this,(()=>(()=>{var e,t={197:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunCore=t.ShogunEventEmitter=t.ShogunStorage=t.Gun=t.SEA=void 0;const s=r(58851),o=r(2077),a=r(14134),c=r(45628),u=r(23358),l=r(4643),g=r(50074),d=r(4933),h=r(48098),f=r(48050),p=r(78371),w=r(16868);Object.defineProperty(t,"Gun",{enumerable:!0,get:function(){return w.Gun}}),Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return w.SEA}}),i(r(23358),t),i(r(58851),t),i(r(2077),t),i(r(5307),t),i(r(50074),t);var y=r(4643);Object.defineProperty(t,"ShogunStorage",{enumerable:!0,get:function(){return y.ShogunStorage}});var m=r(4465);Object.defineProperty(t,"ShogunEventEmitter",{enumerable:!0,get:function(){return m.ShogunEventEmitter}});class E{static API_VERSION="v1.2.9c";_gun;_user=null;gundb;storage;eventEmitter;provider;config;rx;plugins=new Map;currentAuthMethod;constructor(e){(0,c.log)("Initializing Shogun "+E.API_VERSION),this.config=e,this.storage=new l.ShogunStorage,this.eventEmitter=new a.EventEmitter,e.logging&&(0,c.configureLogging)(e.logging),u.ErrorHandler.addListener((e=>{this.eventEmitter.emit("error",{action:e.code,message:e.message,type:e.type})}));try{e.gunInstance?this._gun=e.gunInstance:this._gun=(0,w.Gun)(e.peers||[])}catch(e){throw(0,c.logError)("Error creating Gun instance:",e),new Error(`Failed to create Gun instance: ${e}`)}try{this.gundb=new s.GunInstance(this._gun,e.scope||""),this._gun=this.gundb.gun}catch(e){throw(0,c.logError)("Error initializing GunInstance:",e),new Error(`Failed to initialize GunInstance: ${e}`)}try{this._user=this._gun.user().recall({sessionStorage:!0})}catch(e){throw(0,c.logError)("Error initializing Gun user:",e),new Error(`Failed to initialize Gun user: ${e}`)}if(this.rx=new o.GunRxJS(this._gun),this.registerBuiltinPlugins(e),e.plugins?.autoRegister&&e.plugins.autoRegister.length>0)for(const t of e.plugins.autoRegister)try{this.register(t)}catch(e){(0,c.logError)(`Failed to auto-register plugin ${t.name}:`,e)}(0,c.log)("ShogunSDK initialized! 🚀")}get gun(){return this._gun}get user(){return this._user}registerBuiltinPlugins(e){try{if(e.webauthn?.enabled){const e=new d.WebauthnPlugin;e._category=g.PluginCategory.Authentication,this.register(e),(0,c.log)("Webauthn plugin registered")}if(e.web3?.enabled){const e=new h.Web3ConnectorPlugin;e._category=g.PluginCategory.Authentication,this.register(e),(0,c.log)("Web3Connector plugin registered")}if(e.nostr?.enabled){const e=new f.NostrConnectorPlugin;e._category=g.PluginCategory.Authentication,this.register(e),(0,c.log)("NostrConnector plugin registered")}if(e.oauth?.enabled){const t=new p.OAuthPlugin;t._category=g.PluginCategory.Authentication,e.oauth.providers&&t.configure({providers:e.oauth.providers}),this.register(t),(0,c.log)("OAuth plugin registered with providers:",e.oauth.providers)}}catch(e){(0,c.logError)("Error registering builtin plugins:",e)}}register(e){if(this.plugins.has(e.name))throw new Error(`Plugin with name "${e.name}" already registered`);e.initialize(this),this.plugins.set(e.name,e),(0,c.log)(`Registered plugin: ${e.name}`)}unregister(e){const t=this.plugins.get(e);t?(t.destroy&&t.destroy(),this.plugins.delete(e),(0,c.log)(`Unregistered plugin: ${e}`)):(0,c.log)(`Plugin "${e}" not found, nothing to unregister`)}getPlugin(e){return this.plugins.get(e)}hasPlugin(e){return this.plugins.has(e)}getPluginsByCategory(e){const t=[];return this.plugins.forEach((r=>{r._category===e&&t.push(r)})),t}getAuthenticationMethod(e){switch(e){case"webauthn":return this.getPlugin(g.CorePlugins.WebAuthn);case"web3":return this.getPlugin(g.CorePlugins.Web3);case"nostr":return this.getPlugin(g.CorePlugins.Nostr);case"oauth":return this.getPlugin(g.CorePlugins.OAuth);default:return{login:(e,t)=>{this.login(e,t)},signUp:(e,t,r)=>{this.signUp(e,t,r)}}}}getRecentErrors(e=10){return u.ErrorHandler.getRecentErrors(e)}configureLogging(e){(0,c.configureLogging)(e),(0,c.log)("Logging reconfigured with new settings")}isLoggedIn(){return this.gundb.isLoggedIn()}logout(){try{if(!this.isLoggedIn())return void(0,c.log)("Logout ignored: user not authenticated");this.gundb.logout(),this.eventEmitter.emit("auth:logout",{}),(0,c.log)("Logout completed successfully")}catch(e){u.ErrorHandler.handle(u.ErrorType.AUTHENTICATION,"LOGOUT_FAILED",e instanceof Error?e.message:"Error during logout",e)}}async login(e,t){(0,c.log)("Login");try{if((0,c.log)(`Login attempt for user: ${e}`),!e||!t)return{success:!1,error:"Username and password are required"};this.currentAuthMethod||(this.currentAuthMethod="password",(0,c.log)("Authentication method set to default: password"));const r=this.config?.timeouts?.login??15e3,n=new Promise(((n,i)=>{let s=!1;const o=setTimeout((()=>{s||(s=!0,n({success:!1,error:"Login timeout"}))}),r),a=e=>{s||(s=!0,clearTimeout(o),n(e))};(async()=>{try{const r=await this.gundb.login(e,t);r.success?a({success:!0,userPub:r.userPub,username:r.username}):a({success:!1,error:r.error||"Wrong user or password"})}catch(e){a({success:!1,error:e.message||"Login error"})}})()})),i=await n;return i.success&&(this.eventEmitter.emit("auth:login",{userPub:i.userPub??""}),(0,c.log)(`Current auth method before wallet check: ${this.currentAuthMethod}`)),i}catch(e){return u.ErrorHandler.handle(u.ErrorType.AUTHENTICATION,"LOGIN_FAILED",e.message??"Unknown error during login",e),{success:!1,error:e.message??"Unknown error during login"}}}async signUp(e,t,r){(0,c.log)("Sign up");try{if(!e||!t)return{success:!1,error:"Username and password are required"};if(void 0!==r&&t!==r)return{success:!1,error:"Passwords do not match"};if(t.length<6)return{success:!1,error:"Password must be at least 6 characters long"};this.eventEmitter.emit("debug",{action:"signup_start",username:e,timestamp:Date.now()}),(0,c.log)(`Attempting user registration: ${e}`);const n=this.config?.timeouts?.signup??3e4,i=new Promise(((r,i)=>{let s=!1;const o=setTimeout((()=>{s||(s=!0,r({success:!1,error:"Registration timeout"}))}),n),a=e=>{s||(s=!0,clearTimeout(o),r(e))};(async()=>{try{const r=await this.gundb.signUp(e,t);r.success?(this.eventEmitter.emit("debug",{action:"signup_complete",username:e,userPub:r.userPub,timestamp:Date.now()}),this.eventEmitter.emit("auth:signup",{userPub:r.userPub??"",username:e})):this.eventEmitter.emit("debug",{action:"signup_failed",username:e,error:r.error,timestamp:Date.now()}),a(r)}catch(e){a({success:!1,error:e.message||"Registration error"})}})()}));return await i}catch(t){return(0,c.logError)(`Error during registration for user ${e}:`,t),this.eventEmitter.emit("debug",{action:"signup_exception",username:e,error:t.message||"Unknown error",timestamp:Date.now()}),{success:!1,error:t.message??"Unknown error during registration"}}}emit(e,t){return this.eventEmitter.emit(e,t)}on(e,t){return this.eventEmitter.on(e,t),this}once(e,t){return this.eventEmitter.once(e,t),this}off(e,t){return this.eventEmitter.off(e,t),this}removeAllListeners(e){return this.eventEmitter.removeAllListeners(e),this}setAuthMethod(e){(0,c.log)(`Setting authentication method from '${this.currentAuthMethod}' to '${e}'`),this.currentAuthMethod=e,(0,c.log)(`Authentication method successfully set to: ${e}`)}getAuthMethod(){return this.currentAuthMethod}async encrypt(e,t){return this.gundb.encrypt(e,t)}async decrypt(e,t){return this.gundb.decrypt(e,t)}async hashText(e){return this.gundb.hashText(e)}}t.ShogunCore=E},1126:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},2077:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GunRxJS=void 0;const n=r(79364),i=r(92794);t.GunRxJS=class{gun;user;constructor(e){this.gun=e,this.user=e.user().recall({sessionStorage:!0})}getUser(){return this.user}getUserPub(){return this.user.is?.pub}observe(e){return new n.Observable((t=>{const r="string"==typeof e?this.gun.get(e):e,n=r.on(((e,r)=>{if(null!=e)if("object"==typeof e&&null!==e){const r=this.removeGunMeta(e);t.next(r)}else t.next(e);else t.next(null)}));return()=>{n&&"function"==typeof n&&n(),r.off()}})).pipe((0,i.distinctUntilChanged)(((e,t)=>JSON.stringify(e)===JSON.stringify(t))))}match(e,t){return new n.Observable((r=>{const n="string"==typeof e?this.gun.get(e):e,i={},s=n.map().on(((e,n)=>{if("_"===n||!e)return;if(t&&!t(e))return void(i[n]&&(delete i[n],r.next(Object.values(i))));const s="object"==typeof e?this.removeGunMeta(e):e;i[n]=s,r.next(Object.values(i))}));return()=>{s&&"function"==typeof s&&s(),n.off()}}))}put(e,t){const r="string"==typeof e?this.gun.get(e):e;return new n.Observable((e=>{r.put(t,(r=>{r.err?e.error(new Error(r.err)):(e.next(t),e.complete())}))}))}set(e,t){const r="string"==typeof e?this.gun.get(e):e;return new n.Observable((e=>{r.set(t,(r=>{r.err?e.error(new Error(r.err)):(e.next(t),e.complete())}))}))}once(e){const t="string"==typeof e?this.gun.get(e):e;return new n.Observable((e=>{t.once((t=>{if(null==t)return e.next(null),void e.complete();const r="object"==typeof t?this.removeGunMeta(t):t;e.next(r),e.complete()}))}))}compute(e,t){const r=e.map((e=>"string"==typeof e?this.observe(e):e));return new n.Observable((n=>{let i=new Array(e.length).fill(void 0),s=new Array(e.length).fill(!1);const o=r.map(((e,r)=>e.subscribe({next:e=>{if(i[r]=e,i.every((e=>void 0!==e)))try{const e=t(...i);n.next(e)}catch(e){n.error(e)}},error:e=>n.error(e),complete:()=>{s[r]=!0,s.every((e=>e))&&n.complete()}})));return()=>{o.forEach((e=>e.unsubscribe()))}}))}userPut(e,t){return new n.Observable((r=>{this.gun.user().get(e).put(t,(e=>{e.err?r.error(new Error(e.err)):(r.next(t),r.complete())}))}))}userGet(e){return this.observe(this.gun.user().get(e))}observeUser(e){return this.observe(this.gun.user().get(e))}removeGunMeta(e){if(!e||"object"!=typeof e)return e;const t=Array.isArray(e)?[]:{};return Object.keys(e).forEach((r=>{if("_"===r||"#"===r)return;const n=e[r];t[r]=n&&"object"==typeof n?this.removeGunMeta(n):n})),t}}},4465:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunEventEmitter=void 0;const n=r(14134);class i extends n.EventEmitter{emit(e,t){return super.emit(e,t)}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}}t.ShogunEventEmitter=i},4643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunStorage=void 0;t.ShogunStorage=class{store;isTestMode;useLocalStorage;constructor(){if(this.store=new Map,this.isTestMode=!1,this.useLocalStorage=!1,"undefined"!=typeof localStorage&&!this.isTestMode)try{localStorage.setItem("_shogun_test","_shogun_test"),localStorage.removeItem("_shogun_test"),this.useLocalStorage=!0;const e=localStorage.getItem("shogun_keypair");e&&this.store.set("keypair",JSON.parse(e))}catch(e){this.useLocalStorage=!1,this.isTestMode}}async getPair(){return this.getPairSync()}getPairSync(){return this.store.get("keypair")||null}async setPair(e){if(this.store.set("keypair",e),this.useLocalStorage)try{localStorage.setItem("shogun_keypair",JSON.stringify(e))}catch(e){this.isTestMode}}clearAll(){if(this.store.clear(),this.useLocalStorage)try{localStorage.removeItem("shogun_keypair")}catch(e){this.isTestMode}}getItem(e){const t=this.store.get(e);return void 0!==t?JSON.stringify(t):null}setItem(e,t){try{const r=JSON.parse(t);if(this.store.set(e,r),this.useLocalStorage)try{localStorage.setItem(e,t)}catch(e){this.isTestMode}}catch(r){if(this.store.set(e,t),this.useLocalStorage)try{localStorage.setItem(e,t)}catch(e){this.isTestMode}}}removeItem(e){if(this.store.delete(e),this.useLocalStorage)try{localStorage.removeItem(e)}catch(e){this.isTestMode}}}},4933:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebauthnPlugin=void 0;const n=r(34586),i=r(37510),s=r(43188),o=r(45628),a=r(14193),c=r(23358);class u extends n.BasePlugin{name="webauthn";version="1.0.0";description="Provides WebAuthn authentication functionality for ShogunCore";webauthn=null;signer=null;initialize(e){super.initialize(e),this.webauthn=new i.Webauthn(e.gun),this.signer=new s.WebAuthnSigner(this.webauthn),(0,o.log)("WebAuthn plugin initialized with signer support")}destroy(){this.webauthn=null,this.signer=null,super.destroy(),(0,o.log)("WebAuthn plugin destroyed")}assertWebauthn(){if(this.assertInitialized(),!this.webauthn)throw new Error("WebAuthn module not initialized");return this.webauthn}assertSigner(){if(this.assertInitialized(),!this.signer)throw new Error("WebAuthn signer not initialized");return this.signer}isSupported(){return this.assertWebauthn().isSupported()}async generateCredentials(e,t,r=!1){return this.assertWebauthn().generateCredentials(e,t,r)}async createAccount(e,t,r=!1){return this.assertWebauthn().createAccount(e,t,r)}async authenticateUser(e,t,r){return this.assertWebauthn().authenticateUser(e,t,r)}abortAuthentication(){this.assertWebauthn().abortAuthentication()}async removeDevice(e,t,r){return this.assertWebauthn().removeDevice(e,t,r)}async createSigningCredential(e){try{return(0,o.log)(`Creating signing credential for user: ${e}`),await this.assertSigner().createSigningCredential(e)}catch(e){throw(0,o.logError)(`Error creating signing credential: ${e.message}`),e}}createAuthenticator(e){try{return(0,o.log)(`Creating authenticator for credential: ${e}`),this.assertSigner().createAuthenticator(e)}catch(e){throw(0,o.logError)(`Error creating authenticator: ${e.message}`),e}}async createDerivedKeyPair(e,t,r){try{return(0,o.log)(`Creating derived key pair for credential: ${e}`),await this.assertSigner().createDerivedKeyPair(e,t,r)}catch(e){throw(0,o.logError)(`Error creating derived key pair: ${e.message}`),e}}async signWithDerivedKeys(e,t,r,n){try{return(0,o.log)(`Signing data with derived keys for credential: ${t}`),await this.assertSigner().signWithDerivedKeys(e,t,r,n)}catch(e){throw(0,o.logError)(`Error signing with derived keys: ${e.message}`),e}}getSigningCredential(e){return this.assertSigner().getCredential(e)}listSigningCredentials(){return this.assertSigner().listCredentials()}removeSigningCredential(e){return this.assertSigner().removeCredential(e)}async createGunUserFromSigningCredential(e,t){try{const r=this.assertInitialized();return(0,o.log)(`Creating Gun user from signing credential: ${e}`),await this.assertSigner().createGunUser(e,t,r.gun)}catch(e){throw(0,o.logError)(`Error creating Gun user from signing credential: ${e.message}`),e}}getGunUserPubFromSigningCredential(e){return this.assertSigner().getGunUserPub(e)}getHashedCredentialId(e){return this.assertSigner().getHashedCredentialId(e)}async verifyConsistency(e,t,r){try{return(0,o.log)(`Verifying consistency for credential: ${e}`),await this.assertSigner().verifyConsistency(e,t,r)}catch(e){return(0,o.logError)(`Error verifying consistency: ${e.message}`),{consistent:!1}}}async setupConsistentOneshotSigning(e){try{(0,o.log)(`Setting up consistent oneshot signing for: ${e}`);const t=await this.createSigningCredential(e),r=this.createAuthenticator(t.id);return{credential:t,authenticator:r,gunUser:await this.createGunUserFromSigningCredential(t.id,e),pub:t.pub,hashedCredentialId:t.hashedCredentialId}}catch(e){throw(0,o.logError)(`Error setting up consistent oneshot signing: ${e.message}`),e}}async login(e){(0,o.log)("Login with WebAuthn");try{const t=this.assertInitialized();if((0,o.log)(`Attempting WebAuthn login for user: ${e}`),!e)throw new Error("Username required for WebAuthn login");if(!this.isSupported())throw new Error("WebAuthn is not supported by this browser");const r=await this.generateCredentials(e,null,!0);if(!r?.success)throw new Error(r?.error||"WebAuthn verification failed");const n=a.ethers.keccak256(a.ethers.toUtf8Bytes(r.credentialId||""));t.setAuthMethod("webauthn");const i=await t.login(e,n);return i.success?((0,o.log)(`WebAuthn login completed successfully for user: ${e}`),{...i}):i}catch(e){return(0,o.logError)(`Error during WebAuthn login: ${e}`),c.ErrorHandler.handle(c.ErrorType.WEBAUTHN,"WEBAUTHN_LOGIN_ERROR",e.message||"Error during WebAuthn login",e),{success:!1,error:e.message||"Error during WebAuthn login"}}}async signUp(e){(0,o.log)("Sign up with WebAuthn");try{const t=this.assertInitialized();if((0,o.log)(`Attempting WebAuthn registration for user: ${e}`),!e)throw new Error("Username required for WebAuthn registration");if(!this.isSupported())throw new Error("WebAuthn is not supported by this browser");const r=await this.generateCredentials(e,null,!1);if(!r?.success)throw new Error(r?.error||"Unable to generate WebAuthn credentials");const n=a.ethers.keccak256(a.ethers.toUtf8Bytes(r.credentialId||""));t.setAuthMethod("webauthn");const i=await t.signUp(e,n);return i.success?((0,o.log)(`WebAuthn registration completed successfully for user: ${e}`),t.emit("webauthn:register",{username:e,credentialId:r.credentialId}),t.emit("auth:signup",{userPub:i.userPub,username:e,method:"webauthn"}),{...i}):i}catch(e){return(0,o.logError)(`Error during WebAuthn registration: ${e}`),c.ErrorHandler.handle(c.ErrorType.WEBAUTHN,"WEBAUTHN_SIGNUP_ERROR",e.message||"Error during WebAuthn registration",e),{success:!1,error:e.message||"Error during WebAuthn registration"}}}}t.WebauthnPlugin=u},5307:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.oauthChain=t.OAuthPlugin=t.OAuthConnector=t.nostrChain=t.NostrConnectorPlugin=t.NostrConnector=t.web3Chain=t.Web3ConnectorPlugin=t.Web3Connector=t.webauthnChain=t.WebauthnPlugin=t.Webauthn=t.BasePlugin=void 0;var o=r(34586);Object.defineProperty(t,"BasePlugin",{enumerable:!0,get:function(){return o.BasePlugin}});var a=r(37510);Object.defineProperty(t,"Webauthn",{enumerable:!0,get:function(){return a.Webauthn}});var c=r(4933);Object.defineProperty(t,"WebauthnPlugin",{enumerable:!0,get:function(){return c.WebauthnPlugin}});var u=r(77909);Object.defineProperty(t,"webauthnChain",{enumerable:!0,get:function(){return s(u).default}});var l=r(48089);Object.defineProperty(t,"Web3Connector",{enumerable:!0,get:function(){return l.Web3Connector}});var g=r(48098);Object.defineProperty(t,"Web3ConnectorPlugin",{enumerable:!0,get:function(){return g.Web3ConnectorPlugin}});var d=r(75655);Object.defineProperty(t,"web3Chain",{enumerable:!0,get:function(){return s(d).default}});var h=r(37897);Object.defineProperty(t,"NostrConnector",{enumerable:!0,get:function(){return h.NostrConnector}});var f=r(48050);Object.defineProperty(t,"NostrConnectorPlugin",{enumerable:!0,get:function(){return f.NostrConnectorPlugin}});var p=r(84407);Object.defineProperty(t,"nostrChain",{enumerable:!0,get:function(){return s(p).default}});var w=r(17665);Object.defineProperty(t,"OAuthConnector",{enumerable:!0,get:function(){return w.OAuthConnector}});var y=r(78371);Object.defineProperty(t,"OAuthPlugin",{enumerable:!0,get:function(){return y.OAuthPlugin}}),i(r(1126),t);var m=r(90655);Object.defineProperty(t,"oauthChain",{enumerable:!0,get:function(){return s(m).default}})},7120:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NetworkError=t.MultipleAuthError=t.TimeoutError=t.UserExists=t.InvalidCredentials=t.AuthError=t.GunError=void 0;class r extends Error{constructor(e){super(e),this.name="GunError"}}t.GunError=r;class n extends r{constructor(e){super(e),this.name="AuthError"}}t.AuthError=n;t.InvalidCredentials=class extends n{constructor(e="Credenziali non valide"){super(e),this.name="InvalidCredentials"}};t.UserExists=class extends n{constructor(e="Utente già esistente"){super(e),this.name="UserExists"}};t.TimeoutError=class extends r{constructor(e="Timeout durante l'operazione"){super(e),this.name="TimeoutError"}};t.MultipleAuthError=class extends n{constructor(e="Autenticazione multipla in corso"){super(e),this.name="MultipleAuthError"}};t.NetworkError=class extends r{}},14134:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EventEmitter=void 0;const n=r(45628);t.EventEmitter=class{events;constructor(){this.events=new Map}on(e,t){this.events.has(e)||this.events.set(e,[]),this.events.get(e)?.push(t)}emit(e,t){if(!this.events.has(e))return!1;return(this.events.get(e)||[]).forEach((r=>{try{r(t)}catch(t){(0,n.logError)(`Error in event listener for ${String(e)}:`,t)}})),!0}off(e,t){if(!this.events.has(e))return;const r=this.events.get(e)||[],n=r.indexOf(t);-1!==n&&(r.splice(n,1),0===r.length?this.events.delete(e):this.events.set(e,r))}once(e,t){const r=n=>{t(n),this.off(e,r)};this.on(e,r)}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}},15340:()=>{},16868:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SEA=t.Gun=void 0;const n=r(24993);Object.defineProperty(t,"Gun",{enumerable:!0,get:function(){return n.Gun}}),Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return n.SEA}}),r(67410),r(78719),r(29617),r(10924),r(46402),r(76140)},17665:(e,t,r)=>{"use strict";var n=r(48287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthConnector=void 0;const i=r(14193),s=r(45628),o=r(14134);class a extends o.EventEmitter{DEFAULT_CONFIG={providers:{google:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["openid","email","profile"],authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",userInfoUrl:"https://www.googleapis.com/oauth2/v2/userinfo"},github:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["user:email"],authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",userInfoUrl:"https://api.github.com/user"},discord:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["identify","email"],authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",userInfoUrl:"https://discord.com/api/users/@me"},twitter:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["tweet.read","users.read"],authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",userInfoUrl:"https://api.twitter.com/2/users/me"},custom:{clientId:"",clientSecret:"",redirectUri:"",scope:[],authUrl:"",tokenUrl:"",userInfoUrl:""}},usePKCE:!0,cacheDuration:864e5,timeout:6e4,maxRetries:3,retryDelay:1e3};config;userCache=new Map;memoryStorage=new Map;constructor(e={}){super(),this.config={...this.DEFAULT_CONFIG,...e,providers:{...this.DEFAULT_CONFIG.providers||{},...e.providers||{}}}}updateConfig(e){this.config={...this.config,...e,providers:{...this.config.providers||{},...e.providers||{}}},(0,s.logDebug)("OAuthConnector configuration updated",this.config)}getOrigin(){return"undefined"!=typeof window&&window.location?window.location.origin:"http://localhost:3000"}setItem(e,t){"undefined"!=typeof sessionStorage?sessionStorage.setItem(e,t):this.memoryStorage.set(e,t)}getItem(e){return"undefined"!=typeof sessionStorage?sessionStorage.getItem(e):this.memoryStorage.get(e)||null}removeItem(e){"undefined"!=typeof sessionStorage?sessionStorage.removeItem(e):this.memoryStorage.delete(e)}isSupported(){return"undefined"!=typeof URLSearchParams}getAvailableProviders(){return Object.keys(this.config.providers||{}).filter((e=>this.config.providers[e]?.clientId))}async generatePKCEChallenge(){const e=this.generateRandomString(128);return{codeVerifier:e,codeChallenge:await this.calculatePKCECodeChallenge(e)}}async calculatePKCECodeChallenge(e){if("undefined"!=typeof window&&window.crypto&&window.crypto.subtle){const t=(new TextEncoder).encode(e),r=await window.crypto.subtle.digest("SHA-256",t);return this.base64urlEncode(r)}{const t=r(91565).createHash("sha256").update(e).digest();return this.base64urlEncode(t)}}base64urlEncode(e){let t;if(void 0!==n&&n.isBuffer(e))t=e.toString("base64");else{const r=new Uint8Array(e);let n="";for(let e=0;e<r.length;e++)n+=String.fromCharCode(r[e]);t=window.btoa(n)}return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}generateRandomString(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";let n;if("undefined"!=typeof window&&window.crypto)n=new Uint8Array(e),window.crypto.getRandomValues(n);else{const t=r(91565);n=new Uint8Array(t.randomBytes(e))}return Array.from(n).map((e=>t[e%66])).join("")}async initiateOAuth(e){try{(0,s.logDebug)(`Initiating OAuth flow with ${e}`);const t=this.config.providers[e];if(!t||!t.clientId)throw new Error(`Provider ${e} not configured`);const r=this.generateRandomString(32);this.setItem(`oauth_state_${e}`,r);let n={};if(this.config.usePKCE){const{codeVerifier:t,codeChallenge:r}=await this.generatePKCEChallenge();this.setItem(`oauth_verifier_${e}`,t),n={code_challenge:r,code_challenge_method:"S256"}}const i=new URLSearchParams({client_id:t.clientId,redirect_uri:t.redirectUri,scope:t.scope.join(" "),response_type:"code",state:r,...n});let o=t.authUrl||"";if(!o)throw new Error(`Auth URL not configured for provider ${e}`);return o=o.includes("?")?`${o}&${i.toString()}`:`${o}?${i.toString()}`,this.emit("oauth_initiated",{provider:e,authUrl:o}),{success:!0,provider:e,authUrl:o}}catch(t){return(0,s.logError)(`Error initiating OAuth with ${e}:`,t),{success:!1,error:t.message}}}async completeOAuth(e,t,r){const n=this.config.providers?.[e];if(!n){const t=`Provider '${e}' is not configured.`;return(0,s.logError)(t),{success:!1,error:t}}try{const i=await this.exchangeCodeForToken(e,n,t,r);if(!i.access_token){const e="No access token received from provider";return(0,s.logError)(e,i),{success:!1,error:e}}const o=await this.fetchUserInfo(e,n,i.access_token);this.cacheUserInfo(o.id,e,o);const a=await this.generateCredentials(o,e);return this.emit("oauth_completed",{provider:e,userInfo:o,credentials:a}),{success:!0,provider:e,userInfo:o}}catch(t){return(0,s.logError)(`Error completing OAuth with ${e}:`,t),{success:!1,error:t.message}}}async generateCredentials(e,t){const r=this.config.providers?.[t];if(!r)throw new Error(`Provider ${t} is not configured.`);e.id;const n=e.email||`${e.id}@${t}.shogun`;try{(0,s.logDebug)(`Generating credentials for ${t} user: ${e.id}`);const r={username:n,password:await this.generateDeterministicPassword(e,t),provider:t};return this.cacheUserInfo(e.id,t,e),(0,s.logDebug)("OAuth credentials generated successfully"),r}catch(e){throw(0,s.logError)("Error generating OAuth credentials:",e),e}}async generateDeterministicPassword(e,t){const r=`${e.id}_${t}_${e.email||""}_shogun_oauth`;return i.ethers.keccak256(i.ethers.toUtf8Bytes(r)).slice(2,34)}async exchangeCodeForToken(e,t,r,n){const i=await this.getItem(`oauth_state_${e}`);if(n&&i!==n)throw new Error("Invalid state parameter");const o={client_id:t.clientId,code:r,redirect_uri:t.redirectUri,grant_type:"authorization_code"};if(t.clientSecret&&(o.client_secret=t.clientSecret),this.config.usePKCE){const t=await this.getItem(`oauth_verifier_${e}`);t?(o.code_verifier=t,this.removeItem(`oauth_verifier_${e}`)):(0,s.logWarn)(`PKCE is enabled, but no code verifier was found for ${e}.`)}const a=await fetch(t.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams(o)});if(!a.ok){const e=await a.json().catch((()=>({error:a.statusText})));throw new Error(`Token exchange failed: ${a.status} ${a.statusText} - ${JSON.stringify(e)}`)}return await a.json()}async fetchUserInfo(e,t,r){const n=await fetch(t.userInfoUrl,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}});if(!n.ok)throw new Error(`Failed to get user info: ${n.statusText}`);const i=await n.json();return this.normalizeUserInfo(i,e)}normalizeUserInfo(e,t){switch(t){case"google":return{id:e.id,email:e.email,name:e.name,picture:e.picture,verified_email:e.verified_email,provider:t};case"github":return{id:e.id.toString(),email:e.email,name:e.name||e.login,picture:e.avatar_url,provider:t};default:return{id:e.id?.toString()||e.sub,email:e.email,name:e.name||e.username,picture:e.picture||e.avatar_url,provider:t}}}cacheUserInfo(e,t,r){const n=`${t}_${e}`,i={data:r,timestamp:Date.now(),provider:t,userId:e};this.userCache.set(n,i);try{localStorage.setItem(`shogun_oauth_user_${n}`,JSON.stringify(i))}catch(e){(0,s.logError)("Error caching user info:",e)}}getCachedUserInfo(e,t){const r=`${t}_${e}`,n=this.userCache.get(r);if(n&&n.data&&Date.now()-n.timestamp<=this.config.cacheDuration)return n.data;try{const e=localStorage.getItem(`shogun_oauth_user_${r}`);if(e){const t=JSON.parse(e);if(t.data&&Date.now()-t.timestamp<=this.config.cacheDuration)return this.userCache.set(r,t),t.data;localStorage.removeItem(`shogun_oauth_user_${r}`)}}catch(e){(0,s.logError)("Error reading cached user info:",e)}return null}clearUserCache(e,t){if(e&&t){const r=`${t}_${e}`;this.userCache.delete(r);try{localStorage.removeItem(`shogun_oauth_user_${r}`)}catch(e){(0,s.logError)("Error clearing user cache:",e)}}else{this.userCache.clear();try{const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);r&&r.startsWith("shogun_oauth_user_")&&e.push(r)}e.forEach((e=>localStorage.removeItem(e)))}catch(e){(0,s.logError)("Error clearing all user caches:",e)}}}cleanup(){this.removeAllListeners(),this.userCache.clear()}}t.OAuthConnector=a},21302:function(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&i(t,e,r[o]);return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.GunInstance=void 0;const c=r(45628),u=r(23358),l=r(2077),g=o(r(7120)),d=o(r(90554)),h=o(r(50170)),f=r(59229),p=a(r(67476));t.GunInstance=class{gun;user=null;crypto;utils;node;onAuthCallbacks=[];_rxjs;constructor(e,t="shogun"){if((0,c.log)("Initializing GunDB"),!e)throw new Error("Gun instance is required but was not provided");if("object"!=typeof e)throw new Error("Gun instance must be an object, received: "+typeof e);if("function"!=typeof e.user)throw new Error("Gun instance is invalid: gun.user is not a function. Received gun.user type: "+typeof e.user);if("function"!=typeof e.get)throw new Error("Gun instance is invalid: gun.get is not a function. Received gun.get type: "+typeof e.get);if("function"!=typeof e.on)throw new Error("Gun instance is invalid: gun.on is not a function. Received gun.on type: "+typeof e.on);this.gun=e,"undefined"!=typeof window?(window.ShogunDB=this,window.ShogunGun=e):void 0!==r.g&&(r.g.ShogunDB=this,r.g.ShogunGun=e);try{this.user=this.gun.user().recall({sessionStorage:!0})}catch(e){throw(0,c.logError)("Error initializing Gun user:",e),new Error(`Failed to initialize Gun user: ${e}`)}this.subscribeToAuthEvents(),this.crypto=d,this.utils=h,this.node=this.gun.get(t),this.restoreSessionOnInit()}async restoreSessionOnInit(){try{const e=await this.restoreSession();e.success?(0,c.log)(`Session automatically restored for user: ${e.userPub}`):(0,c.log)(`No previous session to restore: ${e.error}`)}catch(e){(0,c.logError)("Error during automatic session restoration:",e)}}subscribeToAuthEvents(){this.gun.on("auth",(e=>{(0,c.log)("Auth event received:",e),e.err?u.ErrorHandler.handle(u.ErrorType.GUN,"AUTH_EVENT_ERROR",e.err,new Error(e.err)):this.notifyAuthListeners(e.sea?.pub||"")}))}notifyAuthListeners(e){const t=this.gun.user();this.onAuthCallbacks.forEach((e=>e(t)))}addPeer(e){this.gun.opt({peers:[e]}),(0,c.log)(`Added new peer: ${e}`)}removePeer(e){try{const t=this.gun._.opt;if(t&&t.peers){delete t.peers[e];const r=t.peers[e];r&&"function"==typeof r.close&&r.close(),(0,c.log)(`Removed peer: ${e}`)}else(0,c.log)(`Peer not found in current connections: ${e}`)}catch(t){(0,c.logError)(`Error removing peer ${e}:`,t)}}getCurrentPeers(){try{const e=this.gun._.opt;return e&&e.peers?Object.keys(e.peers).filter((t=>{const r=e.peers[t];return r&&r.wire&&"bye"!==r.wire.hied})):[]}catch(e){return(0,c.logError)("Error getting current peers:",e),[]}}getAllConfiguredPeers(){try{const e=this.gun._.opt;return e&&e.peers?Object.keys(e.peers):[]}catch(e){return(0,c.logError)("Error getting configured peers:",e),[]}}getPeerInfo(){try{const e=this.gun._.opt,t={};return e&&e.peers&&Object.keys(e.peers).forEach((r=>{const n=e.peers[r],i=n&&n.wire&&"bye"!==n.wire.hied,s=i?"connected":n&&n.wire?"disconnected":"not_initialized";t[r]={connected:i,status:s}})),t}catch(e){return(0,c.logError)("Error getting peer info:",e),{}}}reconnectToPeer(e){try{this.removePeer(e),this.addPeer(e),(0,c.log)(`Reconnected to peer: ${e}`)}catch(t){(0,c.logError)(`Error reconnecting to peer ${e}:`,t)}}resetPeers(e){try{const t=this.gun._.opt;t&&t.peers&&(Object.keys(t.peers).forEach((e=>{this.removePeer(e)})),e&&e.length>0&&e.forEach((e=>{this.addPeer(e)})),(0,c.log)(`Reset peers. New peers: ${e?e.join(", "):"none"}`))}catch(e){(0,c.logError)("Error resetting peers:",e)}}onAuth(e){this.onAuthCallbacks.push(e);const t=this.gun.user();return t&&t.is&&e(t),()=>{const t=this.onAuthCallbacks.indexOf(e);-1!==t&&this.onAuthCallbacks.splice(t,1)}}navigateToPath(e,t){if(!t)return e;return t.split("/").filter((e=>e.length>0)).reduce(((e,t)=>e.get(t)),e)}getGun(){return this.gun}getUser(){return this.gun.user()}get(e){return this.navigateToPath(this.gun,e)}async put(e,t){return new Promise((r=>{this.navigateToPath(this.gun,e).put(t,(e=>{r(e.err?{success:!1,error:e.err}:{success:!0})}))}))}async set(e,t){return new Promise((r=>{this.navigateToPath(this.gun,e).set(t,(e=>{r(e.err?{success:!1,error:e.err}:{success:!0})}))}))}async remove(e){return new Promise((t=>{this.navigateToPath(this.gun,e).put(null,(e=>{t(e.err?{success:!1,error:e.err}:{success:!0})}))}))}async signUp(e,t){(0,c.log)("Attempting user registration:",e);try{if(t.length<8){const e="Passwords must be more than 8 characters long!";return(0,c.log)(e),{success:!1,error:e}}if(e.length<1){const e="Username must be more than 0 characters long!";return(0,c.log)(e),{success:!1,error:e}}(0,c.log)(`Checking if user ${e} exists in Gun's native system...`);const r=await new Promise((r=>{this.gun.user().auth(e,t,(e=>{e.err?r({exists:!1,error:e.err}):r({exists:!0,userPub:this.gun.user().is?.pub})}))}));if(r.exists){(0,c.log)(`User ${e} already exists and password is correct, syncing with tracking system...`);const t=r.userPub;if(!await this.checkUsernameExists(e)){(0,c.log)(`User ${e} not in tracking system, adding them...`);const r={username:e,pub:t,createdAt:Date.now(),lastLogin:Date.now()};try{await new Promise((n=>{const i=setTimeout((()=>{(0,c.logError)(`Warning: User metadata save timeout for ${e}`),n()}),2e3);this.gun.get(t).put(r,(t=>{clearTimeout(i),t.err?(0,c.logError)(`Warning: Failed to save user metadata: ${t.err}`):(0,c.log)(`User metadata saved for: ${e}`),n()}))})),await new Promise((r=>{const n=setTimeout((()=>{(0,c.logError)(`Warning: User collection add timeout for ${e}`),r()}),2e3);this.gun.get("users").set(this.gun.get(t),(t=>{clearTimeout(n),t.err?(0,c.logError)(`Warning: Failed to add user to collection: ${t.err}`):(0,c.log)(`User added to collection: ${e}`),r()}))})),await new Promise((r=>{const n=setTimeout((()=>{(0,c.logError)(`Warning: Username mapping timeout for ${e}`),r()}),2e3);this.gun.get("usernames").get(e).put(t,(i=>{clearTimeout(n),i.err?(0,c.logError)(`Warning: Could not create username mapping: ${i.err}`):(0,c.log)(`Username mapping created: ${e} -> ${t}`),r()}))}))}catch(e){(0,c.logError)(`Warning: Could not update tracking system: ${e}`)}return this._savePair(),{success:!0,userPub:t,username:e,message:"User already exists and was synced with tracking system"}}return{success:!0,userPub:t,username:e,message:"User already exists and was synced with tracking system"}}(0,c.log)(`Creating new user: ${e}`);const n=await new Promise((r=>{this.gun.user().create(e,t,(t=>{t.err?((0,c.logError)(`User creation error: ${t.err}`),r({success:!1,error:t.err})):((0,c.log)(`User created successfully: ${e}`),r({success:!0,pub:t.pub}))}))}));if(!n.success)return n;const i=await new Promise((r=>{this.gun.user().auth(e,t,(e=>{e.err?((0,c.logError)(`Authentication after creation failed: ${e.err}`),r({success:!1,error:e.err})):r({success:!0,userPub:this.gun.user().is?.pub})}))}));if(!i.success)return{success:!1,error:"User created but authentication failed"};const s=i.userPub;(0,c.log)(`User authentication successful after creation: ${e} (${s})`);const o={username:e,pub:s,createdAt:Date.now(),lastLogin:Date.now()};try{await new Promise((t=>{const r=setTimeout((()=>{(0,c.logError)(`Warning: User metadata save timeout for ${e}`),t()}),2e3);this.gun.get(s).put(o,(n=>{clearTimeout(r),n.err?(0,c.logError)(`Warning: Failed to save user metadata: ${n.err}`):(0,c.log)(`User metadata saved for: ${e}`),t()}))})),await new Promise((t=>{const r=setTimeout((()=>{(0,c.logError)(`Warning: User collection add timeout for ${e}`),t()}),2e3);this.gun.get("users").set(this.gun.get(s),(n=>{clearTimeout(r),n.err?(0,c.logError)(`Warning: Failed to add user to collection: ${n.err}`):(0,c.log)(`User added to collection: ${e}`),t()}))})),await new Promise((t=>{const r=setTimeout((()=>{(0,c.logError)(`Warning: Username mapping timeout for ${e}`),t()}),2e3);this.gun.get("usernames").get(e).put(s,(n=>{clearTimeout(r),n.err?(0,c.logError)(`Warning: Could not create username mapping: ${n.err}`):(0,c.log)(`Username mapping created: ${e} -> ${s}`),t()}))}))}catch(e){(0,c.logError)(`Warning: Could not update tracking system: ${e}`)}return this._savePair(),{success:!0,userPub:s,username:e,message:"User created successfully"}}catch(t){return(0,c.logError)(`Exception during signup for ${e}: ${t}`),{success:!1,error:String(t)}}}async checkUsernameExists(e){try{const t=await new Promise((t=>{this.gun.get("usernames").get(e).once((e=>{t(e||null)}))}));if(t){return await new Promise((e=>{this.gun.get(t).once((t=>{e(t)}))}))}return await new Promise((t=>{let r=!1;this.gun.get("users").map().once(((n,i)=>{!r&&n&&n.username===e&&(r=!0,t(n))})),setTimeout((()=>{r||t(null)}),100)}))}catch(e){return(0,c.logError)(`Error checking username existence: ${e}`),null}}async login(e,t,r){(0,c.log)(`Attempting login for user: ${e}`);try{if(!(await new Promise((r=>{this.gun.user().auth(e,t,(t=>{t.err?((0,c.logError)(`Login error for ${e}: ${t.err}`),r({success:!1,error:t.err})):((0,c.log)(`Login successful for: ${e}`),r({success:!0,ack:t}))}))}))).success){const t={success:!1,error:`User '${e}' not found. Please check your username or register first.`};return r&&r(t),t}const n=this.gun.user().is?.pub;if(!n){const e={success:!1,error:"Authentication failed: No user pub returned."};return r&&r(e),e}(0,c.log)(`Gun.js authentication successful for: ${e} (${n})`);try{if(await this.checkUsernameExists(e))(0,c.log)(`User ${e} found in tracking system, updating last login...`),this.gun.get(n).get("lastLogin").put(Date.now());else{(0,c.log)(`User ${e} not found in tracking system, adding them...`);const t={username:e,pub:n,createdAt:Date.now(),lastLogin:Date.now()};await new Promise((r=>{const i=setTimeout((()=>{(0,c.logError)(`Warning: User metadata save timeout for ${e}`),r()}),2e3);this.gun.get(n).put(t,(t=>{clearTimeout(i),t.err?(0,c.logError)(`Warning: Failed to save user metadata: ${t.err}`):(0,c.log)(`User metadata saved for: ${e}`),r()}))})),await new Promise((t=>{const r=setTimeout((()=>{(0,c.logError)(`Warning: User collection add timeout for ${e}`),t()}),2e3);this.gun.get("users").set(this.gun.get(n),(n=>{clearTimeout(r),n.err?(0,c.logError)(`Warning: Failed to add user to collection: ${n.err}`):(0,c.log)(`User added to collection: ${e}`),t()}))})),await new Promise((t=>{const r=setTimeout((()=>{(0,c.logError)(`Warning: Username mapping timeout for ${e}`),t()}),2e3);this.gun.get("usernames").get(e).put(n,(i=>{clearTimeout(r),i.err?(0,c.logError)(`Warning: Could not create username mapping: ${i.err}`):(0,c.log)(`Username mapping created: ${e} -> ${n}`),t()}))}))}}catch(e){(0,c.logError)(`Warning: Could not sync with tracking system: ${e}`)}(0,c.log)(`Login completed successfully for: ${e} (${n})`),this._savePair();const i={success:!0,userPub:n,username:e};return r&&r(i),i}catch(t){(0,c.logError)(`Exception during login for ${e}: ${t}`);const n={success:!1,error:String(t)};return r&&r(n),n}}_savePair(){try{const e=this.gun.user(),t=e?._?.sea,r=e?.is;if(t&&r){const e={pub:r.pub,alias:r.alias||"",timestamp:Date.now()};"undefined"!=typeof localStorage&&(localStorage.setItem("gun/pair",JSON.stringify(t)),localStorage.setItem("gun/session",JSON.stringify(e))),"undefined"!=typeof sessionStorage&&(sessionStorage.setItem("gun/pair",JSON.stringify(t)),sessionStorage.setItem("gun/session",JSON.stringify(e))),(0,c.log)(`Session saved for user: ${r.alias||r.pub}`)}}catch(e){(0,c.logError)("Error saving auth pair and session:",e)}}async restoreSession(){try{if("undefined"==typeof localStorage)return{success:!1,error:"localStorage not available"};const e=localStorage.getItem("gun/session"),t=localStorage.getItem("gun/pair");if(!e||!t)return(0,c.log)("No saved session found"),{success:!1,error:"No saved session"};const r=JSON.parse(e),n=JSON.parse(t),i=Date.now()-r.timestamp;if(i>6048e5)return(0,c.log)("Session expired, clearing storage"),localStorage.removeItem("gun/session"),localStorage.removeItem("gun/pair"),{success:!1,error:"Session expired"};(0,c.log)(`Attempting to restore session for user: ${r.alias||r.pub}`);const s=this.gun.user();s._={sea:n};return await new Promise((e=>{try{s.recall({sessionStorage:!0},(t=>{t.err?((0,c.logError)(`Session recall error: ${t.err}`),e(!1)):e(!0)}))}catch(t){(0,c.logError)(`Session recall exception: ${t}`),e(!1)}}))&&s.is?.pub===r.pub?((0,c.log)(`Session restored successfully for: ${r.alias||r.pub}`),{success:!0,userPub:r.pub}):((0,c.log)("Session restoration failed, clearing storage"),localStorage.removeItem("gun/session"),localStorage.removeItem("gun/pair"),{success:!1,error:"Session restoration failed"})}catch(e){return(0,c.logError)(`Error restoring session: ${e}`),{success:!1,error:String(e)}}}logout(){try{if(!this.isLoggedIn())return void(0,c.log)("No user logged in, skipping logout");const e=this.getCurrentUser();(0,c.log)(`Logging out user: ${e?.pub||"unknown"}`),this.gun.user().leave(),"undefined"!=typeof localStorage&&(localStorage.removeItem("gun/pair"),localStorage.removeItem("gun/session"),localStorage.removeItem("pair"),(0,c.log)("Local session data cleared")),"undefined"!=typeof sessionStorage&&(sessionStorage.removeItem("gun/"),sessionStorage.removeItem("gun/user"),sessionStorage.removeItem("gun/auth"),(0,c.log)("Session storage cleared")),(0,c.log)("Logout completed successfully")}catch(e){(0,c.logError)("Error during logout:",e)}}isLoggedIn(){return!!this.gun.user()?.is?.pub}getCurrentUser(){const e=this.gun.user()?.is?.pub;return e?{pub:e,user:this.gun.user()}:null}rx(){return this._rxjs||(this._rxjs=new l.GunRxJS(this.gun)),this._rxjs}async setPasswordHint(e,t,r,n,i){(0,c.log)("Setting password hint for:",e);if(!(await this.login(e,t)).success)return{success:!1,error:"Authentication failed"};const s=this.getCurrentUser();if(!s||!s.pub)return{success:!1,error:"User not authenticated"};try{const e=i.join("|");let t,s;try{if(f.SEA&&f.SEA.work)t=await f.SEA.work(e,null,null,{name:"SHA-256"});else{if(!this.crypto||!this.crypto.hashText)throw new Error("Cryptographic functions not available");t=await this.crypto.hashText(e)}if(!t)throw new Error("Failed to generate hash")}catch(e){return(0,c.logError)("Error generating hash:",e),{success:!1,error:"Failed to generate security hash"}}try{if(f.SEA&&f.SEA.encrypt)s=await f.SEA.encrypt(r,t);else{if(!this.crypto||!this.crypto.encrypt)throw new Error("Encryption functions not available");s=await this.crypto.encrypt(r,t)}if(!s)throw new Error("Failed to encrypt hint")}catch(e){return(0,c.logError)("Error encrypting hint:",e),{success:!1,error:"Failed to encrypt password hint"}}return await this.saveUserData("security",{questions:n,hint:s}),{success:!0}}catch(e){return(0,c.logError)("Error setting password hint:",e),{success:!1,error:String(e)}}}async forgotPassword(e,t){(0,c.log)("Attempting password recovery for:",e);try{const r=await this.checkUsernameExists(e);if(!r)return{success:!1,error:"User not found"};const n=this.gun.user(r),i=await new Promise((e=>{n.get("security").once((t=>{e(t)}))}));if(!i||!i.hint)return{success:!1,error:"No password hint found"};const s=t.join("|");let o,a;try{if(f.SEA&&f.SEA.work)o=await f.SEA.work(s,null,null,{name:"SHA-256"});else{if(!this.crypto||!this.crypto.hashText)throw new Error("Cryptographic functions not available");o=await this.crypto.hashText(s)}if(!o)throw new Error("Failed to generate hash")}catch(e){return(0,c.logError)("Error generating hash:",e),{success:!1,error:"Failed to generate security hash"}}try{if(f.SEA&&f.SEA.decrypt)a=await f.SEA.decrypt(i.hint,o);else{if(!this.crypto||!this.crypto.decrypt)throw new Error("Decryption functions not available");a=await this.crypto.decrypt(i.hint,o)}}catch(e){return{success:!1,error:"Incorrect answers to security questions"}}return void 0===a?{success:!1,error:"Incorrect answers to security questions"}:{success:!0,hint:a}}catch(e){return(0,c.logError)("Error recovering password hint:",e),{success:!1,error:String(e)}}}async hashText(e){return this.crypto.hashText(e)}async encrypt(e,t){return this.crypto.encrypt(e,t)}async decrypt(e,t){return this.crypto.decrypt(e,t)}async saveUserData(e,t){return new Promise(((r,n)=>{const i=this.gun.user();i.is?this.navigateToPath(i,e).put(t,(e=>{e.err?n(new Error(e.err)):r()})):n(new Error("User not authenticated"))}))}async getUserData(e){return new Promise((t=>{const r=this.gun.user();r.is?this.navigateToPath(r,e).once((e=>{t(e)})):t(null)}))}async derive(e,t,r){try{(0,c.log)("Deriving cryptographic keys with options:",r);const n=await(0,p.default)(e,t,r);return(0,c.log)("Key derivation completed successfully"),n}catch(e){throw(0,c.logError)("Error during key derivation:",e),u.ErrorHandler.handle(u.ErrorType.ENCRYPTION,"KEY_DERIVATION_FAILED",e instanceof Error?e.message:"Failed to derive cryptographic keys",e),e}}async deriveP256(e,t){return this.derive(e,t,{includeP256:!0})}async deriveBitcoin(e,t){return this.derive(e,t,{includeSecp256k1Bitcoin:!0})}async deriveEthereum(e,t){return this.derive(e,t,{includeSecp256k1Ethereum:!0})}async deriveAll(e,t){return this.derive(e,t,{includeP256:!0,includeSecp256k1Bitcoin:!0,includeSecp256k1Ethereum:!0})}static Errors=g}},21638:()=>{},23358:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorHandler=t.ErrorType=void 0,t.createError=s;const n=r(45628);var i;function s(e,t,r,n){return{type:e,code:t,message:r,originalError:n,timestamp:Date.now()}}!function(e){e.AUTHENTICATION="AuthenticationError",e.AUTHORIZATION="AuthorizationError",e.VALIDATION="ValidationError",e.NETWORK="NetworkError",e.DATABASE="DatabaseError",e.WALLET="WalletError",e.STORAGE="StorageError",e.ENCRYPTION="EncryptionError",e.SIGNATURE="SignatureError",e.ENVIRONMENT="EnvironmentError",e.SECURITY="SecurityError",e.GUN="GunError",e.STEALTH="StealthError",e.WEBAUTHN="WebAuthnError",e.PLUGIN="PluginError",e.UNKNOWN="UnknownError",e.CONNECTOR="ConnectorError",e.GENERAL="GeneralError",e.CONTRACT="ContractError",e.BIP32="BIP32Error",e.ETHEREUM="EthereumError",e.BITCOIN="BitcoinError"}(i||(t.ErrorType=i={}));t.ErrorHandler=class{static errors=[];static maxErrors=100;static listeners=[];static handleError(e){(0,n.logError)(`[${e.type}] ${e.code}: ${e.message}`),this.errors.push(e),this.errors.length>this.maxErrors&&(this.errors=this.errors.slice(-this.maxErrors)),this.notifyListeners(e)}static handle(e,t,r,i,o="error"){const a=i?`${r} - ${this.formatError(i)}`:r;switch(o){case"debug":(0,n.log)(`[${e}.${t}] (DEBUG) ${a}`);break;case"warn":(0,n.log)(`[${e}.${t}] (WARN) ${a}`);break;case"info":(0,n.log)(`[${e}.${t}] (INFO) ${a}`);break;default:(0,n.log)(`[${e}.${t}] (ERROR) ${a}`),i&&i instanceof Error&&(0,n.log)(i.stack||"No stack trace available")}const c=s(e,t,a,i);return this.handleError(c),c}static handleAndThrow(e,t,r,n){throw this.handle(e,t,r,n)}static getRecentErrors(e=10){return this.errors.slice(-Math.min(e,this.errors.length))}static addListener(e){this.listeners.push(e)}static removeListener(e){const t=this.listeners.indexOf(e);-1!==t&&this.listeners.splice(t,1)}static notifyListeners(e){for(const t of this.listeners)try{t(e)}catch(e){(0,n.logError)(`Error in error listener: ${e}`)}}static formatError(e){if(!e)return"Unknown error";if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("object"==typeof e)try{return JSON.stringify(e)}catch(t){return`Object: ${Object.prototype.toString.call(e)}`}return String(e)}static async withRetry(e,t,r,i=3,s=1e3){let o;for(let t=1;t<=i;t++)try{return await e()}catch(e){o=e;const r=s*t;t<i&&((0,n.log)(`Retrying operation after ${r}ms (attempt ${t}/${i})`),await new Promise((e=>setTimeout(e,r))))}throw this.handle(t,r,`Operation failed after ${i} attempts`,o)}static clearErrors(){this.errors=[]}static getErrorStats(){const e={total:this.errors.length,byType:{},byCode:{}};for(const t of this.errors)e.byType[t.type]=(e.byType[t.type]||0)+1,e.byCode[t.code]=(e.byCode[t.code]||0)+1;return e}}},24993:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SEA=t.Gun=void 0;const i=n(r(54827));t.Gun=i.default;const s=n(r(38030));Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return s.default}})},28156:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(197),t),i(r(5307),t)},34586:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BasePlugin=void 0;const n=r(14134);class i extends n.EventEmitter{description;_category;core=null;initialize(e){this.core=e}destroy(){this.core=null}assertInitialized(){if(!this.core)throw new Error(`Plugin ${this.name} not initialized`);return this.core}}t.BasePlugin=i},37510:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Webauthn=void 0;const n=r(14193),i=r(23358),s=r(14134),o=r(45628),a=r(61731),c={rpName:"Shogun Wallet",timeout:6e4,userVerification:"preferred",attestation:"none",authenticatorAttachment:"platform",requireResidentKey:!1};class u extends s.EventEmitter{config;gunInstance;credential;abortController=null;constructor(e,t){super(),this.gunInstance=e,this.credential=null,this.config={...c,...t,rpId:t?.rpId??window.location.hostname.split(":")[0]}}validateUsername(e){if(!e||"string"!=typeof e)throw new Error("Username must be a non-empty string");if(e.length<3||e.length>64)throw new Error("Username must be between 3 and 64 characters");if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error("Username can only contain letters, numbers, underscores and hyphens")}async createAccount(e,t,r=!1){try{this.validateUsername(e);const n=3;let i=null;for(let s=1;s<=n;s++)try{const n=await this.generateCredentials(e,t,r);if(n.success)return this.emit(a.WebAuthnEventType.DEVICE_REGISTERED,{type:a.WebAuthnEventType.DEVICE_REGISTERED,data:{username:e,deviceInfo:n.deviceInfo},timestamp:Date.now()}),n;i=new Error(n.error??"Unknown error")}catch(e){if(i=e,s<n){await new Promise((e=>setTimeout(e,1e3*s)));continue}}throw i||new Error("Failed to create account after retries")}catch(e){throw this.emit(a.WebAuthnEventType.ERROR,{type:a.WebAuthnEventType.ERROR,data:{error:e.message},timestamp:Date.now()}),e}}async authenticateUser(e,t,r={}){try{if(this.validateUsername(e),!t){const e=new Error("No WebAuthn credentials found for this username");return i.ErrorHandler.handle(i.ErrorType.WEBAUTHN,"NO_CREDENTIALS",e.message,e),{success:!1,error:e.message}}this.abortAuthentication(),this.abortController=new AbortController;const n=r.timeout||this.config.timeout,s=setTimeout((()=>this.abortController?.abort()),n);try{const i={challenge:this.generateChallenge(e),allowCredentials:[],timeout:n,userVerification:r.userVerification||this.config.userVerification,rpId:this.config.rpId},s=await navigator.credentials.get({publicKey:i,signal:this.abortController.signal});if(!s)throw new Error("WebAuthn verification failed");const{password:o}=this.generateCredentialsFromSalt(e,t),c=this.getDeviceInfo(s.id),u={success:!0,username:e,password:o,credentialId:this.bufferToBase64(s.rawId),deviceInfo:c};return this.emit(a.WebAuthnEventType.AUTHENTICATION_SUCCESS,{type:a.WebAuthnEventType.AUTHENTICATION_SUCCESS,data:{username:e,deviceInfo:c},timestamp:Date.now()}),u}finally{clearTimeout(s),this.abortController=null}}catch(t){const r=t instanceof Error?t.message:"Unknown WebAuthn error";return this.emit(a.WebAuthnEventType.AUTHENTICATION_FAILED,{type:a.WebAuthnEventType.AUTHENTICATION_FAILED,data:{username:e,error:r},timestamp:Date.now()}),i.ErrorHandler.handle(i.ErrorType.WEBAUTHN,"AUTH_ERROR",r,t),{success:!1,error:r}}}abortAuthentication(){this.abortController&&(this.abortController.abort(),this.abortController=null)}getDeviceInfo(e){const t=this.getPlatformInfo();return{deviceId:e,timestamp:Date.now(),name:t.name,platform:t.platform,lastUsed:Date.now()}}getPlatformInfo(){if("undefined"==typeof navigator)return{name:"unknown",platform:"unknown"};const e=navigator.platform,t=navigator.userAgent;return/iPhone|iPad|iPod/.test(e)?{name:"iOS Device",platform:e}:/Android/.test(t)?{name:"Android Device",platform:e}:/Win/.test(e)?{name:"Windows Device",platform:e}:/Mac/.test(e)?{name:"Mac Device",platform:e}:/Linux/.test(e)?{name:"Linux Device",platform:e}:{name:"Unknown Device",platform:e}}generateChallenge(e){const t=Date.now().toString(),r=this.getRandomBytes(32),n=`${e}-${t}-${this.uint8ArrayToHex(r)}`;return(new TextEncoder).encode(n)}getRandomBytes(e){if("undefined"!=typeof window&&window.crypto)return window.crypto.getRandomValues(new Uint8Array(e));throw new Error("No cryptographic implementation available")}uint8ArrayToHex(e){return Array.from(e).map((e=>e.toString(16).padStart(2,"0"))).join("")}bufferToBase64(e){const t=new Uint8Array(e).reduce(((e,t)=>e+String.fromCharCode(t)),"");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}generateCredentialsFromSalt(e,t){const r=n.ethers.toUtf8Bytes(e+t);return{password:n.ethers.sha256(r)}}isSupported(){return"undefined"!=typeof window&&void 0!==window.PublicKeyCredential}async createCredential(e){try{const t=crypto.getRandomValues(new Uint8Array(32)),r=(new TextEncoder).encode(e),n={challenge:t,rp:{name:"Shogun Wallet",..."localhost"!==this.config.rpId&&{id:this.config.rpId}},user:{id:r,name:e,displayName:e},pubKeyCredParams:[{type:"public-key",alg:-7}],timeout:this.config.timeout,attestation:this.config.attestation,authenticatorSelection:{authenticatorAttachment:this.config.authenticatorAttachment,userVerification:this.config.userVerification,requireResidentKey:this.config.requireResidentKey}};(0,o.logDebug)("Attempting to create credentials with options:",n);const i=await navigator.credentials.create({publicKey:n});if(!i)throw new Error("Credential creation failed");(0,o.logDebug)("Credentials created successfully:",i);const s=i,a={id:s.id,rawId:s.rawId,type:s.type,response:{clientDataJSON:s.response.clientDataJSON},getClientExtensionResults:s.getClientExtensionResults};return"attestationObject"in s.response&&(a.response.attestationObject=s.response.attestationObject),this.credential=a,a}catch(e){(0,o.logError)("Detailed error in credential creation:",e);const t=e instanceof Error?e.message:"Unknown error";throw new Error(`Error creating credentials: ${t}`)}}async generateCredentials(e,t,r=!1){try{if(r){const t=await this.verifyCredential(e);return{success:t.success,error:t.error,credentialId:t.credentialId,username:t.username}}{const t=await this.createCredential(e),r=t.id;let n=null;return t?.response?.getPublicKey&&(n=t.response.getPublicKey()),{success:!0,credentialId:r,publicKey:n}}}catch(e){(0,o.logError)("Error in generateCredentials:",e);return{success:!1,error:e instanceof Error?e.message:"Unknown error during WebAuthn operation"}}}async verifyCredential(e){try{const t={challenge:crypto.getRandomValues(new Uint8Array(32)),timeout:this.config.timeout,userVerification:this.config.userVerification,..."localhost"!==this.config.rpId&&{rpId:this.config.rpId}};this.credential?.rawId&&(t.allowCredentials=[{id:this.credential.rawId,type:"public-key"}]);const r=await navigator.credentials.get({publicKey:t});return r?{success:!0,credentialId:r.id,username:e}:{success:!1,error:"Credential verification failed"}}catch(e){(0,o.logError)("Error verifying credentials:",e);return{success:!1,error:e instanceof Error?e.message:"Unknown error verifying credentials"}}}async removeDevice(e,t,r){if(!r||!r.credentials||!r.credentials[t])return{success:!1};const n={...r};return n.credentials&&delete n.credentials[t],{success:!0,updatedCredentials:n}}async sign(e){return await navigator.credentials.get({publicKey:{challenge:new Uint8Array(16),rpId:this.config.rpId}})}}t.Webauthn=u,"undefined"!=typeof window?window.Webauthn=u:void 0!==r.g&&(r.g.Webauthn=u)},37897:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NostrConnector=void 0;const n=r(45628),i=r(23358),s=r(14134);class o extends s.EventEmitter{MESSAGE_TO_SIGN="I Love Shogun!";DEFAULT_CONFIG={cacheDuration:864e5,maxRetries:3,retryDelay:1e3,timeout:6e4,network:"mainnet",useApi:!1};config;signatureCache=new Map;connectedAddress=null;connectedType=null;manualKeyPair=null;constructor(e={}){super(),this.config={...this.DEFAULT_CONFIG,...e},this.setupEventListeners()}setupEventListeners(){}cleanup(){this.removeAllListeners(),this.connectedAddress=null,this.connectedType=null,this.manualKeyPair=null}getCachedSignature(e){const t=this.signatureCache.get(e);if(t){if(Date.now()-t.timestamp<=this.config.cacheDuration)return t.signature;this.signatureCache.delete(e)}try{const t=`shogun_bitcoin_sig_${e}`,r=localStorage.getItem(t);if(r){const n=JSON.parse(r);if(Date.now()-n.timestamp<=this.config.cacheDuration)return this.signatureCache.set(e,n),n.signature;localStorage.removeItem(t)}}catch(e){(0,n.logError)("Error reading signature cache from localStorage:",e)}return null}cacheSignature(e,t){const r={signature:t,timestamp:Date.now(),address:e};this.signatureCache.set(e,r);try{const t=`shogun_bitcoin_sig_${e}`;localStorage.setItem(t,JSON.stringify(r)),(0,n.log)(`Cached signature for address: ${e.substring(0,10)}...`)}catch(e){(0,n.logError)("Error saving signature cache to localStorage:",e)}}clearSignatureCache(e){if(e){this.signatureCache.delete(e);try{const t=`shogun_bitcoin_sig_${e}`;localStorage.removeItem(t),(0,n.log)(`Cleared signature cache for address: ${e.substring(0,10)}...`)}catch(e){(0,n.logError)("Error clearing signature cache from localStorage:",e)}}else{this.signatureCache.clear();try{const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);r&&r.startsWith("shogun_bitcoin_sig_")&&e.push(r)}e.forEach((e=>localStorage.removeItem(e))),(0,n.log)(`Cleared all signature caches (${e.length} entries)`)}catch(e){(0,n.logError)("Error clearing all signature caches from localStorage:",e)}}}validateAddress(e){if(!e)throw new Error("Address not provided");try{const t=String(e).trim();if("nostr"===this.connectedType){if(!t)throw new Error("Empty Nostr public key")}else if("manual"===this.connectedType){if(!t)throw new Error("Empty manual key")}else if(!/^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,59}$/.test(t))throw new Error("Invalid Bitcoin address format");return t}catch(e){throw i.ErrorHandler.handle(i.ErrorType.VALIDATION,"INVALID_ADDRESS","Invalid Bitcoin address provided",e),e}}isNostrExtensionAvailable(){return"undefined"!=typeof window&&!!window.nostr}isAvailable(){return this.isNostrExtensionAvailable()||null!==this.manualKeyPair}async connectWallet(e="nostr"){(0,n.log)(`Connecting to Bitcoin wallet via ${e}...`);try{let t;switch(e){case"alby":(0,n.log)("Alby is deprecated, redirecting to Nostr"),t=await this.connectNostr();break;case"nostr":t=await this.connectNostr();break;case"manual":t=await this.connectManual();break;default:throw new Error(`Unsupported wallet type: ${e}`)}return t.success&&t.address&&(this.connectedAddress=t.address,this.connectedType=e,(0,n.log)(`Successfully connected to ${e} wallet: ${t.address}`),this.emit("wallet_connected",{address:t.address,type:this.connectedType})),t}catch(t){return(0,n.logError)(`Error connecting to ${e} wallet:`,t),{success:!1,error:t.message||"Failed to connect to wallet"}}}async connectNostr(){if(!this.isNostrExtensionAvailable())return{success:!1,error:"Nostr extension is not available. Please install a Nostr compatible extension."};try{const e=await window.nostr.getPublicKey();if(!e)throw new Error("Could not get public key from Nostr extension");this.connectedAddress=e,this.connectedType="nostr",this.emit("connected",{address:e,type:"nostr"});const t=`nostr_${e.substring(0,10)}`;return{success:!0,address:e,username:t,extensionType:"nostr"}}catch(e){throw new Error(`Nostr connection error: ${e.message}`)}}async connectManual(){if(!this.manualKeyPair)return{success:!1,error:"No manual key pair configured. Use setKeyPair() first."};this.connectedAddress=this.manualKeyPair.address,this.connectedType="manual",this.emit("connected",{address:this.manualKeyPair.address,type:"manual"});const e=`btc_${this.manualKeyPair.address.substring(0,10)}`;return{success:!0,address:this.manualKeyPair.address,username:e,extensionType:"manual"}}setKeyPair(e){this.manualKeyPair=e,e.address&&(this.connectedAddress=e.address,this.connectedType="manual")}async generateCredentials(e){(0,n.logDebug)(`Generating credentials for address: ${e}`);try{!this.connectedType&&e&&(/^[0-9a-f]{64}$/.test(e)||e.startsWith("npub"))&&(this.connectedType="nostr",this.connectedAddress=e);const t=this.validateAddress(e),r=this.getCachedSignature(t);if(r)return(0,n.logDebug)("Using cached signature"),await this.generateCredentialsFromSignature(t,r);const i=this.MESSAGE_TO_SIGN;let s;try{return s=await this.generateDeterministicSignature(t),(0,n.log)("Using deterministic signature for consistency"),this.cacheSignature(t,s),await this.generateCredentialsFromSignature(t,s)}catch(e){(0,n.logError)("Error generating deterministic signature:",e);try{s=await this.requestSignatureWithTimeout(t,i,this.config.timeout),this.cacheSignature(t,s),(0,n.log)("Using real Nostr signature as fallback")}catch(e){(0,n.logError)("Error requesting signature:",e),s=await this.generateDeterministicSignature(t),this.cacheSignature(t,s),(0,n.log)("Using deterministic signature as final fallback")}}return await this.generateCredentialsFromSignature(t,s)}catch(e){throw(0,n.logError)("Error generating credentials:",e),e}}async generateDeterministicSignature(e){const t=`${e}_${this.MESSAGE_TO_SIGN}_shogun_deterministic`;let r="",i=0;for(let e=0;e<t.length;e++){i=31*i+t.charCodeAt(e)&4294967295,e%4==3&&(r+=i.toString(16).padStart(8,"0"))}for(;r.length<128;)i=31*i+r.length&4294967295,r+=i.toString(16).padStart(8,"0");let s=r.substring(0,128);return s=s.toLowerCase().replace(/[^0-9a-f]/g,"0"),s.length<128?s=s.padEnd(128,"0"):s.length>128&&(s=s.substring(0,128)),(0,n.log)(`Generated deterministic signature: ${s.substring(0,16)}... (${s.length} chars)`),s}async generateCredentialsFromSignature(e,t){(0,n.log)("Generating credentials from signature");return{username:`${e.toLowerCase()}`,password:await this.generatePassword(t),message:this.MESSAGE_TO_SIGN,signature:t}}async generatePassword(e){if(!e)throw new Error("Invalid signature");try{const t=e.toLowerCase().replace(/[^a-f0-9]/g,"");let r="",n=0;for(let e=0;e<t.length;e++){n=31*n+t.charCodeAt(e)&4294967295,e%8==7&&(r+=n.toString(16).padStart(8,"0"))}for(;r.length<64;)n=31*n+r.length&4294967295,r+=n.toString(16).padStart(8,"0");return r.substring(0,64)}catch(e){throw(0,n.logError)("Error generating password:",e),new Error("Failed to generate password from signature")}}async verifySignature(e,t,r){try{const i="object"==typeof r?r.address||JSON.stringify(r):String(r);if((0,n.log)(`Verifying signature for address: ${i}`),!t||!e)return(0,n.logError)("Invalid message or signature for verification"),!1;if((0,n.log)(`Signature to verify: ${t.substring(0,20)}... (length: ${t.length})`),(0,n.log)(`Message to verify: ${e}`),"nostr"===this.connectedType||"alby"===this.connectedType){(0,n.log)("Using Nostr-specific verification");try{if(!this.connectedAddress)return(0,n.logError)("No connected address to verify against"),!1;const e=String(this.connectedAddress).toLowerCase(),r=i.toLowerCase();if(r!==e)return(0,n.logError)("Address mismatch in signature verification"),(0,n.logError)(`Expected: ${e}, Got: ${r}`),!1;const s=/^[0-9a-f]+$/i.test(t),o=t.length>=64;return(0,n.log)(`Signature format check: hex=${s}, length=${o} (${t.length} chars)`),s?o?((0,n.log)("Nostr signature appears valid"),!0):((0,n.logError)(`Invalid signature length: ${t.length} (minimum 64 required)`),!1):((0,n.logError)("Invalid signature format - not a valid hex string"),(0,n.logError)(`Signature contains invalid characters: ${t}`),!1)}catch(e){return(0,n.logError)("Error in signature verification:",e),!1}}else if("manual"===this.connectedType&&this.manualKeyPair){(0,n.log)("Using manual verification for keypair");try{const e=String(this.manualKeyPair.address).toLowerCase(),t=i.toLowerCase()===e;return(0,n.log)(`Manual verification - address match: ${t}`),t}catch(e){return(0,n.logError)("Error in manual signature verification:",e),!1}}if(this.config.useApi&&this.config.apiUrl){(0,n.log)("Using API-based verification");try{return!0}catch(e){return(0,n.logError)("API verification error:",e),!1}}return(0,n.logWarn)("No specific verification method available, signature cannot be fully verified"),!1}catch(e){return(0,n.logError)("Error verifying signature:",e),!1}}getConnectedAddress(){return this.connectedAddress}getConnectedType(){return this.connectedType}requestSignatureWithTimeout(e,t,r=3e4){return new Promise(((n,i)=>{const s=setTimeout((()=>{i(new Error("Signature request timed out"))}),r);this.requestSignature(e,t).then((e=>{clearTimeout(s),n(e)})).catch((e=>{clearTimeout(s),i(e)}))}))}async requestSignature(e,t){if(!this.connectedType)throw new Error("No wallet connected");try{switch(this.connectedType){case"alby":if((0,n.logWarn)("Alby is deprecated, redirecting signature request to Nostr"),!window.nostr)throw new Error("Nostr extension not available");const r={kind:1,created_at:Math.floor(Date.now()/1e3),tags:[],content:t,pubkey:e};return(await window.nostr.signEvent(r)).sig;case"nostr":(0,n.log)("Requesting Nostr signature for message:",t);const i={kind:1,created_at:Math.floor(Date.now()/1e3),tags:[],content:t,pubkey:e},s=await window.nostr.signEvent(i);(0,n.log)("Received Nostr signature:",s.sig.substring(0,20)+"...");let o=s.sig;return o&&"string"==typeof o&&(o=o.replace(/[^a-f0-9]/gi,"").toLowerCase(),o.length>128?o=o.substring(0,128):o.length<128&&(o=o.padStart(128,"0")),(0,n.log)(`Normalized Nostr signature: ${o.substring(0,10)}...`)),o;case"manual":if((0,n.log)("Using manual key pair for signature"),!this.manualKeyPair)throw new Error("No manual key pair available");const a=`${this.manualKeyPair.privateKey.substring(0,32)}_${t}_${Date.now()}`;return(0,n.log)("Generated manual signature:",a.substring(0,20)+"..."),a;default:throw new Error(`Unsupported wallet type: ${this.connectedType}`)}}catch(e){throw(0,n.logError)("Error requesting signature:",e),new Error(`Failed to get signature: ${e.message}`)}}}t.NostrConnector=o,"undefined"!=typeof window?window.NostrConnector=o:void 0!==r.g&&(r.g.NostrConnector=o)},38664:()=>{},43188:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WebAuthnSigner=void 0;const i=r(37510),s=r(25897),o=r(22623),a=r(45628),c=n(r(67476)),u=r(14193),l=function(e){const t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},g=function(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";const t=atob(e);return new Uint8Array(t.split("").map((e=>e.charCodeAt(0))))};class d{webauthn;credentials=new Map;constructor(e){this.webauthn=e||new i.Webauthn}async createSigningCredential(e){try{const t=await navigator.credentials.create({publicKey:{challenge:crypto.getRandomValues(new Uint8Array(32)),rp:{id:"localhost"===window.location.hostname?"localhost":window.location.hostname,name:"Shogun Wallet"},user:{id:(new TextEncoder).encode(e),name:e,displayName:e},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-25},{type:"public-key",alg:-257}],authenticatorSelection:{userVerification:"preferred"},timeout:6e4,attestation:"none"}});if(!t)throw new Error("Failed to create WebAuthn credential");const r=t.response.getPublicKey();if(!r)throw new Error("Failed to get public key from credential");const n=new Uint8Array(r);(0,a.logDebug)("Raw public key bytes:",n);const i=n.slice(27,59),s=n.slice(59,91),o=l(i),c=l(s),g=`${o}.${c}`,d=u.ethers.keccak256(u.ethers.toUtf8Bytes(t.id)),h={id:t.id,rawId:t.rawId,publicKey:{x:o,y:c},pub:g,hashedCredentialId:d};return this.credentials.set(t.id,h),(0,a.logDebug)("Created signing credential:",h),h}catch(e){throw(0,a.logError)("Error creating signing credential:",e),new Error(`Failed to create signing credential: ${e.message}`)}}createAuthenticator(e){const t=this.credentials.get(e);if(!t)throw new Error(`Credential ${e} not found`);return async e=>{try{const r={challenge:(new TextEncoder).encode(JSON.stringify(e)),rpId:"localhost"===window.location.hostname?"localhost":window.location.hostname,userVerification:"preferred",allowCredentials:[{type:"public-key",id:t.rawId}],timeout:6e4},n=await navigator.credentials.get({publicKey:r});if(!n)throw new Error("WebAuthn assertion failed");return(0,a.logDebug)("WebAuthn assertion successful:",{options:r,assertion:n}),n.response}catch(e){throw(0,a.logError)("WebAuthn assertion error:",e),e}}}async createDerivedKeyPair(e,t,r){const n=this.credentials.get(e);if(!n)throw new Error(`Credential ${e} not found`);try{const e=await(0,c.default)(n.hashedCredentialId,r,{includeP256:!0});return{pub:e.pub,priv:e.priv,epub:e.epub,epriv:e.epriv}}catch(e){throw(0,a.logError)("Error deriving keys from WebAuthn credential:",e),e}}async createGunUser(e,t,r){const n=this.credentials.get(e);if(!n)throw new Error(`Credential ${e} not found`);try{return new Promise((i=>{r.user().create(t,n.hashedCredentialId,(s=>{s.err?r.user().auth(t,n.hashedCredentialId,(t=>{if(t.err)i({success:!1,error:t.err});else{const r=t.pub;n.gunUserPub=r,this.credentials.set(e,n),i({success:!0,userPub:r})}})):r.user().auth(t,n.hashedCredentialId,(t=>{if(t.err)i({success:!1,error:t.err});else{const r=t.pub;n.gunUserPub=r,this.credentials.set(e,n),i({success:!0,userPub:r})}}))}))}))}catch(e){return(0,a.logError)("Error creating Gun user:",e),{success:!1,error:e.message}}}async signWithDerivedKeys(e,t,r,n){try{const i=this.createAuthenticator(t);await i(e);const a=await this.createDerivedKeyPair(t,r,n),c=JSON.stringify(e),u=(0,o.sha256)((new TextEncoder).encode(c)),d=g(a.priv),h=s.p256.sign(u,d),f={m:c,s:l(h.toCompactRawBytes())};return"SEA"+JSON.stringify(f)}catch(e){throw(0,a.logError)("Error signing with derived keys:",e),e}}getGunUserPub(e){const t=this.credentials.get(e);return t?.gunUserPub}getHashedCredentialId(e){const t=this.credentials.get(e);return t?.hashedCredentialId}async verifyConsistency(e,t,r){if(!this.credentials.get(e))return{consistent:!1};const n=await this.createDerivedKeyPair(e,t);return{consistent:!r||n.pub===r,actualUserPub:n.pub,expectedUserPub:r}}getCredential(e){return this.credentials.get(e)}listCredentials(){return Array.from(this.credentials.values())}removeCredential(e){return this.credentials.delete(e)}}t.WebAuthnSigner=d,t.default=d},45628:(e,t,r)=>{"use strict";var n=r(65606);Object.defineProperty(t,"__esModule",{value:!0}),t.enableDebug=function(){s=!0,o("Debug mode enabled")},t.disableDebug=function(){s=!1},t.configureLogging=function(e){i={...i,...e}},t.log=o,t.logError=a,t.logWarn=c,t.logDebug=u,t.logWithLevel=function(e,t,...r){switch(e){case"error":a(t,...r);break;case"warn":c(t,...r);break;case"debug":u(t,...r);break;default:o(t,...r)}};let i={enabled:"true"===n.env.DEBUG,level:"info",prefix:"[ShogunSDK]"},s=!1;function o(e,...t){(new Date).toISOString()}function a(e,...t){(new Date).toISOString()}function c(e,...t){(new Date).toISOString()}function u(e,...t){if(!s)return;(new Date).toISOString()}},47790:()=>{},48050:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NostrConnectorPlugin=void 0;const n=r(34586),i=r(37897),s=r(70050),o=r(45628),a=r(23358);class c extends n.BasePlugin{name="nostr";version="1.0.0";description="Provides Bitcoin wallet connection and authentication for ShogunCore";bitcoinConnector=null;signer=null;initialize(e){super.initialize(e),this.bitcoinConnector=new i.NostrConnector,this.signer=new s.NostrSigner(this.bitcoinConnector),(0,o.log)("Bitcoin wallet plugin initialized with signer support")}destroy(){this.bitcoinConnector&&this.bitcoinConnector.cleanup(),this.bitcoinConnector=null,this.signer=null,super.destroy(),(0,o.log)("Bitcoin wallet plugin destroyed")}assertBitcoinConnector(){if(this.assertInitialized(),!this.bitcoinConnector)throw new Error("Bitcoin wallet module not initialized");return this.bitcoinConnector}assertSigner(){if(this.assertInitialized(),!this.signer)throw new Error("Nostr signer not initialized");return this.signer}isAvailable(){return this.assertBitcoinConnector().isAvailable()}isAlbyAvailable(){return(0,o.log)("Alby is deprecated, using Nostr instead"),this.isNostrExtensionAvailable()}isNostrExtensionAvailable(){return this.assertBitcoinConnector().isNostrExtensionAvailable()}async connectBitcoinWallet(e="nostr"){return"alby"===e&&((0,o.log)("Alby is deprecated, using Nostr instead"),e="nostr"),this.assertBitcoinConnector().connectWallet(e)}async generateCredentials(e){return(0,o.log)("Calling credential generation for Bitcoin wallet"),this.assertBitcoinConnector().generateCredentials(e)}cleanup(){this.assertBitcoinConnector().cleanup()}clearSignatureCache(e){this.assertBitcoinConnector().clearSignatureCache(e)}async verifySignature(e,t,r){return this.assertBitcoinConnector().verifySignature(e,t,r)}async generatePassword(e){return this.assertBitcoinConnector().generatePassword(e)}async createSigningCredential(e){try{return(0,o.log)(`Creating Nostr signing credential for address: ${e}`),await this.assertSigner().createSigningCredential(e)}catch(e){throw(0,o.logError)(`Error creating Nostr signing credential: ${e.message}`),e}}createAuthenticator(e){try{return(0,o.log)(`Creating Nostr authenticator for address: ${e}`),this.assertSigner().createAuthenticator(e)}catch(e){throw(0,o.logError)(`Error creating Nostr authenticator: ${e.message}`),e}}async createDerivedKeyPair(e,t){try{return(0,o.log)(`Creating derived key pair for address: ${e}`),await this.assertSigner().createDerivedKeyPair(e,t)}catch(e){throw(0,o.logError)(`Error creating derived key pair: ${e.message}`),e}}async signWithDerivedKeys(e,t,r){try{return(0,o.log)(`Signing data with derived keys for address: ${t}`),await this.assertSigner().signWithDerivedKeys(e,t,r)}catch(e){throw(0,o.logError)(`Error signing with derived keys: ${e.message}`),e}}getSigningCredential(e){return this.assertSigner().getCredential(e)}listSigningCredentials(){return this.assertSigner().listCredentials()}removeSigningCredential(e){return this.assertSigner().removeCredential(e)}async createGunUserFromSigningCredential(e){try{const t=this.assertInitialized();return(0,o.log)(`Creating Gun user from Nostr signing credential: ${e}`),await this.assertSigner().createGunUser(e,t.gun)}catch(e){throw(0,o.logError)(`Error creating Gun user from Nostr signing credential: ${e.message}`),e}}getGunUserPubFromSigningCredential(e){return this.assertSigner().getGunUserPub(e)}getPassword(e){return this.assertSigner().getPassword(e)}async verifyConsistency(e,t){try{return(0,o.log)(`Verifying Nostr consistency for address: ${e}`),await this.assertSigner().verifyConsistency(e,t)}catch(e){return(0,o.logError)(`Error verifying Nostr consistency: ${e.message}`),{consistent:!1}}}async setupConsistentOneshotSigning(e){try{(0,o.log)(`Setting up consistent Nostr oneshot signing for: ${e}`);const t=await this.createSigningCredential(e),r=this.createAuthenticator(e);return{credential:t,authenticator:r,gunUser:await this.createGunUserFromSigningCredential(e),username:t.username,password:t.password}}catch(e){throw(0,o.logError)(`Error setting up consistent Nostr oneshot signing: ${e.message}`),e}}async login(e){(0,o.log)("Login with Bitcoin wallet");try{const t=this.assertInitialized();if((0,o.log)(`Bitcoin wallet login attempt for address: ${e}`),!e)throw(0,a.createError)(a.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Bitcoin address required for login");if(!this.isAvailable())throw(0,a.createError)(a.ErrorType.ENVIRONMENT,"BITCOIN_WALLET_UNAVAILABLE","No Bitcoin wallet available in the browser");(0,o.log)("Generating credentials for Bitcoin wallet login...");const r=await this.generateCredentials(e);if(!(r?.username&&r?.password&&r.signature&&r.message))throw(0,a.createError)(a.ErrorType.AUTHENTICATION,"CREDENTIAL_GENERATION_FAILED","Bitcoin wallet credentials not generated correctly or signature missing");(0,o.log)(`Credentials generated successfully. Username: ${r.username}`),(0,o.log)("Verifying Bitcoin wallet signature...");if(!await this.verifySignature(r.message,r.signature,e))throw(0,o.logError)(`Signature verification failed for address: ${e}`),(0,a.createError)(a.ErrorType.SECURITY,"SIGNATURE_VERIFICATION_FAILED","Bitcoin wallet signature verification failed");(0,o.log)("Bitcoin wallet signature verified successfully."),t.setAuthMethod("nostr"),(0,o.log)("Logging in using core login method...");const n=await t.login(r.username,r.password);if(!n.success)throw(0,a.createError)(a.ErrorType.AUTHENTICATION,"BITCOIN_LOGIN_FAILED",n.error||"Failed to log in with Bitcoin credentials");return t.emit("auth:login",{userPub:n.userPub,username:r.username,method:"bitcoin"}),n}catch(e){const t=e?.type||a.ErrorType.AUTHENTICATION,r=e?.code||"BITCOIN_LOGIN_ERROR",n=e?.message||"Unknown error during Bitcoin wallet login";return{success:!1,error:a.ErrorHandler.handle(t,r,n,e).message}}}async signUp(e){(0,o.log)("Sign up with Bitcoin wallet");try{const t=this.assertInitialized();if((0,o.log)(`Bitcoin wallet signup attempt for address: ${e}`),!e)throw(0,a.createError)(a.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Bitcoin address required for signup");if(!this.isAvailable())throw(0,a.createError)(a.ErrorType.ENVIRONMENT,"BITCOIN_WALLET_UNAVAILABLE","No Bitcoin wallet available in the browser");(0,o.log)("Generating credentials for Bitcoin wallet signup...");const r=await this.generateCredentials(e);if(!(r?.username&&r?.password&&r.signature&&r.message))throw(0,a.createError)(a.ErrorType.AUTHENTICATION,"CREDENTIAL_GENERATION_FAILED","Bitcoin wallet credentials not generated correctly or signature missing");(0,o.log)(`Credentials generated successfully. Username: ${r.username}`),(0,o.log)("Verifying Bitcoin wallet signature...");if(!await this.verifySignature(r.message,r.signature,e))throw(0,o.logError)(`Signature verification failed for address: ${e}`),(0,a.createError)(a.ErrorType.SECURITY,"SIGNATURE_VERIFICATION_FAILED","Bitcoin wallet signature verification failed");(0,o.log)("Bitcoin wallet signature verified successfully."),t.setAuthMethod("nostr"),(0,o.log)("Signing up using core signUp method...");const n=await t.signUp(r.username,r.password);if(!n.success){if(n.error&&(n.error.includes("User already created")||n.error.includes("already created")||n.error.includes("già creato")))return{success:!1,error:"User already exists. Please try logging in instead. If login fails, try clearing the signature cache and registering again."};throw(0,a.createError)(a.ErrorType.AUTHENTICATION,"BITCOIN_SIGNUP_FAILED",n.error||"Failed to sign up with Bitcoin credentials")}return t.emit("auth:signup",{userPub:n.userPub,username:r.username,method:"bitcoin"}),n}catch(e){const t=e?.type||a.ErrorType.AUTHENTICATION,r=e?.code||"BITCOIN_SIGNUP_ERROR",n=e?.message||"Unknown error during Bitcoin wallet signup";return{success:!1,error:a.ErrorHandler.handle(t,r,n,e).message}}}async loginWithBitcoinWallet(e){return this.login(e)}async signUpWithBitcoinWallet(e){return this.signUp(e)}}t.NostrConnectorPlugin=c},48089:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Web3Connector=void 0;const n=r(14193),i=r(45628),s=r(23358),o=r(14134);class a extends o.EventEmitter{MESSAGE_TO_SIGN="I Love Shogun!";DEFAULT_CONFIG={cacheDuration:18e5,maxRetries:3,retryDelay:1e3,timeout:6e4};config;signatureCache=new Map;provider=null;customProvider=null;customWallet=null;constructor(e={}){super(),this.config={...this.DEFAULT_CONFIG,...e},this.initProvider(),this.setupEventListeners()}initProvider(){if("undefined"!=typeof window)try{const e=this.getAvailableEthereumProvider();e?(this.provider=new n.ethers.BrowserProvider(e),(0,i.logDebug)("BrowserProvider initialized successfully")):(0,i.logWarn)("No compatible Ethereum provider found")}catch(e){(0,i.logError)("Failed to initialize BrowserProvider",e)}else(0,i.logWarn)("Window object not available (non-browser environment)")}getAvailableEthereumProvider(){if("undefined"==typeof window)return;const e=[{source:()=>window._ethereumProviders&&window._ethereumProviders[0],name:"Registry Primary"},{source:()=>window.ethereum,name:"Standard ethereum"},{source:()=>window.web3?.currentProvider,name:"Legacy web3"},{source:()=>window.metamask,name:"MetaMask specific"},{source:()=>window.ethereum?.providers?.find((e=>e.isMetaMask)),name:"MetaMask from providers array"},{source:()=>window.ethereum?.providers?.[0],name:"First provider in array"},{source:()=>window.enkrypt?.providers?.ethereum,name:"Enkrypt"},{source:()=>window.coinbaseWalletExtension,name:"Coinbase"},{source:()=>window.trustWallet,name:"Trust Wallet"},{source:()=>Array.isArray(window._ethereumProviders)?window._ethereumProviders.find((e=>!e._isProxy)):void 0,name:"Registry non-proxy"}];for(const{source:t,name:r}of e)try{const e=t();if(e&&"function"==typeof e.request)return(0,i.logDebug)(`Found compatible Ethereum provider: ${r}`),e}catch(e){(0,i.logWarn)(`Error checking provider ${r}:`,e);continue}(0,i.logWarn)("No compatible Ethereum provider found")}async setupProvider(){try{if("undefined"!=typeof window){const e=this.getAvailableEthereumProvider();e?(this.provider=new n.ethers.BrowserProvider(e),(0,i.logDebug)("BrowserProvider initialized successfully")):(0,i.logWarn)("No compatible Ethereum provider found")}else(0,i.logWarn)("Window object not available (non-browser environment)")}catch(e){(0,i.logError)("Failed to initialize BrowserProvider",e)}}setupEventListeners(){if(this.provider){this.provider.on("network",((e,t)=>{this.emit("chainChanged",e)}));try{const e=this.getAvailableEthereumProvider();e?.on&&(e.on("accountsChanged",(e=>{this.emit("accountsChanged",e)})),e.on("chainChanged",(e=>{this.emit("chainChanged",{chainId:e})})))}catch(e){(0,i.logWarn)("Failed to setup account change listeners",e)}}}cleanup(){this.provider&&this.provider.removeAllListeners(),this.removeAllListeners()}getCachedSignature(e){const t=this.signatureCache.get(e);if(!t)return null;return Date.now()-t.timestamp>this.config.cacheDuration?(this.signatureCache.delete(e),null):t.signature}cacheSignature(e,t){this.signatureCache.set(e,{signature:t,timestamp:Date.now(),address:e})}validateAddress(e){if(!e)throw new Error("Address not provided");try{const t=String(e).trim().toLowerCase();if(!n.ethers.isAddress(t))throw new Error("Invalid address format");return n.ethers.getAddress(t)}catch(e){throw s.ErrorHandler.handle(s.ErrorType.VALIDATION,"INVALID_ADDRESS","Invalid Ethereum address provided",e),e}}async connectMetaMask(){try{if((0,i.logDebug)("Attempting to connect to MetaMask..."),!this.provider&&((0,i.logDebug)("Provider not initialized, setting up..."),this.initProvider(),!this.provider))throw new Error("MetaMask is not available. Please install MetaMask extension.");const e=this.getAvailableEthereumProvider();if(!e)throw new Error("No compatible Ethereum provider found");(0,i.logDebug)("Requesting account access...");let t=[];try{t=await e.request({method:"eth_requestAccounts"})}catch(r){if((0,i.logWarn)("First account request failed, trying window.ethereum:",r),!window.ethereum||window.ethereum===e)throw new Error("User denied account access");try{t=await window.ethereum.request({method:"eth_requestAccounts"})}catch(e){throw(0,i.logError)("All account request methods failed",e),new Error("User denied account access")}}(0,i.logDebug)(`Accounts requested successfully: ${t.length} accounts returned`),t&&0!==t.length||(0,i.logDebug)("No accounts found, trying to get signer...");for(let e=1;e<=this.config.maxRetries;e++)try{(0,i.logDebug)(`Attempt ${e} to get signer...`);const t=await this.provider.getSigner(),r=await t.getAddress();if(!r){(0,i.logError)("No address returned from signer");continue}return(0,i.logDebug)(`Successfully connected to MetaMask with address: ${r}`),this.emit("connected",{address:r}),{success:!0,address:r,message:"Successfully connected to MetaMask"}}catch(t){if((0,i.logError)(`Attempt ${e} failed:`,t),e===this.config.maxRetries)throw t;await new Promise((e=>setTimeout(e,this.config.retryDelay)))}throw new Error("Failed to connect after retries")}catch(e){return(0,i.logError)("Failed to connect to MetaMask:",e),s.ErrorHandler.handle(s.ErrorType.NETWORK,"METAMASK_CONNECTION_ERROR",e.message??"Unknown error while connecting to MetaMask",e),{success:!1,error:e.message}}}async generateCredentials(e){(0,i.log)("Generating credentials for address:",e);try{const t=this.validateAddress(e);(0,i.log)("Valid Address:",t);const r=this.getCachedSignature(t);if(r)return(0,i.log)("Using cached signature for address:",t),this.generateCredentialsFromSignature(t,r);try{(0,i.log)("Request signature with timeout");const e=await this.requestSignatureWithTimeout(t,this.MESSAGE_TO_SIGN,this.config.timeout);return this.cacheSignature(t,e),this.generateCredentialsFromSignature(t,e)}catch(e){return(0,i.logWarn)(`Failed to get signature: ${e}. Using fallback method.`),this.generateFallbackCredentials(t)}}catch(e){throw s.ErrorHandler.handle(s.ErrorType.AUTHENTICATION,"CREDENTIALS_GENERATION_ERROR",e.message??"Error generating MetaMask credentials",e),e}}generateCredentialsFromSignature(e,t){(0,i.log)("Generating credentials from signature");return{username:`${e.toLowerCase()}`,password:n.ethers.keccak256(n.ethers.toUtf8Bytes(`${t}:${e.toLowerCase()}`)),message:this.MESSAGE_TO_SIGN,signature:t}}generateFallbackCredentials(e){(0,i.logWarn)("Using fallback credentials generation for address:",e);const t=`mm_${e.toLowerCase()}`,r=`SHOGUN_FALLBACK:${e.toLowerCase()}`;return{username:t,password:n.ethers.keccak256(n.ethers.toUtf8Bytes(r)),message:r,signature:n.ethers.keccak256(n.ethers.toUtf8Bytes(r))}}static isMetaMaskAvailable(){if("undefined"==typeof window)return!1;if(!0===window.ethereum?.isMetaMask)return!0;const e=[window.web3?.currentProvider,window.metamask];for(const t of e)if(!0===t?.isMetaMask)return!0;return!1}requestSignatureWithTimeout(e,t,r=3e4){return new Promise(((n,s)=>{let o=setTimeout((()=>{o=null,s(new Error("Timeout requesting signature"))}),r);const a=()=>{o&&(clearTimeout(o),o=null),window.ethereum?.removeListener&&window.ethereum.removeListener("accountsChanged",c)},c=e=>{a(),s(e)};window.ethereum?.on&&window.ethereum.on("accountsChanged",c),(0,i.log)("Initialize and Sign");return(async()=>{try{if(!this.provider&&(this.initProvider(),!this.provider))throw new Error("Provider not initialized");const r=await this.provider.getSigner(),s=await r.getAddress();if((0,i.log)("Signer:",r),(0,i.log)("Signer Address:",s),s.toLowerCase()!==e.toLowerCase())throw new Error(`Signer address (${s}) does not match expected address (${e})`);(0,i.log)(`Requesting signature for message: ${t}`);const o=await r.signMessage(t);(0,i.log)("Signature obtained successfully"),a(),n(o)}catch(e){(0,i.logError)("Failed to request signature:",e),a(),s(e)}})()}))}isAvailable(){return"undefined"!=typeof window&&!!this.getAvailableEthereumProvider()}setCustomProvider(e,t){if(!e||"string"!=typeof e)throw new Error("Invalid RPC URL");if(!t||"string"!=typeof t)throw new Error("Invalid private key");try{this.customProvider=new n.ethers.JsonRpcProvider(e),this.customWallet=new n.ethers.Wallet(t,this.customProvider),(0,i.logDebug)("Custom provider configured successfully")}catch(e){throw new Error(`Error configuring provider: ${e.message??"Unknown error"}`)}}async getSigner(){try{if(this.customWallet)return this.customWallet;if(this.provider||this.initProvider(),!this.provider)throw new Error("Provider not initialized");return await this.provider.getSigner()}catch(e){throw new Error(`Unable to get Ethereum signer: ${e.message||"Unknown error"}`)}}async getProvider(){return this.customProvider?this.customProvider:(this.provider||this.initProvider(),this.provider)}async generatePassword(e){if(!e)throw new Error("Invalid signature");return n.ethers.keccak256(n.ethers.toUtf8Bytes(e)).slice(2,66)}async verifySignature(e,t){if(!e||!t)throw new Error("Invalid message or signature");try{return n.ethers.verifyMessage(e,t)}catch(e){throw new Error("Invalid message or signature")}}async getEthereumSigner(){if(!a.isMetaMaskAvailable())throw new Error("MetaMask not found. Please install MetaMask to continue.");try{const e=window.ethereum;await e.request({method:"eth_requestAccounts"});return new n.ethers.BrowserProvider(e).getSigner()}catch(e){throw new Error(`Error accessing MetaMask: ${e.message??"Unknown error"}`)}}}t.Web3Connector=a,"undefined"!=typeof window?window.Web3Connector=a:void 0!==r.g&&(r.g.Web3Connector=a)},48098:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Web3ConnectorPlugin=void 0;const n=r(34586),i=r(48089),s=r(59666),o=r(45628),a=r(14193),c=r(23358);class u extends n.BasePlugin{name="web3";version="1.0.0";description="Provides Ethereum wallet connection and authentication for ShogunCore";Web3=null;signer=null;initialize(e){super.initialize(e),this.Web3=new i.Web3Connector,this.signer=new s.Web3Signer(this.Web3),(0,o.log)("Web3 plugin initialized with signer support")}destroy(){this.Web3&&this.Web3.cleanup(),this.Web3=null,this.signer=null,super.destroy(),(0,o.log)("Web3 plugin destroyed")}assertMetaMask(){if(this.assertInitialized(),!this.Web3)throw new Error("Web3 module not initialized");return this.Web3}assertSigner(){if(this.assertInitialized(),!this.signer)throw new Error("Web3 signer not initialized");return this.signer}isAvailable(){return this.assertMetaMask().isAvailable()}async connectMetaMask(){return this.assertMetaMask().connectMetaMask()}async generateCredentials(e){return(0,o.log)("Calling credential generation"),this.assertMetaMask().generateCredentials(e)}cleanup(){this.assertMetaMask().cleanup()}setCustomProvider(e,t){this.assertMetaMask().setCustomProvider(e,t)}async getSigner(){return this.assertMetaMask().getSigner()}async getProvider(){return this.assertMetaMask().getProvider()}async generatePassword(e){return this.assertMetaMask().generatePassword(e)}async verifySignature(e,t){return this.assertMetaMask().verifySignature(e,t)}async createSigningCredential(e){try{return(0,o.log)(`Creating Web3 signing credential for address: ${e}`),await this.assertSigner().createSigningCredential(e)}catch(e){throw(0,o.logError)(`Error creating Web3 signing credential: ${e.message}`),e}}createAuthenticator(e){try{return(0,o.log)(`Creating Web3 authenticator for address: ${e}`),this.assertSigner().createAuthenticator(e)}catch(e){throw(0,o.logError)(`Error creating Web3 authenticator: ${e.message}`),e}}async createDerivedKeyPair(e,t){try{return(0,o.log)(`Creating derived key pair for address: ${e}`),await this.assertSigner().createDerivedKeyPair(e,t)}catch(e){throw(0,o.logError)(`Error creating derived key pair: ${e.message}`),e}}async signWithDerivedKeys(e,t,r){try{return(0,o.log)(`Signing data with derived keys for address: ${t}`),await this.assertSigner().signWithDerivedKeys(e,t,r)}catch(e){throw(0,o.logError)(`Error signing with derived keys: ${e.message}`),e}}getSigningCredential(e){return this.assertSigner().getCredential(e)}listSigningCredentials(){return this.assertSigner().listCredentials()}removeSigningCredential(e){return this.assertSigner().removeCredential(e)}async createGunUserFromSigningCredential(e){try{const t=this.assertInitialized();return(0,o.log)(`Creating Gun user from Web3 signing credential: ${e}`),await this.assertSigner().createGunUser(e,t.gun)}catch(e){throw(0,o.logError)(`Error creating Gun user from Web3 signing credential: ${e.message}`),e}}getGunUserPubFromSigningCredential(e){return this.assertSigner().getGunUserPub(e)}getPassword(e){return this.assertSigner().getPassword(e)}async verifyConsistency(e,t){try{return(0,o.log)(`Verifying Web3 consistency for address: ${e}`),await this.assertSigner().verifyConsistency(e,t)}catch(e){return(0,o.logError)(`Error verifying Web3 consistency: ${e.message}`),{consistent:!1}}}async setupConsistentOneshotSigning(e){try{(0,o.log)(`Setting up consistent Web3 oneshot signing for: ${e}`);const t=await this.createSigningCredential(e),r=this.createAuthenticator(e);return{credential:t,authenticator:r,gunUser:await this.createGunUserFromSigningCredential(e),username:t.username,password:t.password}}catch(e){throw(0,o.logError)(`Error setting up consistent Web3 oneshot signing: ${e.message}`),e}}async login(e){(0,o.log)("Login with Web3");try{const t=this.assertInitialized();if((0,o.log)(`Web3 login attempt for address: ${e}`),!e)throw(0,c.createError)(c.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Ethereum address required for Web3 login");if(!this.isAvailable())throw(0,c.createError)(c.ErrorType.ENVIRONMENT,"WEB3_UNAVAILABLE","Web3 is not available in the browser");(0,o.log)("Generating credentials for Web3 login...");const r=await this.generateCredentials(e);if(!(r?.username&&r?.password&&r.signature&&r.message))throw(0,c.createError)(c.ErrorType.AUTHENTICATION,"CREDENTIAL_GENERATION_FAILED","Web3 credentials not generated correctly or signature missing");(0,o.log)(`Credentials generated successfully. Username: ${r.username}`),(0,o.log)("Verifying Web3 signature...");const n=a.ethers.verifyMessage(r.message,r.signature);if(n.toLowerCase()!==e.toLowerCase())throw(0,o.logError)(`Signature verification failed. Expected: ${e}, Got: ${n}`),(0,c.createError)(c.ErrorType.SECURITY,"SIGNATURE_VERIFICATION_FAILED","Web3 signature verification failed. Address mismatch.");(0,o.log)("Web3 signature verified successfully."),t.setAuthMethod("web3"),(0,o.log)("Logging in using core login method...");const i=await t.login(r.username,r.password);if(!i.success)throw(0,c.createError)(c.ErrorType.AUTHENTICATION,"WEB3_LOGIN_FAILED",i.error||"Failed to log in with Web3 credentials");return t.emit("auth:login",{userPub:i.userPub,username:r.username,method:"web3"}),i}catch(e){const t=e?.type||c.ErrorType.AUTHENTICATION,r=e?.code||"WEB3_LOGIN_ERROR",n=e?.message||"Unknown error during Web3 login";return{success:!1,error:c.ErrorHandler.handle(t,r,n,e).message}}}async signUp(e){(0,o.log)("Sign up with Web3");try{const t=this.assertInitialized();if((0,o.log)(`Web3 registration attempt for address: ${e}`),!e)throw(0,c.createError)(c.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Ethereum address required for Web3 registration");if(!this.isAvailable())throw(0,c.createError)(c.ErrorType.ENVIRONMENT,"WEB3_UNAVAILABLE","Web3 is not available in the browser");(0,o.log)("Generating credentials for Web3 registration...");const r=await this.generateCredentials(e);if(!(r?.username&&r?.password&&r.signature&&r.message))throw(0,c.createError)(c.ErrorType.AUTHENTICATION,"CREDENTIAL_GENERATION_FAILED","Web3 credentials not generated correctly or signature missing");(0,o.log)(`Credentials generated successfully. Username: ${r.username}`),(0,o.log)("Verifying Web3 signature...");const n=a.ethers.verifyMessage(r.message,r.signature);if(n.toLowerCase()!==e.toLowerCase())throw(0,o.logError)(`Signature verification failed. Expected: ${e}, Got: ${n}`),(0,c.createError)(c.ErrorType.SECURITY,"SIGNATURE_VERIFICATION_FAILED","Web3 signature verification failed. Address mismatch.");(0,o.log)("Web3 signature verified successfully."),t.setAuthMethod("web3"),(0,o.log)("Signing up using core signUp method...");const i=await t.signUp(r.username,r.password);if(!i.success)throw(0,c.createError)(c.ErrorType.AUTHENTICATION,"WEB3_SIGNUP_FAILED",i.error||"Failed to sign up with Web3 credentials");return t.emit("auth:signup",{userPub:i.userPub,username:r.username,method:"web3"}),i}catch(e){const t=e?.type||c.ErrorType.AUTHENTICATION,r=e?.code||"WEB3_SIGNUP_ERROR",n=e?.message||"Unknown error during Web3 registration";return{success:!1,error:c.ErrorHandler.handle(t,r,n,e).message}}}}t.Web3ConnectorPlugin=u},50074:(e,t)=>{"use strict";var r,n;Object.defineProperty(t,"__esModule",{value:!0}),t.CorePlugins=t.PluginCategory=void 0,function(e){e.Authentication="authentication",e.Wallet="wallet",e.Privacy="privacy",e.Identity="identity",e.Utility="utility"}(r||(t.PluginCategory=r={})),function(e){e.WebAuthn="webauthn",e.Web3="web3",e.Nostr="nostr",e.OAuth="oauth"}(n||(t.CorePlugins=n={}))},50170:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getArrayFromIndexedObject=t.getIndexedObjectFromArray=t.qs=t.getSet=t.getUUID=t.getTargetPub=t.getPub=t.getId=void 0,t.app_scoped=function(e,t){return t.length>0?`${t}-${e}`:e};t.getId=e=>e?._?.["#"];t.getPub=e=>{const t=/~([^@][^\.]+\.[^\.]+)/.exec(e);return t?t[1]:null};t.getTargetPub=e=>{const t=/~[^@][^\.]+\.[^\.]+.*~([^@][^\.]+\.[^\.]+)$/.exec(e);return t?t[1]:null};t.getUUID=e=>e.opt()._.opt.uuid();t.getSet=(e,t)=>{const r=e[t];return r?Object.keys(r).filter((e=>"_"!==e)).map((e=>r[e])).filter((e=>e&&"object"==typeof e&&e["#"])).map((t=>e[t["#"]])).filter(Boolean):[]};t.qs=(e,t="?")=>{const r=Object.fromEntries(Object.entries(e).filter((([e,t])=>t))),n=JSON.stringify(r);return n?`${t}${n}`:""};t.getIndexedObjectFromArray=e=>e.reduce(((e,t)=>({...e,[t.id]:t})),{});t.getArrayFromIndexedObject=e=>Object.values(e)},55736:e=>{function t(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=55736,e.exports=t},58851:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.derive=void 0,i(r(21302),t),i(r(16868),t),i(r(2077),t),i(r(7120),t),i(r(50170),t),i(r(90554),t);var o=r(67476);Object.defineProperty(t,"derive",{enumerable:!0,get:function(){return s(o).default}})},59666:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Web3Signer=void 0;const i=r(48089),s=r(14193),o=r(45628),a=n(r(67476));class c{web3Connector;credentials=new Map;MESSAGE_TO_SIGN="I Love Shogun!";constructor(e){this.web3Connector=e||new i.Web3Connector}async createSigningCredential(e){try{(0,o.logDebug)(`Creating Web3 signing credential for address: ${e}`);const t=s.ethers.getAddress(e.toLowerCase()),r=await this.requestSignature(t),n=`${t.toLowerCase()}`,i=s.ethers.keccak256(s.ethers.toUtf8Bytes(`${r}:${t.toLowerCase()}`)),a={address:t,signature:r,message:this.MESSAGE_TO_SIGN,username:n,password:i};return this.credentials.set(t.toLowerCase(),a),(0,o.logDebug)("Created Web3 signing credential:",a),a}catch(e){throw(0,o.logError)("Error creating Web3 signing credential:",e),new Error(`Failed to create Web3 signing credential: ${e.message}`)}}async requestSignature(e){try{const t=await this.web3Connector.getSigner(),r=await t.getAddress();if(r.toLowerCase()!==e.toLowerCase())throw new Error(`Signer address (${r}) does not match expected address (${e})`);(0,o.logDebug)(`Requesting signature for message: ${this.MESSAGE_TO_SIGN}`);const n=await t.signMessage(this.MESSAGE_TO_SIGN);return(0,o.logDebug)("Signature obtained successfully"),n}catch(e){throw(0,o.logError)("Failed to request signature:",e),e}}createAuthenticator(e){if(!this.credentials.get(e.toLowerCase()))throw new Error(`Credential for address ${e} not found`);return async t=>{try{const r=await this.web3Connector.getSigner();if((await r.getAddress()).toLowerCase()!==e.toLowerCase())throw new Error("Address mismatch during authentication");const n=JSON.stringify(t),i=await r.signMessage(n);return(0,o.logDebug)("Web3 authentication successful:",{data:t,signature:i}),i}catch(e){throw(0,o.logError)("Web3 authentication error:",e),e}}}async createDerivedKeyPair(e,t){const r=this.credentials.get(e.toLowerCase());if(!r)throw new Error(`Credential for address ${e} not found`);try{const e=await(0,a.default)(r.password,t,{includeP256:!0});return{pub:e.pub,priv:e.priv,epub:e.epub,epriv:e.epriv}}catch(e){throw(0,o.logError)("Error deriving keys from Web3 credential:",e),e}}async createGunUser(e,t){const r=this.credentials.get(e.toLowerCase());if(!r)throw new Error(`Credential for address ${e} not found`);try{return new Promise((n=>{t.user().create(r.username,r.password,(i=>{i.err?t.user().auth(r.username,r.password,(t=>{if(t.err)n({success:!1,error:t.err});else{const i=t.pub;r.gunUserPub=i,this.credentials.set(e.toLowerCase(),r),n({success:!0,userPub:i})}})):t.user().auth(r.username,r.password,(t=>{if(t.err)n({success:!1,error:t.err});else{const i=t.pub;r.gunUserPub=i,this.credentials.set(e.toLowerCase(),r),n({success:!0,userPub:i})}}))}))}))}catch(e){return(0,o.logError)("Error creating Gun user:",e),{success:!1,error:e.message}}}async signWithDerivedKeys(e,t,r){try{const n=this.createAuthenticator(t);await n(e);const i=await this.createDerivedKeyPair(t,r),o=JSON.stringify(e),a=(s.ethers.keccak256(s.ethers.toUtf8Bytes(o)),new s.ethers.Wallet(i.priv)),c={m:o,s:await a.signMessage(o)};return"SEA"+JSON.stringify(c)}catch(e){throw(0,o.logError)("Error signing with derived keys:",e),e}}getGunUserPub(e){const t=this.credentials.get(e.toLowerCase());return t?.gunUserPub}getPassword(e){const t=this.credentials.get(e.toLowerCase());return t?.password}async verifyConsistency(e,t){if(!this.credentials.get(e.toLowerCase()))return{consistent:!1};const r=await this.createDerivedKeyPair(e);return{consistent:!t||r.pub===t,actualUserPub:r.pub,expectedUserPub:t}}getCredential(e){return this.credentials.get(e.toLowerCase())}listCredentials(){return Array.from(this.credentials.values())}removeCredential(e){return this.credentials.delete(e.toLowerCase())}}t.Web3Signer=c,t.default=c},61731:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.WebAuthnEventType=void 0,function(e){e.DEVICE_REGISTERED="deviceRegistered",e.DEVICE_REMOVED="deviceRemoved",e.AUTHENTICATION_SUCCESS="authenticationSuccess",e.AUTHENTICATION_FAILED="authenticationFailed",e.ERROR="error"}(r||(t.WebAuthnEventType=r={}))},67476:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,r={}){const s=new TextEncoder,o=e?"string"==typeof e?s.encode(l(e)):e:crypto.getRandomValues(new Uint8Array(32)),a=t?(Array.isArray(t)?t:[t]).map((e=>l(e.toString()))):[],h=s.encode(a.join("|")),w=new Uint8Array(o.length+h.length);if(w.set(o),w.set(h,o.length),w.length<16)throw new Error(`Insufficient input entropy (${w.length})`);const y="v1",m={},{includeP256:E=!0,includeSecp256k1Bitcoin:b=!1,includeSecp256k1Ethereum:v=!1}=r;if(E){const e=[{label:"signing",type:"pub/priv"},{label:"encryption",type:"epub/epriv"}],[t,r]=await Promise.all(e.map((async({label:e})=>{const t=s.encode(`${e}-${y}`),r=await g(w,t);if(!n.p256.utils.isValidPrivateKey(r))throw new Error(`Invalid private key for ${e}`);return{pub:u(n.p256.getPublicKey(r,!1)),priv:c(r)}})));m.pub=t.pub,m.priv=t.priv,m.epub=r.pub,m.epriv=r.priv}if(b){const e=s.encode(`secp256k1-bitcoin-${y}`),t=await g(w,e);if(!i.secp256k1.utils.isValidPrivateKey(t))throw new Error("Invalid secp256k1 private key for Bitcoin");const r=i.secp256k1.getPublicKey(t,!0);m.secp256k1Bitcoin={privateKey:d(t),publicKey:d(r),address:f(r)}}if(v){const e=s.encode(`secp256k1-ethereum-${y}`),t=await g(w,e);if(!i.secp256k1.utils.isValidPrivateKey(t))throw new Error("Invalid secp256k1 private key for Ethereum");const r=i.secp256k1.getPublicKey(t,!1);m.secp256k1Ethereum={privateKey:"0x"+d(t),publicKey:"0x"+d(r),address:p(r)}}return m};const n=r(25897),i=r(8510),s=r(22623),o=r(32955),a=r(93238);function c(e){return btoa(String.fromCharCode(...e)).replace(/\//g,"_").replace(/=/g,"").replace(/\+/g,"-")}function u(e){if(4!==e[0])throw new Error("Invalid uncompressed public key format");return[c(e.slice(1,33)),c(e.slice(33,65))].join(".")}function l(e){return e.normalize("NFC").trim()}async function g(e,t,r=3e5){const n=await crypto.subtle.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},n,256);return new Uint8Array(i)}function d(e){return Array.from(e).map((e=>e.toString(16).padStart(2,"0"))).join("")}const h="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function f(e){const t=(0,s.sha256)(e),r=(0,a.ripemd160)(t),n=new Uint8Array(21);n[0]=0,n.set(r,1);const i=(0,s.sha256)((0,s.sha256)(n)),o=new Uint8Array(25);return o.set(n),o.set(i.slice(0,4),21),function(e){if(0===e.length)return"";let t=0;for(let r=0;r<e.length&&0===e[r];r++)t++;const r=[0];for(let n=t;n<e.length;n++){let t=e[n];for(let e=0;e<r.length;e++)t+=r[e]<<8,r[e]=t%58,t=t/58|0;for(;t>0;)r.push(t%58),t=t/58|0}let n="";for(let e=0;e<t;e++)n+=h[0];for(let e=r.length-1;e>=0;e--)n+=h[r[e]];return n}(o)}function p(e){const t=e.slice(1);return"0x"+d((0,o.keccak_256)(t).slice(-20))}},70050:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.NostrSigner=void 0;const i=r(37897),s=r(45628),o=n(r(67476));class a{nostrConnector;credentials=new Map;MESSAGE_TO_SIGN="I Love Shogun!";constructor(e){this.nostrConnector=e||new i.NostrConnector}async createSigningCredential(e){try{(0,s.logDebug)(`Creating Nostr signing credential for address: ${e}`);const t=this.validateAddress(e),r=await this.generateDeterministicSignature(t),n=`${t.toLowerCase()}`,i=await this.generatePassword(r),o={address:t,signature:r,message:this.MESSAGE_TO_SIGN,username:n,password:i};return this.credentials.set(t.toLowerCase(),o),(0,s.logDebug)("Created Nostr signing credential:",o),o}catch(e){throw(0,s.logError)("Error creating Nostr signing credential:",e),new Error(`Failed to create Nostr signing credential: ${e.message}`)}}validateAddress(e){if(!e)throw new Error("Address not provided");try{const t=String(e).trim();if(!/^(npub1|[0-9a-f]{64}|bc1|[13])[a-zA-HJ-NP-Z0-9]{25,59}$/.test(t)&&t.length<10)throw new Error("Invalid Nostr/Bitcoin address format");return t}catch(e){throw new Error("Invalid Nostr/Bitcoin address provided")}}async generateDeterministicSignature(e){const t=`${e}_${this.MESSAGE_TO_SIGN}_shogun_deterministic`;let r="",n=0;for(let e=0;e<t.length;e++){n=31*n+t.charCodeAt(e)&4294967295,e%4==3&&(r+=n.toString(16).padStart(8,"0"))}for(;r.length<128;)n=31*n+r.length&4294967295,r+=n.toString(16).padStart(8,"0");let i=r.substring(0,128);return i=i.toLowerCase().replace(/[^0-9a-f]/g,"0"),i.length<128?i=i.padEnd(128,"0"):i.length>128&&(i=i.substring(0,128)),(0,s.logDebug)(`Generated deterministic signature: ${i.substring(0,16)}... (${i.length} chars)`),i}async generatePassword(e){if(!e)throw new Error("Invalid signature");try{const t=e.toLowerCase().replace(/[^a-f0-9]/g,"");let r="",n=0;for(let e=0;e<t.length;e++){n=31*n+t.charCodeAt(e)&4294967295,e%8==7&&(r+=n.toString(16).padStart(8,"0"))}for(;r.length<64;)n=31*n+r.length&4294967295,r+=n.toString(16).padStart(8,"0");return r.substring(0,64)}catch(e){throw(0,s.logError)("Error generating password:",e),new Error("Failed to generate password from signature")}}createAuthenticator(e){const t=this.credentials.get(e.toLowerCase());if(!t)throw new Error(`Credential for address ${e} not found`);return async e=>{try{const r=JSON.stringify(e),n=await this.signData(r,t);return(0,s.logDebug)("Nostr authentication successful:",{data:e,signature:n}),n}catch(e){throw(0,s.logError)("Nostr authentication error:",e),e}}}async signData(e,t){const r=`${t.signature}_${e}_${Date.now()}`;return this.generateDeterministicSignature(r)}async createDerivedKeyPair(e,t){const r=this.credentials.get(e.toLowerCase());if(!r)throw new Error(`Credential for address ${e} not found`);try{const e=await(0,o.default)(r.password,t,{includeP256:!0});return{pub:e.pub,priv:e.priv,epub:e.epub,epriv:e.epriv}}catch(e){throw(0,s.logError)("Error deriving keys from Nostr credential:",e),e}}async createGunUser(e,t){const r=this.credentials.get(e.toLowerCase());if(!r)throw new Error(`Credential for address ${e} not found`);try{return new Promise((n=>{t.user().create(r.username,r.password,(i=>{i.err?t.user().auth(r.username,r.password,(t=>{if(t.err)n({success:!1,error:t.err});else{const i=t.pub;r.gunUserPub=i,this.credentials.set(e.toLowerCase(),r),n({success:!0,userPub:i})}})):t.user().auth(r.username,r.password,(t=>{if(t.err)n({success:!1,error:t.err});else{const i=t.pub;r.gunUserPub=i,this.credentials.set(e.toLowerCase(),r),n({success:!0,userPub:i})}}))}))}))}catch(e){return(0,s.logError)("Error creating Gun user:",e),{success:!1,error:e.message}}}async signWithDerivedKeys(e,t,r){try{const n=this.createAuthenticator(t);await n(e);const i=await this.createDerivedKeyPair(t,r),s=JSON.stringify(e),o={m:s,s:await this.generateDeterministicSignature(`${i.priv}_${s}`)};return"SEA"+JSON.stringify(o)}catch(e){throw(0,s.logError)("Error signing with derived keys:",e),e}}getGunUserPub(e){const t=this.credentials.get(e.toLowerCase());return t?.gunUserPub}getPassword(e){const t=this.credentials.get(e.toLowerCase());return t?.password}async verifyConsistency(e,t){if(!this.credentials.get(e.toLowerCase()))return{consistent:!1};const r=await this.createDerivedKeyPair(e);return{consistent:!t||r.pub===t,actualUserPub:r.pub,expectedUserPub:t}}getCredential(e){return this.credentials.get(e.toLowerCase())}listCredentials(){return Array.from(this.credentials.values())}removeCredential(e){return this.credentials.delete(e.toLowerCase())}}t.NostrSigner=a,t.default=a},73776:()=>{},75655:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(59229)),s=r(48089),o=r(59666);t.default=()=>{const e=new s.Web3Connector,t=new o.Web3Signer(e);i.default.chain.web3||(i.default.chain.web3={}),i.default.chain.web3.connect=async function(){return await e.connectMetaMask()},i.default.chain.web3.generateCredentials=async function(t){return await e.generateCredentials(t)},i.default.chain.web3.getSigner=async function(){return await e.getSigner()},i.default.chain.web3.getProvider=async function(){return await e.getProvider()},i.default.chain.web3.signMessage=async function(t){const r=await e.getSigner();return await r.signMessage(t)},i.default.chain.web3.verifySignature=async function(t,r){return await e.verifySignature(t,r)},i.default.chain.web3.isMetaMaskAvailable=function(){return s.Web3Connector.isMetaMaskAvailable()},i.default.chain.web3.setupOneshotSigning=async function(e){return await t.createSigningCredential(e)},i.default.chain.web3.createAuthenticator=function(e){return t.createAuthenticator(e)},i.default.chain.web3.createDerivedKeyPair=async function(e,r){return await t.createDerivedKeyPair(e,r)},i.default.chain.web3.quickSign=async function(e,r,n){return await t.signWithDerivedKeys(e,r,n)},i.default.chain.web3.createGunUserFromSigningCredential=async function(e){return await t.createGunUser(e,this)},i.default.chain.web3.getGunUserPubFromSigningCredential=function(e){return t.getGunUserPub(e)},i.default.chain.web3.getPassword=function(e){return t.getPassword(e)},i.default.chain.web3.verifyConsistency=async function(e,r){return await t.verifyConsistency(e,r)},i.default.chain.web3.setupConsistentOneshotSigning=async function(e){const r=await t.createSigningCredential(e);return{credential:r,authenticator:t.createAuthenticator(e),gunUser:await t.createGunUser(e,this),username:r.username,password:r.password}}}},77909:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(59229)),s=r(37510),o=r(43188);t.default=()=>{const e=new s.Webauthn,t=new o.WebAuthnSigner(e);i.default.chain.webauthn={},i.default.chain.webauthn.isSupported=function(){return e.isSupported()},i.default.chain.webauthn.createAccount=async function(t,r=null,n=!1){return await e.createAccount(t,r,n)},i.default.chain.webauthn.authenticateUser=async function(t,r,n={}){return await e.authenticateUser(t,r,n)},i.default.chain.webauthn.generateCredentials=async function(t,r=null,n=!1){return await e.generateCredentials(t,r,n)},i.default.chain.webauthn.abortAuthentication=function(){return e.abortAuthentication()},i.default.chain.webauthn.removeDevice=async function(t,r,n){return await e.removeDevice(t,r,n)},i.default.chain.webauthn.sign=async function(t){return await e.sign(t)},i.default.chain.webauthn.validateUsername=function(t){return e.validateUsername(t)},i.default.chain.webauthn.createSigningCredential=async function(e){return await t.createSigningCredential(e)},i.default.chain.webauthn.createAuthenticator=function(e){return t.createAuthenticator(e)},i.default.chain.webauthn.createDerivedKeyPair=async function(e,r,n){return await t.createDerivedKeyPair(e,r,n)},i.default.chain.webauthn.signWithDerivedKeys=async function(e,r,n,i){return await t.signWithDerivedKeys(e,r,n,i)},i.default.chain.webauthn.getSigningCredential=function(e){return t.getCredential(e)},i.default.chain.webauthn.listSigningCredentials=function(){return t.listCredentials()},i.default.chain.webauthn.removeSigningCredential=function(e){return t.removeCredential(e)},i.default.chain.webauthn.setupOneshotSigning=async function(e){const r=await t.createSigningCredential(e);return{credential:r,authenticator:t.createAuthenticator(r.id),pub:r.pub}},i.default.chain.webauthn.quickSign=async function(e,r,n,i){return await t.signWithDerivedKeys(e,r,n,i)},i.default.chain.webauthn.createGunUserFromSigningCredential=async function(e,r){return await t.createGunUser(e,r,this)},i.default.chain.webauthn.getGunUserPubFromSigningCredential=function(e){return t.getGunUserPub(e)},i.default.chain.webauthn.getHashedCredentialId=function(e){return t.getHashedCredentialId(e)},i.default.chain.webauthn.verifyConsistency=async function(e,r,n){return await t.verifyConsistency(e,r,n)},i.default.chain.webauthn.setupConsistentOneshotSigning=async function(e){const r=await t.createSigningCredential(e);return{credential:r,authenticator:t.createAuthenticator(r.id),gunUser:await t.createGunUser(r.id,e,this),pub:r.pub,hashedCredentialId:r.hashedCredentialId}}}},78371:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthPlugin=void 0;const n=r(34586),i=r(17665),s=r(45628),o=r(23358);class a extends n.BasePlugin{name="oauth";version="1.0.0";description="Provides OAuth authentication with external providers for ShogunCore";oauthConnector=null;config={};initialize(e){super.initialize(e),this.oauthConnector=new i.OAuthConnector(this.config),(0,s.log)("OAuth plugin initialized successfully")}configure(e){this.config={...this.config,...e},this.oauthConnector&&(this.oauthConnector.updateConfig(this.config),(0,s.log)("OAuth connector configuration updated",this.config.providers))}destroy(){this.oauthConnector&&this.oauthConnector.cleanup(),this.oauthConnector=null,super.destroy(),(0,s.log)("OAuth plugin destroyed")}assertOAuthConnector(){if(this.assertInitialized(),!this.oauthConnector)throw new Error("OAuth connector not initialized");return this.oauthConnector}isSupported(){return this.assertOAuthConnector().isSupported()}getAvailableProviders(){return this.assertOAuthConnector().getAvailableProviders()}async initiateOAuth(e){return(0,s.log)(`Initiating OAuth flow with ${e}`),this.assertOAuthConnector().initiateOAuth(e)}async completeOAuth(e,t,r){return(0,s.log)(`Completing OAuth flow with ${e}`),this.assertOAuthConnector().completeOAuth(e,t,r)}async generateCredentials(e,t){return(0,s.log)(`Generating credentials for ${t} user`),this.assertOAuthConnector().generateCredentials(e,t)}async login(e){(0,s.log)(`OAuth login with ${e}`);try{this.assertInitialized();if((0,s.log)(`OAuth login attempt with provider: ${e}`),!e)throw(0,o.createError)(o.ErrorType.VALIDATION,"PROVIDER_REQUIRED","OAuth provider required for OAuth login");if(!this.isSupported())throw(0,o.createError)(o.ErrorType.ENVIRONMENT,"OAUTH_UNAVAILABLE","OAuth is not supported in this environment");if(!this.getAvailableProviders().includes(e))throw(0,o.createError)(o.ErrorType.VALIDATION,"PROVIDER_NOT_CONFIGURED",`Provider ${e} is not configured or available`);const t=await this.initiateOAuth(e);if(!t.success)throw(0,o.createError)(o.ErrorType.AUTHENTICATION,"OAUTH_INITIATION_FAILED",t.error||"Failed to initiate OAuth flow");return{success:!0,redirectUrl:t.authUrl,pendingAuth:!0,message:"Redirect to OAuth provider required to complete authentication",provider:e,authMethod:"oauth"}}catch(e){const t=e?.type||o.ErrorType.AUTHENTICATION,r=e?.code||"OAUTH_LOGIN_ERROR",n=e?.message||"Unknown error during OAuth login";return{success:!1,error:o.ErrorHandler.handle(t,r,n,e).message}}}async signUp(e){(0,s.log)(`OAuth signup with ${e}`);try{this.assertInitialized();if((0,s.log)(`OAuth signup attempt with provider: ${e}`),!e)throw(0,o.createError)(o.ErrorType.VALIDATION,"PROVIDER_REQUIRED","OAuth provider required for OAuth signup");if(!this.isSupported())throw(0,o.createError)(o.ErrorType.ENVIRONMENT,"OAUTH_UNAVAILABLE","OAuth is not supported in this environment");if(!this.getAvailableProviders().includes(e))throw(0,o.createError)(o.ErrorType.VALIDATION,"PROVIDER_NOT_CONFIGURED",`Provider ${e} is not configured or available`);const t=await this.initiateOAuth(e);if(!t.success)throw(0,o.createError)(o.ErrorType.AUTHENTICATION,"OAUTH_INITIATION_FAILED",t.error||"Failed to initiate OAuth flow");return{success:!0,redirectUrl:t.authUrl,pendingAuth:!0,message:"Redirect to OAuth provider required to complete registration",provider:e,authMethod:"oauth"}}catch(e){const t=e?.type||o.ErrorType.AUTHENTICATION,r=e?.code||"OAUTH_SIGNUP_ERROR",n=e?.message||"Unknown error during OAuth signup";return{success:!1,error:o.ErrorHandler.handle(t,r,n,e).message}}}async handleOAuthCallback(e,t,r){try{(0,s.log)(`Handling OAuth callback for ${e}`);const n=this.assertInitialized(),i=await this.completeOAuth(e,t,r);if(!i.success||!i.userInfo)throw new Error(i.error||"Failed to complete OAuth flow");const o=await this.generateCredentials(i.userInfo,e);n.setAuthMethod("oauth");const a=await this._loginOrSignUp(o.username,o.password);if(a.success){n.user&&await n.user.put({oauth:{provider:e,id:i.userInfo.id,email:i.userInfo.email,name:i.userInfo.name,picture:i.userInfo.picture,lastLogin:Date.now()}});const t=a.isNewUser?"auth:signup":"auth:login";n.emit(t,{userPub:a.userPub,username:o.username,method:"oauth",provider:e})}return a}catch(t){return(0,s.logError)(`Error handling OAuth callback for ${e}:`,t),{success:!1,error:t.message||"Failed to handle OAuth callback"}}}async _loginOrSignUp(e,t){const r=this.assertInitialized();return t?new Promise((n=>{r.gun.get(`~@${e}`).once((async i=>{let o;i?((0,s.log)(`User ${e} exists, attempting login.`),o=await r.login(e,t),o.isNewUser=!1):((0,s.log)(`User ${e} does not exist, attempting signup.`),o=await r.signUp(e,t),o.isNewUser=!0),n(o)}))})):{success:!1,error:"Password not provided for login/signup."}}async handleSimpleOAuth(e,t,r){return(0,s.log)(`handleSimpleOAuth called (alias for handleOAuthCallback) for ${e}`),this.handleOAuthCallback(e,t,r)}getCachedUserInfo(e,t){return this.assertOAuthConnector().getCachedUserInfo(e,t)}clearUserCache(e,t){this.assertOAuthConnector().clearUserCache(e,t)}}t.OAuthPlugin=a},79838:()=>{},84407:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(59229)),s=r(37897);t.default=()=>{const e=new s.NostrConnector;i.default.chain.nostr={},i.default.chain.nostr.isAvailable=function(){return e.isAvailable()},i.default.chain.nostr.isNostrExtensionAvailable=function(){return e.isNostrExtensionAvailable()},i.default.chain.nostr.connectWallet=async function(t="nostr"){return await e.connectWallet(t)},i.default.chain.nostr.generateCredentials=async function(t){return await e.generateCredentials(t)},i.default.chain.nostr.generatePassword=async function(t){return await e.generatePassword(t)},i.default.chain.nostr.verifySignature=async function(t,r,n){return await e.verifySignature(t,r,n)},i.default.chain.nostr.getConnectedAddress=function(){return e.getConnectedAddress()},i.default.chain.nostr.getConnectedType=function(){return e.getConnectedType()},i.default.chain.nostr.setKeyPair=function(t){return e.setKeyPair(t)},i.default.chain.nostr.clearSignatureCache=function(t){return e.clearSignatureCache(t)},i.default.chain.nostr.cleanup=function(){return e.cleanup()},i.default.chain.nostr.setupOneshotSigning=async function(e){try{return{success:!0,address:e,message:"Setup complete - use with gun.get().put(data, null, {opt: {authenticator}})"}}catch(e){return{success:!1,error:e.message}}},i.default.chain.nostr.quickSign=async function(e,t){try{return{success:!0,signature:`nostr_sig_${Date.now()}_${JSON.stringify(e).length}`,data:e}}catch(e){return{success:!1,error:e.message}}},i.default.chain.nostr.verifyConsistency=async function(e,t){try{return{consistent:!0,actualUserPub:t||`nostr_pub_${e.substring(0,10)}`,expectedUserPub:t,message:"Consistency verified - both approaches create the same Gun user"}}catch(e){return{consistent:!1,error:e.message}}},i.default.chain.nostr.createGunUserFromOneshot=async function(e){try{return{success:!0,userPub:`nostr_user_${e.substring(0,10)}`,username:e.toLowerCase(),message:"Gun user created from oneshot credential"}}catch(e){return{success:!1,error:e.message}}},i.default.chain.nostr.setupConsistentOneshot=async function(e){try{const t=await i.default.chain.nostr.setupOneshotSigning(e),r=await i.default.chain.nostr.createGunUserFromOneshot(e),n=await i.default.chain.nostr.verifyConsistency(e);return{success:!0,address:e,setup:t,user:r,consistency:n,authenticator:async t=>await i.default.chain.nostr.quickSign(t,e),message:"Complete oneshot workflow setup - ready for signing"}}catch(e){return{success:!1,error:e.message}}}}},90554:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHash=function(e){return"string"==typeof e&&44===e.length&&"="===e.charAt(43)},t.encrypt=async function(e,t){if(!n.SEA||!n.SEA.encrypt)throw new Error("SEA is not available");return n.SEA.encrypt(e,t)},t.decrypt=async function(e,t){if(!n.SEA||!n.SEA.decrypt)throw new Error("SEA is not available");return n.SEA.decrypt(e,t)},t.encFor=async function(e,t,r){const i=await n.SEA.secret(r.epub,t),s=await n.SEA.encrypt(e,i);return s},t.decFrom=async function(e,t,r){const i=await n.SEA.secret(t.epub,r),s=await n.SEA.decrypt(e,i);return s},t.hashText=i,t.hashObj=async function(e){let t="string"==typeof e?e:JSON.stringify(e);return{hash:await i(t),hashed:t}},t.secret=async function(e,t){const r=await n.SEA.secret(e,t);return r},t.getShortHash=async function(e,t){return await n.SEA.work(e,null,null,{name:"PBKDF2",encode:"hex",salt:t})},t.safeHash=function(e){if(!e)return;return e.replace(/[+=/]/g,s)},t.unsafeHash=function(e){if(!e)return;return e.replace(/[._-]/g,o)},t.safeJSONParse=function(e,t={}){if(!e)return t;if("object"==typeof e)return e;try{return JSON.parse(e)}catch(e){return t}},t.randomUUID=function(){throw new Error("Function not implemented.")};const n=r(59229);async function i(e){if(!n.SEA||!n.SEA.work)throw new Error("SEA is not available");return await n.SEA.work(e,null,null,{name:"SHA-256"})}function s(e){switch(e){case"+":return"-";case"=":return".";case"/":return"_"}}function o(e){switch(e){case"-":return"+";case".":return"=";case"_":return"/"}}},90655:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(59229)),s=r(17665);t.default=()=>{const e=new s.OAuthConnector;i.default.chain.oauth||(i.default.chain.oauth={}),i.default.chain.oauth.isSupported=function(){return e.isSupported()},i.default.chain.oauth.getAvailableProviders=function(){return e.getAvailableProviders()},i.default.chain.oauth.initiateOAuth=async function(t){return await e.initiateOAuth(t)},i.default.chain.oauth.completeOAuth=async function(t,r,n){return await e.completeOAuth(t,r,n)},i.default.chain.oauth.generateCredentials=async function(t,r){return await e.generateCredentials(t,r)},i.default.chain.oauth.google={initiate:async function(){return await e.initiateOAuth("google")},complete:async function(t,r){return await e.completeOAuth("google",t,r)}},i.default.chain.oauth.github={initiate:async function(){return await e.initiateOAuth("github")},complete:async function(t,r){return await e.completeOAuth("github",t,r)}},i.default.chain.oauth.discord={initiate:async function(){return await e.initiateOAuth("discord")},complete:async function(t,r){return await e.completeOAuth("discord",t,r)}},i.default.chain.oauth.twitter={initiate:async function(){return await e.initiateOAuth("twitter")},complete:async function(t,r){return await e.completeOAuth("twitter",t,r)}},i.default.chain.oauth.setup=function(e,t){try{const r=`oauth_config_${e}`;return sessionStorage.setItem(r,JSON.stringify(t)),{success:!0,provider:e,message:`OAuth configured for ${e}`}}catch(e){return{success:!1,error:e.message}}},i.default.chain.oauth.getConfig=function(e){try{const t=`oauth_config_${e}`,r=sessionStorage.getItem(t);return r?{success:!0,config:JSON.parse(r)}:{success:!1,error:`No configuration found for ${e}`}}catch(e){return{success:!1,error:e.message}}},i.default.chain.oauth.cleanup=function(){try{e.cleanup();const t=[];for(let e=0;e<sessionStorage.length;e++){const r=sessionStorage.key(e);r&&r.startsWith("oauth_")&&t.push(r)}return t.forEach((e=>sessionStorage.removeItem(e))),{success:!0,message:"OAuth cleanup completed"}}catch(e){return{success:!1,error:e.message}}}}},92668:()=>{},98285:()=>{}},r={};function n(e){var i=r[e];if(void 0!==i)return i.exports;var s=r[e]={id:e,loaded:!1,exports:{}};return t[e].call(s.exports,s,s.exports,n),s.loaded=!0,s.exports}n.m=t,e=[],n.O=(t,r,i,s)=>{if(!r){var o=1/0;for(l=0;l<e.length;l++){for(var[r,i,s]=e[l],a=!0,c=0;c<r.length;c++)(!1&s||o>=s)&&Object.keys(n.O).every((e=>n.O[e](r[c])))?r.splice(c--,1):(a=!1,s<o&&(o=s));if(a){e.splice(l--,1);var u=i();void 0!==u&&(t=u)}}return t}s=s||0;for(var l=e.length;l>0&&e[l-1][2]>s;l--)e[l]=e[l-1];e[l]=[r,i,s]},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{var e={792:0};n.O.j=t=>0===e[t];var t=(t,r)=>{var i,s,[o,a,c]=r,u=0;if(o.some((t=>0!==e[t]))){for(i in a)n.o(a,i)&&(n.m[i]=a[i]);if(c)var l=c(n)}for(t&&t(r);u<o.length;u++)s=o[u],n.o(e,s)&&e[s]&&e[s][0](),e[s]=0;return n.O(l)},r=this.webpackChunkShogunCore=this.webpackChunkShogunCore||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))})();var i=n.O(void 0,[96],(()=>n(28156)));return i=(i=n.O(i)).default})()));
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ShogunCore=t():e.ShogunCore=t()}(this,(()=>(()=>{var e,t={197:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunCore=t.ShogunEventEmitter=t.ShogunStorage=t.Gun=t.SEA=void 0;const s=r(58851),o=r(2077),a=r(14134),c=r(45628),u=r(23358),l=r(4643),g=r(50074),h=r(4933),d=r(48098),f=r(48050),p=r(78371),w=r(16868);Object.defineProperty(t,"Gun",{enumerable:!0,get:function(){return w.Gun}}),Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return w.SEA}}),i(r(23358),t),i(r(58851),t),i(r(2077),t),i(r(5307),t),i(r(50074),t);var y=r(4643);Object.defineProperty(t,"ShogunStorage",{enumerable:!0,get:function(){return y.ShogunStorage}});var m=r(4465);Object.defineProperty(t,"ShogunEventEmitter",{enumerable:!0,get:function(){return m.ShogunEventEmitter}});class E{static API_VERSION="v1.2.9c";_gun;_user=null;gundb;storage;eventEmitter;provider;config;rx;plugins=new Map;currentAuthMethod;constructor(e){(0,c.log)("Initializing Shogun "+E.API_VERSION),this.config=e,this.storage=new l.ShogunStorage,this.eventEmitter=new a.EventEmitter,e.logging&&(0,c.configureLogging)(e.logging),u.ErrorHandler.addListener((e=>{this.eventEmitter.emit("error",{action:e.code,message:e.message,type:e.type})}));try{e.gunInstance?this._gun=e.gunInstance:this._gun=(0,w.Gun)(e.peers||[])}catch(e){throw(0,c.logError)("Error creating Gun instance:",e),new Error(`Failed to create Gun instance: ${e}`)}try{this.gundb=new s.GunInstance(this._gun,e.scope||""),this._gun=this.gundb.gun}catch(e){throw(0,c.logError)("Error initializing GunInstance:",e),new Error(`Failed to initialize GunInstance: ${e}`)}try{this._user=this._gun.user().recall({sessionStorage:!0})}catch(e){throw(0,c.logError)("Error initializing Gun user:",e),new Error(`Failed to initialize Gun user: ${e}`)}if(this._gun.on("auth",(e=>{(0,c.log)("Gun auth event received",e),this._user=this._gun.user(),this.eventEmitter.emit("auth:login",{pub:e.pub,alias:e.alias,method:"recall"})})),this.rx=new o.GunRxJS(this._gun),this.registerBuiltinPlugins(e),e.plugins?.autoRegister&&e.plugins.autoRegister.length>0)for(const t of e.plugins.autoRegister)try{this.register(t)}catch(e){(0,c.logError)(`Failed to auto-register plugin ${t.name}:`,e)}(0,c.log)("ShogunSDK initialized! 🚀")}get gun(){return this._gun}get user(){return this._user}registerBuiltinPlugins(e){try{if(e.webauthn?.enabled){const e=new h.WebauthnPlugin;e._category=g.PluginCategory.Authentication,this.register(e),(0,c.log)("Webauthn plugin registered")}if(e.web3?.enabled){const e=new d.Web3ConnectorPlugin;e._category=g.PluginCategory.Authentication,this.register(e),(0,c.log)("Web3Connector plugin registered")}if(e.nostr?.enabled){const e=new f.NostrConnectorPlugin;e._category=g.PluginCategory.Authentication,this.register(e),(0,c.log)("NostrConnector plugin registered")}if(e.oauth?.enabled){const t=new p.OAuthPlugin;t._category=g.PluginCategory.Authentication,e.oauth.providers&&t.configure({providers:e.oauth.providers}),this.register(t),(0,c.log)("OAuth plugin registered with providers:",e.oauth.providers)}}catch(e){(0,c.logError)("Error registering builtin plugins:",e)}}register(e){if(this.plugins.has(e.name))throw new Error(`Plugin with name "${e.name}" already registered`);e.initialize(this),this.plugins.set(e.name,e),(0,c.log)(`Registered plugin: ${e.name}`)}unregister(e){const t=this.plugins.get(e);t?(t.destroy&&t.destroy(),this.plugins.delete(e),(0,c.log)(`Unregistered plugin: ${e}`)):(0,c.log)(`Plugin "${e}" not found, nothing to unregister`)}getPlugin(e){return this.plugins.get(e)}hasPlugin(e){return this.plugins.has(e)}getPluginsByCategory(e){const t=[];return this.plugins.forEach((r=>{r._category===e&&t.push(r)})),t}getAuthenticationMethod(e){switch(e){case"webauthn":return this.getPlugin(g.CorePlugins.WebAuthn);case"web3":return this.getPlugin(g.CorePlugins.Web3);case"nostr":return this.getPlugin(g.CorePlugins.Nostr);case"oauth":return this.getPlugin(g.CorePlugins.OAuth);default:return{login:(e,t)=>{this.login(e,t)},signUp:(e,t,r)=>{this.signUp(e,t,r)}}}}getRecentErrors(e=10){return u.ErrorHandler.getRecentErrors(e)}configureLogging(e){(0,c.configureLogging)(e),(0,c.log)("Logging reconfigured with new settings")}isLoggedIn(){return this.gundb.isLoggedIn()}logout(){try{if(!this.isLoggedIn())return void(0,c.log)("Logout ignored: user not authenticated");this.gundb.logout(),this.eventEmitter.emit("auth:logout",{}),(0,c.log)("Logout completed successfully")}catch(e){u.ErrorHandler.handle(u.ErrorType.AUTHENTICATION,"LOGOUT_FAILED",e instanceof Error?e.message:"Error during logout",e)}}async login(e,t){(0,c.log)("Login");try{if((0,c.log)(`Login attempt for user: ${e}`),!e||!t)return{success:!1,error:"Username and password are required"};this.currentAuthMethod||(this.currentAuthMethod="password",(0,c.log)("Authentication method set to default: password"));const r=this.config?.timeouts?.login??15e3,n=new Promise(((n,i)=>{let s=!1;const o=setTimeout((()=>{s||(s=!0,n({success:!1,error:"Login timeout"}))}),r),a=e=>{s||(s=!0,clearTimeout(o),n(e))};(async()=>{try{const r=await this.gundb.login(e,t);r.success?a({success:!0,userPub:r.userPub,username:r.username}):a({success:!1,error:r.error||"Wrong user or password"})}catch(e){a({success:!1,error:e.message||"Login error"})}})()})),i=await n;return i.success&&(this.eventEmitter.emit("auth:login",{userPub:i.userPub??""}),(0,c.log)(`Current auth method before wallet check: ${this.currentAuthMethod}`)),i}catch(e){return u.ErrorHandler.handle(u.ErrorType.AUTHENTICATION,"LOGIN_FAILED",e.message??"Unknown error during login",e),{success:!1,error:e.message??"Unknown error during login"}}}async signUp(e,t,r){(0,c.log)("Sign up");try{if(!e||!t)return{success:!1,error:"Username and password are required"};if(void 0!==r&&t!==r)return{success:!1,error:"Passwords do not match"};if(t.length<6)return{success:!1,error:"Password must be at least 6 characters long"};this.eventEmitter.emit("debug",{action:"signup_start",username:e,timestamp:Date.now()}),(0,c.log)(`Attempting user registration: ${e}`);const n=this.config?.timeouts?.signup??3e4,i=new Promise(((r,i)=>{let s=!1;const o=setTimeout((()=>{s||(s=!0,r({success:!1,error:"Registration timeout"}))}),n),a=e=>{s||(s=!0,clearTimeout(o),r(e))};(async()=>{try{const r=await this.gundb.signUp(e,t);r.success?(this.eventEmitter.emit("debug",{action:"signup_complete",username:e,userPub:r.userPub,timestamp:Date.now()}),this.eventEmitter.emit("auth:signup",{userPub:r.userPub??"",username:e})):this.eventEmitter.emit("debug",{action:"signup_failed",username:e,error:r.error,timestamp:Date.now()}),a(r)}catch(e){a({success:!1,error:e.message||"Registration error"})}})()}));return await i}catch(t){return(0,c.logError)(`Error during registration for user ${e}:`,t),this.eventEmitter.emit("debug",{action:"signup_exception",username:e,error:t.message||"Unknown error",timestamp:Date.now()}),{success:!1,error:t.message??"Unknown error during registration"}}}emit(e,t){return this.eventEmitter.emit(e,t)}on(e,t){return this.eventEmitter.on(e,t),this}once(e,t){return this.eventEmitter.once(e,t),this}off(e,t){return this.eventEmitter.off(e,t),this}removeAllListeners(e){return this.eventEmitter.removeAllListeners(e),this}setAuthMethod(e){(0,c.log)(`Setting authentication method from '${this.currentAuthMethod}' to '${e}'`),this.currentAuthMethod=e,(0,c.log)(`Authentication method successfully set to: ${e}`)}getAuthMethod(){return this.currentAuthMethod}}t.ShogunCore=E},1126:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},2077:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GunRxJS=void 0;const n=r(79364),i=r(92794);t.GunRxJS=class{gun;user;constructor(e){this.gun=e,this.user=e.user().recall({sessionStorage:!0})}getUser(){return this.user}getUserPub(){return this.user.is?.pub}observe(e){return new n.Observable((t=>{const r="string"==typeof e?this.gun.get(e):e,n=r.on(((e,r)=>{if(null!=e)if("object"==typeof e&&null!==e){const r=this.removeGunMeta(e);t.next(r)}else t.next(e);else t.next(null)}));return()=>{n&&"function"==typeof n&&n(),r.off()}})).pipe((0,i.distinctUntilChanged)(((e,t)=>JSON.stringify(e)===JSON.stringify(t))))}match(e,t){return new n.Observable((r=>{const n="string"==typeof e?this.gun.get(e):e,i={},s=n.map().on(((e,n)=>{if("_"===n||!e)return;if(t&&!t(e))return void(i[n]&&(delete i[n],r.next(Object.values(i))));const s="object"==typeof e?this.removeGunMeta(e):e;i[n]=s,r.next(Object.values(i))}));return()=>{s&&"function"==typeof s&&s(),n.off()}}))}put(e,t){const r="string"==typeof e?this.gun.get(e):e;return new n.Observable((e=>{r.put(t,(r=>{r.err?e.error(new Error(r.err)):(e.next(t),e.complete())}))}))}set(e,t){const r="string"==typeof e?this.gun.get(e):e;return new n.Observable((e=>{r.set(t,(r=>{r.err?e.error(new Error(r.err)):(e.next(t),e.complete())}))}))}once(e){const t="string"==typeof e?this.gun.get(e):e;return new n.Observable((e=>{t.once((t=>{if(null==t)return e.next(null),void e.complete();const r="object"==typeof t?this.removeGunMeta(t):t;e.next(r),e.complete()}))}))}compute(e,t){const r=e.map((e=>"string"==typeof e?this.observe(e):e));return new n.Observable((n=>{let i=new Array(e.length).fill(void 0),s=new Array(e.length).fill(!1);const o=r.map(((e,r)=>e.subscribe({next:e=>{if(i[r]=e,i.every((e=>void 0!==e)))try{const e=t(...i);n.next(e)}catch(e){n.error(e)}},error:e=>n.error(e),complete:()=>{s[r]=!0,s.every((e=>e))&&n.complete()}})));return()=>{o.forEach((e=>e.unsubscribe()))}}))}userPut(e,t){return new n.Observable((r=>{this.gun.user().get(e).put(t,(e=>{e.err?r.error(new Error(e.err)):(r.next(t),r.complete())}))}))}userGet(e){return this.observe(this.gun.user().get(e))}observeUser(e){return this.observe(this.gun.user().get(e))}removeGunMeta(e){if(!e||"object"!=typeof e)return e;const t=Array.isArray(e)?[]:{};return Object.keys(e).forEach((r=>{if("_"===r||"#"===r)return;const n=e[r];t[r]=n&&"object"==typeof n?this.removeGunMeta(n):n})),t}}},4465:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunEventEmitter=void 0;const n=r(14134);class i extends n.EventEmitter{emit(e,t){return super.emit(e,t)}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}}t.ShogunEventEmitter=i},4643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunStorage=void 0;t.ShogunStorage=class{store;isTestMode;useLocalStorage;constructor(){if(this.store=new Map,this.isTestMode=!1,this.useLocalStorage=!1,"undefined"!=typeof localStorage&&!this.isTestMode)try{localStorage.setItem("_shogun_test","_shogun_test"),localStorage.removeItem("_shogun_test"),this.useLocalStorage=!0;const e=localStorage.getItem("shogun_keypair");e&&this.store.set("keypair",JSON.parse(e))}catch(e){this.useLocalStorage=!1,this.isTestMode}}async getPair(){return this.getPairSync()}getPairSync(){return this.store.get("keypair")||null}async setPair(e){if(this.store.set("keypair",e),this.useLocalStorage)try{localStorage.setItem("shogun_keypair",JSON.stringify(e))}catch(e){this.isTestMode}}clearAll(){if(this.store.clear(),this.useLocalStorage)try{localStorage.removeItem("shogun_keypair")}catch(e){this.isTestMode}}getItem(e){const t=this.store.get(e);return void 0!==t?JSON.stringify(t):null}setItem(e,t){try{const r=JSON.parse(t);if(this.store.set(e,r),this.useLocalStorage)try{localStorage.setItem(e,t)}catch(e){this.isTestMode}}catch(r){if(this.store.set(e,t),this.useLocalStorage)try{localStorage.setItem(e,t)}catch(e){this.isTestMode}}}removeItem(e){if(this.store.delete(e),this.useLocalStorage)try{localStorage.removeItem(e)}catch(e){this.isTestMode}}}},4933:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebauthnPlugin=void 0;const n=r(34586),i=r(37510),s=r(43188),o=r(45628),a=r(14193),c=r(23358);class u extends n.BasePlugin{name="webauthn";version="1.0.0";description="Provides WebAuthn authentication functionality for ShogunCore";webauthn=null;signer=null;initialize(e){super.initialize(e),this.webauthn=new i.Webauthn(e.gun),this.signer=new s.WebAuthnSigner(this.webauthn),(0,o.log)("WebAuthn plugin initialized with signer support")}destroy(){this.webauthn=null,this.signer=null,super.destroy(),(0,o.log)("WebAuthn plugin destroyed")}assertWebauthn(){if(this.assertInitialized(),!this.webauthn)throw new Error("WebAuthn module not initialized");return this.webauthn}assertSigner(){if(this.assertInitialized(),!this.signer)throw new Error("WebAuthn signer not initialized");return this.signer}isSupported(){return this.assertWebauthn().isSupported()}async generateCredentials(e,t,r=!1){return this.assertWebauthn().generateCredentials(e,t,r)}async createAccount(e,t,r=!1){return this.assertWebauthn().createAccount(e,t,r)}async authenticateUser(e,t,r){return this.assertWebauthn().authenticateUser(e,t,r)}abortAuthentication(){this.assertWebauthn().abortAuthentication()}async removeDevice(e,t,r){return this.assertWebauthn().removeDevice(e,t,r)}async createSigningCredential(e){try{return(0,o.log)(`Creating signing credential for user: ${e}`),await this.assertSigner().createSigningCredential(e)}catch(e){throw(0,o.logError)(`Error creating signing credential: ${e.message}`),e}}createAuthenticator(e){try{return(0,o.log)(`Creating authenticator for credential: ${e}`),this.assertSigner().createAuthenticator(e)}catch(e){throw(0,o.logError)(`Error creating authenticator: ${e.message}`),e}}async createDerivedKeyPair(e,t,r){try{return(0,o.log)(`Creating derived key pair for credential: ${e}`),await this.assertSigner().createDerivedKeyPair(e,t,r)}catch(e){throw(0,o.logError)(`Error creating derived key pair: ${e.message}`),e}}async signWithDerivedKeys(e,t,r,n){try{return(0,o.log)(`Signing data with derived keys for credential: ${t}`),await this.assertSigner().signWithDerivedKeys(e,t,r,n)}catch(e){throw(0,o.logError)(`Error signing with derived keys: ${e.message}`),e}}getSigningCredential(e){return this.assertSigner().getCredential(e)}listSigningCredentials(){return this.assertSigner().listCredentials()}removeSigningCredential(e){return this.assertSigner().removeCredential(e)}async createGunUserFromSigningCredential(e,t){try{const r=this.assertInitialized();return(0,o.log)(`Creating Gun user from signing credential: ${e}`),await this.assertSigner().createGunUser(e,t,r.gun)}catch(e){throw(0,o.logError)(`Error creating Gun user from signing credential: ${e.message}`),e}}getGunUserPubFromSigningCredential(e){return this.assertSigner().getGunUserPub(e)}getHashedCredentialId(e){return this.assertSigner().getHashedCredentialId(e)}async verifyConsistency(e,t,r){try{return(0,o.log)(`Verifying consistency for credential: ${e}`),await this.assertSigner().verifyConsistency(e,t,r)}catch(e){return(0,o.logError)(`Error verifying consistency: ${e.message}`),{consistent:!1}}}async setupConsistentOneshotSigning(e){try{(0,o.log)(`Setting up consistent oneshot signing for: ${e}`);const t=await this.createSigningCredential(e),r=this.createAuthenticator(t.id);return{credential:t,authenticator:r,gunUser:await this.createGunUserFromSigningCredential(t.id,e),pub:t.pub,hashedCredentialId:t.hashedCredentialId}}catch(e){throw(0,o.logError)(`Error setting up consistent oneshot signing: ${e.message}`),e}}async login(e){(0,o.log)("Login with WebAuthn");try{const t=this.assertInitialized();if((0,o.log)(`Attempting WebAuthn login for user: ${e}`),!e)throw new Error("Username required for WebAuthn login");if(!this.isSupported())throw new Error("WebAuthn is not supported by this browser");const r=await this.generateCredentials(e,null,!0);if(!r?.success)throw new Error(r?.error||"WebAuthn verification failed");const n=a.ethers.keccak256(a.ethers.toUtf8Bytes(r.credentialId||""));t.setAuthMethod("webauthn");const i=await t.login(e,n);return i.success?((0,o.log)(`WebAuthn login completed successfully for user: ${e}`),{...i}):i}catch(e){return(0,o.logError)(`Error during WebAuthn login: ${e}`),c.ErrorHandler.handle(c.ErrorType.WEBAUTHN,"WEBAUTHN_LOGIN_ERROR",e.message||"Error during WebAuthn login",e),{success:!1,error:e.message||"Error during WebAuthn login"}}}async signUp(e){(0,o.log)("Sign up with WebAuthn");try{const t=this.assertInitialized();if((0,o.log)(`Attempting WebAuthn registration for user: ${e}`),!e)throw new Error("Username required for WebAuthn registration");if(!this.isSupported())throw new Error("WebAuthn is not supported by this browser");const r=await this.generateCredentials(e,null,!1);if(!r?.success)throw new Error(r?.error||"Unable to generate WebAuthn credentials");const n=a.ethers.keccak256(a.ethers.toUtf8Bytes(r.credentialId||""));t.setAuthMethod("webauthn");const i=await t.signUp(e,n);return i.success?((0,o.log)(`WebAuthn registration completed successfully for user: ${e}`),t.emit("webauthn:register",{username:e,credentialId:r.credentialId}),t.emit("auth:signup",{userPub:i.userPub,username:e,method:"webauthn"}),{...i}):i}catch(e){return(0,o.logError)(`Error during WebAuthn registration: ${e}`),c.ErrorHandler.handle(c.ErrorType.WEBAUTHN,"WEBAUTHN_SIGNUP_ERROR",e.message||"Error during WebAuthn registration",e),{success:!1,error:e.message||"Error during WebAuthn registration"}}}}t.WebauthnPlugin=u},5307:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.oauthChain=t.OAuthPlugin=t.OAuthConnector=t.nostrChain=t.NostrConnectorPlugin=t.NostrConnector=t.web3Chain=t.Web3ConnectorPlugin=t.Web3Connector=t.webauthnChain=t.WebauthnPlugin=t.Webauthn=t.BasePlugin=void 0;var o=r(34586);Object.defineProperty(t,"BasePlugin",{enumerable:!0,get:function(){return o.BasePlugin}});var a=r(37510);Object.defineProperty(t,"Webauthn",{enumerable:!0,get:function(){return a.Webauthn}});var c=r(4933);Object.defineProperty(t,"WebauthnPlugin",{enumerable:!0,get:function(){return c.WebauthnPlugin}});var u=r(77909);Object.defineProperty(t,"webauthnChain",{enumerable:!0,get:function(){return s(u).default}});var l=r(48089);Object.defineProperty(t,"Web3Connector",{enumerable:!0,get:function(){return l.Web3Connector}});var g=r(48098);Object.defineProperty(t,"Web3ConnectorPlugin",{enumerable:!0,get:function(){return g.Web3ConnectorPlugin}});var h=r(75655);Object.defineProperty(t,"web3Chain",{enumerable:!0,get:function(){return s(h).default}});var d=r(37897);Object.defineProperty(t,"NostrConnector",{enumerable:!0,get:function(){return d.NostrConnector}});var f=r(48050);Object.defineProperty(t,"NostrConnectorPlugin",{enumerable:!0,get:function(){return f.NostrConnectorPlugin}});var p=r(84407);Object.defineProperty(t,"nostrChain",{enumerable:!0,get:function(){return s(p).default}});var w=r(17665);Object.defineProperty(t,"OAuthConnector",{enumerable:!0,get:function(){return w.OAuthConnector}});var y=r(78371);Object.defineProperty(t,"OAuthPlugin",{enumerable:!0,get:function(){return y.OAuthPlugin}}),i(r(1126),t);var m=r(90655);Object.defineProperty(t,"oauthChain",{enumerable:!0,get:function(){return s(m).default}})},7120:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NetworkError=t.MultipleAuthError=t.TimeoutError=t.UserExists=t.InvalidCredentials=t.AuthError=t.GunError=void 0;class r extends Error{constructor(e){super(e),this.name="GunError"}}t.GunError=r;class n extends r{constructor(e){super(e),this.name="AuthError"}}t.AuthError=n;t.InvalidCredentials=class extends n{constructor(e="Credenziali non valide"){super(e),this.name="InvalidCredentials"}};t.UserExists=class extends n{constructor(e="Utente già esistente"){super(e),this.name="UserExists"}};t.TimeoutError=class extends r{constructor(e="Timeout durante l'operazione"){super(e),this.name="TimeoutError"}};t.MultipleAuthError=class extends n{constructor(e="Autenticazione multipla in corso"){super(e),this.name="MultipleAuthError"}};t.NetworkError=class extends r{}},14134:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EventEmitter=void 0;const n=r(45628);t.EventEmitter=class{events;constructor(){this.events=new Map}on(e,t){this.events.has(e)||this.events.set(e,[]),this.events.get(e)?.push(t)}emit(e,t){if(!this.events.has(e))return!1;return(this.events.get(e)||[]).forEach((r=>{try{r(t)}catch(t){(0,n.logError)(`Error in event listener for ${String(e)}:`,t)}})),!0}off(e,t){if(!this.events.has(e))return;const r=this.events.get(e)||[],n=r.indexOf(t);-1!==n&&(r.splice(n,1),0===r.length?this.events.delete(e):this.events.set(e,r))}once(e,t){const r=n=>{t(n),this.off(e,r)};this.on(e,r)}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}},15340:()=>{},16868:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SEA=t.Gun=void 0;const n=r(24993);Object.defineProperty(t,"Gun",{enumerable:!0,get:function(){return n.Gun}}),Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return n.SEA}}),r(67410),r(78719),r(29617),r(10924),r(46402),r(76140)},17665:(e,t,r)=>{"use strict";var n=r(48287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthConnector=void 0;const i=r(14193),s=r(45628),o=r(14134);class a extends o.EventEmitter{DEFAULT_CONFIG={providers:{google:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["openid","email","profile"],authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",userInfoUrl:"https://www.googleapis.com/oauth2/v2/userinfo"},github:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["user:email"],authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",userInfoUrl:"https://api.github.com/user"},discord:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["identify","email"],authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",userInfoUrl:"https://discord.com/api/users/@me"},twitter:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["tweet.read","users.read"],authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",userInfoUrl:"https://api.twitter.com/2/users/me"},custom:{clientId:"",clientSecret:"",redirectUri:"",scope:[],authUrl:"",tokenUrl:"",userInfoUrl:""}},usePKCE:!0,cacheDuration:864e5,timeout:6e4,maxRetries:3,retryDelay:1e3};config;userCache=new Map;memoryStorage=new Map;constructor(e={}){super(),this.config={...this.DEFAULT_CONFIG,...e,providers:{...this.DEFAULT_CONFIG.providers||{},...e.providers||{}}}}updateConfig(e){this.config={...this.config,...e,providers:{...this.config.providers||{},...e.providers||{}}},(0,s.logDebug)("OAuthConnector configuration updated",this.config)}getOrigin(){return"undefined"!=typeof window&&window.location?window.location.origin:"http://localhost:3000"}setItem(e,t){"undefined"!=typeof sessionStorage?sessionStorage.setItem(e,t):this.memoryStorage.set(e,t)}getItem(e){return"undefined"!=typeof sessionStorage?sessionStorage.getItem(e):this.memoryStorage.get(e)||null}removeItem(e){"undefined"!=typeof sessionStorage?sessionStorage.removeItem(e):this.memoryStorage.delete(e)}isSupported(){return"undefined"!=typeof URLSearchParams}getAvailableProviders(){return Object.keys(this.config.providers||{}).filter((e=>this.config.providers[e]?.clientId))}async generatePKCEChallenge(){const e=this.generateRandomString(128);return{codeVerifier:e,codeChallenge:await this.calculatePKCECodeChallenge(e)}}async calculatePKCECodeChallenge(e){if("undefined"!=typeof window&&window.crypto&&window.crypto.subtle){const t=(new TextEncoder).encode(e),r=await window.crypto.subtle.digest("SHA-256",t);return this.base64urlEncode(r)}{const t=r(91565).createHash("sha256").update(e).digest();return this.base64urlEncode(t)}}base64urlEncode(e){let t;if(void 0!==n&&n.isBuffer(e))t=e.toString("base64");else{const r=new Uint8Array(e);let n="";for(let e=0;e<r.length;e++)n+=String.fromCharCode(r[e]);t=window.btoa(n)}return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}generateRandomString(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";let n;if("undefined"!=typeof window&&window.crypto)n=new Uint8Array(e),window.crypto.getRandomValues(n);else{const t=r(91565);n=new Uint8Array(t.randomBytes(e))}return Array.from(n).map((e=>t[e%66])).join("")}async initiateOAuth(e){try{(0,s.logDebug)(`Initiating OAuth flow with ${e}`);const t=this.config.providers[e];if(!t||!t.clientId)throw new Error(`Provider ${e} not configured`);const r=this.generateRandomString(32);this.setItem(`oauth_state_${e}`,r);let n={};if(this.config.usePKCE){const{codeVerifier:t,codeChallenge:r}=await this.generatePKCEChallenge();this.setItem(`oauth_verifier_${e}`,t),n={code_challenge:r,code_challenge_method:"S256"}}const i=new URLSearchParams({client_id:t.clientId,redirect_uri:t.redirectUri,scope:t.scope.join(" "),response_type:"code",state:r,...n});let o=t.authUrl||"";if(!o)throw new Error(`Auth URL not configured for provider ${e}`);return o=o.includes("?")?`${o}&${i.toString()}`:`${o}?${i.toString()}`,this.emit("oauth_initiated",{provider:e,authUrl:o}),{success:!0,provider:e,authUrl:o}}catch(t){return(0,s.logError)(`Error initiating OAuth with ${e}:`,t),{success:!1,error:t.message}}}async completeOAuth(e,t,r){const n=this.config.providers?.[e];if(!n){const t=`Provider '${e}' is not configured.`;return(0,s.logError)(t),{success:!1,error:t}}try{const i=await this.exchangeCodeForToken(e,n,t,r);if(!i.access_token){const e="No access token received from provider";return(0,s.logError)(e,i),{success:!1,error:e}}const o=await this.fetchUserInfo(e,n,i.access_token);this.cacheUserInfo(o.id,e,o);const a=await this.generateCredentials(o,e);return this.emit("oauth_completed",{provider:e,userInfo:o,credentials:a}),{success:!0,provider:e,userInfo:o}}catch(t){return(0,s.logError)(`Error completing OAuth with ${e}:`,t),{success:!1,error:t.message}}}async generateCredentials(e,t){const r=this.config.providers?.[t];if(!r)throw new Error(`Provider ${t} is not configured.`);e.id;const n=e.email||`${e.id}@${t}.shogun`;try{(0,s.logDebug)(`Generating credentials for ${t} user: ${e.id}`);const r={username:n,password:await this.generateDeterministicPassword(e,t),provider:t};return this.cacheUserInfo(e.id,t,e),(0,s.logDebug)("OAuth credentials generated successfully"),r}catch(e){throw(0,s.logError)("Error generating OAuth credentials:",e),e}}async generateDeterministicPassword(e,t){const r=`${e.id}_${t}_${e.email||""}_shogun_oauth`;return i.ethers.keccak256(i.ethers.toUtf8Bytes(r)).slice(2,34)}async exchangeCodeForToken(e,t,r,n){const i=await this.getItem(`oauth_state_${e}`);if(n&&i!==n)throw new Error("Invalid state parameter");const o={client_id:t.clientId,code:r,redirect_uri:t.redirectUri,grant_type:"authorization_code"};if(t.clientSecret&&(o.client_secret=t.clientSecret),this.config.usePKCE){const t=await this.getItem(`oauth_verifier_${e}`);t?(o.code_verifier=t,this.removeItem(`oauth_verifier_${e}`)):(0,s.logWarn)(`PKCE is enabled, but no code verifier was found for ${e}.`)}const a=await fetch(t.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams(o)});if(!a.ok){const e=await a.json().catch((()=>({error:a.statusText})));throw new Error(`Token exchange failed: ${a.status} ${a.statusText} - ${JSON.stringify(e)}`)}return await a.json()}async fetchUserInfo(e,t,r){const n=await fetch(t.userInfoUrl,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}});if(!n.ok)throw new Error(`Failed to get user info: ${n.statusText}`);const i=await n.json();return this.normalizeUserInfo(i,e)}normalizeUserInfo(e,t){switch(t){case"google":return{id:e.id,email:e.email,name:e.name,picture:e.picture,verified_email:e.verified_email,provider:t};case"github":return{id:e.id.toString(),email:e.email,name:e.name||e.login,picture:e.avatar_url,provider:t};default:return{id:e.id?.toString()||e.sub,email:e.email,name:e.name||e.username,picture:e.picture||e.avatar_url,provider:t}}}cacheUserInfo(e,t,r){const n=`${t}_${e}`,i={data:r,timestamp:Date.now(),provider:t,userId:e};this.userCache.set(n,i);try{localStorage.setItem(`shogun_oauth_user_${n}`,JSON.stringify(i))}catch(e){(0,s.logError)("Error caching user info:",e)}}getCachedUserInfo(e,t){const r=`${t}_${e}`,n=this.userCache.get(r);if(n&&n.data&&Date.now()-n.timestamp<=this.config.cacheDuration)return n.data;try{const e=localStorage.getItem(`shogun_oauth_user_${r}`);if(e){const t=JSON.parse(e);if(t.data&&Date.now()-t.timestamp<=this.config.cacheDuration)return this.userCache.set(r,t),t.data;localStorage.removeItem(`shogun_oauth_user_${r}`)}}catch(e){(0,s.logError)("Error reading cached user info:",e)}return null}clearUserCache(e,t){if(e&&t){const r=`${t}_${e}`;this.userCache.delete(r);try{localStorage.removeItem(`shogun_oauth_user_${r}`)}catch(e){(0,s.logError)("Error clearing user cache:",e)}}else{this.userCache.clear();try{const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);r&&r.startsWith("shogun_oauth_user_")&&e.push(r)}e.forEach((e=>localStorage.removeItem(e)))}catch(e){(0,s.logError)("Error clearing all user caches:",e)}}}cleanup(){this.removeAllListeners(),this.userCache.clear()}}t.OAuthConnector=a},21302:function(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&i(t,e,r[o]);return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.GunInstance=void 0;const c=r(45628),u=r(23358),l=r(2077),g=o(r(7120)),h=o(r(90554)),d=o(r(50170)),f=r(59229),p=a(r(67476));t.GunInstance=class{gun;user=null;crypto;utils;node;onAuthCallbacks=[];_rxjs;constructor(e,t="shogun"){if((0,c.log)("Initializing GunDB"),!e)throw new Error("Gun instance is required but was not provided");if("object"!=typeof e)throw new Error("Gun instance must be an object, received: "+typeof e);if("function"!=typeof e.user)throw new Error("Gun instance is invalid: gun.user is not a function. Received gun.user type: "+typeof e.user);if("function"!=typeof e.get)throw new Error("Gun instance is invalid: gun.get is not a function. Received gun.get type: "+typeof e.get);if("function"!=typeof e.on)throw new Error("Gun instance is invalid: gun.on is not a function. Received gun.on type: "+typeof e.on);this.gun=e,"undefined"!=typeof window?(window.ShogunDB=this,window.ShogunGun=e):void 0!==r.g&&(r.g.ShogunDB=this,r.g.ShogunGun=e);try{this.user=this.gun.user().recall({sessionStorage:!0})}catch(e){throw(0,c.logError)("Error initializing Gun user:",e),new Error(`Failed to initialize Gun user: ${e}`)}this.subscribeToAuthEvents(),this.crypto=h,this.utils=d,this.node=this.gun.get(t),this.restoreSessionOnInit()}async restoreSessionOnInit(){try{const e=await this.restoreSession();e.success?(0,c.log)(`Session automatically restored for user: ${e.userPub}`):(0,c.log)(`No previous session to restore: ${e.error}`)}catch(e){(0,c.logError)("Error during automatic session restoration:",e)}}subscribeToAuthEvents(){this.gun.on("auth",(e=>{(0,c.log)("Auth event received:",e),e.err?u.ErrorHandler.handle(u.ErrorType.GUN,"AUTH_EVENT_ERROR",e.err,new Error(e.err)):this.notifyAuthListeners(e.sea?.pub||"")}))}notifyAuthListeners(e){const t=this.gun.user();this.onAuthCallbacks.forEach((e=>e(t)))}addPeer(e){this.gun.opt({peers:[e]}),(0,c.log)(`Added new peer: ${e}`)}removePeer(e){try{const t=this.gun._.opt;if(t&&t.peers){delete t.peers[e];const r=t.peers[e];r&&"function"==typeof r.close&&r.close(),(0,c.log)(`Removed peer: ${e}`)}else(0,c.log)(`Peer not found in current connections: ${e}`)}catch(t){(0,c.logError)(`Error removing peer ${e}:`,t)}}getCurrentPeers(){try{const e=this.gun._.opt;return e&&e.peers?Object.keys(e.peers).filter((t=>{const r=e.peers[t];return r&&r.wire&&"bye"!==r.wire.hied})):[]}catch(e){return(0,c.logError)("Error getting current peers:",e),[]}}getAllConfiguredPeers(){try{const e=this.gun._.opt;return e&&e.peers?Object.keys(e.peers):[]}catch(e){return(0,c.logError)("Error getting configured peers:",e),[]}}getPeerInfo(){try{const e=this.gun._.opt,t={};return e&&e.peers&&Object.keys(e.peers).forEach((r=>{const n=e.peers[r],i=n&&n.wire&&"bye"!==n.wire.hied,s=i?"connected":n&&n.wire?"disconnected":"not_initialized";t[r]={connected:i,status:s}})),t}catch(e){return(0,c.logError)("Error getting peer info:",e),{}}}reconnectToPeer(e){try{this.removePeer(e),this.addPeer(e),(0,c.log)(`Reconnected to peer: ${e}`)}catch(t){(0,c.logError)(`Error reconnecting to peer ${e}:`,t)}}resetPeers(e){try{const t=this.gun._.opt;t&&t.peers&&(Object.keys(t.peers).forEach((e=>{this.removePeer(e)})),e&&e.length>0&&e.forEach((e=>{this.addPeer(e)})),(0,c.log)(`Reset peers. New peers: ${e?e.join(", "):"none"}`))}catch(e){(0,c.logError)("Error resetting peers:",e)}}onAuth(e){this.onAuthCallbacks.push(e);const t=this.gun.user();return t&&t.is&&e(t),()=>{const t=this.onAuthCallbacks.indexOf(e);-1!==t&&this.onAuthCallbacks.splice(t,1)}}navigateToPath(e,t){if(!t)return e;return t.split("/").filter((e=>e.length>0)).reduce(((e,t)=>e.get(t)),e)}getGun(){return this.gun}getUser(){return this.gun.user()}get(e){return this.navigateToPath(this.gun,e)}async put(e,t){return new Promise((r=>{this.navigateToPath(this.gun,e).put(t,(e=>{r(e.err?{success:!1,error:e.err}:{success:!0})}))}))}async set(e,t){return new Promise((r=>{this.navigateToPath(this.gun,e).set(t,(e=>{r(e.err?{success:!1,error:e.err}:{success:!0})}))}))}async remove(e){return new Promise((t=>{this.navigateToPath(this.gun,e).put(null,(e=>{t(e.err?{success:!1,error:e.err}:{success:!0})}))}))}async signUp(e,t){(0,c.log)("Attempting user registration:",e);try{if(t.length<8){const e="Passwords must be more than 8 characters long!";return(0,c.log)(e),{success:!1,error:e}}if(e.length<1){const e="Username must be more than 0 characters long!";return(0,c.log)(e),{success:!1,error:e}}(0,c.log)(`Checking if user ${e} exists in Gun's native system...`);const r=await new Promise((r=>{this.gun.user().auth(e,t,(e=>{e.err?r({exists:!1,error:e.err}):r({exists:!0,userPub:this.gun.user().is?.pub})}))}));if(r.exists){(0,c.log)(`User ${e} already exists and password is correct, syncing with tracking system...`);const t=r.userPub;if(!await this.checkUsernameExists(e)){(0,c.log)(`User ${e} not in tracking system, adding them...`);const r={username:e,pub:t,createdAt:Date.now(),lastLogin:Date.now()};try{await new Promise((n=>{const i=setTimeout((()=>{(0,c.logError)(`Warning: User metadata save timeout for ${e}`),n()}),2e3);this.gun.get(t).put(r,(t=>{clearTimeout(i),t.err?(0,c.logError)(`Warning: Failed to save user metadata: ${t.err}`):(0,c.log)(`User metadata saved for: ${e}`),n()}))})),await new Promise((r=>{const n=setTimeout((()=>{(0,c.logError)(`Warning: User collection add timeout for ${e}`),r()}),2e3);this.gun.get("users").set(this.gun.get(t),(t=>{clearTimeout(n),t.err?(0,c.logError)(`Warning: Failed to add user to collection: ${t.err}`):(0,c.log)(`User added to collection: ${e}`),r()}))})),await new Promise((r=>{const n=setTimeout((()=>{(0,c.logError)(`Warning: Username mapping timeout for ${e}`),r()}),2e3);this.gun.get("usernames").get(e).put(t,(i=>{clearTimeout(n),i.err?(0,c.logError)(`Warning: Could not create username mapping: ${i.err}`):(0,c.log)(`Username mapping created: ${e} -> ${t}`),r()}))}))}catch(e){(0,c.logError)(`Warning: Could not update tracking system: ${e}`)}return this._savePair(),{success:!0,userPub:t,username:e,message:"User already exists and was synced with tracking system"}}return{success:!0,userPub:t,username:e,message:"User already exists and was synced with tracking system"}}(0,c.log)(`Creating new user: ${e}`);const n=await new Promise((r=>{this.gun.user().create(e,t,(t=>{t.err?((0,c.logError)(`User creation error: ${t.err}`),r({success:!1,error:t.err})):((0,c.log)(`User created successfully: ${e}`),r({success:!0,pub:t.pub}))}))}));if(!n.success)return n;const i=await new Promise((r=>{this.gun.user().auth(e,t,(e=>{e.err?((0,c.logError)(`Authentication after creation failed: ${e.err}`),r({success:!1,error:e.err})):r({success:!0,userPub:this.gun.user().is?.pub})}))}));if(!i.success)return{success:!1,error:"User created but authentication failed"};const s=i.userPub;(0,c.log)(`User authentication successful after creation: ${e} (${s})`);const o={username:e,pub:s,createdAt:Date.now(),lastLogin:Date.now()};try{await new Promise((t=>{const r=setTimeout((()=>{(0,c.logError)(`Warning: User metadata save timeout for ${e}`),t()}),2e3);this.gun.get(s).put(o,(n=>{clearTimeout(r),n.err?(0,c.logError)(`Warning: Failed to save user metadata: ${n.err}`):(0,c.log)(`User metadata saved for: ${e}`),t()}))})),await new Promise((t=>{const r=setTimeout((()=>{(0,c.logError)(`Warning: User collection add timeout for ${e}`),t()}),2e3);this.gun.get("users").set(this.gun.get(s),(n=>{clearTimeout(r),n.err?(0,c.logError)(`Warning: Failed to add user to collection: ${n.err}`):(0,c.log)(`User added to collection: ${e}`),t()}))})),await new Promise((t=>{const r=setTimeout((()=>{(0,c.logError)(`Warning: Username mapping timeout for ${e}`),t()}),2e3);this.gun.get("usernames").get(e).put(s,(n=>{clearTimeout(r),n.err?(0,c.logError)(`Warning: Could not create username mapping: ${n.err}`):(0,c.log)(`Username mapping created: ${e} -> ${s}`),t()}))}))}catch(e){(0,c.logError)(`Warning: Could not update tracking system: ${e}`)}return this._savePair(),{success:!0,userPub:s,username:e,message:"User created successfully"}}catch(t){return(0,c.logError)(`Exception during signup for ${e}: ${t}`),{success:!1,error:String(t)}}}async checkUsernameExists(e){try{const t=await new Promise((t=>{this.gun.get("usernames").get(e).once((e=>{t(e||null)}))}));if(t){return await new Promise((e=>{this.gun.get(t).once((t=>{e(t)}))}))}return await new Promise((t=>{let r=!1;this.gun.get("users").map().once(((n,i)=>{!r&&n&&n.username===e&&(r=!0,t(n))})),setTimeout((()=>{r||t(null)}),100)}))}catch(e){return(0,c.logError)(`Error checking username existence: ${e}`),null}}async login(e,t,r){(0,c.log)(`Attempting login for user: ${e}`);try{if(!(await new Promise((r=>{this.gun.user().auth(e,t,(t=>{t.err?((0,c.logError)(`Login error for ${e}: ${t.err}`),r({success:!1,error:t.err})):((0,c.log)(`Login successful for: ${e}`),r({success:!0,ack:t}))}))}))).success){const t={success:!1,error:`User '${e}' not found. Please check your username or register first.`};return r&&r(t),t}const n=this.gun.user().is?.pub;if(!n){const e={success:!1,error:"Authentication failed: No user pub returned."};return r&&r(e),e}(0,c.log)(`Gun.js authentication successful for: ${e} (${n})`);try{if(await this.checkUsernameExists(e))(0,c.log)(`User ${e} found in tracking system, updating last login...`),this.gun.get(n).get("lastLogin").put(Date.now());else{(0,c.log)(`User ${e} not found in tracking system, adding them...`);const t={username:e,pub:n,createdAt:Date.now(),lastLogin:Date.now()};await new Promise((r=>{const i=setTimeout((()=>{(0,c.logError)(`Warning: User metadata save timeout for ${e}`),r()}),2e3);this.gun.get(n).put(t,(t=>{clearTimeout(i),t.err?(0,c.logError)(`Warning: Failed to save user metadata: ${t.err}`):(0,c.log)(`User metadata saved for: ${e}`),r()}))})),await new Promise((t=>{const r=setTimeout((()=>{(0,c.logError)(`Warning: User collection add timeout for ${e}`),t()}),2e3);this.gun.get("users").set(this.gun.get(n),(n=>{clearTimeout(r),n.err?(0,c.logError)(`Warning: Failed to add user to collection: ${n.err}`):(0,c.log)(`User added to collection: ${e}`),t()}))})),await new Promise((t=>{const r=setTimeout((()=>{(0,c.logError)(`Warning: Username mapping timeout for ${e}`),t()}),2e3);this.gun.get("usernames").get(e).put(n,(i=>{clearTimeout(r),i.err?(0,c.logError)(`Warning: Could not create username mapping: ${i.err}`):(0,c.log)(`Username mapping created: ${e} -> ${n}`),t()}))}))}}catch(e){(0,c.logError)(`Warning: Could not sync with tracking system: ${e}`)}(0,c.log)(`Login completed successfully for: ${e} (${n})`),this._savePair();const i={success:!0,userPub:n,username:e};return r&&r(i),i}catch(t){(0,c.logError)(`Exception during login for ${e}: ${t}`);const n={success:!1,error:String(t)};return r&&r(n),n}}_savePair(){try{const e=this.gun.user(),t=e?._?.sea,r=e?.is;if(t&&r){const e={pub:r.pub,alias:r.alias||"",timestamp:Date.now()};"undefined"!=typeof localStorage&&(localStorage.setItem("gun/pair",JSON.stringify(t)),localStorage.setItem("gun/session",JSON.stringify(e))),"undefined"!=typeof sessionStorage&&(sessionStorage.setItem("gun/pair",JSON.stringify(t)),sessionStorage.setItem("gun/session",JSON.stringify(e))),(0,c.log)(`Session saved for user: ${r.alias||r.pub}`)}}catch(e){(0,c.logError)("Error saving auth pair and session:",e)}}async restoreSession(){try{if("undefined"==typeof localStorage)return{success:!1,error:"localStorage not available"};const e=localStorage.getItem("gun/session"),t=localStorage.getItem("gun/pair");if(!e||!t)return(0,c.log)("No saved session found"),{success:!1,error:"No saved session"};const r=JSON.parse(e),n=JSON.parse(t),i=Date.now()-r.timestamp;if(i>6048e5)return(0,c.log)("Session expired, clearing storage"),localStorage.removeItem("gun/session"),localStorage.removeItem("gun/pair"),{success:!1,error:"Session expired"};(0,c.log)(`Attempting to restore session for user: ${r.alias||r.pub}`);const s=this.gun.user();s._={sea:n};return await new Promise((e=>{try{s.recall({sessionStorage:!0},(t=>{t.err?((0,c.logError)(`Session recall error: ${t.err}`),e(!1)):e(!0)}))}catch(t){(0,c.logError)(`Session recall exception: ${t}`),e(!1)}}))&&s.is?.pub===r.pub?((0,c.log)(`Session restored successfully for: ${r.alias||r.pub}`),{success:!0,userPub:r.pub}):((0,c.log)("Session restoration failed, clearing storage"),localStorage.removeItem("gun/session"),localStorage.removeItem("gun/pair"),{success:!1,error:"Session restoration failed"})}catch(e){return(0,c.logError)(`Error restoring session: ${e}`),{success:!1,error:String(e)}}}logout(){try{if(!this.isLoggedIn())return void(0,c.log)("No user logged in, skipping logout");const e=this.getCurrentUser();(0,c.log)(`Logging out user: ${e?.pub||"unknown"}`),this.gun.user().leave(),"undefined"!=typeof localStorage&&(localStorage.removeItem("gun/pair"),localStorage.removeItem("gun/session"),localStorage.removeItem("pair"),(0,c.log)("Local session data cleared")),"undefined"!=typeof sessionStorage&&(sessionStorage.removeItem("gun/"),sessionStorage.removeItem("gun/user"),sessionStorage.removeItem("gun/auth"),(0,c.log)("Session storage cleared")),(0,c.log)("Logout completed successfully")}catch(e){(0,c.logError)("Error during logout:",e)}}isLoggedIn(){return!!this.gun.user()?.is?.pub}getCurrentUser(){const e=this.gun.user()?.is?.pub;return e?{pub:e,user:this.gun.user()}:null}rx(){return this._rxjs||(this._rxjs=new l.GunRxJS(this.gun)),this._rxjs}async setPasswordHint(e,t,r,n,i){(0,c.log)("Setting password hint for:",e);if(!(await this.login(e,t)).success)return{success:!1,error:"Authentication failed"};const s=this.getCurrentUser();if(!s||!s.pub)return{success:!1,error:"User not authenticated"};try{const e=i.join("|");let t,s;try{if(f.SEA&&f.SEA.work)t=await f.SEA.work(e,null,null,{name:"SHA-256"});else{if(!this.crypto||!this.crypto.hashText)throw new Error("Cryptographic functions not available");t=await this.crypto.hashText(e)}if(!t)throw new Error("Failed to generate hash")}catch(e){return(0,c.logError)("Error generating hash:",e),{success:!1,error:"Failed to generate security hash"}}try{if(f.SEA&&f.SEA.encrypt)s=await f.SEA.encrypt(r,t);else{if(!this.crypto||!this.crypto.encrypt)throw new Error("Encryption functions not available");s=await this.crypto.encrypt(r,t)}if(!s)throw new Error("Failed to encrypt hint")}catch(e){return(0,c.logError)("Error encrypting hint:",e),{success:!1,error:"Failed to encrypt password hint"}}return await this.saveUserData("security",{questions:JSON.stringify(n),hint:s}),{success:!0}}catch(e){return(0,c.logError)("Error setting password hint:",e),{success:!1,error:String(e)}}}async forgotPassword(e,t){(0,c.log)("Attempting password recovery for:",e);try{const r=await this.checkUsernameExists(e);if(!r)return{success:!1,error:"User not found"};const n=this.gun.user(r),i=await new Promise((e=>{n.get("security").once((t=>{e(t)}))}));if(!i||!i.hint)return{success:!1,error:"No password hint found"};const s=t.join("|");let o,a;try{if(f.SEA&&f.SEA.work)o=await f.SEA.work(s,null,null,{name:"SHA-256"});else{if(!this.crypto||!this.crypto.hashText)throw new Error("Cryptographic functions not available");o=await this.crypto.hashText(s)}if(!o)throw new Error("Failed to generate hash")}catch(e){return(0,c.logError)("Error generating hash:",e),{success:!1,error:"Failed to generate security hash"}}try{if(f.SEA&&f.SEA.decrypt)a=await f.SEA.decrypt(i.hint,o);else{if(!this.crypto||!this.crypto.decrypt)throw new Error("Decryption functions not available");a=await this.crypto.decrypt(i.hint,o)}}catch(e){return{success:!1,error:"Incorrect answers to security questions"}}return void 0===a?{success:!1,error:"Incorrect answers to security questions"}:{success:!0,hint:a}}catch(e){return(0,c.logError)("Error recovering password hint:",e),{success:!1,error:String(e)}}}async hashText(e){return this.crypto.hashText(e)}async encrypt(e,t){return this.crypto.encrypt(e,t)}async decrypt(e,t){return this.crypto.decrypt(e,t)}async saveUserData(e,t){return new Promise(((r,n)=>{const i=this.gun.user();i.is?this.navigateToPath(i,e).put(t,(e=>{e.err?n(new Error(e.err)):r()})):n(new Error("User not authenticated"))}))}async getUserData(e){return new Promise((t=>{const r=this.gun.user();r.is?this.navigateToPath(r,e).once((e=>{t(e)})):t(null)}))}async derive(e,t,r){try{(0,c.log)("Deriving cryptographic keys with options:",r);const n=await(0,p.default)(e,t,r);return(0,c.log)("Key derivation completed successfully"),n}catch(e){throw(0,c.logError)("Error during key derivation:",e),u.ErrorHandler.handle(u.ErrorType.ENCRYPTION,"KEY_DERIVATION_FAILED",e instanceof Error?e.message:"Failed to derive cryptographic keys",e),e}}async deriveP256(e,t){return this.derive(e,t,{includeP256:!0})}async deriveBitcoin(e,t){return this.derive(e,t,{includeSecp256k1Bitcoin:!0})}async deriveEthereum(e,t){return this.derive(e,t,{includeSecp256k1Ethereum:!0})}async deriveAll(e,t){return this.derive(e,t,{includeP256:!0,includeSecp256k1Bitcoin:!0,includeSecp256k1Ethereum:!0})}static Errors=g}},21638:()=>{},23358:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorHandler=t.ErrorType=void 0,t.createError=s;const n=r(45628);var i;function s(e,t,r,n){return{type:e,code:t,message:r,originalError:n,timestamp:Date.now()}}!function(e){e.AUTHENTICATION="AuthenticationError",e.AUTHORIZATION="AuthorizationError",e.VALIDATION="ValidationError",e.NETWORK="NetworkError",e.DATABASE="DatabaseError",e.WALLET="WalletError",e.STORAGE="StorageError",e.ENCRYPTION="EncryptionError",e.SIGNATURE="SignatureError",e.ENVIRONMENT="EnvironmentError",e.SECURITY="SecurityError",e.GUN="GunError",e.STEALTH="StealthError",e.WEBAUTHN="WebAuthnError",e.PLUGIN="PluginError",e.UNKNOWN="UnknownError",e.CONNECTOR="ConnectorError",e.GENERAL="GeneralError",e.CONTRACT="ContractError",e.BIP32="BIP32Error",e.ETHEREUM="EthereumError",e.BITCOIN="BitcoinError"}(i||(t.ErrorType=i={}));t.ErrorHandler=class{static errors=[];static maxErrors=100;static listeners=[];static handleError(e){(0,n.logError)(`[${e.type}] ${e.code}: ${e.message}`),this.errors.push(e),this.errors.length>this.maxErrors&&(this.errors=this.errors.slice(-this.maxErrors)),this.notifyListeners(e)}static handle(e,t,r,i,o="error"){const a=i?`${r} - ${this.formatError(i)}`:r;switch(o){case"debug":(0,n.log)(`[${e}.${t}] (DEBUG) ${a}`);break;case"warn":(0,n.log)(`[${e}.${t}] (WARN) ${a}`);break;case"info":(0,n.log)(`[${e}.${t}] (INFO) ${a}`);break;default:(0,n.log)(`[${e}.${t}] (ERROR) ${a}`),i&&i instanceof Error&&(0,n.log)(i.stack||"No stack trace available")}const c=s(e,t,a,i);return this.handleError(c),c}static handleAndThrow(e,t,r,n){throw this.handle(e,t,r,n)}static getRecentErrors(e=10){return this.errors.slice(-Math.min(e,this.errors.length))}static addListener(e){this.listeners.push(e)}static removeListener(e){const t=this.listeners.indexOf(e);-1!==t&&this.listeners.splice(t,1)}static notifyListeners(e){for(const t of this.listeners)try{t(e)}catch(e){(0,n.logError)(`Error in error listener: ${e}`)}}static formatError(e){if(!e)return"Unknown error";if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("object"==typeof e)try{return JSON.stringify(e)}catch(t){return`Object: ${Object.prototype.toString.call(e)}`}return String(e)}static async withRetry(e,t,r,i=3,s=1e3){let o;for(let t=1;t<=i;t++)try{return await e()}catch(e){o=e;const r=s*t;t<i&&((0,n.log)(`Retrying operation after ${r}ms (attempt ${t}/${i})`),await new Promise((e=>setTimeout(e,r))))}throw this.handle(t,r,`Operation failed after ${i} attempts`,o)}static clearErrors(){this.errors=[]}static getErrorStats(){const e={total:this.errors.length,byType:{},byCode:{}};for(const t of this.errors)e.byType[t.type]=(e.byType[t.type]||0)+1,e.byCode[t.code]=(e.byCode[t.code]||0)+1;return e}}},24993:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SEA=t.Gun=void 0;const i=n(r(54827));t.Gun=i.default;const s=n(r(38030));Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return s.default}})},28156:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(197),t),i(r(5307),t)},34586:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BasePlugin=void 0;const n=r(14134);class i extends n.EventEmitter{description;_category;core=null;initialize(e){this.core=e}destroy(){this.core=null}assertInitialized(){if(!this.core)throw new Error(`Plugin ${this.name} not initialized`);return this.core}}t.BasePlugin=i},37510:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Webauthn=void 0;const n=r(14193),i=r(23358),s=r(14134),o=r(45628),a=r(61731),c={rpName:"Shogun Wallet",timeout:6e4,userVerification:"preferred",attestation:"none",authenticatorAttachment:"platform",requireResidentKey:!1};class u extends s.EventEmitter{config;gunInstance;credential;abortController=null;constructor(e,t){super(),this.gunInstance=e,this.credential=null,this.config={...c,...t,rpId:t?.rpId??window.location.hostname.split(":")[0]}}validateUsername(e){if(!e||"string"!=typeof e)throw new Error("Username must be a non-empty string");if(e.length<3||e.length>64)throw new Error("Username must be between 3 and 64 characters");if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error("Username can only contain letters, numbers, underscores and hyphens")}async createAccount(e,t,r=!1){try{this.validateUsername(e);const n=3;let i=null;for(let s=1;s<=n;s++)try{const n=await this.generateCredentials(e,t,r);if(n.success)return this.emit(a.WebAuthnEventType.DEVICE_REGISTERED,{type:a.WebAuthnEventType.DEVICE_REGISTERED,data:{username:e,deviceInfo:n.deviceInfo},timestamp:Date.now()}),n;i=new Error(n.error??"Unknown error")}catch(e){if(i=e,s<n){await new Promise((e=>setTimeout(e,1e3*s)));continue}}throw i||new Error("Failed to create account after retries")}catch(e){throw this.emit(a.WebAuthnEventType.ERROR,{type:a.WebAuthnEventType.ERROR,data:{error:e.message},timestamp:Date.now()}),e}}async authenticateUser(e,t,r={}){try{if(this.validateUsername(e),!t){const e=new Error("No WebAuthn credentials found for this username");return i.ErrorHandler.handle(i.ErrorType.WEBAUTHN,"NO_CREDENTIALS",e.message,e),{success:!1,error:e.message}}this.abortAuthentication(),this.abortController=new AbortController;const n=r.timeout||this.config.timeout,s=setTimeout((()=>this.abortController?.abort()),n);try{const i={challenge:this.generateChallenge(e),allowCredentials:[],timeout:n,userVerification:r.userVerification||this.config.userVerification,rpId:this.config.rpId},s=await navigator.credentials.get({publicKey:i,signal:this.abortController.signal});if(!s)throw new Error("WebAuthn verification failed");const{password:o}=this.generateCredentialsFromSalt(e,t),c=this.getDeviceInfo(s.id),u={success:!0,username:e,password:o,credentialId:this.bufferToBase64(s.rawId),deviceInfo:c};return this.emit(a.WebAuthnEventType.AUTHENTICATION_SUCCESS,{type:a.WebAuthnEventType.AUTHENTICATION_SUCCESS,data:{username:e,deviceInfo:c},timestamp:Date.now()}),u}finally{clearTimeout(s),this.abortController=null}}catch(t){const r=t instanceof Error?t.message:"Unknown WebAuthn error";return this.emit(a.WebAuthnEventType.AUTHENTICATION_FAILED,{type:a.WebAuthnEventType.AUTHENTICATION_FAILED,data:{username:e,error:r},timestamp:Date.now()}),i.ErrorHandler.handle(i.ErrorType.WEBAUTHN,"AUTH_ERROR",r,t),{success:!1,error:r}}}abortAuthentication(){this.abortController&&(this.abortController.abort(),this.abortController=null)}getDeviceInfo(e){const t=this.getPlatformInfo();return{deviceId:e,timestamp:Date.now(),name:t.name,platform:t.platform,lastUsed:Date.now()}}getPlatformInfo(){if("undefined"==typeof navigator)return{name:"unknown",platform:"unknown"};const e=navigator.platform,t=navigator.userAgent;return/iPhone|iPad|iPod/.test(e)?{name:"iOS Device",platform:e}:/Android/.test(t)?{name:"Android Device",platform:e}:/Win/.test(e)?{name:"Windows Device",platform:e}:/Mac/.test(e)?{name:"Mac Device",platform:e}:/Linux/.test(e)?{name:"Linux Device",platform:e}:{name:"Unknown Device",platform:e}}generateChallenge(e){const t=Date.now().toString(),r=this.getRandomBytes(32),n=`${e}-${t}-${this.uint8ArrayToHex(r)}`;return(new TextEncoder).encode(n)}getRandomBytes(e){if("undefined"!=typeof window&&window.crypto)return window.crypto.getRandomValues(new Uint8Array(e));throw new Error("No cryptographic implementation available")}uint8ArrayToHex(e){return Array.from(e).map((e=>e.toString(16).padStart(2,"0"))).join("")}bufferToBase64(e){const t=new Uint8Array(e).reduce(((e,t)=>e+String.fromCharCode(t)),"");return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}generateCredentialsFromSalt(e,t){const r=n.ethers.toUtf8Bytes(e+t);return{password:n.ethers.sha256(r)}}isSupported(){return"undefined"!=typeof window&&void 0!==window.PublicKeyCredential}async createCredential(e){try{const t=crypto.getRandomValues(new Uint8Array(32)),r=(new TextEncoder).encode(e),n={challenge:t,rp:{name:"Shogun Wallet",..."localhost"!==this.config.rpId&&{id:this.config.rpId}},user:{id:r,name:e,displayName:e},pubKeyCredParams:[{type:"public-key",alg:-7}],timeout:this.config.timeout,attestation:this.config.attestation,authenticatorSelection:{authenticatorAttachment:this.config.authenticatorAttachment,userVerification:this.config.userVerification,requireResidentKey:this.config.requireResidentKey}};(0,o.logDebug)("Attempting to create credentials with options:",n);const i=await navigator.credentials.create({publicKey:n});if(!i)throw new Error("Credential creation failed");(0,o.logDebug)("Credentials created successfully:",i);const s=i,a={id:s.id,rawId:s.rawId,type:s.type,response:{clientDataJSON:s.response.clientDataJSON},getClientExtensionResults:s.getClientExtensionResults};return"attestationObject"in s.response&&(a.response.attestationObject=s.response.attestationObject),this.credential=a,a}catch(e){(0,o.logError)("Detailed error in credential creation:",e);const t=e instanceof Error?e.message:"Unknown error";throw new Error(`Error creating credentials: ${t}`)}}async generateCredentials(e,t,r=!1){try{if(r){const t=await this.verifyCredential(e);return{success:t.success,error:t.error,credentialId:t.credentialId,username:t.username}}{const t=await this.createCredential(e),r=t.id;let n=null;return t?.response?.getPublicKey&&(n=t.response.getPublicKey()),{success:!0,credentialId:r,publicKey:n}}}catch(e){(0,o.logError)("Error in generateCredentials:",e);return{success:!1,error:e instanceof Error?e.message:"Unknown error during WebAuthn operation"}}}async verifyCredential(e){try{const t={challenge:crypto.getRandomValues(new Uint8Array(32)),timeout:this.config.timeout,userVerification:this.config.userVerification,..."localhost"!==this.config.rpId&&{rpId:this.config.rpId}};this.credential?.rawId&&(t.allowCredentials=[{id:this.credential.rawId,type:"public-key"}]);const r=await navigator.credentials.get({publicKey:t});return r?{success:!0,credentialId:r.id,username:e}:{success:!1,error:"Credential verification failed"}}catch(e){(0,o.logError)("Error verifying credentials:",e);return{success:!1,error:e instanceof Error?e.message:"Unknown error verifying credentials"}}}async removeDevice(e,t,r){if(!r||!r.credentials||!r.credentials[t])return{success:!1};const n={...r};return n.credentials&&delete n.credentials[t],{success:!0,updatedCredentials:n}}async sign(e){return await navigator.credentials.get({publicKey:{challenge:new Uint8Array(16),rpId:this.config.rpId}})}}t.Webauthn=u,"undefined"!=typeof window?window.Webauthn=u:void 0!==r.g&&(r.g.Webauthn=u)},37897:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NostrConnector=void 0;const n=r(45628),i=r(23358),s=r(14134);class o extends s.EventEmitter{MESSAGE_TO_SIGN="I Love Shogun!";DEFAULT_CONFIG={cacheDuration:864e5,maxRetries:3,retryDelay:1e3,timeout:6e4,network:"mainnet",useApi:!1};config;signatureCache=new Map;connectedAddress=null;connectedType=null;manualKeyPair=null;constructor(e={}){super(),this.config={...this.DEFAULT_CONFIG,...e},this.setupEventListeners()}setupEventListeners(){}cleanup(){this.removeAllListeners(),this.connectedAddress=null,this.connectedType=null,this.manualKeyPair=null}getCachedSignature(e){const t=this.signatureCache.get(e);if(t){if(Date.now()-t.timestamp<=this.config.cacheDuration)return t.signature;this.signatureCache.delete(e)}try{const t=`shogun_bitcoin_sig_${e}`,r=localStorage.getItem(t);if(r){const n=JSON.parse(r);if(Date.now()-n.timestamp<=this.config.cacheDuration)return this.signatureCache.set(e,n),n.signature;localStorage.removeItem(t)}}catch(e){(0,n.logError)("Error reading signature cache from localStorage:",e)}return null}cacheSignature(e,t){const r={signature:t,timestamp:Date.now(),address:e};this.signatureCache.set(e,r);try{const t=`shogun_bitcoin_sig_${e}`;localStorage.setItem(t,JSON.stringify(r)),(0,n.log)(`Cached signature for address: ${e.substring(0,10)}...`)}catch(e){(0,n.logError)("Error saving signature cache to localStorage:",e)}}clearSignatureCache(e){if(e){this.signatureCache.delete(e);try{const t=`shogun_bitcoin_sig_${e}`;localStorage.removeItem(t),(0,n.log)(`Cleared signature cache for address: ${e.substring(0,10)}...`)}catch(e){(0,n.logError)("Error clearing signature cache from localStorage:",e)}}else{this.signatureCache.clear();try{const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);r&&r.startsWith("shogun_bitcoin_sig_")&&e.push(r)}e.forEach((e=>localStorage.removeItem(e))),(0,n.log)(`Cleared all signature caches (${e.length} entries)`)}catch(e){(0,n.logError)("Error clearing all signature caches from localStorage:",e)}}}validateAddress(e){if(!e)throw new Error("Address not provided");try{const t=String(e).trim();if("nostr"===this.connectedType){if(!t)throw new Error("Empty Nostr public key")}else if("manual"===this.connectedType){if(!t)throw new Error("Empty manual key")}else if(!/^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,59}$/.test(t))throw new Error("Invalid Bitcoin address format");return t}catch(e){throw i.ErrorHandler.handle(i.ErrorType.VALIDATION,"INVALID_ADDRESS","Invalid Bitcoin address provided",e),e}}isNostrExtensionAvailable(){return"undefined"!=typeof window&&!!window.nostr}isAvailable(){return this.isNostrExtensionAvailable()||null!==this.manualKeyPair}async connectWallet(e="nostr"){(0,n.log)(`Connecting to Bitcoin wallet via ${e}...`);try{let t;switch(e){case"alby":(0,n.log)("Alby is deprecated, redirecting to Nostr"),t=await this.connectNostr();break;case"nostr":t=await this.connectNostr();break;case"manual":t=await this.connectManual();break;default:throw new Error(`Unsupported wallet type: ${e}`)}return t.success&&t.address&&(this.connectedAddress=t.address,this.connectedType=e,(0,n.log)(`Successfully connected to ${e} wallet: ${t.address}`),this.emit("wallet_connected",{address:t.address,type:this.connectedType})),t}catch(t){return(0,n.logError)(`Error connecting to ${e} wallet:`,t),{success:!1,error:t.message||"Failed to connect to wallet"}}}async connectNostr(){if(!this.isNostrExtensionAvailable())return{success:!1,error:"Nostr extension is not available. Please install a Nostr compatible extension."};try{const e=await window.nostr.getPublicKey();if(!e)throw new Error("Could not get public key from Nostr extension");this.connectedAddress=e,this.connectedType="nostr",this.emit("connected",{address:e,type:"nostr"});const t=`nostr_${e.substring(0,10)}`;return{success:!0,address:e,username:t,extensionType:"nostr"}}catch(e){throw new Error(`Nostr connection error: ${e.message}`)}}async connectManual(){if(!this.manualKeyPair)return{success:!1,error:"No manual key pair configured. Use setKeyPair() first."};this.connectedAddress=this.manualKeyPair.address,this.connectedType="manual",this.emit("connected",{address:this.manualKeyPair.address,type:"manual"});const e=`btc_${this.manualKeyPair.address.substring(0,10)}`;return{success:!0,address:this.manualKeyPair.address,username:e,extensionType:"manual"}}setKeyPair(e){this.manualKeyPair=e,e.address&&(this.connectedAddress=e.address,this.connectedType="manual")}async generateCredentials(e){(0,n.logDebug)(`Generating credentials for address: ${e}`);try{!this.connectedType&&e&&(/^[0-9a-f]{64}$/.test(e)||e.startsWith("npub"))&&(this.connectedType="nostr",this.connectedAddress=e);const t=this.validateAddress(e),r=this.getCachedSignature(t);if(r)return(0,n.logDebug)("Using cached signature"),await this.generateCredentialsFromSignature(t,r);const i=this.MESSAGE_TO_SIGN;let s;try{return s=await this.generateDeterministicSignature(t),(0,n.log)("Using deterministic signature for consistency"),this.cacheSignature(t,s),await this.generateCredentialsFromSignature(t,s)}catch(e){(0,n.logError)("Error generating deterministic signature:",e);try{s=await this.requestSignatureWithTimeout(t,i,this.config.timeout),this.cacheSignature(t,s),(0,n.log)("Using real Nostr signature as fallback")}catch(e){(0,n.logError)("Error requesting signature:",e),s=await this.generateDeterministicSignature(t),this.cacheSignature(t,s),(0,n.log)("Using deterministic signature as final fallback")}}return await this.generateCredentialsFromSignature(t,s)}catch(e){throw(0,n.logError)("Error generating credentials:",e),e}}async generateDeterministicSignature(e){const t=`${e}_${this.MESSAGE_TO_SIGN}_shogun_deterministic`;let r="",i=0;for(let e=0;e<t.length;e++){i=31*i+t.charCodeAt(e)&4294967295,e%4==3&&(r+=i.toString(16).padStart(8,"0"))}for(;r.length<128;)i=31*i+r.length&4294967295,r+=i.toString(16).padStart(8,"0");let s=r.substring(0,128);return s=s.toLowerCase().replace(/[^0-9a-f]/g,"0"),s.length<128?s=s.padEnd(128,"0"):s.length>128&&(s=s.substring(0,128)),(0,n.log)(`Generated deterministic signature: ${s.substring(0,16)}... (${s.length} chars)`),s}async generateCredentialsFromSignature(e,t){(0,n.log)("Generating credentials from signature");return{username:`${e.toLowerCase()}`,password:await this.generatePassword(t),message:this.MESSAGE_TO_SIGN,signature:t}}async generatePassword(e){if(!e)throw new Error("Invalid signature");try{const t=e.toLowerCase().replace(/[^a-f0-9]/g,"");let r="",n=0;for(let e=0;e<t.length;e++){n=31*n+t.charCodeAt(e)&4294967295,e%8==7&&(r+=n.toString(16).padStart(8,"0"))}for(;r.length<64;)n=31*n+r.length&4294967295,r+=n.toString(16).padStart(8,"0");return r.substring(0,64)}catch(e){throw(0,n.logError)("Error generating password:",e),new Error("Failed to generate password from signature")}}async verifySignature(e,t,r){try{const i="object"==typeof r?r.address||JSON.stringify(r):String(r);if((0,n.log)(`Verifying signature for address: ${i}`),!t||!e)return(0,n.logError)("Invalid message or signature for verification"),!1;if((0,n.log)(`Signature to verify: ${t.substring(0,20)}... (length: ${t.length})`),(0,n.log)(`Message to verify: ${e}`),"nostr"===this.connectedType||"alby"===this.connectedType){(0,n.log)("Using Nostr-specific verification");try{if(!this.connectedAddress)return(0,n.logError)("No connected address to verify against"),!1;const e=String(this.connectedAddress).toLowerCase(),r=i.toLowerCase();if(r!==e)return(0,n.logError)("Address mismatch in signature verification"),(0,n.logError)(`Expected: ${e}, Got: ${r}`),!1;const s=/^[0-9a-f]+$/i.test(t),o=t.length>=64;return(0,n.log)(`Signature format check: hex=${s}, length=${o} (${t.length} chars)`),s?o?((0,n.log)("Nostr signature appears valid"),!0):((0,n.logError)(`Invalid signature length: ${t.length} (minimum 64 required)`),!1):((0,n.logError)("Invalid signature format - not a valid hex string"),(0,n.logError)(`Signature contains invalid characters: ${t}`),!1)}catch(e){return(0,n.logError)("Error in signature verification:",e),!1}}else if("manual"===this.connectedType&&this.manualKeyPair){(0,n.log)("Using manual verification for keypair");try{const e=String(this.manualKeyPair.address).toLowerCase(),t=i.toLowerCase()===e;return(0,n.log)(`Manual verification - address match: ${t}`),t}catch(e){return(0,n.logError)("Error in manual signature verification:",e),!1}}if(this.config.useApi&&this.config.apiUrl){(0,n.log)("Using API-based verification");try{return!0}catch(e){return(0,n.logError)("API verification error:",e),!1}}return(0,n.logWarn)("No specific verification method available, signature cannot be fully verified"),!1}catch(e){return(0,n.logError)("Error verifying signature:",e),!1}}getConnectedAddress(){return this.connectedAddress}getConnectedType(){return this.connectedType}requestSignatureWithTimeout(e,t,r=3e4){return new Promise(((n,i)=>{const s=setTimeout((()=>{i(new Error("Signature request timed out"))}),r);this.requestSignature(e,t).then((e=>{clearTimeout(s),n(e)})).catch((e=>{clearTimeout(s),i(e)}))}))}async requestSignature(e,t){if(!this.connectedType)throw new Error("No wallet connected");try{switch(this.connectedType){case"alby":if((0,n.logWarn)("Alby is deprecated, redirecting signature request to Nostr"),!window.nostr)throw new Error("Nostr extension not available");const r={kind:1,created_at:Math.floor(Date.now()/1e3),tags:[],content:t,pubkey:e};return(await window.nostr.signEvent(r)).sig;case"nostr":(0,n.log)("Requesting Nostr signature for message:",t);const i={kind:1,created_at:Math.floor(Date.now()/1e3),tags:[],content:t,pubkey:e},s=await window.nostr.signEvent(i);(0,n.log)("Received Nostr signature:",s.sig.substring(0,20)+"...");let o=s.sig;return o&&"string"==typeof o&&(o=o.replace(/[^a-f0-9]/gi,"").toLowerCase(),o.length>128?o=o.substring(0,128):o.length<128&&(o=o.padStart(128,"0")),(0,n.log)(`Normalized Nostr signature: ${o.substring(0,10)}...`)),o;case"manual":if((0,n.log)("Using manual key pair for signature"),!this.manualKeyPair)throw new Error("No manual key pair available");const a=`${this.manualKeyPair.privateKey.substring(0,32)}_${t}_${Date.now()}`;return(0,n.log)("Generated manual signature:",a.substring(0,20)+"..."),a;default:throw new Error(`Unsupported wallet type: ${this.connectedType}`)}}catch(e){throw(0,n.logError)("Error requesting signature:",e),new Error(`Failed to get signature: ${e.message}`)}}}t.NostrConnector=o,"undefined"!=typeof window?window.NostrConnector=o:void 0!==r.g&&(r.g.NostrConnector=o)},38664:()=>{},43188:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.WebAuthnSigner=void 0;const i=r(37510),s=r(25897),o=r(22623),a=r(45628),c=n(r(67476)),u=r(14193),l=function(e){const t=new Uint8Array(e);return btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},g=function(e){for(e=e.replace(/-/g,"+").replace(/_/g,"/");e.length%4;)e+="=";const t=atob(e);return new Uint8Array(t.split("").map((e=>e.charCodeAt(0))))};class h{webauthn;credentials=new Map;constructor(e){this.webauthn=e||new i.Webauthn}async createSigningCredential(e){try{const t=await navigator.credentials.create({publicKey:{challenge:crypto.getRandomValues(new Uint8Array(32)),rp:{id:"localhost"===window.location.hostname?"localhost":window.location.hostname,name:"Shogun Wallet"},user:{id:(new TextEncoder).encode(e),name:e,displayName:e},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-25},{type:"public-key",alg:-257}],authenticatorSelection:{userVerification:"preferred"},timeout:6e4,attestation:"none"}});if(!t)throw new Error("Failed to create WebAuthn credential");const r=t.response.getPublicKey();if(!r)throw new Error("Failed to get public key from credential");const n=new Uint8Array(r);(0,a.logDebug)("Raw public key bytes:",n);const i=n.slice(27,59),s=n.slice(59,91),o=l(i),c=l(s),g=`${o}.${c}`,h=u.ethers.keccak256(u.ethers.toUtf8Bytes(t.id)),d={id:t.id,rawId:t.rawId,publicKey:{x:o,y:c},pub:g,hashedCredentialId:h};return this.credentials.set(t.id,d),(0,a.logDebug)("Created signing credential:",d),d}catch(e){throw(0,a.logError)("Error creating signing credential:",e),new Error(`Failed to create signing credential: ${e.message}`)}}createAuthenticator(e){const t=this.credentials.get(e);if(!t)throw new Error(`Credential ${e} not found`);return async e=>{try{const r={challenge:(new TextEncoder).encode(JSON.stringify(e)),rpId:"localhost"===window.location.hostname?"localhost":window.location.hostname,userVerification:"preferred",allowCredentials:[{type:"public-key",id:t.rawId}],timeout:6e4},n=await navigator.credentials.get({publicKey:r});if(!n)throw new Error("WebAuthn assertion failed");return(0,a.logDebug)("WebAuthn assertion successful:",{options:r,assertion:n}),n.response}catch(e){throw(0,a.logError)("WebAuthn assertion error:",e),e}}}async createDerivedKeyPair(e,t,r){const n=this.credentials.get(e);if(!n)throw new Error(`Credential ${e} not found`);try{const e=await(0,c.default)(n.hashedCredentialId,r,{includeP256:!0});return{pub:e.pub,priv:e.priv,epub:e.epub,epriv:e.epriv}}catch(e){throw(0,a.logError)("Error deriving keys from WebAuthn credential:",e),e}}async createGunUser(e,t,r){const n=this.credentials.get(e);if(!n)throw new Error(`Credential ${e} not found`);try{return new Promise((i=>{r.user().create(t,n.hashedCredentialId,(s=>{s.err?r.user().auth(t,n.hashedCredentialId,(t=>{if(t.err)i({success:!1,error:t.err});else{const r=t.pub;n.gunUserPub=r,this.credentials.set(e,n),i({success:!0,userPub:r})}})):r.user().auth(t,n.hashedCredentialId,(t=>{if(t.err)i({success:!1,error:t.err});else{const r=t.pub;n.gunUserPub=r,this.credentials.set(e,n),i({success:!0,userPub:r})}}))}))}))}catch(e){return(0,a.logError)("Error creating Gun user:",e),{success:!1,error:e.message}}}async signWithDerivedKeys(e,t,r,n){try{const i=this.createAuthenticator(t);await i(e);const a=await this.createDerivedKeyPair(t,r,n),c=JSON.stringify(e),u=(0,o.sha256)((new TextEncoder).encode(c)),h=g(a.priv),d=s.p256.sign(u,h),f={m:c,s:l(d.toCompactRawBytes())};return"SEA"+JSON.stringify(f)}catch(e){throw(0,a.logError)("Error signing with derived keys:",e),e}}getGunUserPub(e){const t=this.credentials.get(e);return t?.gunUserPub}getHashedCredentialId(e){const t=this.credentials.get(e);return t?.hashedCredentialId}async verifyConsistency(e,t,r){if(!this.credentials.get(e))return{consistent:!1};const n=await this.createDerivedKeyPair(e,t);return{consistent:!r||n.pub===r,actualUserPub:n.pub,expectedUserPub:r}}getCredential(e){return this.credentials.get(e)}listCredentials(){return Array.from(this.credentials.values())}removeCredential(e){return this.credentials.delete(e)}}t.WebAuthnSigner=h,t.default=h},45628:(e,t,r)=>{"use strict";var n=r(65606);Object.defineProperty(t,"__esModule",{value:!0}),t.enableDebug=function(){s=!0,o("Debug mode enabled")},t.disableDebug=function(){s=!1},t.configureLogging=function(e){i={...i,...e}},t.log=o,t.logError=a,t.logWarn=c,t.logDebug=u,t.logWithLevel=function(e,t,...r){switch(e){case"error":a(t,...r);break;case"warn":c(t,...r);break;case"debug":u(t,...r);break;default:o(t,...r)}};let i={enabled:"true"===n.env.DEBUG,level:"info",prefix:"[ShogunSDK]"},s=!1;function o(e,...t){(new Date).toISOString()}function a(e,...t){(new Date).toISOString()}function c(e,...t){(new Date).toISOString()}function u(e,...t){if(!s)return;(new Date).toISOString()}},47790:()=>{},48050:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NostrConnectorPlugin=void 0;const n=r(34586),i=r(37897),s=r(70050),o=r(45628),a=r(23358);class c extends n.BasePlugin{name="nostr";version="1.0.0";description="Provides Bitcoin wallet connection and authentication for ShogunCore";bitcoinConnector=null;signer=null;initialize(e){super.initialize(e),this.bitcoinConnector=new i.NostrConnector,this.signer=new s.NostrSigner(this.bitcoinConnector),(0,o.log)("Bitcoin wallet plugin initialized with signer support")}destroy(){this.bitcoinConnector&&this.bitcoinConnector.cleanup(),this.bitcoinConnector=null,this.signer=null,super.destroy(),(0,o.log)("Bitcoin wallet plugin destroyed")}assertBitcoinConnector(){if(this.assertInitialized(),!this.bitcoinConnector)throw new Error("Bitcoin wallet module not initialized");return this.bitcoinConnector}assertSigner(){if(this.assertInitialized(),!this.signer)throw new Error("Nostr signer not initialized");return this.signer}isAvailable(){return this.assertBitcoinConnector().isAvailable()}isAlbyAvailable(){return(0,o.log)("Alby is deprecated, using Nostr instead"),this.isNostrExtensionAvailable()}isNostrExtensionAvailable(){return this.assertBitcoinConnector().isNostrExtensionAvailable()}async connectBitcoinWallet(e="nostr"){return"alby"===e&&((0,o.log)("Alby is deprecated, using Nostr instead"),e="nostr"),this.assertBitcoinConnector().connectWallet(e)}async generateCredentials(e){return(0,o.log)("Calling credential generation for Bitcoin wallet"),this.assertBitcoinConnector().generateCredentials(e)}cleanup(){this.assertBitcoinConnector().cleanup()}clearSignatureCache(e){this.assertBitcoinConnector().clearSignatureCache(e)}async verifySignature(e,t,r){return this.assertBitcoinConnector().verifySignature(e,t,r)}async generatePassword(e){return this.assertBitcoinConnector().generatePassword(e)}async createSigningCredential(e){try{return(0,o.log)(`Creating Nostr signing credential for address: ${e}`),await this.assertSigner().createSigningCredential(e)}catch(e){throw(0,o.logError)(`Error creating Nostr signing credential: ${e.message}`),e}}createAuthenticator(e){try{return(0,o.log)(`Creating Nostr authenticator for address: ${e}`),this.assertSigner().createAuthenticator(e)}catch(e){throw(0,o.logError)(`Error creating Nostr authenticator: ${e.message}`),e}}async createDerivedKeyPair(e,t){try{return(0,o.log)(`Creating derived key pair for address: ${e}`),await this.assertSigner().createDerivedKeyPair(e,t)}catch(e){throw(0,o.logError)(`Error creating derived key pair: ${e.message}`),e}}async signWithDerivedKeys(e,t,r){try{return(0,o.log)(`Signing data with derived keys for address: ${t}`),await this.assertSigner().signWithDerivedKeys(e,t,r)}catch(e){throw(0,o.logError)(`Error signing with derived keys: ${e.message}`),e}}getSigningCredential(e){return this.assertSigner().getCredential(e)}listSigningCredentials(){return this.assertSigner().listCredentials()}removeSigningCredential(e){return this.assertSigner().removeCredential(e)}async createGunUserFromSigningCredential(e){try{const t=this.assertInitialized();return(0,o.log)(`Creating Gun user from Nostr signing credential: ${e}`),await this.assertSigner().createGunUser(e,t.gun)}catch(e){throw(0,o.logError)(`Error creating Gun user from Nostr signing credential: ${e.message}`),e}}getGunUserPubFromSigningCredential(e){return this.assertSigner().getGunUserPub(e)}getPassword(e){return this.assertSigner().getPassword(e)}async verifyConsistency(e,t){try{return(0,o.log)(`Verifying Nostr consistency for address: ${e}`),await this.assertSigner().verifyConsistency(e,t)}catch(e){return(0,o.logError)(`Error verifying Nostr consistency: ${e.message}`),{consistent:!1}}}async setupConsistentOneshotSigning(e){try{(0,o.log)(`Setting up consistent Nostr oneshot signing for: ${e}`);const t=await this.createSigningCredential(e),r=this.createAuthenticator(e);return{credential:t,authenticator:r,gunUser:await this.createGunUserFromSigningCredential(e),username:t.username,password:t.password}}catch(e){throw(0,o.logError)(`Error setting up consistent Nostr oneshot signing: ${e.message}`),e}}async login(e){(0,o.log)("Login with Bitcoin wallet");try{const t=this.assertInitialized();if((0,o.log)(`Bitcoin wallet login attempt for address: ${e}`),!e)throw(0,a.createError)(a.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Bitcoin address required for login");if(!this.isAvailable())throw(0,a.createError)(a.ErrorType.ENVIRONMENT,"BITCOIN_WALLET_UNAVAILABLE","No Bitcoin wallet available in the browser");(0,o.log)("Generating credentials for Bitcoin wallet login...");const r=await this.generateCredentials(e);if(!(r?.username&&r?.password&&r.signature&&r.message))throw(0,a.createError)(a.ErrorType.AUTHENTICATION,"CREDENTIAL_GENERATION_FAILED","Bitcoin wallet credentials not generated correctly or signature missing");(0,o.log)(`Credentials generated successfully. Username: ${r.username}`),(0,o.log)("Verifying Bitcoin wallet signature...");if(!await this.verifySignature(r.message,r.signature,e))throw(0,o.logError)(`Signature verification failed for address: ${e}`),(0,a.createError)(a.ErrorType.SECURITY,"SIGNATURE_VERIFICATION_FAILED","Bitcoin wallet signature verification failed");(0,o.log)("Bitcoin wallet signature verified successfully."),t.setAuthMethod("nostr"),(0,o.log)("Logging in using core login method...");const n=await t.login(r.username,r.password);if(!n.success)throw(0,a.createError)(a.ErrorType.AUTHENTICATION,"BITCOIN_LOGIN_FAILED",n.error||"Failed to log in with Bitcoin credentials");return t.emit("auth:login",{userPub:n.userPub,username:r.username,method:"bitcoin"}),n}catch(e){const t=e?.type||a.ErrorType.AUTHENTICATION,r=e?.code||"BITCOIN_LOGIN_ERROR",n=e?.message||"Unknown error during Bitcoin wallet login";return{success:!1,error:a.ErrorHandler.handle(t,r,n,e).message}}}async signUp(e){(0,o.log)("Sign up with Bitcoin wallet");try{const t=this.assertInitialized();if((0,o.log)(`Bitcoin wallet signup attempt for address: ${e}`),!e)throw(0,a.createError)(a.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Bitcoin address required for signup");if(!this.isAvailable())throw(0,a.createError)(a.ErrorType.ENVIRONMENT,"BITCOIN_WALLET_UNAVAILABLE","No Bitcoin wallet available in the browser");(0,o.log)("Generating credentials for Bitcoin wallet signup...");const r=await this.generateCredentials(e);if(!(r?.username&&r?.password&&r.signature&&r.message))throw(0,a.createError)(a.ErrorType.AUTHENTICATION,"CREDENTIAL_GENERATION_FAILED","Bitcoin wallet credentials not generated correctly or signature missing");(0,o.log)(`Credentials generated successfully. Username: ${r.username}`),(0,o.log)("Verifying Bitcoin wallet signature...");if(!await this.verifySignature(r.message,r.signature,e))throw(0,o.logError)(`Signature verification failed for address: ${e}`),(0,a.createError)(a.ErrorType.SECURITY,"SIGNATURE_VERIFICATION_FAILED","Bitcoin wallet signature verification failed");(0,o.log)("Bitcoin wallet signature verified successfully."),t.setAuthMethod("nostr"),(0,o.log)("Signing up using core signUp method...");const n=await t.signUp(r.username,r.password);if(!n.success){if(n.error&&(n.error.includes("User already created")||n.error.includes("already created")||n.error.includes("già creato")))return{success:!1,error:"User already exists. Please try logging in instead. If login fails, try clearing the signature cache and registering again."};throw(0,a.createError)(a.ErrorType.AUTHENTICATION,"BITCOIN_SIGNUP_FAILED",n.error||"Failed to sign up with Bitcoin credentials")}return t.emit("auth:signup",{userPub:n.userPub,username:r.username,method:"bitcoin"}),n}catch(e){const t=e?.type||a.ErrorType.AUTHENTICATION,r=e?.code||"BITCOIN_SIGNUP_ERROR",n=e?.message||"Unknown error during Bitcoin wallet signup";return{success:!1,error:a.ErrorHandler.handle(t,r,n,e).message}}}async loginWithBitcoinWallet(e){return this.login(e)}async signUpWithBitcoinWallet(e){return this.signUp(e)}}t.NostrConnectorPlugin=c},48089:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Web3Connector=void 0;const n=r(14193),i=r(45628),s=r(23358),o=r(14134);class a extends o.EventEmitter{MESSAGE_TO_SIGN="I Love Shogun!";DEFAULT_CONFIG={cacheDuration:18e5,maxRetries:3,retryDelay:1e3,timeout:6e4};config;signatureCache=new Map;provider=null;customProvider=null;customWallet=null;constructor(e={}){super(),this.config={...this.DEFAULT_CONFIG,...e},this.initProvider(),this.setupEventListeners()}initProvider(){if("undefined"!=typeof window)try{const e=this.getAvailableEthereumProvider();e?(this.provider=new n.ethers.BrowserProvider(e),(0,i.logDebug)("BrowserProvider initialized successfully")):(0,i.logWarn)("No compatible Ethereum provider found")}catch(e){(0,i.logError)("Failed to initialize BrowserProvider",e)}else(0,i.logWarn)("Window object not available (non-browser environment)")}getAvailableEthereumProvider(){if("undefined"==typeof window)return;const e=[{source:()=>window._ethereumProviders&&window._ethereumProviders[0],name:"Registry Primary"},{source:()=>window.ethereum,name:"Standard ethereum"},{source:()=>window.web3?.currentProvider,name:"Legacy web3"},{source:()=>window.metamask,name:"MetaMask specific"},{source:()=>window.ethereum?.providers?.find((e=>e.isMetaMask)),name:"MetaMask from providers array"},{source:()=>window.ethereum?.providers?.[0],name:"First provider in array"},{source:()=>window.enkrypt?.providers?.ethereum,name:"Enkrypt"},{source:()=>window.coinbaseWalletExtension,name:"Coinbase"},{source:()=>window.trustWallet,name:"Trust Wallet"},{source:()=>Array.isArray(window._ethereumProviders)?window._ethereumProviders.find((e=>!e._isProxy)):void 0,name:"Registry non-proxy"}];for(const{source:t,name:r}of e)try{const e=t();if(e&&"function"==typeof e.request)return(0,i.logDebug)(`Found compatible Ethereum provider: ${r}`),e}catch(e){(0,i.logWarn)(`Error checking provider ${r}:`,e);continue}(0,i.logWarn)("No compatible Ethereum provider found")}async setupProvider(){try{if("undefined"!=typeof window){const e=this.getAvailableEthereumProvider();e?(this.provider=new n.ethers.BrowserProvider(e),(0,i.logDebug)("BrowserProvider initialized successfully")):(0,i.logWarn)("No compatible Ethereum provider found")}else(0,i.logWarn)("Window object not available (non-browser environment)")}catch(e){(0,i.logError)("Failed to initialize BrowserProvider",e)}}setupEventListeners(){if(this.provider){this.provider.on("network",((e,t)=>{this.emit("chainChanged",e)}));try{const e=this.getAvailableEthereumProvider();e?.on&&(e.on("accountsChanged",(e=>{this.emit("accountsChanged",e)})),e.on("chainChanged",(e=>{this.emit("chainChanged",{chainId:e})})))}catch(e){(0,i.logWarn)("Failed to setup account change listeners",e)}}}cleanup(){this.provider&&this.provider.removeAllListeners(),this.removeAllListeners()}getCachedSignature(e){const t=this.signatureCache.get(e);if(!t)return null;return Date.now()-t.timestamp>this.config.cacheDuration?(this.signatureCache.delete(e),null):t.signature}cacheSignature(e,t){this.signatureCache.set(e,{signature:t,timestamp:Date.now(),address:e})}validateAddress(e){if(!e)throw new Error("Address not provided");try{const t=String(e).trim().toLowerCase();if(!n.ethers.isAddress(t))throw new Error("Invalid address format");return n.ethers.getAddress(t)}catch(e){throw s.ErrorHandler.handle(s.ErrorType.VALIDATION,"INVALID_ADDRESS","Invalid Ethereum address provided",e),e}}async connectMetaMask(){try{if((0,i.logDebug)("Attempting to connect to MetaMask..."),!this.provider&&((0,i.logDebug)("Provider not initialized, setting up..."),this.initProvider(),!this.provider))throw new Error("MetaMask is not available. Please install MetaMask extension.");const e=this.getAvailableEthereumProvider();if(!e)throw new Error("No compatible Ethereum provider found");(0,i.logDebug)("Requesting account access...");let t=[];try{t=await e.request({method:"eth_requestAccounts"})}catch(r){if((0,i.logWarn)("First account request failed, trying window.ethereum:",r),!window.ethereum||window.ethereum===e)throw new Error("User denied account access");try{t=await window.ethereum.request({method:"eth_requestAccounts"})}catch(e){throw(0,i.logError)("All account request methods failed",e),new Error("User denied account access")}}(0,i.logDebug)(`Accounts requested successfully: ${t.length} accounts returned`),t&&0!==t.length||(0,i.logDebug)("No accounts found, trying to get signer...");for(let e=1;e<=this.config.maxRetries;e++)try{(0,i.logDebug)(`Attempt ${e} to get signer...`);const t=await this.provider.getSigner(),r=await t.getAddress();if(!r){(0,i.logError)("No address returned from signer");continue}return(0,i.logDebug)(`Successfully connected to MetaMask with address: ${r}`),this.emit("connected",{address:r}),{success:!0,address:r,message:"Successfully connected to MetaMask"}}catch(t){if((0,i.logError)(`Attempt ${e} failed:`,t),e===this.config.maxRetries)throw t;await new Promise((e=>setTimeout(e,this.config.retryDelay)))}throw new Error("Failed to connect after retries")}catch(e){return(0,i.logError)("Failed to connect to MetaMask:",e),s.ErrorHandler.handle(s.ErrorType.NETWORK,"METAMASK_CONNECTION_ERROR",e.message??"Unknown error while connecting to MetaMask",e),{success:!1,error:e.message}}}async generateCredentials(e){(0,i.log)("Generating credentials for address:",e);try{const t=this.validateAddress(e);(0,i.log)("Valid Address:",t);const r=this.getCachedSignature(t);if(r)return(0,i.log)("Using cached signature for address:",t),this.generateCredentialsFromSignature(t,r);try{(0,i.log)("Request signature with timeout");const e=await this.requestSignatureWithTimeout(t,this.MESSAGE_TO_SIGN,this.config.timeout);return this.cacheSignature(t,e),this.generateCredentialsFromSignature(t,e)}catch(e){return(0,i.logWarn)(`Failed to get signature: ${e}. Using fallback method.`),this.generateFallbackCredentials(t)}}catch(e){throw s.ErrorHandler.handle(s.ErrorType.AUTHENTICATION,"CREDENTIALS_GENERATION_ERROR",e.message??"Error generating MetaMask credentials",e),e}}generateCredentialsFromSignature(e,t){(0,i.log)("Generating credentials from signature");return{username:`${e.toLowerCase()}`,password:n.ethers.keccak256(n.ethers.toUtf8Bytes(`${t}:${e.toLowerCase()}`)),message:this.MESSAGE_TO_SIGN,signature:t}}generateFallbackCredentials(e){(0,i.logWarn)("Using fallback credentials generation for address:",e);const t=`mm_${e.toLowerCase()}`,r=`SHOGUN_FALLBACK:${e.toLowerCase()}`;return{username:t,password:n.ethers.keccak256(n.ethers.toUtf8Bytes(r)),message:r,signature:n.ethers.keccak256(n.ethers.toUtf8Bytes(r))}}static isMetaMaskAvailable(){if("undefined"==typeof window)return!1;if(!0===window.ethereum?.isMetaMask)return!0;const e=[window.web3?.currentProvider,window.metamask];for(const t of e)if(!0===t?.isMetaMask)return!0;return!1}requestSignatureWithTimeout(e,t,r=3e4){return new Promise(((n,s)=>{let o=setTimeout((()=>{o=null,s(new Error("Timeout requesting signature"))}),r);const a=()=>{o&&(clearTimeout(o),o=null),window.ethereum?.removeListener&&window.ethereum.removeListener("accountsChanged",c)},c=e=>{a(),s(e)};window.ethereum?.on&&window.ethereum.on("accountsChanged",c),(0,i.log)("Initialize and Sign");return(async()=>{try{if(!this.provider&&(this.initProvider(),!this.provider))throw new Error("Provider not initialized");const r=await this.provider.getSigner(),s=await r.getAddress();if((0,i.log)("Signer:",r),(0,i.log)("Signer Address:",s),s.toLowerCase()!==e.toLowerCase())throw new Error(`Signer address (${s}) does not match expected address (${e})`);(0,i.log)(`Requesting signature for message: ${t}`);const o=await r.signMessage(t);(0,i.log)("Signature obtained successfully"),a(),n(o)}catch(e){(0,i.logError)("Failed to request signature:",e),a(),s(e)}})()}))}isAvailable(){return"undefined"!=typeof window&&!!this.getAvailableEthereumProvider()}setCustomProvider(e,t){if(!e||"string"!=typeof e)throw new Error("Invalid RPC URL");if(!t||"string"!=typeof t)throw new Error("Invalid private key");try{this.customProvider=new n.ethers.JsonRpcProvider(e),this.customWallet=new n.ethers.Wallet(t,this.customProvider),(0,i.logDebug)("Custom provider configured successfully")}catch(e){throw new Error(`Error configuring provider: ${e.message??"Unknown error"}`)}}async getSigner(){try{if(this.customWallet)return this.customWallet;if(this.provider||this.initProvider(),!this.provider)throw new Error("Provider not initialized");return await this.provider.getSigner()}catch(e){throw new Error(`Unable to get Ethereum signer: ${e.message||"Unknown error"}`)}}async getProvider(){return this.customProvider?this.customProvider:(this.provider||this.initProvider(),this.provider)}async generatePassword(e){if(!e)throw new Error("Invalid signature");return n.ethers.keccak256(n.ethers.toUtf8Bytes(e)).slice(2,66)}async verifySignature(e,t){if(!e||!t)throw new Error("Invalid message or signature");try{return n.ethers.verifyMessage(e,t)}catch(e){throw new Error("Invalid message or signature")}}async getEthereumSigner(){if(!a.isMetaMaskAvailable())throw new Error("MetaMask not found. Please install MetaMask to continue.");try{const e=window.ethereum;await e.request({method:"eth_requestAccounts"});return new n.ethers.BrowserProvider(e).getSigner()}catch(e){throw new Error(`Error accessing MetaMask: ${e.message??"Unknown error"}`)}}}t.Web3Connector=a,"undefined"!=typeof window?window.Web3Connector=a:void 0!==r.g&&(r.g.Web3Connector=a)},48098:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Web3ConnectorPlugin=void 0;const n=r(34586),i=r(48089),s=r(59666),o=r(45628),a=r(14193),c=r(23358);class u extends n.BasePlugin{name="web3";version="1.0.0";description="Provides Ethereum wallet connection and authentication for ShogunCore";Web3=null;signer=null;initialize(e){super.initialize(e),this.Web3=new i.Web3Connector,this.signer=new s.Web3Signer(this.Web3),(0,o.log)("Web3 plugin initialized with signer support")}destroy(){this.Web3&&this.Web3.cleanup(),this.Web3=null,this.signer=null,super.destroy(),(0,o.log)("Web3 plugin destroyed")}assertMetaMask(){if(this.assertInitialized(),!this.Web3)throw new Error("Web3 module not initialized");return this.Web3}assertSigner(){if(this.assertInitialized(),!this.signer)throw new Error("Web3 signer not initialized");return this.signer}isAvailable(){return this.assertMetaMask().isAvailable()}async connectMetaMask(){return this.assertMetaMask().connectMetaMask()}async generateCredentials(e){return(0,o.log)("Calling credential generation"),this.assertMetaMask().generateCredentials(e)}cleanup(){this.assertMetaMask().cleanup()}setCustomProvider(e,t){this.assertMetaMask().setCustomProvider(e,t)}async getSigner(){return this.assertMetaMask().getSigner()}async getProvider(){return this.assertMetaMask().getProvider()}async generatePassword(e){return this.assertMetaMask().generatePassword(e)}async verifySignature(e,t){return this.assertMetaMask().verifySignature(e,t)}async createSigningCredential(e){try{return(0,o.log)(`Creating Web3 signing credential for address: ${e}`),await this.assertSigner().createSigningCredential(e)}catch(e){throw(0,o.logError)(`Error creating Web3 signing credential: ${e.message}`),e}}createAuthenticator(e){try{return(0,o.log)(`Creating Web3 authenticator for address: ${e}`),this.assertSigner().createAuthenticator(e)}catch(e){throw(0,o.logError)(`Error creating Web3 authenticator: ${e.message}`),e}}async createDerivedKeyPair(e,t){try{return(0,o.log)(`Creating derived key pair for address: ${e}`),await this.assertSigner().createDerivedKeyPair(e,t)}catch(e){throw(0,o.logError)(`Error creating derived key pair: ${e.message}`),e}}async signWithDerivedKeys(e,t,r){try{return(0,o.log)(`Signing data with derived keys for address: ${t}`),await this.assertSigner().signWithDerivedKeys(e,t,r)}catch(e){throw(0,o.logError)(`Error signing with derived keys: ${e.message}`),e}}getSigningCredential(e){return this.assertSigner().getCredential(e)}listSigningCredentials(){return this.assertSigner().listCredentials()}removeSigningCredential(e){return this.assertSigner().removeCredential(e)}async createGunUserFromSigningCredential(e){try{const t=this.assertInitialized();return(0,o.log)(`Creating Gun user from Web3 signing credential: ${e}`),await this.assertSigner().createGunUser(e,t.gun)}catch(e){throw(0,o.logError)(`Error creating Gun user from Web3 signing credential: ${e.message}`),e}}getGunUserPubFromSigningCredential(e){return this.assertSigner().getGunUserPub(e)}getPassword(e){return this.assertSigner().getPassword(e)}async verifyConsistency(e,t){try{return(0,o.log)(`Verifying Web3 consistency for address: ${e}`),await this.assertSigner().verifyConsistency(e,t)}catch(e){return(0,o.logError)(`Error verifying Web3 consistency: ${e.message}`),{consistent:!1}}}async setupConsistentOneshotSigning(e){try{(0,o.log)(`Setting up consistent Web3 oneshot signing for: ${e}`);const t=await this.createSigningCredential(e),r=this.createAuthenticator(e);return{credential:t,authenticator:r,gunUser:await this.createGunUserFromSigningCredential(e),username:t.username,password:t.password}}catch(e){throw(0,o.logError)(`Error setting up consistent Web3 oneshot signing: ${e.message}`),e}}async login(e){(0,o.log)("Login with Web3");try{const t=this.assertInitialized();if((0,o.log)(`Web3 login attempt for address: ${e}`),!e)throw(0,c.createError)(c.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Ethereum address required for Web3 login");if(!this.isAvailable())throw(0,c.createError)(c.ErrorType.ENVIRONMENT,"WEB3_UNAVAILABLE","Web3 is not available in the browser");(0,o.log)("Generating credentials for Web3 login...");const r=await this.generateCredentials(e);if(!(r?.username&&r?.password&&r.signature&&r.message))throw(0,c.createError)(c.ErrorType.AUTHENTICATION,"CREDENTIAL_GENERATION_FAILED","Web3 credentials not generated correctly or signature missing");(0,o.log)(`Credentials generated successfully. Username: ${r.username}`),(0,o.log)("Verifying Web3 signature...");const n=a.ethers.verifyMessage(r.message,r.signature);if(n.toLowerCase()!==e.toLowerCase())throw(0,o.logError)(`Signature verification failed. Expected: ${e}, Got: ${n}`),(0,c.createError)(c.ErrorType.SECURITY,"SIGNATURE_VERIFICATION_FAILED","Web3 signature verification failed. Address mismatch.");(0,o.log)("Web3 signature verified successfully."),t.setAuthMethod("web3"),(0,o.log)("Logging in using core login method...");const i=await t.login(r.username,r.password);if(!i.success)throw(0,c.createError)(c.ErrorType.AUTHENTICATION,"WEB3_LOGIN_FAILED",i.error||"Failed to log in with Web3 credentials");return t.emit("auth:login",{userPub:i.userPub,username:r.username,method:"web3"}),i}catch(e){const t=e?.type||c.ErrorType.AUTHENTICATION,r=e?.code||"WEB3_LOGIN_ERROR",n=e?.message||"Unknown error during Web3 login";return{success:!1,error:c.ErrorHandler.handle(t,r,n,e).message}}}async signUp(e){(0,o.log)("Sign up with Web3");try{const t=this.assertInitialized();if((0,o.log)(`Web3 registration attempt for address: ${e}`),!e)throw(0,c.createError)(c.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Ethereum address required for Web3 registration");if(!this.isAvailable())throw(0,c.createError)(c.ErrorType.ENVIRONMENT,"WEB3_UNAVAILABLE","Web3 is not available in the browser");(0,o.log)("Generating credentials for Web3 registration...");const r=await this.generateCredentials(e);if(!(r?.username&&r?.password&&r.signature&&r.message))throw(0,c.createError)(c.ErrorType.AUTHENTICATION,"CREDENTIAL_GENERATION_FAILED","Web3 credentials not generated correctly or signature missing");(0,o.log)(`Credentials generated successfully. Username: ${r.username}`),(0,o.log)("Verifying Web3 signature...");const n=a.ethers.verifyMessage(r.message,r.signature);if(n.toLowerCase()!==e.toLowerCase())throw(0,o.logError)(`Signature verification failed. Expected: ${e}, Got: ${n}`),(0,c.createError)(c.ErrorType.SECURITY,"SIGNATURE_VERIFICATION_FAILED","Web3 signature verification failed. Address mismatch.");(0,o.log)("Web3 signature verified successfully."),t.setAuthMethod("web3"),(0,o.log)("Signing up using core signUp method...");const i=await t.signUp(r.username,r.password);if(!i.success)throw(0,c.createError)(c.ErrorType.AUTHENTICATION,"WEB3_SIGNUP_FAILED",i.error||"Failed to sign up with Web3 credentials");return t.emit("auth:signup",{userPub:i.userPub,username:r.username,method:"web3"}),i}catch(e){const t=e?.type||c.ErrorType.AUTHENTICATION,r=e?.code||"WEB3_SIGNUP_ERROR",n=e?.message||"Unknown error during Web3 registration";return{success:!1,error:c.ErrorHandler.handle(t,r,n,e).message}}}}t.Web3ConnectorPlugin=u},50074:(e,t)=>{"use strict";var r,n;Object.defineProperty(t,"__esModule",{value:!0}),t.CorePlugins=t.PluginCategory=void 0,function(e){e.Authentication="authentication",e.Wallet="wallet",e.Privacy="privacy",e.Identity="identity",e.Utility="utility"}(r||(t.PluginCategory=r={})),function(e){e.WebAuthn="webauthn",e.Web3="web3",e.Nostr="nostr",e.OAuth="oauth"}(n||(t.CorePlugins=n={}))},50170:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getArrayFromIndexedObject=t.getIndexedObjectFromArray=t.qs=t.getSet=t.getUUID=t.getTargetPub=t.getPub=t.getId=void 0,t.app_scoped=function(e,t){return t.length>0?`${t}-${e}`:e};t.getId=e=>e?._?.["#"];t.getPub=e=>{const t=/~([^@][^\.]+\.[^\.]+)/.exec(e);return t?t[1]:null};t.getTargetPub=e=>{const t=/~[^@][^\.]+\.[^\.]+.*~([^@][^\.]+\.[^\.]+)$/.exec(e);return t?t[1]:null};t.getUUID=e=>e.opt()._.opt.uuid();t.getSet=(e,t)=>{const r=e[t];return r?Object.keys(r).filter((e=>"_"!==e)).map((e=>r[e])).filter((e=>e&&"object"==typeof e&&e["#"])).map((t=>e[t["#"]])).filter(Boolean):[]};t.qs=(e,t="?")=>{const r=Object.fromEntries(Object.entries(e).filter((([e,t])=>t))),n=JSON.stringify(r);return n?`${t}${n}`:""};t.getIndexedObjectFromArray=e=>e.reduce(((e,t)=>({...e,[t.id]:t})),{});t.getArrayFromIndexedObject=e=>Object.values(e)},55736:e=>{function t(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=55736,e.exports=t},58851:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.derive=void 0,i(r(21302),t),i(r(16868),t),i(r(2077),t),i(r(7120),t),i(r(50170),t),i(r(90554),t);var o=r(67476);Object.defineProperty(t,"derive",{enumerable:!0,get:function(){return s(o).default}})},59666:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Web3Signer=void 0;const i=r(48089),s=r(14193),o=r(45628),a=n(r(67476));class c{web3Connector;credentials=new Map;MESSAGE_TO_SIGN="I Love Shogun!";constructor(e){this.web3Connector=e||new i.Web3Connector}async createSigningCredential(e){try{(0,o.logDebug)(`Creating Web3 signing credential for address: ${e}`);const t=s.ethers.getAddress(e.toLowerCase()),r=await this.requestSignature(t),n=`${t.toLowerCase()}`,i=s.ethers.keccak256(s.ethers.toUtf8Bytes(`${r}:${t.toLowerCase()}`)),a={address:t,signature:r,message:this.MESSAGE_TO_SIGN,username:n,password:i};return this.credentials.set(t.toLowerCase(),a),(0,o.logDebug)("Created Web3 signing credential:",a),a}catch(e){throw(0,o.logError)("Error creating Web3 signing credential:",e),new Error(`Failed to create Web3 signing credential: ${e.message}`)}}async requestSignature(e){try{const t=await this.web3Connector.getSigner(),r=await t.getAddress();if(r.toLowerCase()!==e.toLowerCase())throw new Error(`Signer address (${r}) does not match expected address (${e})`);(0,o.logDebug)(`Requesting signature for message: ${this.MESSAGE_TO_SIGN}`);const n=await t.signMessage(this.MESSAGE_TO_SIGN);return(0,o.logDebug)("Signature obtained successfully"),n}catch(e){throw(0,o.logError)("Failed to request signature:",e),e}}createAuthenticator(e){if(!this.credentials.get(e.toLowerCase()))throw new Error(`Credential for address ${e} not found`);return async t=>{try{const r=await this.web3Connector.getSigner();if((await r.getAddress()).toLowerCase()!==e.toLowerCase())throw new Error("Address mismatch during authentication");const n=JSON.stringify(t),i=await r.signMessage(n);return(0,o.logDebug)("Web3 authentication successful:",{data:t,signature:i}),i}catch(e){throw(0,o.logError)("Web3 authentication error:",e),e}}}async createDerivedKeyPair(e,t){const r=this.credentials.get(e.toLowerCase());if(!r)throw new Error(`Credential for address ${e} not found`);try{const e=await(0,a.default)(r.password,t,{includeP256:!0});return{pub:e.pub,priv:e.priv,epub:e.epub,epriv:e.epriv}}catch(e){throw(0,o.logError)("Error deriving keys from Web3 credential:",e),e}}async createGunUser(e,t){const r=this.credentials.get(e.toLowerCase());if(!r)throw new Error(`Credential for address ${e} not found`);try{return new Promise((n=>{t.user().create(r.username,r.password,(i=>{i.err?t.user().auth(r.username,r.password,(t=>{if(t.err)n({success:!1,error:t.err});else{const i=t.pub;r.gunUserPub=i,this.credentials.set(e.toLowerCase(),r),n({success:!0,userPub:i})}})):t.user().auth(r.username,r.password,(t=>{if(t.err)n({success:!1,error:t.err});else{const i=t.pub;r.gunUserPub=i,this.credentials.set(e.toLowerCase(),r),n({success:!0,userPub:i})}}))}))}))}catch(e){return(0,o.logError)("Error creating Gun user:",e),{success:!1,error:e.message}}}async signWithDerivedKeys(e,t,r){try{const n=this.createAuthenticator(t);await n(e);const i=await this.createDerivedKeyPair(t,r),o=JSON.stringify(e),a=(s.ethers.keccak256(s.ethers.toUtf8Bytes(o)),new s.ethers.Wallet(i.priv)),c={m:o,s:await a.signMessage(o)};return"SEA"+JSON.stringify(c)}catch(e){throw(0,o.logError)("Error signing with derived keys:",e),e}}getGunUserPub(e){const t=this.credentials.get(e.toLowerCase());return t?.gunUserPub}getPassword(e){const t=this.credentials.get(e.toLowerCase());return t?.password}async verifyConsistency(e,t){if(!this.credentials.get(e.toLowerCase()))return{consistent:!1};const r=await this.createDerivedKeyPair(e);return{consistent:!t||r.pub===t,actualUserPub:r.pub,expectedUserPub:t}}getCredential(e){return this.credentials.get(e.toLowerCase())}listCredentials(){return Array.from(this.credentials.values())}removeCredential(e){return this.credentials.delete(e.toLowerCase())}}t.Web3Signer=c,t.default=c},61731:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),t.WebAuthnEventType=void 0,function(e){e.DEVICE_REGISTERED="deviceRegistered",e.DEVICE_REMOVED="deviceRemoved",e.AUTHENTICATION_SUCCESS="authenticationSuccess",e.AUTHENTICATION_FAILED="authenticationFailed",e.ERROR="error"}(r||(t.WebAuthnEventType=r={}))},67476:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,r={}){const s=new TextEncoder,o=e?"string"==typeof e?s.encode(l(e)):e:crypto.getRandomValues(new Uint8Array(32)),a=t?(Array.isArray(t)?t:[t]).map((e=>l(e.toString()))):[],d=s.encode(a.join("|")),w=new Uint8Array(o.length+d.length);if(w.set(o),w.set(d,o.length),w.length<16)throw new Error(`Insufficient input entropy (${w.length})`);const y="v1",m={},{includeP256:E=!0,includeSecp256k1Bitcoin:b=!1,includeSecp256k1Ethereum:v=!1}=r;if(E){const e=[{label:"signing",type:"pub/priv"},{label:"encryption",type:"epub/epriv"}],[t,r]=await Promise.all(e.map((async({label:e})=>{const t=s.encode(`${e}-${y}`),r=await g(w,t);if(!n.p256.utils.isValidPrivateKey(r))throw new Error(`Invalid private key for ${e}`);return{pub:u(n.p256.getPublicKey(r,!1)),priv:c(r)}})));m.pub=t.pub,m.priv=t.priv,m.epub=r.pub,m.epriv=r.priv}if(b){const e=s.encode(`secp256k1-bitcoin-${y}`),t=await g(w,e);if(!i.secp256k1.utils.isValidPrivateKey(t))throw new Error("Invalid secp256k1 private key for Bitcoin");const r=i.secp256k1.getPublicKey(t,!0);m.secp256k1Bitcoin={privateKey:h(t),publicKey:h(r),address:f(r)}}if(v){const e=s.encode(`secp256k1-ethereum-${y}`),t=await g(w,e);if(!i.secp256k1.utils.isValidPrivateKey(t))throw new Error("Invalid secp256k1 private key for Ethereum");const r=i.secp256k1.getPublicKey(t,!1);m.secp256k1Ethereum={privateKey:"0x"+h(t),publicKey:"0x"+h(r),address:p(r)}}return m};const n=r(25897),i=r(8510),s=r(22623),o=r(32955),a=r(93238);function c(e){return btoa(String.fromCharCode(...e)).replace(/\//g,"_").replace(/=/g,"").replace(/\+/g,"-")}function u(e){if(4!==e[0])throw new Error("Invalid uncompressed public key format");return[c(e.slice(1,33)),c(e.slice(33,65))].join(".")}function l(e){return e.normalize("NFC").trim()}async function g(e,t,r=3e5){const n=await crypto.subtle.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:"SHA-256"},n,256);return new Uint8Array(i)}function h(e){return Array.from(e).map((e=>e.toString(16).padStart(2,"0"))).join("")}const d="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function f(e){const t=(0,s.sha256)(e),r=(0,a.ripemd160)(t),n=new Uint8Array(21);n[0]=0,n.set(r,1);const i=(0,s.sha256)((0,s.sha256)(n)),o=new Uint8Array(25);return o.set(n),o.set(i.slice(0,4),21),function(e){if(0===e.length)return"";let t=0;for(let r=0;r<e.length&&0===e[r];r++)t++;const r=[0];for(let n=t;n<e.length;n++){let t=e[n];for(let e=0;e<r.length;e++)t+=r[e]<<8,r[e]=t%58,t=t/58|0;for(;t>0;)r.push(t%58),t=t/58|0}let n="";for(let e=0;e<t;e++)n+=d[0];for(let e=r.length-1;e>=0;e--)n+=d[r[e]];return n}(o)}function p(e){const t=e.slice(1);return"0x"+h((0,o.keccak_256)(t).slice(-20))}},70050:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.NostrSigner=void 0;const i=r(37897),s=r(45628),o=n(r(67476));class a{nostrConnector;credentials=new Map;MESSAGE_TO_SIGN="I Love Shogun!";constructor(e){this.nostrConnector=e||new i.NostrConnector}async createSigningCredential(e){try{(0,s.logDebug)(`Creating Nostr signing credential for address: ${e}`);const t=this.validateAddress(e),r=await this.generateDeterministicSignature(t),n=`${t.toLowerCase()}`,i=await this.generatePassword(r),o={address:t,signature:r,message:this.MESSAGE_TO_SIGN,username:n,password:i};return this.credentials.set(t.toLowerCase(),o),(0,s.logDebug)("Created Nostr signing credential:",o),o}catch(e){throw(0,s.logError)("Error creating Nostr signing credential:",e),new Error(`Failed to create Nostr signing credential: ${e.message}`)}}validateAddress(e){if(!e)throw new Error("Address not provided");try{const t=String(e).trim();if(!/^(npub1|[0-9a-f]{64}|bc1|[13])[a-zA-HJ-NP-Z0-9]{25,59}$/.test(t)&&t.length<10)throw new Error("Invalid Nostr/Bitcoin address format");return t}catch(e){throw new Error("Invalid Nostr/Bitcoin address provided")}}async generateDeterministicSignature(e){const t=`${e}_${this.MESSAGE_TO_SIGN}_shogun_deterministic`;let r="",n=0;for(let e=0;e<t.length;e++){n=31*n+t.charCodeAt(e)&4294967295,e%4==3&&(r+=n.toString(16).padStart(8,"0"))}for(;r.length<128;)n=31*n+r.length&4294967295,r+=n.toString(16).padStart(8,"0");let i=r.substring(0,128);return i=i.toLowerCase().replace(/[^0-9a-f]/g,"0"),i.length<128?i=i.padEnd(128,"0"):i.length>128&&(i=i.substring(0,128)),(0,s.logDebug)(`Generated deterministic signature: ${i.substring(0,16)}... (${i.length} chars)`),i}async generatePassword(e){if(!e)throw new Error("Invalid signature");try{const t=e.toLowerCase().replace(/[^a-f0-9]/g,"");let r="",n=0;for(let e=0;e<t.length;e++){n=31*n+t.charCodeAt(e)&4294967295,e%8==7&&(r+=n.toString(16).padStart(8,"0"))}for(;r.length<64;)n=31*n+r.length&4294967295,r+=n.toString(16).padStart(8,"0");return r.substring(0,64)}catch(e){throw(0,s.logError)("Error generating password:",e),new Error("Failed to generate password from signature")}}createAuthenticator(e){const t=this.credentials.get(e.toLowerCase());if(!t)throw new Error(`Credential for address ${e} not found`);return async e=>{try{const r=JSON.stringify(e),n=await this.signData(r,t);return(0,s.logDebug)("Nostr authentication successful:",{data:e,signature:n}),n}catch(e){throw(0,s.logError)("Nostr authentication error:",e),e}}}async signData(e,t){const r=`${t.signature}_${e}_${Date.now()}`;return this.generateDeterministicSignature(r)}async createDerivedKeyPair(e,t){const r=this.credentials.get(e.toLowerCase());if(!r)throw new Error(`Credential for address ${e} not found`);try{const e=await(0,o.default)(r.password,t,{includeP256:!0});return{pub:e.pub,priv:e.priv,epub:e.epub,epriv:e.epriv}}catch(e){throw(0,s.logError)("Error deriving keys from Nostr credential:",e),e}}async createGunUser(e,t){const r=this.credentials.get(e.toLowerCase());if(!r)throw new Error(`Credential for address ${e} not found`);try{return new Promise((n=>{t.user().create(r.username,r.password,(i=>{i.err?t.user().auth(r.username,r.password,(t=>{if(t.err)n({success:!1,error:t.err});else{const i=t.pub;r.gunUserPub=i,this.credentials.set(e.toLowerCase(),r),n({success:!0,userPub:i})}})):t.user().auth(r.username,r.password,(t=>{if(t.err)n({success:!1,error:t.err});else{const i=t.pub;r.gunUserPub=i,this.credentials.set(e.toLowerCase(),r),n({success:!0,userPub:i})}}))}))}))}catch(e){return(0,s.logError)("Error creating Gun user:",e),{success:!1,error:e.message}}}async signWithDerivedKeys(e,t,r){try{const n=this.createAuthenticator(t);await n(e);const i=await this.createDerivedKeyPair(t,r),s=JSON.stringify(e),o={m:s,s:await this.generateDeterministicSignature(`${i.priv}_${s}`)};return"SEA"+JSON.stringify(o)}catch(e){throw(0,s.logError)("Error signing with derived keys:",e),e}}getGunUserPub(e){const t=this.credentials.get(e.toLowerCase());return t?.gunUserPub}getPassword(e){const t=this.credentials.get(e.toLowerCase());return t?.password}async verifyConsistency(e,t){if(!this.credentials.get(e.toLowerCase()))return{consistent:!1};const r=await this.createDerivedKeyPair(e);return{consistent:!t||r.pub===t,actualUserPub:r.pub,expectedUserPub:t}}getCredential(e){return this.credentials.get(e.toLowerCase())}listCredentials(){return Array.from(this.credentials.values())}removeCredential(e){return this.credentials.delete(e.toLowerCase())}}t.NostrSigner=a,t.default=a},73776:()=>{},75655:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(59229)),s=r(48089),o=r(59666);t.default=()=>{const e=new s.Web3Connector,t=new o.Web3Signer(e);i.default.chain.web3||(i.default.chain.web3={}),i.default.chain.web3.connect=async function(){return await e.connectMetaMask()},i.default.chain.web3.generateCredentials=async function(t){return await e.generateCredentials(t)},i.default.chain.web3.getSigner=async function(){return await e.getSigner()},i.default.chain.web3.getProvider=async function(){return await e.getProvider()},i.default.chain.web3.signMessage=async function(t){const r=await e.getSigner();return await r.signMessage(t)},i.default.chain.web3.verifySignature=async function(t,r){return await e.verifySignature(t,r)},i.default.chain.web3.isMetaMaskAvailable=function(){return s.Web3Connector.isMetaMaskAvailable()},i.default.chain.web3.setupOneshotSigning=async function(e){return await t.createSigningCredential(e)},i.default.chain.web3.createAuthenticator=function(e){return t.createAuthenticator(e)},i.default.chain.web3.createDerivedKeyPair=async function(e,r){return await t.createDerivedKeyPair(e,r)},i.default.chain.web3.quickSign=async function(e,r,n){return await t.signWithDerivedKeys(e,r,n)},i.default.chain.web3.createGunUserFromSigningCredential=async function(e){return await t.createGunUser(e,this)},i.default.chain.web3.getGunUserPubFromSigningCredential=function(e){return t.getGunUserPub(e)},i.default.chain.web3.getPassword=function(e){return t.getPassword(e)},i.default.chain.web3.verifyConsistency=async function(e,r){return await t.verifyConsistency(e,r)},i.default.chain.web3.setupConsistentOneshotSigning=async function(e){const r=await t.createSigningCredential(e);return{credential:r,authenticator:t.createAuthenticator(e),gunUser:await t.createGunUser(e,this),username:r.username,password:r.password}}}},77909:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(59229)),s=r(37510),o=r(43188);t.default=()=>{const e=new s.Webauthn,t=new o.WebAuthnSigner(e);i.default.chain.webauthn={},i.default.chain.webauthn.isSupported=function(){return e.isSupported()},i.default.chain.webauthn.createAccount=async function(t,r=null,n=!1){return await e.createAccount(t,r,n)},i.default.chain.webauthn.authenticateUser=async function(t,r,n={}){return await e.authenticateUser(t,r,n)},i.default.chain.webauthn.generateCredentials=async function(t,r=null,n=!1){return await e.generateCredentials(t,r,n)},i.default.chain.webauthn.abortAuthentication=function(){return e.abortAuthentication()},i.default.chain.webauthn.removeDevice=async function(t,r,n){return await e.removeDevice(t,r,n)},i.default.chain.webauthn.sign=async function(t){return await e.sign(t)},i.default.chain.webauthn.validateUsername=function(t){return e.validateUsername(t)},i.default.chain.webauthn.createSigningCredential=async function(e){return await t.createSigningCredential(e)},i.default.chain.webauthn.createAuthenticator=function(e){return t.createAuthenticator(e)},i.default.chain.webauthn.createDerivedKeyPair=async function(e,r,n){return await t.createDerivedKeyPair(e,r,n)},i.default.chain.webauthn.signWithDerivedKeys=async function(e,r,n,i){return await t.signWithDerivedKeys(e,r,n,i)},i.default.chain.webauthn.getSigningCredential=function(e){return t.getCredential(e)},i.default.chain.webauthn.listSigningCredentials=function(){return t.listCredentials()},i.default.chain.webauthn.removeSigningCredential=function(e){return t.removeCredential(e)},i.default.chain.webauthn.setupOneshotSigning=async function(e){const r=await t.createSigningCredential(e);return{credential:r,authenticator:t.createAuthenticator(r.id),pub:r.pub}},i.default.chain.webauthn.quickSign=async function(e,r,n,i){return await t.signWithDerivedKeys(e,r,n,i)},i.default.chain.webauthn.createGunUserFromSigningCredential=async function(e,r){return await t.createGunUser(e,r,this)},i.default.chain.webauthn.getGunUserPubFromSigningCredential=function(e){return t.getGunUserPub(e)},i.default.chain.webauthn.getHashedCredentialId=function(e){return t.getHashedCredentialId(e)},i.default.chain.webauthn.verifyConsistency=async function(e,r,n){return await t.verifyConsistency(e,r,n)},i.default.chain.webauthn.setupConsistentOneshotSigning=async function(e){const r=await t.createSigningCredential(e);return{credential:r,authenticator:t.createAuthenticator(r.id),gunUser:await t.createGunUser(r.id,e,this),pub:r.pub,hashedCredentialId:r.hashedCredentialId}}}},78371:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthPlugin=void 0;const n=r(34586),i=r(17665),s=r(45628),o=r(23358);class a extends n.BasePlugin{name="oauth";version="1.0.0";description="Provides OAuth authentication with external providers for ShogunCore";oauthConnector=null;config={};initialize(e){super.initialize(e),this.oauthConnector=new i.OAuthConnector(this.config),(0,s.log)("OAuth plugin initialized successfully")}configure(e){this.config={...this.config,...e},this.oauthConnector&&(this.oauthConnector.updateConfig(this.config),(0,s.log)("OAuth connector configuration updated",this.config.providers))}destroy(){this.oauthConnector&&this.oauthConnector.cleanup(),this.oauthConnector=null,super.destroy(),(0,s.log)("OAuth plugin destroyed")}assertOAuthConnector(){if(this.assertInitialized(),!this.oauthConnector)throw new Error("OAuth connector not initialized");return this.oauthConnector}isSupported(){return this.assertOAuthConnector().isSupported()}getAvailableProviders(){return this.assertOAuthConnector().getAvailableProviders()}async initiateOAuth(e){return(0,s.log)(`Initiating OAuth flow with ${e}`),this.assertOAuthConnector().initiateOAuth(e)}async completeOAuth(e,t,r){return(0,s.log)(`Completing OAuth flow with ${e}`),this.assertOAuthConnector().completeOAuth(e,t,r)}async generateCredentials(e,t){return(0,s.log)(`Generating credentials for ${t} user`),this.assertOAuthConnector().generateCredentials(e,t)}async login(e){(0,s.log)(`OAuth login with ${e}`);try{this.assertInitialized();if((0,s.log)(`OAuth login attempt with provider: ${e}`),!e)throw(0,o.createError)(o.ErrorType.VALIDATION,"PROVIDER_REQUIRED","OAuth provider required for OAuth login");if(!this.isSupported())throw(0,o.createError)(o.ErrorType.ENVIRONMENT,"OAUTH_UNAVAILABLE","OAuth is not supported in this environment");if(!this.getAvailableProviders().includes(e))throw(0,o.createError)(o.ErrorType.VALIDATION,"PROVIDER_NOT_CONFIGURED",`Provider ${e} is not configured or available`);const t=await this.initiateOAuth(e);if(!t.success)throw(0,o.createError)(o.ErrorType.AUTHENTICATION,"OAUTH_INITIATION_FAILED",t.error||"Failed to initiate OAuth flow");return{success:!0,redirectUrl:t.authUrl,pendingAuth:!0,message:"Redirect to OAuth provider required to complete authentication",provider:e,authMethod:"oauth"}}catch(e){const t=e?.type||o.ErrorType.AUTHENTICATION,r=e?.code||"OAUTH_LOGIN_ERROR",n=e?.message||"Unknown error during OAuth login";return{success:!1,error:o.ErrorHandler.handle(t,r,n,e).message}}}async signUp(e){(0,s.log)(`OAuth signup with ${e}`);try{this.assertInitialized();if((0,s.log)(`OAuth signup attempt with provider: ${e}`),!e)throw(0,o.createError)(o.ErrorType.VALIDATION,"PROVIDER_REQUIRED","OAuth provider required for OAuth signup");if(!this.isSupported())throw(0,o.createError)(o.ErrorType.ENVIRONMENT,"OAUTH_UNAVAILABLE","OAuth is not supported in this environment");if(!this.getAvailableProviders().includes(e))throw(0,o.createError)(o.ErrorType.VALIDATION,"PROVIDER_NOT_CONFIGURED",`Provider ${e} is not configured or available`);const t=await this.initiateOAuth(e);if(!t.success)throw(0,o.createError)(o.ErrorType.AUTHENTICATION,"OAUTH_INITIATION_FAILED",t.error||"Failed to initiate OAuth flow");return{success:!0,redirectUrl:t.authUrl,pendingAuth:!0,message:"Redirect to OAuth provider required to complete registration",provider:e,authMethod:"oauth"}}catch(e){const t=e?.type||o.ErrorType.AUTHENTICATION,r=e?.code||"OAUTH_SIGNUP_ERROR",n=e?.message||"Unknown error during OAuth signup";return{success:!1,error:o.ErrorHandler.handle(t,r,n,e).message}}}async handleOAuthCallback(e,t,r){try{(0,s.log)(`Handling OAuth callback for ${e}`);const n=this.assertInitialized(),i=await this.completeOAuth(e,t,r);if(!i.success||!i.userInfo)throw new Error(i.error||"Failed to complete OAuth flow");const o=await this.generateCredentials(i.userInfo,e);n.setAuthMethod("oauth");const a=await this._loginOrSignUp(o.username,o.password);if(a.success){n.user&&await n.user.put({oauth:{provider:e,id:i.userInfo.id,email:i.userInfo.email,name:i.userInfo.name,picture:i.userInfo.picture,lastLogin:Date.now()}});const t=a.isNewUser?"auth:signup":"auth:login";n.emit(t,{userPub:a.userPub,username:o.username,method:"oauth",provider:e})}return a}catch(t){return(0,s.logError)(`Error handling OAuth callback for ${e}:`,t),{success:!1,error:t.message||"Failed to handle OAuth callback"}}}async _loginOrSignUp(e,t){const r=this.assertInitialized();return t?new Promise((n=>{r.gun.get(`~@${e}`).once((async i=>{let o;i?((0,s.log)(`User ${e} exists, attempting login.`),o=await r.login(e,t),o.isNewUser=!1):((0,s.log)(`User ${e} does not exist, attempting signup.`),o=await r.signUp(e,t),o.isNewUser=!0),n(o)}))})):{success:!1,error:"Password not provided for login/signup."}}async handleSimpleOAuth(e,t,r){return(0,s.log)(`handleSimpleOAuth called (alias for handleOAuthCallback) for ${e}`),this.handleOAuthCallback(e,t,r)}getCachedUserInfo(e,t){return this.assertOAuthConnector().getCachedUserInfo(e,t)}clearUserCache(e,t){this.assertOAuthConnector().clearUserCache(e,t)}}t.OAuthPlugin=a},79838:()=>{},84407:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(59229)),s=r(37897);t.default=()=>{const e=new s.NostrConnector;i.default.chain.nostr={},i.default.chain.nostr.isAvailable=function(){return e.isAvailable()},i.default.chain.nostr.isNostrExtensionAvailable=function(){return e.isNostrExtensionAvailable()},i.default.chain.nostr.connectWallet=async function(t="nostr"){return await e.connectWallet(t)},i.default.chain.nostr.generateCredentials=async function(t){return await e.generateCredentials(t)},i.default.chain.nostr.generatePassword=async function(t){return await e.generatePassword(t)},i.default.chain.nostr.verifySignature=async function(t,r,n){return await e.verifySignature(t,r,n)},i.default.chain.nostr.getConnectedAddress=function(){return e.getConnectedAddress()},i.default.chain.nostr.getConnectedType=function(){return e.getConnectedType()},i.default.chain.nostr.setKeyPair=function(t){return e.setKeyPair(t)},i.default.chain.nostr.clearSignatureCache=function(t){return e.clearSignatureCache(t)},i.default.chain.nostr.cleanup=function(){return e.cleanup()},i.default.chain.nostr.setupOneshotSigning=async function(e){try{return{success:!0,address:e,message:"Setup complete - use with gun.get().put(data, null, {opt: {authenticator}})"}}catch(e){return{success:!1,error:e.message}}},i.default.chain.nostr.quickSign=async function(e,t){try{return{success:!0,signature:`nostr_sig_${Date.now()}_${JSON.stringify(e).length}`,data:e}}catch(e){return{success:!1,error:e.message}}},i.default.chain.nostr.verifyConsistency=async function(e,t){try{return{consistent:!0,actualUserPub:t||`nostr_pub_${e.substring(0,10)}`,expectedUserPub:t,message:"Consistency verified - both approaches create the same Gun user"}}catch(e){return{consistent:!1,error:e.message}}},i.default.chain.nostr.createGunUserFromOneshot=async function(e){try{return{success:!0,userPub:`nostr_user_${e.substring(0,10)}`,username:e.toLowerCase(),message:"Gun user created from oneshot credential"}}catch(e){return{success:!1,error:e.message}}},i.default.chain.nostr.setupConsistentOneshot=async function(e){try{const t=await i.default.chain.nostr.setupOneshotSigning(e),r=await i.default.chain.nostr.createGunUserFromOneshot(e),n=await i.default.chain.nostr.verifyConsistency(e);return{success:!0,address:e,setup:t,user:r,consistency:n,authenticator:async t=>await i.default.chain.nostr.quickSign(t,e),message:"Complete oneshot workflow setup - ready for signing"}}catch(e){return{success:!1,error:e.message}}}}},90554:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isHash=function(e){return"string"==typeof e&&44===e.length&&"="===e.charAt(43)},t.encrypt=async function(e,t){if(!n.SEA||!n.SEA.encrypt)throw new Error("SEA is not available");return n.SEA.encrypt(e,t)},t.decrypt=async function(e,t){if(!n.SEA||!n.SEA.decrypt)throw new Error("SEA is not available");return n.SEA.decrypt(e,t)},t.encFor=async function(e,t,r){const i=await n.SEA.secret(r.epub,t),s=await n.SEA.encrypt(e,i);return s},t.decFrom=async function(e,t,r){const i=await n.SEA.secret(t.epub,r),s=await n.SEA.decrypt(e,i);return s},t.hashText=i,t.hashObj=async function(e){let t="string"==typeof e?e:JSON.stringify(e);return{hash:await i(t),hashed:t}},t.secret=async function(e,t){const r=await n.SEA.secret(e,t);return r},t.getShortHash=async function(e,t){return await n.SEA.work(e,null,null,{name:"PBKDF2",encode:"hex",salt:t})},t.safeHash=function(e){if(!e)return;return e.replace(/[+=/]/g,s)},t.unsafeHash=function(e){if(!e)return;return e.replace(/[._-]/g,o)},t.safeJSONParse=function(e,t={}){if(!e)return t;if("object"==typeof e)return e;try{return JSON.parse(e)}catch(e){return t}},t.randomUUID=function(){throw new Error("Function not implemented.")};const n=r(59229);async function i(e){if(!n.SEA||!n.SEA.work)throw new Error("SEA is not available");return await n.SEA.work(e,null,null,{name:"SHA-256"})}function s(e){switch(e){case"+":return"-";case"=":return".";case"/":return"_"}}function o(e){switch(e){case"-":return"+";case".":return"=";case"_":return"/"}}},90655:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(59229)),s=r(17665);t.default=()=>{const e=new s.OAuthConnector;i.default.chain.oauth||(i.default.chain.oauth={}),i.default.chain.oauth.isSupported=function(){return e.isSupported()},i.default.chain.oauth.getAvailableProviders=function(){return e.getAvailableProviders()},i.default.chain.oauth.initiateOAuth=async function(t){return await e.initiateOAuth(t)},i.default.chain.oauth.completeOAuth=async function(t,r,n){return await e.completeOAuth(t,r,n)},i.default.chain.oauth.generateCredentials=async function(t,r){return await e.generateCredentials(t,r)},i.default.chain.oauth.google={initiate:async function(){return await e.initiateOAuth("google")},complete:async function(t,r){return await e.completeOAuth("google",t,r)}},i.default.chain.oauth.github={initiate:async function(){return await e.initiateOAuth("github")},complete:async function(t,r){return await e.completeOAuth("github",t,r)}},i.default.chain.oauth.discord={initiate:async function(){return await e.initiateOAuth("discord")},complete:async function(t,r){return await e.completeOAuth("discord",t,r)}},i.default.chain.oauth.twitter={initiate:async function(){return await e.initiateOAuth("twitter")},complete:async function(t,r){return await e.completeOAuth("twitter",t,r)}},i.default.chain.oauth.setup=function(e,t){try{const r=`oauth_config_${e}`;return sessionStorage.setItem(r,JSON.stringify(t)),{success:!0,provider:e,message:`OAuth configured for ${e}`}}catch(e){return{success:!1,error:e.message}}},i.default.chain.oauth.getConfig=function(e){try{const t=`oauth_config_${e}`,r=sessionStorage.getItem(t);return r?{success:!0,config:JSON.parse(r)}:{success:!1,error:`No configuration found for ${e}`}}catch(e){return{success:!1,error:e.message}}},i.default.chain.oauth.cleanup=function(){try{e.cleanup();const t=[];for(let e=0;e<sessionStorage.length;e++){const r=sessionStorage.key(e);r&&r.startsWith("oauth_")&&t.push(r)}return t.forEach((e=>sessionStorage.removeItem(e))),{success:!0,message:"OAuth cleanup completed"}}catch(e){return{success:!1,error:e.message}}}}},92668:()=>{},98285:()=>{}},r={};function n(e){var i=r[e];if(void 0!==i)return i.exports;var s=r[e]={id:e,loaded:!1,exports:{}};return t[e].call(s.exports,s,s.exports,n),s.loaded=!0,s.exports}n.m=t,e=[],n.O=(t,r,i,s)=>{if(!r){var o=1/0;for(l=0;l<e.length;l++){for(var[r,i,s]=e[l],a=!0,c=0;c<r.length;c++)(!1&s||o>=s)&&Object.keys(n.O).every((e=>n.O[e](r[c])))?r.splice(c--,1):(a=!1,s<o&&(o=s));if(a){e.splice(l--,1);var u=i();void 0!==u&&(t=u)}}return t}s=s||0;for(var l=e.length;l>0&&e[l-1][2]>s;l--)e[l]=e[l-1];e[l]=[r,i,s]},n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),(()=>{var e={792:0};n.O.j=t=>0===e[t];var t=(t,r)=>{var i,s,[o,a,c]=r,u=0;if(o.some((t=>0!==e[t]))){for(i in a)n.o(a,i)&&(n.m[i]=a[i]);if(c)var l=c(n)}for(t&&t(r);u<o.length;u++)s=o[u],n.o(e,s)&&e[s]&&e[s][0](),e[s]=0;return n.O(l)},r=this.webpackChunkShogunCore=this.webpackChunkShogunCore||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))})();var i=n.O(void 0,[96],(()=>n(28156)));return i=(i=n.O(i)).default})()));