shogun-core 1.2.7 → 1.2.8

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.
Files changed (67) hide show
  1. package/README.md +0 -1
  2. package/dist/browser/shogun-core.js +1 -1
  3. package/dist/browser/shogun-core.js.LICENSE.txt +2 -0
  4. package/dist/browser/shogun-core.light.js +1 -1
  5. package/dist/browser/shogun-core.vendors.light.js +1 -1
  6. package/dist/core.js +31 -71
  7. package/dist/gundb/{instance.js → gunInstance.js} +135 -115
  8. package/dist/gundb/index.js +3 -20
  9. package/dist/plugins/index.js +23 -1
  10. package/dist/plugins/nostr/index.js +1 -0
  11. package/dist/plugins/nostr/nostrChain.js +128 -0
  12. package/dist/plugins/nostr/nostrConnector.js +42 -7
  13. package/dist/plugins/nostr/nostrConnectorPlugin.js +157 -1
  14. package/dist/plugins/nostr/nostrSigner.js +343 -0
  15. package/dist/plugins/oauth/index.js +13 -0
  16. package/dist/plugins/oauth/oauthChain.js +161 -0
  17. package/dist/plugins/oauth/oauthConnector.js +542 -0
  18. package/dist/plugins/oauth/oauthPlugin.js +302 -0
  19. package/dist/plugins/oauth/types.js +2 -0
  20. package/dist/plugins/web3/index.js +1 -0
  21. package/dist/plugins/web3/web3Chain.js +77 -2
  22. package/dist/plugins/web3/web3Connector.js +159 -37
  23. package/dist/plugins/web3/web3ConnectorPlugin.js +157 -1
  24. package/dist/plugins/web3/web3Signer.js +268 -0
  25. package/dist/plugins/webauthn/webauthnChain.js +78 -0
  26. package/dist/plugins/webauthn/webauthnPlugin.js +154 -1
  27. package/dist/plugins/webauthn/webauthnSigner.js +318 -0
  28. package/dist/storage/storage.js +0 -8
  29. package/dist/types/core.d.ts +10 -34
  30. package/dist/types/gundb/gun-es/gun-es.d.ts +1 -0
  31. package/dist/types/gundb/{instance.d.ts → gunInstance.d.ts} +2 -2
  32. package/dist/types/gundb/index.d.ts +1 -4
  33. package/dist/types/plugins/index.d.ts +4 -0
  34. package/dist/types/plugins/nostr/index.d.ts +1 -0
  35. package/dist/types/plugins/nostr/nostrConnector.d.ts +3 -2
  36. package/dist/types/plugins/nostr/nostrConnectorPlugin.d.ts +82 -0
  37. package/dist/types/plugins/nostr/nostrSigner.d.ts +104 -0
  38. package/dist/types/plugins/oauth/index.d.ts +4 -0
  39. package/dist/types/plugins/oauth/oauthChain.d.ts +2 -0
  40. package/dist/types/plugins/oauth/oauthConnector.d.ts +100 -0
  41. package/dist/types/plugins/oauth/oauthPlugin.d.ts +89 -0
  42. package/dist/types/plugins/oauth/types.d.ts +106 -0
  43. package/dist/types/plugins/web3/index.d.ts +1 -0
  44. package/dist/types/plugins/web3/types.d.ts +1 -0
  45. package/dist/types/plugins/web3/web3Connector.d.ts +8 -2
  46. package/dist/types/plugins/web3/web3ConnectorPlugin.d.ts +82 -0
  47. package/dist/types/plugins/web3/web3Signer.d.ts +93 -0
  48. package/dist/types/plugins/webauthn/webauthnPlugin.d.ts +81 -0
  49. package/dist/types/plugins/webauthn/webauthnSigner.d.ts +90 -0
  50. package/dist/types/shogun.js +1 -28
  51. package/dist/types/types/events.d.ts +2 -2
  52. package/dist/types/types/shogun.d.ts +13 -49
  53. package/package.json +2 -1
  54. package/dist/browser.js +0 -107
  55. package/dist/contracts/base.js +0 -152
  56. package/dist/contracts/entryPoint.js +0 -407
  57. package/dist/contracts/index.js +0 -47
  58. package/dist/contracts/registry.js +0 -259
  59. package/dist/contracts/relay.js +0 -494
  60. package/dist/contracts/utils.js +0 -582
  61. package/dist/types/browser.d.ts +0 -27
  62. package/dist/types/contracts/base.d.ts +0 -82
  63. package/dist/types/contracts/entryPoint.d.ts +0 -138
  64. package/dist/types/contracts/index.d.ts +0 -17
  65. package/dist/types/contracts/registry.d.ts +0 -97
  66. package/dist/types/contracts/relay.d.ts +0 -165
  67. package/dist/types/contracts/utils.d.ts +0 -173
@@ -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,(function(){return function(){var e,t={74:function(e,t){"use strict";var r,n,i,o;Object.defineProperty(t,"__esModule",{value:!0}),t.AuthEvent=t.AuthState=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"}(n||(t.CorePlugins=n={})),function(e){e.UNAUTHENTICATED="unauthenticated",e.AUTHENTICATING="authenticating",e.AUTHENTICATED="authenticated",e.AUTHENTICATION_FAILED="authentication_failed",e.WALLET_INITIALIZING="wallet_initializing",e.WALLET_READY="wallet_ready",e.ERROR="error"}(i||(t.AuthState=i={})),function(e){e.LOGIN_START="login_start",e.LOGIN_SUCCESS="login_success",e.LOGIN_FAILED="login_failed",e.LOGOUT="logout",e.WALLET_INIT_START="wallet_init_start",e.WALLET_INIT_SUCCESS="wallet_init_success",e.WALLET_INIT_FAILED="wallet_init_failed",e.ERROR="error"}(o||(t.AuthEvent=o={}))},170:function(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)},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)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunCore=t.ShogunEventEmitter=t.ShogunStorage=t.Webauthn=t.Web3Connector=t.derive=t.GunDB=t.RelayVerifier=void 0;const s=r(8851),a=r(2077),c=r(4134),u=r(5628),l=r(3358),d=r(4643),g=r(74),h=r(4933),y=r(8098),f=r(8050),E=o(r(9229));r(8030);var p=r(7405);Object.defineProperty(t,"RelayVerifier",{enumerable:!0,get:function(){return p.RelayVerifier}}),i(r(3358),t),i(r(2077),t),i(r(5307),t),i(r(6640),t),i(r(7405),t),i(r(5349),t),i(r(8777),t),i(r(74),t);var w=r(8851);Object.defineProperty(t,"GunDB",{enumerable:!0,get:function(){return w.GunDB}});var b=r(8851);Object.defineProperty(t,"derive",{enumerable:!0,get:function(){return b.derive}});var m=r(8089);Object.defineProperty(t,"Web3Connector",{enumerable:!0,get:function(){return m.Web3Connector}});var A=r(7510);Object.defineProperty(t,"Webauthn",{enumerable:!0,get:function(){return A.Webauthn}});var v=r(4643);Object.defineProperty(t,"ShogunStorage",{enumerable:!0,get:function(){return v.ShogunStorage}});var _=r(4465);Object.defineProperty(t,"ShogunEventEmitter",{enumerable:!0,get:function(){return _.ShogunEventEmitter}});t.ShogunCore=class{static API_VERSION="2.0.0";_gun;_user=null;gundb;storage;eventEmitter;provider;config;rx;plugins=new Map;currentAuthMethod;constructor(e){(0,u.log)("Initializing ShogunSDK"),this.config=e,e.logging&&((0,u.configureLogging)(e.logging),(0,u.log)("Logging configured with custom settings")),this.storage=new d.ShogunStorage,this.eventEmitter=new c.EventEmitter,l.ErrorHandler.addListener((e=>{this.eventEmitter.emit("error",{action:e.code,message:e.message,type:e.type})})),(0,u.log)("Creating Gun instance...");try{e.gunInstance?((0,u.log)("Using provided Gun instance"),this._gun=e.gunInstance):((0,u.log)(`Creating new Gun instance with peers: ${JSON.stringify(e.peers)}`),this._gun=(0,E.default)(e.peers||[])),(0,u.log)("Gun instance created and validated successfully")}catch(e){throw(0,u.logError)("Error creating Gun instance:",e),new Error(`Failed to create Gun instance: ${e}`)}(0,u.log)("Initializing GunDB...");try{this.gundb=new s.GunDB(this._gun,e.scope||""),this._gun=this.gundb.gun,(0,u.log)("GunDB initialized successfully")}catch(e){throw(0,u.logError)("Error initializing GunDB:",e),new Error(`Failed to initialize GunDB: ${e}`)}(0,u.log)("Initialized Gun instance");try{this._user=this._gun.user().recall({sessionStorage:!0}),(0,u.log)("Gun user initialized successfully")}catch(e){throw(0,u.logError)("Error initializing Gun user:",e),new Error(`Failed to initialize Gun user: ${e}`)}if(this.rx=new a.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),(0,u.log)(`Auto-registered plugin: ${t.name}`)}catch(e){(0,u.logError)(`Failed to auto-register plugin ${t.name}:`,e)}(0,u.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,u.log)("Webauthn plugin registered")}if(e.web3?.enabled){const e=new y.Web3ConnectorPlugin;e._category=g.PluginCategory.Authentication,this.register(e),(0,u.log)("Web3Connector plugin registered")}if(e.nostr?.enabled){const e=new f.NostrConnectorPlugin;e._category=g.PluginCategory.Authentication,this.register(e),(0,u.log)("NostrConnector plugin registered")}}catch(e){(0,u.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,u.log)(`Registered plugin: ${e.name}`)}unregister(e){const t=this.plugins.get(e);t?(t.destroy&&t.destroy(),this.plugins.delete(e),(0,u.log)(`Unregistered plugin: ${e}`)):(0,u.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);default:return{login:(e,t)=>{this.login(e,t)},signUp:(e,t,r)=>{this.signUp(e,t,r)}}}}getRecentErrors(e=10){return l.ErrorHandler.getRecentErrors(e)}configureLogging(e){(0,u.configureLogging)(e),(0,u.log)("Logging reconfigured with new settings")}isLoggedIn(){return this.gundb.isLoggedIn()}logout(){try{if(!this.isLoggedIn())return void(0,u.log)("Logout ignored: user not authenticated");this.gundb.logout(),this.eventEmitter.emit("auth:logout",{}),(0,u.log)("Logout completed successfully")}catch(e){l.ErrorHandler.handle(l.ErrorType.AUTHENTICATION,"LOGOUT_FAILED",e instanceof Error?e.message:"Error during logout",e)}}async login(e,t){(0,u.log)("Login");try{if((0,u.log)(`Login attempt for user: ${e}`),!e||!t)return{success:!1,error:"Username and password are required"};this.currentAuthMethod||(this.currentAuthMethod="password",(0,u.log)("Authentication method set to default: password"));const r=this.config?.timeouts?.login??15e3,n=new Promise((async n=>{const i=setTimeout((()=>{n({success:!1,error:"Login timeout"})}),r);try{const r=await this.gundb.login(e,t);clearTimeout(i),r.success?n({success:!0,userPub:r.userPub,username:r.username}):n({success:!1,error:r.error||"Wrong user or password"})}catch(e){clearTimeout(i),n({success:!1,error:e.message||"Login error"})}})),i=await n;return i.success&&(this.eventEmitter.emit("auth:login",{userPub:i.userPub??""}),(0,u.log)(`Current auth method before wallet check: ${this.currentAuthMethod}`)),i}catch(e){return l.ErrorHandler.handle(l.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,u.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,u.log)(`Attempting user registration: ${e}`);const n=this.config?.timeouts?.signup??3e4,i=new Promise((async r=>{const i=setTimeout((()=>{r({success:!1,error:"Registration timeout"})}),n);try{const n=await this.gundb.signUp(e,t);clearTimeout(i),n.success?(this.eventEmitter.emit("debug",{action:"signup_complete",username:e,userPub:n.userPub,timestamp:Date.now()}),this.eventEmitter.emit("auth:signup",{userPub:n.userPub??"",username:e})):this.eventEmitter.emit("debug",{action:"signup_failed",username:e,error:n.error,timestamp:Date.now()}),r(n)}catch(e){clearTimeout(i),r({success:!1,error:e.message||"Registration error"})}}));return await i}catch(t){return(0,u.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,u.log)(`Setting authentication method from '${this.currentAuthMethod}' to '${e}'`),this.currentAuthMethod=e,(0,u.log)(`Authentication method successfully set to: ${e}`)}getAuthMethod(){return this.currentAuthMethod}}},554:function(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(!Gun.SEA)throw new Error("SEA is not available");return Gun.SEA.encrypt(e,t)},t.decrypt=async function(e,t){if(!Gun.SEA)throw new Error("SEA is not available");return Gun.SEA.decrypt(e,t)},t.encFor=async function(e,t,r){const i=await n.SEA.secret(r.epub,t),o=await n.SEA.encrypt(e,i);return o},t.decFrom=async function(e,t,r){const i=await n.SEA.secret(t.epub,r),o=await n.SEA.decrypt(e,i);return o},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,o)},t.unsafeHash=function(e){if(!e)return;return e.replace(/[._-]/g,s)},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(9229);async function i(e){return await n.SEA.work(e,null,null,{name:"SHA-256"})}function o(e){switch(e){case"+":return"-";case"=":return".";case"/":return"_"}}function s(e){switch(e){case"-":return"+";case".":return"=";case"_":return"/"}}},1731:function(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={}))},2077:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GunRxJS=void 0;const n=r(9364),i=r(2794);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={},o=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 o="object"==typeof e?this.removeGunMeta(e):e;i[n]=o,r.next(Object.values(i))}));return()=>{o&&"function"==typeof o&&o(),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),o=new Array(e.length).fill(!1);const s=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:()=>{o[r]=!0,o.every((e=>e))&&n.complete()}})));return()=>{s.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}}},3358:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorHandler=t.ErrorType=void 0,t.createError=o;const n=r(5628);var i;function o(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,s="error"){const a=i?`${r} - ${this.formatError(i)}`:r;switch(s){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=o(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,o=1e3){let s;for(let t=1;t<=i;t++)try{return await e()}catch(e){s=e;const r=o*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`,s)}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}}},3490: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)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.webauthnChain=void 0,i(r(4933),t),i(r(1731),t),i(r(7510),t);var s=r(7909);Object.defineProperty(t,"webauthnChain",{enumerable:!0,get:function(){return o(s).default}})},4134:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EventEmitter=void 0;const n=r(5628);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()}}},4407: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(9229)),o=r(7897);t.default=()=>{const e=new o.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()}}},4465:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunEventEmitter=void 0;const n=r(4134);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},4586:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BasePlugin=void 0;const n=r(4134);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},4643:function(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:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebauthnPlugin=void 0;const n=r(4586),i=r(7510),o=r(5628),s=r(4193),a=r(3358);class c extends n.BasePlugin{name="webauthn";version="1.0.0";description="Provides WebAuthn authentication functionality for ShogunCore";webauthn=null;initialize(e){super.initialize(e),this.webauthn=new i.Webauthn(e.gun),(0,o.log)("WebAuthn plugin initialized")}destroy(){this.webauthn=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}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 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=s.ethers.keccak256(s.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}`),a.ErrorHandler.handle(a.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=s.ethers.keccak256(s.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}`),a.ErrorHandler.handle(a.ErrorType.WEBAUTHN,"WEBAUTHN_SIGNUP_ERROR",e.message||"Error during WebAuthn registration",e),{success:!1,error:e.message||"Error during WebAuthn registration"}}}}t.WebauthnPlugin=c},4993: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(4827));t.Gun=i.default;const o=n(r(8030));Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return o.default}})},5256: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]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=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),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.GunDB=void 0;const c=r(5628),u=r(3358),l=r(2077),d=s(r(7120)),g=s(r(554)),h=s(r(170)),y=a(r(7476));t.GunDB=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;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=g,this.utils=h,this.node=this.gun.get(t),setTimeout((async()=>{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)}}),500)}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,o=i?"connected":n&&n.wire?"disconnected":"not_initialized";t[r]={connected:i,status:o}})),t}catch(e){return(0,c.logError)("Error getting peer info:",e),{}}}reconnectToPeer(e){try{this.removePeer(e),setTimeout((()=>{this.addPeer(e),(0,c.log)(`Reconnected to peer: ${e}`)}),1e3)}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 username ${e} already exists in tracking system...`);const r=await this.checkUsernameExists(e);if(r)return(0,c.log)(`Username ${e} already exists in tracking system with pub: ${r.pub}`),{success:!1,error:"User already created!"};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){if(n.error&&n.error.includes("User already created")){(0,c.log)(`User ${e} already exists in Gun.js, attempting login...`);try{const r=await this.login(e,t);return r.success?((0,c.log)(`Login successful after failed registration for: ${e}`),{success:!0,userPub:r.userPub,username:r.username}):{success:!1,error:"User already created!"}}catch(e){return(0,c.logError)(`Login after failed registration error: ${e}`),{success:!1,error:"User already created!"}}}return n}try{const t=this.gun.get(n.pub),r={username:e,pub:n.pub,createdAt:Date.now()};await new Promise(((n,i)=>{t.put(r,(t=>{t.err?((0,c.logError)(`Warning: Failed to save user metadata: ${t.err}`),n()):((0,c.log)(`User metadata saved for: ${e}`),n())}))})),await new Promise(((r,n)=>{this.gun.get("users").set(t,(t=>{t.err?((0,c.logError)(`Warning: Failed to add user to collection: ${t.err}`),r()):((0,c.log)(`User added to collection: ${e}`),r())}))})),await new Promise(((t,r)=>{this.gun.get("usernames").get(e).put(n.pub,(r=>{r.err?((0,c.logError)(`Warning: Could not create username mapping: ${r.err}`),t()):((0,c.log)(`Username mapping created: ${e} -> ${n.pub}`),t())}))}))}catch(e){(0,c.logError)(`Warning: Could not store user metadata: ${e}`)}(0,c.log)(`Attempting login after registration for: ${e}`);let i=0;const o=3;for(;i<o;)try{const r=await this.login(e,t);if(r.success)return(0,c.log)(`Login after registration successful for: ${e}`),{success:!0,userPub:r.userPub,username:r.username};if(i++,!(i<o))return(0,c.logError)(`Login after registration failed after ${o} attempts: ${r.error}`),{success:!1,error:`Registration completed but login failed: ${r.error}`};(0,c.log)(`Login attempt ${i} failed, retrying...`),await new Promise((e=>setTimeout(e,1e3*i)))}catch(e){if(i++,i>=o)return(0,c.logError)(`Exception during post-registration login: ${e}`),{success:!1,error:"Exception during post-registration login"};await new Promise((e=>setTimeout(e,1e3*i)))}return{success:!1,error:"Failed to login after registration"}}catch(e){return(0,c.logError)(`Unexpected error during registration flow: ${e}`),{success:!1,error:`Unexpected error during registration: ${e}`}}}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,n=!1;this.gun.get("users").map().once(((i,o)=>{!n&&i&&i.username===e&&(n=!0,clearTimeout(r),t(i))})),r=setTimeout((()=>{r&&clearTimeout(r),n||t(null)}),2e3)}))}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,i)=>{this.gun.get(n).put(t,(t=>{t.err?((0,c.logError)(`Warning: Failed to save user metadata: ${t.err}`),r()):((0,c.log)(`User metadata saved for: ${e}`),r())}))})),await new Promise(((t,r)=>{this.gun.get("users").set(this.gun.get(n),(r=>{r.err?((0,c.logError)(`Warning: Failed to add user to collection: ${r.err}`),t()):((0,c.log)(`User added to collection: ${e}`),t())}))})),await new Promise(((t,r)=>{this.gun.get("usernames").get(e).put(n,(r=>{r.err?((0,c.logError)(`Warning: Could not create username mapping: ${r.err}`),t()):((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&&"undefined"!=typeof localStorage){localStorage.setItem("gun/pair",JSON.stringify(t));const e={pub:r.pub,alias:r.alias||"",timestamp:Date.now()};localStorage.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 o=this.gun.user();o._={sea:n};return await new Promise((e=>{try{o.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)}setTimeout((()=>e(!1)),3e3)}))&&o.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"};try{const e=await this.crypto.hashText(i.join("|")),t=await this.crypto.encrypt(r,e);return await this.saveUserData("security",{questions:n,hint:t}),{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 e=this.gun.user().recall({sessionStorage:!0});if(!e||!e.is)return{success:!1,error:"User not found"};const r=await this.getUserData("security");if(!r||!r.hint)return{success:!1,error:"No password hint found"};const n=await this.crypto.decrypt(r.hint,await this.crypto.hashText(t.join("|")));return void 0===n?{success:!1,error:"Incorrect answers to security questions"}:{success:!0,hint:n}}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,y.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=d}},5307: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.nostrChain=t.NostrConnectorPlugin=t.NostrConnector=t.web3Chain=t.Web3ConnectorPlugin=t.Web3Connector=t.webauthnChain=t.WebauthnPlugin=t.Webauthn=t.BasePlugin=void 0;var i=r(4586);Object.defineProperty(t,"BasePlugin",{enumerable:!0,get:function(){return i.BasePlugin}});var o=r(7510);Object.defineProperty(t,"Webauthn",{enumerable:!0,get:function(){return o.Webauthn}});var s=r(4933);Object.defineProperty(t,"WebauthnPlugin",{enumerable:!0,get:function(){return s.WebauthnPlugin}});var a=r(7909);Object.defineProperty(t,"webauthnChain",{enumerable:!0,get:function(){return n(a).default}});var c=r(8089);Object.defineProperty(t,"Web3Connector",{enumerable:!0,get:function(){return c.Web3Connector}});var u=r(8098);Object.defineProperty(t,"Web3ConnectorPlugin",{enumerable:!0,get:function(){return u.Web3ConnectorPlugin}});var l=r(5655);Object.defineProperty(t,"web3Chain",{enumerable:!0,get:function(){return n(l).default}});var d=r(7897);Object.defineProperty(t,"NostrConnector",{enumerable:!0,get:function(){return d.NostrConnector}});var g=r(8050);Object.defineProperty(t,"NostrConnectorPlugin",{enumerable:!0,get:function(){return g.NostrConnectorPlugin}});var h=r(4407);Object.defineProperty(t,"nostrChain",{enumerable:!0,get:function(){return n(h).default}})},5349:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Registry=void 0;const n=r(4193),i=r(3358),o=r(8711);class s extends o.BaseContract{constructor(e){super(e.registryAddress,o.REGISTRY_ABI,e)}async isRegisteredRelay(e){try{if(!this.contract)throw new Error("Registry contract not initialized");return await this.contract.isRegisteredRelay(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_IS_REGISTERED_FAILED",`Failed to check if relay at ${e} is registered`,t),!1}}async isRelayActive(e){try{if(!this.contract)throw new Error("Registry contract not initialized");return await this.contract.isRelayActive(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_IS_ACTIVE_FAILED",`Failed to check if relay at ${e} is active`,t),!1}}async findRelayByUrl(e){try{if(!this.contract)throw new Error("Registry contract not initialized");return await this.contract.findRelayByUrl(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_FIND_RELAY_FAILED",`Failed to find relay with URL ${e}`,t),n.ethers.ZeroAddress}}async getRelayInfo(e){try{if(!this.contract)throw new Error("Registry contract not initialized");const[t,r,n,i,o]=await this.contract.getRelayInfo(e);return{owner:t,url:r,metadata:n,registrationTime:i,active:o}}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_GET_RELAY_INFO_FAILED",`Failed to get relay info for ${e}`,t),null}}async getRelayCountByOwner(e){try{if(!this.contract)throw new Error("Registry contract not initialized");const t=await this.contract.getRelayCountByOwner(e);return Number(t)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_GET_RELAY_COUNT_FAILED",`Failed to get relay count for owner ${e}`,t),0}}async getRelaysByOwner(e,t=0,r=10){try{if(!this.contract)throw new Error("Registry contract not initialized");return await this.contract.getRelaysByOwner(e,t,r)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_GET_RELAYS_BY_OWNER_FAILED",`Failed to get relays for owner ${e}`,t),null}}async getAllRelays(e=!0,t=0,r=10){try{if(!this.contract)throw new Error("Registry contract not initialized");return await this.contract.getAllRelays(e,t,r)}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_GET_ALL_RELAYS_FAILED","Failed to get all relays",e),null}}async registerRelay(e,t,r){try{if(!this.contract)throw new Error("Registry contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.registerRelay(e,t,r)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_REGISTER_RELAY_FAILED",`Failed to register relay at ${e}`,t),null}}async updateRelay(e,t="",r=""){try{if(!this.contract)throw new Error("Registry contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.updateRelay(e,t,r)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_UPDATE_RELAY_FAILED",`Failed to update relay at ${e}`,t),null}}async deactivateRelay(e){try{if(!this.contract)throw new Error("Registry contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.deactivateRelay(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_DEACTIVATE_RELAY_FAILED",`Failed to deactivate relay at ${e}`,t),null}}async reactivateRelay(e){try{if(!this.contract)throw new Error("Registry contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.reactivateRelay(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_REACTIVATE_RELAY_FAILED",`Failed to reactivate relay at ${e}`,t),null}}async setRegistrationOpen(e){try{if(!this.contract)throw new Error("Registry contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.setRegistrationOpen(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"REGISTRY_SET_REGISTRATION_OPEN_FAILED",`Failed to set registration open to ${e}`,t),null}}}t.Registry=s},5628:function(e,t,r){"use strict";var n=r(5606);Object.defineProperty(t,"__esModule",{value:!0}),t.enableDebug=function(){o=!0,s("Debug mode enabled")},t.disableDebug=function(){o=!1},t.configureLogging=function(e){i={...i,...e}},t.log=s,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:s(t,...r)}};let i={enabled:"true"===n.env.DEBUG,level:"info",prefix:"[ShogunSDK]"},o=!1;function s(e,...t){(new Date).toISOString()}function a(e,...t){(new Date).toISOString()}function c(e,...t){(new Date).toISOString()}function u(e,...t){if(!o)return;(new Date).toISOString()}},5655: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(9229)),o=r(8089);t.default=()=>{const e=new o.Web3Connector;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.verifySignature=async function(t,r){return await e.verifySignature(t,r)},i.default.chain.isMetaMaskAvailable=function(){return o.Web3Connector.isMetaMaskAvailable()}}},5736:function(e){function t(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=function(){return[]},t.resolve=t,t.id=5736,e.exports=t},6640:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EntryPoint=void 0;const n=r(4193),i=r(3358),o=r(8711);class s extends o.BaseContract{constructor(e){super(e.entryPointAddress,o.ENTRY_POINT_ABI,e)}async getRegistryAddress(){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");return await this.contract.registry()}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_GET_REGISTRY_FAILED","Failed to get registry address",e),null}}async getServiceFeePercentage(){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");const e=await this.contract.serviceFeePercentage();return Number(e)}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_GET_FEE_PERCENTAGE_FAILED","Failed to get service fee percentage",e),null}}async calculateFee(e){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");return await this.contract.calculateFee(e)}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_CALCULATE_FEE_FAILED","Failed to calculate fee",e),null}}async checkSubscription(e,t){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");return await this.contract.checkSubscription(e,t)}catch(r){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_CHECK_SUBSCRIPTION_FAILED",`Failed to check subscription for user ${e} on relay ${t}`,r),!1}}async hasRegisteredPubKey(e,t){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");return await this.contract.hasRegisteredPubKey(e,t)}catch(r){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_HAS_REGISTERED_PUBKEY_FAILED",`Failed to check if user ${e} has registered pubkey on relay ${t}`,r),!1}}async isPubKeySubscribed(e,t){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");const r=t instanceof Uint8Array?n.ethers.hexlify(t):t;return await this.contract.isPubKeySubscribed(e,r)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_IS_PUBKEY_SUBSCRIBED_FAILED",`Failed to check if pubkey is subscribed on relay ${e}`,t),!1}}async batchCheckPubKeySubscription(e,t){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");if(e.length!==t.length)throw new Error("Array lengths must match");const r=t.map((e=>e instanceof Uint8Array?n.ethers.hexlify(e):e));return await this.contract.batchCheckPubKeySubscription(e,r)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_BATCH_CHECK_PUBKEYS_FAILED","Failed to batch check public key subscriptions",t),Array(e.length).fill(!1)}}async getSubscriptionDetails(e,t){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");const[r,i]=await this.contract.getSubscriptionDetails(e,t);return{expires:r,pubKey:n.ethers.hexlify(i)}}catch(r){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_GET_SUBSCRIPTION_DETAILS_FAILED",`Failed to get subscription details for user ${e} on relay ${t}`,r),null}}async batchCheckSubscriptions(e,t){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");return await this.contract.batchCheckSubscriptions(e,t)}catch(r){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_BATCH_CHECK_SUBSCRIPTIONS_FAILED",`Failed to batch check subscriptions for user ${e}`,r),Array(t.length).fill(!1)}}async batchCheckPubKeys(e,t){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");return await this.contract.batchCheckPubKeys(e,t)}catch(r){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_BATCH_CHECK_PUBKEYS_FAILED",`Failed to batch check pubkeys for user ${e}`,r),Array(t.length).fill(!1)}}async getStatistics(){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");const[e,t,r,n,i,o,s]=await this.contract.getStatistics();return{userCount:e,totalSubscriptions:t,totalViaUrl:r,totalViaDirect:n,totalAmountProcessed:i,totalFeesCollected:o,currentBalance:s}}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_GET_STATISTICS_FAILED","Failed to get EntryPoint statistics",e),null}}async subscribeViaUrl(e,t,r,o){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");const i=r instanceof Uint8Array?n.ethers.hexlify(r):r,s={value:o||n.ethers.parseEther("0.01")};return await this.contract.subscribeViaUrl(e,t,i,s)}catch(r){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_SUBSCRIBE_VIA_URL_FAILED",`Failed to subscribe via URL ${e} for ${t} months`,r),null}}async subscribeDirect(e,t,r,o){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");const i=r instanceof Uint8Array?n.ethers.hexlify(r):r,s={value:o||n.ethers.parseEther("0.01")};return await this.contract.subscribeDirect(e,t,i,s)}catch(r){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_SUBSCRIBE_DIRECT_FAILED",`Failed to subscribe directly to relay ${e} for ${t} months`,r),null}}async batchSubscribe(e,t,r,o){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");if(e.length!==r.length)throw new Error("Array lengths must match");const i=r.map((e=>e instanceof Uint8Array?n.ethers.hexlify(e):e)),s={value:o||n.ethers.parseEther("0.01")*BigInt(e.length)};return await this.contract.batchSubscribe(e,t,i,s)}catch(r){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_BATCH_SUBSCRIBE_FAILED",`Failed to batch subscribe to ${e.length} relays for ${t} months`,r),null}}async updateRegistry(e){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.updateRegistry(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_UPDATE_REGISTRY_FAILED",`Failed to update registry to ${e}`,t),null}}async updateServiceFee(e){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.updateServiceFee(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_UPDATE_SERVICE_FEE_FAILED",`Failed to update service fee to ${e}`,t),null}}async withdrawFees(){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.withdrawFees()}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_WITHDRAW_FEES_FAILED","Failed to withdraw fees",e),null}}async isRelayInProtocolMode(e){try{if(!this.contract)throw new Error("EntryPoint contract not initialized");return 1===await this.contract.isRelayInProtocolMode(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"ENTRY_POINT_IS_RELAY_IN_PROTOCOL_MODE_FAILED",`Failed to check if relay ${e} is in protocol mode`,t),!1}}}t.EntryPoint=s},6868:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SEA=t.Gun=void 0;const n=r(4993);Object.defineProperty(t,"Gun",{enumerable:!0,get:function(){return n.Gun}}),Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return n.SEA}}),r(7410),r(8719),r(9617),r(924),r(6402),r(6140)},6882:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0})},7120:function(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{}},7405:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RelayVerifier=t.RelayEventType=void 0,t.getRelayUrls=l,t.getRegisteredPubKeys=async function(e,t,r,n=!0){try{const o=[],s=await l(e,n);if(r&&r.length>0)for(const e of r)for(const r of s){if(await t.hasRegisteredPubKey(e,r.address)){const n=await t.getSubscriptionDetails(e,r.address);n&&n.pubKey&&o.push({relayAddress:r.address,relayUrl:r.url,pubKey:n.pubKey,userAddress:e,expires:n.expires})}}else for(const t of s)try{new i.SimpleRelay({relayAddress:t.address,registryAddress:e.getAddress(),providerUrl:void e.getAddress()})}catch(e){}const a={};for(const e of o)a[e.pubKey]||(a[e.pubKey]={pubKey:e.pubKey,relays:[]}),a[e.pubKey].relays.push({relayAddress:e.relayAddress,relayUrl:e.relayUrl,userAddress:e.userAddress,expires:e.expires});return a}catch(e){return{}}},t.getSubscriptionHistory=async function(e,t="month"){try{const e=new Date,r=[];let n;switch(t){case"day":n=24;for(let t=0;t<n;t++){const n=new Date(e);n.setHours(n.getHours()-t),r.push({date:n.toISOString(),count:Math.floor(10*Math.random())+1})}break;case"week":n=7;for(let t=0;t<n;t++){const n=new Date(e);n.setDate(n.getDate()-t),r.push({date:n.toISOString().split("T")[0],count:Math.floor(25*Math.random())+5})}break;default:n=30;for(let t=0;t<n;t++){const n=new Date(e);n.setDate(n.getDate()-t),r.push({date:n.toISOString().split("T")[0],count:Math.floor(50*Math.random())+10})}}return r.sort(((e,t)=>new Date(e.date).getTime()-new Date(t.date).getTime()))}catch(e){return[]}},t.getRelayPerformance=async function(e,t){try{if(!await e.isRegisteredRelay(t))throw new Error(`Relay ${t} non è registrato`);const r=await e.getRelayInfo(t);if(!r)throw new Error(`Impossibile ottenere informazioni per il relay ${t}`);return{uptime:r.active?5*Math.random()+95:0,responseTime:Math.floor(500*Math.random())+50,successRate:r.active?10*Math.random()+90:0,lastChecked:(new Date).toISOString()}}catch(e){return{uptime:0,responseTime:0,successRate:0,lastChecked:(new Date).toISOString()}}},t.getNetworkSummary=async function(e,t){try{const r=await e.getAllRelays(!1,0,1e3);if(!r)throw new Error("Impossibile ottenere l'elenco dei relay");let i=0;for(const t of r.relays){await e.isRelayActive(t)&&i++}const o=await t.getStatistics();n.ethers.parseEther("0");const s=n.ethers.parseEther("0.01");return{totalRelays:Number(r.total),activeRelays:i,totalSubscriptions:o?Number(o.totalSubscriptions):0,activeSubscriptions:o?.7*Number(o.totalSubscriptions):0,averagePrice:n.ethers.formatEther(s),totalProcessedAmount:o?n.ethers.formatEther(o.totalAmountProcessed):"0",totalFeesCollected:o?n.ethers.formatEther(o.totalFeesCollected):"0"}}catch(e){return{totalRelays:0,activeRelays:0,totalSubscriptions:0,activeSubscriptions:0,averagePrice:"0",totalProcessedAmount:"0",totalFeesCollected:"0"}}},t.subscribeToRelayEvents=function(e,t){u.on("relayEvent",t);const r=setInterval((()=>{const e=Object.values(c),t=e[Math.floor(Math.random()*e.length)],r={type:t,timestamp:Date.now(),relayAddress:`0x${Math.random().toString(16).substring(2,42)}`,userAddress:t.includes("Subscription")?`0x${Math.random().toString(16).substring(2,42)}`:void 0,transactionHash:`0x${Math.random().toString(16).substring(2,66)}`};u.emit("relayEvent",r)}),1e4);return()=>{clearInterval(r),u.removeListener("relayEvent",t)}},t.getUsageDataForChart=async function(e,t,r){try{const e=new Date,n=[];let i=0,o="",s="";switch(r){case"daily":i=24;break;case"weekly":i=7;break;default:i=30}for(let o=0;o<i;o++){const i=new Date(e);if("daily"===r){i.setHours(i.getHours()-o);const e=`${i.getHours()}:00`;let r=0;switch(t){case"subscriptions":r=Math.floor(15*Math.random())+1;break;case"revenue":r=.5*Math.random()+.1;break;case"users":r=Math.floor(20*Math.random())+5}n.push({label:e,value:r})}else{i.setDate(i.getDate()-o);const e=i.toISOString().split("T")[0];let r=0;switch(t){case"subscriptions":r=Math.floor(50*Math.random())+10;break;case"revenue":r=2*Math.random()+.5;break;case"users":r=Math.floor(100*Math.random())+20}n.push({label:e,value:r})}}switch(t){case"subscriptions":o="Sottoscrizioni",s="Numero di sottoscrizioni "+("daily"===r?"giornaliere":"weekly"===r?"settimanali":"mensili");break;case"revenue":o="Ricavi",s=`Ricavi ${"daily"===r?"giornalieri":"weekly"===r?"settimanali":"mensili"} in ETH`;break;case"users":o="Utenti",s="Numero di utenti attivi "+("daily"===r?"giornalieri":"weekly"===r?"settimanali":"mensili")}return{dataPoints:n.sort(((e,t)=>"daily"===r?parseInt(e.label.split(":")[0])-parseInt(t.label.split(":")[0]):new Date(e.label).getTime()-new Date(t.label).getTime())),title:o,description:s}}catch(e){return{dataPoints:[],title:"Errore",description:"Impossibile caricare i dati"}}};const n=r(4193),i=r(8777),o=r(7007),s=r(3358),a=r(5628);var c;!function(e){e.NEW_SUBSCRIPTION="newSubscription",e.SUBSCRIPTION_EXPIRED="subscriptionExpired",e.RELAY_REGISTERED="relayRegistered",e.RELAY_DEACTIVATED="relayDeactivated",e.RELAY_REACTIVATED="relayReactivated"}(c||(t.RelayEventType=c={}));const u=new o.EventEmitter;async function l(e,t=!0){try{const r=[];let n=0;const i=100;let o=!0;for(;o;){const s=await e.getAllRelays(t,n,i);if(s&&0!==s.relays.length){for(const t of s.relays){const n=await e.getRelayInfo(t);n&&n.url&&r.push({url:n.url,address:t})}n+=s.relays.length,o=n<Number(s.total)}else o=!1}return r}catch(e){return[]}}t.RelayVerifier=class{registry=null;entryPoint=null;simpleRelay=null;constructor(e,t,r){this.registry=e??null,this.entryPoint=t??null,this.simpleRelay=r??null}async isPublicKeyAuthorized(e,t){try{if(this.simpleRelay)try{if(await this.simpleRelay.isSubscribed(t))return!0}catch(e){(0,a.logError)("Error checking SimpleRelay subscription:",e)}if(this.entryPoint&&this.registry)try{const e=await this.registry.getAllRelays(!0,0,100);if(e&&e.relays&&e.relays.length>0)for(const r of e.relays){if(await this.entryPoint.isPubKeySubscribed(r,t))return!0}}catch(e){(0,a.logError)("Error checking EntryPoint subscriptions:",e)}return!1}catch(e){return s.ErrorHandler.handle(s.ErrorType.CONTRACT,"RELAY_VERIFIER_ERROR","Error in isPublicKeyAuthorized check",e),!1}}async isUserSubscribedToRelay(e,t){try{return this.simpleRelay&&this.simpleRelay.getAddress()===e?await this.simpleRelay.isSubscribed(t):!!this.entryPoint&&await this.entryPoint.isPubKeySubscribed(e,t)}catch(t){return s.ErrorHandler.handle(s.ErrorType.CONTRACT,"RELAY_VERIFIER_ERROR",`Error checking subscription to relay ${e}`,t),!1}}async getAllRelays(e=!0,t=0,r=100){try{if(!this.registry)return[];const n=await this.registry.getAllRelays(e,t,r);return n?.relays||[]}catch(e){return s.ErrorHandler.handle(s.ErrorType.CONTRACT,"RELAY_VERIFIER_ERROR","Error getting all relays",e),[]}}setRegistry(e){this.registry=e}setEntryPoint(e){this.entryPoint=e}setSimpleRelay(e){this.simpleRelay=e}}},7476:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=async function(e,t,r={}){const o=new TextEncoder,s=e?"string"==typeof e?o.encode(l(e)):e:crypto.getRandomValues(new Uint8Array(32)),a=t?(Array.isArray(t)?t:[t]).map((e=>l(e.toString()))):[],h=o.encode(a.join("|")),E=new Uint8Array(s.length+h.length);if(E.set(s),E.set(h,s.length),E.length<16)throw new Error(`Insufficient input entropy (${E.length})`);const p="v1",w={},{includeP256:b=!0,includeSecp256k1Bitcoin:m=!1,includeSecp256k1Ethereum:A=!1}=r;if(b){const e=[{label:"signing",type:"pub/priv"},{label:"encryption",type:"epub/epriv"}],[t,r]=await Promise.all(e.map((async({label:e})=>{const t=o.encode(`${e}-${p}`),r=await d(E,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)}})));w.pub=t.pub,w.priv=t.priv,w.epub=r.pub,w.epriv=r.priv}if(m){const e=o.encode(`secp256k1-bitcoin-${p}`),t=await d(E,e);if(!i.secp256k1.utils.isValidPrivateKey(t))throw new Error("Invalid secp256k1 private key for Bitcoin");const r=i.secp256k1.getPublicKey(t,!0);w.secp256k1Bitcoin={privateKey:g(t),publicKey:g(r),address:y(r)}}if(A){const e=o.encode(`secp256k1-ethereum-${p}`),t=await d(E,e);if(!i.secp256k1.utils.isValidPrivateKey(t))throw new Error("Invalid secp256k1 private key for Ethereum");const r=i.secp256k1.getPublicKey(t,!1);w.secp256k1Ethereum={privateKey:"0x"+g(t),publicKey:"0x"+g(r),address:f(r)}}return w};const n=r(5897),i=r(8510),o=r(2623),s=r(5336),a=r(3238);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 d(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 g(e){return Array.from(e).map((e=>e.toString(16).padStart(2,"0"))).join("")}const h="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function y(e){const t=(0,o.sha256)(e),r=(0,a.ripemd160)(t),n=new Uint8Array(21);n[0]=0,n.set(r,1);const i=(0,o.sha256)((0,o.sha256)(n)),s=new Uint8Array(25);return s.set(n),s.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}(s)}function f(e){const t=e.slice(1);return"0x"+g((0,s.keccak_256)(t).slice(-20))}},7510:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Webauthn=void 0;const n=r(4193),i=r(3358),o=r(4134),s=r(5628),a=r(1731),c={rpName:"Shogun Wallet",timeout:6e4,userVerification:"preferred",attestation:"none",authenticatorAttachment:"platform",requireResidentKey:!1};class u extends o.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 o=1;o<=n;o++)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,o<n){await new Promise((e=>setTimeout(e,1e3*o)));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,o=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},o=await navigator.credentials.get({publicKey:i,signal:this.abortController.signal});if(!o)throw new Error("WebAuthn verification failed");const{password:s}=this.generateCredentialsFromSalt(e,t),c=this.getDeviceInfo(o.id),u={success:!0,username:e,password:s,credentialId:this.bufferToBase64(o.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(o),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,s.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,s.logDebug)("Credentials created successfully:",i);const o=i,a={id:o.id,rawId:o.rawId,type:o.type,response:{clientDataJSON:o.response.clientDataJSON},getClientExtensionResults:o.getClientExtensionResults};return"attestationObject"in o.response&&(a.response.attestationObject=o.response.attestationObject),this.credential=a,a}catch(e){(0,s.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,s.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,s.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)},7897:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NostrConnector=void 0;const n=r(5628),i=r(3358),o=r(4134);class s extends o.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(!/^(npub1|[0-9a-f]{64})/.test(t))throw new Error("Invalid Nostr public key format")}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{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 o;try{return o=await this.generateDeterministicSignature(t),(0,n.log)("Using deterministic signature for consistency"),this.cacheSignature(t,o),await this.generateCredentialsFromSignature(t,o)}catch(e){(0,n.logError)("Error generating deterministic signature:",e);try{o=await this.requestSignatureWithTimeout(t,i,this.config.timeout),this.cacheSignature(t,o),(0,n.log)("Using real Nostr signature as fallback")}catch(e){(0,n.logError)("Error requesting signature:",e),o=await this.generateDeterministicSignature(t),this.cacheSignature(t,o),(0,n.log)("Using deterministic signature as final fallback")}}return await this.generateCredentialsFromSignature(t,o)}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 o=r.substring(0,128);return o=o.toLowerCase().replace(/[^0-9a-f]/g,"0"),o.length<128?o=o.padEnd(128,"0"):o.length>128&&(o=o.substring(0,128)),(0,n.log)(`Generated deterministic signature: ${o.substring(0,16)}... (${o.length} chars)`),o}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{if((0,n.log)(`Verifying signature for address: ${r}`),!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(r.toLowerCase()!==this.connectedAddress?.toLowerCase())return(0,n.logError)("Address mismatch in signature verification"),(0,n.logError)(`Expected: ${this.connectedAddress}, Got: ${r}`),!1;const e=/^[0-9a-f]+$/i.test(t),i=t.length>=64;return(0,n.log)(`Signature format check: hex=${e}, length=${i} (${t.length} chars)`),e?i?((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=r.toLowerCase()===this.manualKeyPair.address.toLowerCase();return(0,n.log)(`Manual verification - address match: ${e}`),e}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 o=setTimeout((()=>{i(new Error("Signature request timed out"))}),r);this.requestSignature(e,t).then((e=>{clearTimeout(o),n(e)})).catch((e=>{clearTimeout(o),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},o=await window.nostr.signEvent(i);(0,n.log)("Received Nostr signature:",o.sig.substring(0,20)+"...");let s=o.sig;return s&&"string"==typeof s&&(s=s.replace(/[^a-f0-9]/gi,"").toLowerCase(),s.length>128?s=s.substring(0,128):s.length<128&&(s=s.padStart(128,"0")),(0,n.log)(`Normalized Nostr signature: ${s.substring(0,10)}...`)),s;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=s},7909: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(9229)),o=r(7510);t.default=()=>{const e=new o.Webauthn;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)}}},8050:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NostrConnectorPlugin=void 0;const n=r(4586),i=r(7897),o=r(5628),s=r(3358);class a extends n.BasePlugin{name="nostr";version="1.0.0";description="Provides Bitcoin wallet connection and authentication for ShogunCore";bitcoinConnector=null;initialize(e){super.initialize(e),this.bitcoinConnector=new i.NostrConnector,(0,o.log)("Bitcoin wallet plugin initialized")}destroy(){this.bitcoinConnector&&this.bitcoinConnector.cleanup(),this.bitcoinConnector=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}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 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,s.createError)(s.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Bitcoin address required for login");if(!this.isAvailable())throw(0,s.createError)(s.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,s.createError)(s.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,s.createError)(s.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,s.createError)(s.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||s.ErrorType.AUTHENTICATION,r=e?.code||"BITCOIN_LOGIN_ERROR",n=e?.message||"Unknown error during Bitcoin wallet login";return{success:!1,error:s.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,s.createError)(s.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Bitcoin address required for signup");if(!this.isAvailable())throw(0,s.createError)(s.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,s.createError)(s.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,s.createError)(s.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,s.createError)(s.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||s.ErrorType.AUTHENTICATION,r=e?.code||"BITCOIN_SIGNUP_ERROR",n=e?.message||"Unknown error during Bitcoin wallet signup";return{success:!1,error:s.ErrorHandler.handle(t,r,n,e).message}}}async loginWithBitcoinWallet(e){return this.login(e)}async signUpWithBitcoinWallet(e){return this.signUp(e)}}t.NostrConnectorPlugin=a},8089:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Web3Connector=void 0;const n=r(4193),i=r(5628),o=r(3358),s=r(4134);class a extends s.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&&window.ethereum)try{this.provider=new n.ethers.BrowserProvider(window.ethereum),(0,i.logDebug)("BrowserProvider initialized successfully")}catch(e){(0,i.logError)("Failed to initialize BrowserProvider",e)}else(0,i.logWarn)("Window.ethereum is not available")}async setupProvider(){try{"undefined"!=typeof window&&window.ethereum?(this.provider=new n.ethers.BrowserProvider(window.ethereum),(0,i.logDebug)("BrowserProvider initialized successfully")):(0,i.logWarn)("Window.ethereum is not available")}catch(e){(0,i.logError)("Failed to initialize BrowserProvider",e)}}setupEventListeners(){this.provider&&(this.provider.on("network",((e,t)=>{this.emit("chainChanged",e)})),window.ethereum?.on&&window.ethereum.on("accountsChanged",(e=>{this.emit("accountsChanged",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 o.ErrorHandler.handle(o.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.");(0,i.logDebug)("Requesting account access...");let e=[];if(window.ethereum)try{e=await window.ethereum.request({method:"eth_requestAccounts"}),(0,i.logDebug)(`Accounts requested successfully: ${e.length} accounts returned`)}catch(e){throw(0,i.logError)("Error requesting MetaMask accounts:",e),new Error("User denied account access")}e&&0!==e.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)throw(0,i.logError)("No address returned from signer"),new Error("No accounts found in MetaMask");(0,i.logDebug)(`Signer address obtained: ${r}`);const n=`${r.toLowerCase()}`;return this.emit("connected",{address:r}),(0,i.logDebug)(`MetaMask connected successfully with address: ${r}`),{success:!0,address:r,username:n}}catch(t){if((0,i.logError)(`Error in connection attempt ${e}:`,t),e===this.config.maxRetries)throw t;(0,i.logDebug)(`Retrying in ${this.config.retryDelay}ms...`),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),o.ErrorHandler.handle(o.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 o.ErrorHandler.handle(o.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(){const e=window.ethereum;return"undefined"!=typeof window&&void 0!==e&&!0===e?.isMetaMask}requestSignatureWithTimeout(e,t,r=3e4){return new Promise(((n,o)=>{let s=setTimeout((()=>{s=null,o(new Error("Timeout requesting signature"))}),r);const a=()=>{s&&(clearTimeout(s),s=null),window.ethereum?.removeListener&&window.ethereum.removeListener("accountsChanged",c)},c=e=>{a(),o(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(),o=await r.getAddress();if((0,i.log)("Signer:",r),(0,i.log)("Signer Address:",o),o.toLowerCase()!==e.toLowerCase())throw new Error(`Signer address (${o}) does not match expected address (${e})`);(0,i.log)(`Requesting signature for message: ${t}`);const s=await r.signMessage(t);(0,i.log)("Signature obtained successfully"),a(),n(s)}catch(e){(0,i.logError)("Failed to request signature:",e),a(),o(e)}})()}))}isAvailable(){return"undefined"!=typeof window&&!!window.ethereum}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)},8098:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Web3ConnectorPlugin=void 0;const n=r(4586),i=r(8089),o=r(5628),s=r(4193),a=r(3358);class c extends n.BasePlugin{name="web3";version="1.0.0";description="Provides Ethereum wallet connection and authentication for ShogunCore";Web3=null;initialize(e){super.initialize(e),this.Web3=new i.Web3Connector,(0,o.log)("Web3 plugin initialized")}destroy(){this.Web3&&this.Web3.cleanup(),this.Web3=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}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 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,a.createError)(a.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Ethereum address required for Web3 login");if(!this.isAvailable())throw(0,a.createError)(a.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,a.createError)(a.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=s.ethers.verifyMessage(r.message,r.signature);if(n.toLowerCase()!==e.toLowerCase())throw(0,o.logError)(`Signature verification failed. Expected: ${e}, Got: ${n}`),(0,a.createError)(a.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,a.createError)(a.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||a.ErrorType.AUTHENTICATION,r=e?.code||"WEB3_LOGIN_ERROR",n=e?.message||"Unknown error during Web3 login";return{success:!1,error:a.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,a.createError)(a.ErrorType.VALIDATION,"ADDRESS_REQUIRED","Ethereum address required for Web3 registration");if(!this.isAvailable())throw(0,a.createError)(a.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,a.createError)(a.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=s.ethers.verifyMessage(r.message,r.signature);if(n.toLowerCase()!==e.toLowerCase())throw(0,o.logError)(`Signature verification failed. Expected: ${e}, Got: ${n}`),(0,a.createError)(a.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,a.createError)(a.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||a.ErrorType.AUTHENTICATION,r=e?.code||"WEB3_SIGNUP_ERROR",n=e?.message||"Unknown error during Web3 registration";return{success:!1,error:a.ErrorHandler.handle(t,r,n,e).message}}}}t.Web3ConnectorPlugin=c},8156: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)},8711:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BaseContract=t.ENTRY_POINT_ABI=t.SIMPLE_RELAY_ABI=t.REGISTRY_ABI=t.RelayOperatingMode=void 0;const n=r(4193),i=r(3358),o=r(5628);t.REGISTRY_ABI=["function isRegisteredRelay(address _relayAddress) external view returns (bool)","function isRelayActive(address _relayAddress) external view returns (bool)","function findRelayByUrl(string calldata _url) external view returns (address)","function getRelayInfo(address _relayAddress) external view returns (address owner, string memory url, string memory metadata, uint256 registrationTime, bool active)","function getRelayCountByOwner(address _owner) external view returns (uint256)","function getRelaysByOwner(address _owner, uint256 _offset, uint256 _limit) external view returns (tuple(address[] relays, uint256 total, uint256 offset, uint256 limit))","function getAllRelays(bool _onlyActive, uint256 _offset, uint256 _limit) external view returns (tuple(address[] relays, uint256 total, uint256 offset, uint256 limit))","function registerRelay(address _relayAddress, string calldata _url, string calldata _metadata) external","function updateRelay(address _relayAddress, string calldata _newUrl, string calldata _newMetadata) external","function deactivateRelay(address _relayAddress) external","function reactivateRelay(address _relayAddress) external","function setRegistrationOpen(bool _isOpen) external"];t.SIMPLE_RELAY_ABI=["function isSubscriptionActive(address _user) external view returns (bool)","function getUserSubscriptionInfo(address _user) external view returns (uint256 expires, bytes memory pubKey)","function isAuthorizedByPubKey(bytes calldata _pubKey) external view returns (bool)","function isSubscribed(bytes calldata _pubKey) external view returns (bool)","function pricePerMonth() external view returns (uint256)","function daysPerMonth() external view returns (uint256)","function relayUrl() external view returns (string)","function getRelayOperationalConfig() external view returns (string memory _url, uint256 _price, uint256 _daysInMonth)","function mode() external view returns (uint8)","function registryAddress() external view returns (address)","function entryPointAddress() external view returns (address)","function isRegisteredInRegistry() external view returns (bool)","function getRelayMode() external view returns (uint8 _mode, address _registry, address _entryPoint, bool _isRegistered)","function setRegistry(address _registryAddress, bool _autoRegister, string calldata _metadata) external","function setEntryPoint(address _entryPointAddress, bool _enableProtocolMode) external","function setOperatingMode(uint8 _newMode) external","function registerInRegistry(string calldata _metadata) external","function subscribe(uint256 _months, bytes calldata _pubKey) external payable","function setPrice(uint256 _newPrice) external","function setDaysPerMonth(uint256 _days) external","function updateRelayUrl(string calldata _newUrl) external","function withdrawFunds() external","function decommissionAndWithdrawAllFunds() external","function execute(address _to, uint256 _value, bytes calldata _data) external returns (bool success, bytes memory result)"];var s;t.ENTRY_POINT_ABI=["function registry() external view returns (address)","function serviceFeePercentage() external view returns (uint256)","function calculateFee(uint256 _amount) external view returns (uint256)","function checkSubscription(address _user, address _relayAddress) external view returns (bool)","function hasRegisteredPubKey(address _user, address _relayAddress) external view returns (bool)","function isPubKeySubscribed(address _relayAddress, bytes calldata _pubKey) external view returns (bool)","function batchCheckPubKeySubscription(address[] calldata _relayAddresses, bytes[] calldata _pubKeys) external view returns (bool[] memory)","function getSubscriptionDetails(address _user, address _relayAddress) external view returns (uint256 expires, bytes memory pubKey)","function batchCheckSubscriptions(address _user, address[] calldata _relayAddresses) external view returns (bool[] memory)","function batchCheckPubKeys(address _user, address[] calldata _relayAddresses) external view returns (bool[] memory)","function getStatistics() external view returns (uint256 _userCount, uint256 _totalSubscriptions, uint256 _totalViaUrl, uint256 _totalViaDirect, uint256 _totalAmountProcessed, uint256 _totalFeesCollected, uint256 _currentBalance)","function subscribeViaUrl(string calldata _relayUrl, uint256 _months, bytes calldata _pubKey) external payable","function subscribeDirect(address _relayAddress, uint256 _months, bytes calldata _pubKey) external payable","function batchSubscribe(address[] calldata _relayAddresses, uint256 _months, bytes[] calldata _pubKeys) external payable","function updateRegistry(address _newRegistry) external","function updateServiceFee(uint256 _newFeePercentage) external","function withdrawFees() external"],function(e){e[e.SINGLE=0]="SINGLE",e[e.PROTOCOL=1]="PROTOCOL"}(s||(t.RelayOperatingMode=s={}));t.BaseContract=class{provider=null;signer=null;contract=null;contractAddress;constructor(e,t,r){if(this.contractAddress=e,r.provider?this.provider=r.provider:r.providerUrl&&(this.provider=new n.ethers.JsonRpcProvider(r.providerUrl)),this.signer=r.signer||null,this.provider)try{this.signer?this.contract=new n.ethers.Contract(e,t,this.signer):this.contract=new n.ethers.Contract(e,t,this.provider)}catch(t){i.ErrorHandler.handle(i.ErrorType.CONTRACT,"CONTRACT_INIT_FAILED",`Failed to initialize contract at ${e}`,t)}else(0,o.logError)("No provider available for contract initialization")}setProvider(e){this.provider=e,this.contract&&(this.contract=this.contract.connect(e))}setSigner(e){this.signer=e,this.contract&&this.signer&&(this.contract=this.contract.connect(e))}getAddress(){return this.contractAddress}}},8777:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SimpleRelay=void 0;const n=r(4193),i=r(3358),o=r(8711);class s extends o.BaseContract{constructor(e){super(e.relayAddress,o.SIMPLE_RELAY_ABI,e)}async isSubscriptionActive(e){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");return await this.contract.isSubscriptionActive(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_IS_SUBSCRIPTION_ACTIVE_FAILED",`Failed to check if subscription is active for user ${e}`,t),!1}}async getUserSubscriptionInfo(e){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");const[t,r]=await this.contract.getUserSubscriptionInfo(e),i=await this.contract.isSubscriptionActive(e);return{expires:t,pubKey:n.ethers.hexlify(r),isActive:i}}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_GET_SUBSCRIPTION_INFO_FAILED",`Failed to get subscription info for user ${e}`,t),null}}async isAuthorizedByPubKey(e){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");const t=e instanceof Uint8Array?n.ethers.hexlify(e):e;return await this.contract.isAuthorizedByPubKey(t)}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_IS_AUTHORIZED_FAILED","Failed to check if public key is authorized",e),!1}}async isSubscribed(e){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");const t=e instanceof Uint8Array?n.ethers.hexlify(e):e;return await this.contract.isSubscribed(t)}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_IS_SUBSCRIBED_FAILED","Failed to check if public key is subscribed",e),!1}}async getPricePerMonth(){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");return await this.contract.pricePerMonth()}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_GET_PRICE_FAILED","Failed to get price per month",e),null}}async getDaysPerMonth(){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");const e=await this.contract.daysPerMonth();return Number(e)}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_GET_DAYS_PER_MONTH_FAILED","Failed to get days per month",e),null}}async getRelayUrl(){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");return await this.contract.relayUrl()}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_GET_URL_FAILED","Failed to get relay URL",e),null}}async getRelayOperationalConfig(){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");const[e,t,r]=await this.contract.getRelayOperationalConfig();return{url:e,price:t,daysInMonth:r}}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_GET_CONFIG_FAILED","Failed to get relay operational config",e),null}}async subscribe(e,t){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");const r=t instanceof Uint8Array?n.ethers.hexlify(t):t,i=await this.contract.pricePerMonth()*BigInt(e);return await this.contract.subscribe(e,r,{value:i})}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_SUBSCRIBE_FAILED",`Failed to subscribe for ${e} months`,t),null}}async setPrice(e){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.setPrice(e)}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_SET_PRICE_FAILED","Failed to set new price",e),null}}async setDaysPerMonth(e){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");if(e<1||e>31)throw new Error("Days must be between 1 and 31");return await this.contract.setDaysPerMonth(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_SET_DAYS_PER_MONTH_FAILED",`Failed to set days per month to ${e}`,t),null}}async updateRelayUrl(e){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.updateRelayUrl(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_UPDATE_URL_FAILED",`Failed to update URL to ${e}`,t),null}}async withdrawFunds(){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.withdrawFunds()}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_WITHDRAW_FUNDS_FAILED","Failed to withdraw funds",e),null}}async decommissionAndWithdrawAllFunds(){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.decommissionAndWithdrawAllFunds()}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_DECOMMISSION_FAILED","Failed to decommission relay",e),null}}async execute(e,t,r){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");const[i,o]=await this.contract.execute(e,t,r);return{success:i,result:n.ethers.hexlify(o)}}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_EXECUTE_FAILED",`Failed to execute transaction to ${e}`,t),null}}async getOperatingMode(){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");return await this.contract.mode()}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_GET_MODE_FAILED","Failed to get relay operating mode",e),null}}async getRegistryAddress(){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");return await this.contract.registryAddress()}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_GET_REGISTRY_ADDRESS_FAILED","Failed to get registry address",e),null}}async getEntryPointAddress(){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");return await this.contract.entryPointAddress()}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_GET_ENTRY_POINT_ADDRESS_FAILED","Failed to get entry point address",e),null}}async isRegisteredInRegistry(){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");return await this.contract.isRegisteredInRegistry()}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_IS_REGISTERED_FAILED","Failed to check if relay is registered in registry",e),!1}}async getRelayMode(){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");const[e,t,r,n]=await this.contract.getRelayMode();return{mode:e,registryAddress:t,entryPointAddress:r,isRegistered:n}}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_GET_MODE_INFO_FAILED","Failed to get relay mode information",e),null}}async setRegistry(e,t=!1,r=""){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.setRegistry(e,t,r)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_SET_REGISTRY_FAILED",`Failed to set registry to ${e}`,t),null}}async setEntryPoint(e,t=!1){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.setEntryPoint(e,t)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_SET_ENTRY_POINT_FAILED",`Failed to set entry point to ${e}`,t),null}}async setOperatingMode(e){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.setOperatingMode(e)}catch(t){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_SET_MODE_FAILED",`Failed to set operating mode to ${e}`,t),null}}async registerInRegistry(e=""){try{if(!this.contract)throw new Error("SimpleRelay contract not initialized");if(!this.signer)throw new Error("Signer required for this operation");return await this.contract.registerInRegistry(e)}catch(e){return i.ErrorHandler.handle(i.ErrorType.CONTRACT,"RELAY_REGISTER_IN_REGISTRY_FAILED","Failed to register relay in registry",e),null}}}t.SimpleRelay=s},8807: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)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.web3Chain=void 0,i(r(8098),t),i(r(6882),t),i(r(8089),t);var s=r(5655);Object.defineProperty(t,"web3Chain",{enumerable:!0,get:function(){return o(s).default}})},8851: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.app_scoped=t.getArrayFromIndexedObject=t.getIndexedObjectFromArray=t.qs=t.getSet=t.getUUID=t.getTargetPub=t.getPub=t.getId=t.derive=t.SEA=t.Gun=t.GunDB=void 0;var i=r(5256);Object.defineProperty(t,"GunDB",{enumerable:!0,get:function(){return i.GunDB}});var o=r(6868);Object.defineProperty(t,"Gun",{enumerable:!0,get:function(){return o.Gun}}),Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return o.SEA}});var s=r(7476);Object.defineProperty(t,"derive",{enumerable:!0,get:function(){return n(s).default}});var a=r(170);Object.defineProperty(t,"getId",{enumerable:!0,get:function(){return a.getId}}),Object.defineProperty(t,"getPub",{enumerable:!0,get:function(){return a.getPub}}),Object.defineProperty(t,"getTargetPub",{enumerable:!0,get:function(){return a.getTargetPub}}),Object.defineProperty(t,"getUUID",{enumerable:!0,get:function(){return a.getUUID}}),Object.defineProperty(t,"getSet",{enumerable:!0,get:function(){return a.getSet}}),Object.defineProperty(t,"qs",{enumerable:!0,get:function(){return a.qs}}),Object.defineProperty(t,"getIndexedObjectFromArray",{enumerable:!0,get:function(){return a.getIndexedObjectFromArray}}),Object.defineProperty(t,"getArrayFromIndexedObject",{enumerable:!0,get:function(){return a.getArrayFromIndexedObject}}),Object.defineProperty(t,"app_scoped",{enumerable:!0,get:function(){return a.app_scoped}})},9148: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]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=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),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t}),a=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||i(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunCore=t.modules=void 0,t.initShogunBrowser=y;const c=r(8156);Object.defineProperty(t,"ShogunCore",{enumerable:!0,get:function(){return c.ShogunCore}});const u=r(3490),l=r(8807),d={webauthn:{webauthn:()=>Promise.resolve().then((()=>s(r(7510))))},web3:{web3Connector:()=>Promise.resolve().then((()=>s(r(8098))))},nostr:{nostrConnector:()=>Promise.resolve().then((()=>s(r(8050))))}};let g=null,h=null;function y(e){const t={...e};return g=new c.ShogunCore(t),h=g?.gun,(0,u.webauthnChain)(),(0,l.web3Chain)(),"undefined"!=typeof window&&(window.shogun=g,window.gun=h),g}t.modules={webauthn:{loadWebAuthn:d.webauthn.webauthn},web3:{loadMetaMask:d.web3.web3Connector},nostr:{loadNostrConnector:d.nostr.nostrConnector}},a(r(74),t),"undefined"!=typeof window&&(window.initShogunBrowser=y)}},r={};function n(e){var i=r[e];if(void 0!==i)return i.exports;var o=r[e]={id:e,loaded:!1,exports:{}};return t[e].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}n.m=t,e=[],n.O=function(t,r,i,o){if(!r){var s=1/0;for(l=0;l<e.length;l++){r=e[l][0],i=e[l][1],o=e[l][2];for(var a=!0,c=0;c<r.length;c++)(!1&o||s>=o)&&Object.keys(n.O).every((function(e){return n.O[e](r[c])}))?r.splice(c--,1):(a=!1,o<s&&(s=o));if(a){e.splice(l--,1);var u=i();void 0!==u&&(t=u)}}return t}o=o||0;for(var l=e.length;l>0&&e[l-1][2]>o;l--)e[l]=e[l-1];e[l]=[r,i,o]},n.d=function(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=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.nmd=function(e){return e.paths=[],e.children||(e.children=[]),e},function(){var e={792:0};n.O.j=function(t){return 0===e[t]};var t=function(t,r){var i,o,s=r[0],a=r[1],c=r[2],u=0;if(s.some((function(t){return 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<s.length;u++)o=s[u],n.o(e,o)&&e[o]&&e[o][0](),e[o]=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],(function(){return n(9148)}));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),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}});t.ShogunCore=class{static API_VERSION="2.0.0";_gun;_user=null;gundb;storage;eventEmitter;provider;config;rx;plugins=new Map;currentAuthMethod;constructor(e){(0,c.log)("Initializing Shogun"),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);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((async n=>{const i=setTimeout((()=>{n({success:!1,error:"Login timeout"})}),r);try{const r=await this.gundb.login(e,t);clearTimeout(i),r.success?n({success:!0,userPub:r.userPub,username:r.username}):n({success:!1,error:r.error||"Wrong user or password"})}catch(e){clearTimeout(i),n({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((async r=>{const i=setTimeout((()=>{r({success:!1,error:"Registration timeout"})}),n);try{const n=await this.gundb.signUp(e,t);clearTimeout(i),n.success?(this.eventEmitter.emit("debug",{action:"signup_complete",username:e,userPub:n.userPub,timestamp:Date.now()}),this.eventEmitter.emit("auth:signup",{userPub:n.userPub??"",username:e})):this.eventEmitter.emit("debug",{action:"signup_failed",username:e,error:n.error,timestamp:Date.now()}),r(n)}catch(e){clearTimeout(i),r({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}}},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=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),setTimeout((async()=>{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)}}),500)}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),setTimeout((()=>{this.addPeer(e),(0,c.log)(`Reconnected to peer: ${e}`)}),1e3)}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()};await new Promise((n=>{this.gun.get(t).put(r,(t=>{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=>{this.gun.get("users").set(this.gun.get(t),(t=>{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=>{this.gun.get("usernames").get(e).put(t,(n=>{n.err?(0,c.logError)(`Warning: Could not create username mapping: ${n.err}`):(0,c.log)(`Username mapping created: ${e} -> ${t}`),r()}))}))}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=>{this.gun.get(s).put(o,(r=>{r.err?(0,c.logError)(`Warning: Failed to save user metadata: ${r.err}`):(0,c.log)(`User metadata saved for: ${e}`),t()}))})),await new Promise((t=>{this.gun.get("users").set(this.gun.get(s),(r=>{r.err?(0,c.logError)(`Warning: Failed to add user to collection: ${r.err}`):(0,c.log)(`User added to collection: ${e}`),t()}))})),await new Promise((t=>{this.gun.get("usernames").get(e).put(s,(r=>{r.err?(0,c.logError)(`Warning: Could not create username mapping: ${r.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,n=!1;this.gun.get("users").map().once(((i,s)=>{!n&&i&&i.username===e&&(n=!0,clearTimeout(r),t(i))})),r=setTimeout((()=>{r&&clearTimeout(r),n||t(null)}),2e3)}))}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,i)=>{this.gun.get(n).put(t,(t=>{t.err?((0,c.logError)(`Warning: Failed to save user metadata: ${t.err}`),r()):((0,c.log)(`User metadata saved for: ${e}`),r())}))})),await new Promise(((t,r)=>{this.gun.get("users").set(this.gun.get(n),(r=>{r.err?((0,c.logError)(`Warning: Failed to add user to collection: ${r.err}`),t()):((0,c.log)(`User added to collection: ${e}`),t())}))})),await new Promise(((t,r)=>{this.gun.get("usernames").get(e).put(n,(r=>{r.err?((0,c.logError)(`Warning: Could not create username mapping: ${r.err}`),t()):((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&&"undefined"!=typeof localStorage){localStorage.setItem("gun/pair",JSON.stringify(t));const e={pub:r.pub,alias:r.alias||"",timestamp:Date.now()};localStorage.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)}setTimeout((()=>e(!1)),3e3)}))&&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"};try{const e=await this.crypto.hashText(i.join("|")),t=await this.crypto.encrypt(r,e);return await this.saveUserData("security",{questions:n,hint:t}),{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 e=this.gun.user().recall({sessionStorage:!0});if(!e||!e.is)return{success:!1,error:"User not found"};const r=await this.getUserData("security");if(!r||!r.hint)return{success:!1,error:"No password hint found"};const n=await this.crypto.decrypt(r.hint,await this.crypto.hashText(t.join("|")));return void 0===n?{success:!1,error:"Incorrect answers to security questions"}:{success:!0,hint:n}}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,f.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"}(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:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SEA=t.Gun=t.GunInstance=void 0;var n=r(21302);Object.defineProperty(t,"GunInstance",{enumerable:!0,get:function(){return n.GunInstance}});var i=r(16868);Object.defineProperty(t,"Gun",{enumerable:!0,get:function(){return i.Gun}}),Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return i.SEA}})},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(!Gun.SEA)throw new Error("SEA is not available");return Gun.SEA.encrypt(e,t)},t.decrypt=async function(e,t){if(!Gun.SEA)throw new Error("SEA is not available");return Gun.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){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})()));