shogun-core 5.2.0 → 5.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/README.md +145 -1143
  2. package/dist/browser/defaultVendors-node_modules_hpke_chacha20poly1305_esm_mod_js.shogun-core.js +1220 -0
  3. package/dist/browser/defaultVendors-node_modules_hpke_chacha20poly1305_esm_mod_js.shogun-core.js.map +1 -0
  4. package/dist/browser/defaultVendors-node_modules_hpke_hybridkem-x-wing_esm_mod_js.shogun-core.js +844 -0
  5. package/dist/browser/defaultVendors-node_modules_hpke_hybridkem-x-wing_esm_mod_js.shogun-core.js.map +1 -0
  6. package/dist/browser/defaultVendors-node_modules_mlkem_esm_mod_js.shogun-core.js +2335 -0
  7. package/dist/browser/defaultVendors-node_modules_mlkem_esm_mod_js.shogun-core.js.map +1 -0
  8. package/dist/browser/defaultVendors-node_modules_noble_ciphers_chacha_js.shogun-core.js +999 -0
  9. package/dist/browser/defaultVendors-node_modules_noble_ciphers_chacha_js.shogun-core.js.map +1 -0
  10. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_abstract_curve_js-node_modules_noble_curves_esm_-1ce4ed.shogun-core.js +1651 -0
  11. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_abstract_curve_js-node_modules_noble_curves_esm_-1ce4ed.shogun-core.js.map +1 -0
  12. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_abstract_edwards_js-node_modules_noble_curves_es-a82056.shogun-core.js +825 -0
  13. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_abstract_edwards_js-node_modules_noble_curves_es-a82056.shogun-core.js.map +1 -0
  14. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_ed25519_js.shogun-core.js +508 -0
  15. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_ed25519_js.shogun-core.js.map +1 -0
  16. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_ed448_js.shogun-core.js +747 -0
  17. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_ed448_js.shogun-core.js.map +1 -0
  18. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_nist_js.shogun-core.js +1608 -0
  19. package/dist/browser/defaultVendors-node_modules_noble_curves_esm_nist_js.shogun-core.js.map +1 -0
  20. package/dist/browser/defaultVendors-node_modules_noble_post-quantum_ml-dsa_js.shogun-core.js +2117 -0
  21. package/dist/browser/defaultVendors-node_modules_noble_post-quantum_ml-dsa_js.shogun-core.js.map +1 -0
  22. package/dist/browser/defaultVendors-node_modules_openpgp_dist_openpgp_min_mjs.shogun-core.js +86 -0
  23. package/dist/browser/defaultVendors-node_modules_openpgp_dist_openpgp_min_mjs.shogun-core.js.map +1 -0
  24. package/dist/browser/node_modules_hpke_ml-kem_esm_mod_js.shogun-core.js +539 -0
  25. package/dist/browser/node_modules_hpke_ml-kem_esm_mod_js.shogun-core.js.map +1 -0
  26. package/dist/browser/shogun-core.js +160386 -0
  27. package/dist/browser/shogun-core.js.map +1 -0
  28. package/dist/config/simplified-config.js +236 -0
  29. package/dist/core.js +329 -0
  30. package/dist/crypto/asymmetric.js +99 -0
  31. package/dist/crypto/double-ratchet.js +370 -0
  32. package/dist/crypto/file-encryption.js +213 -0
  33. package/dist/crypto/hashing.js +87 -0
  34. package/dist/crypto/index.js +34 -0
  35. package/dist/crypto/mls-codec.js +202 -0
  36. package/dist/crypto/mls.js +550 -0
  37. package/dist/crypto/pgp.js +390 -0
  38. package/dist/crypto/random-generation.js +341 -0
  39. package/dist/crypto/sframe.js +350 -0
  40. package/dist/crypto/signal-protocol.js +376 -0
  41. package/dist/crypto/symmetric.js +91 -0
  42. package/dist/crypto/types.js +2 -0
  43. package/dist/crypto/utils.js +140 -0
  44. package/dist/examples/auth-test.js +253 -0
  45. package/dist/examples/crypto-identity-example.js +151 -0
  46. package/dist/examples/crypto-working-test.js +83 -0
  47. package/dist/examples/double-ratchet-test.js +155 -0
  48. package/dist/examples/mls-advanced-example.js +294 -0
  49. package/dist/examples/mls-sframe-test.js +304 -0
  50. package/dist/examples/pgp-example.js +200 -0
  51. package/dist/examples/quick-auth-test.js +61 -0
  52. package/dist/examples/random-generation-test.js +151 -0
  53. package/dist/examples/signal-protocol-test.js +38 -0
  54. package/dist/examples/simple-api-test.js +114 -0
  55. package/dist/examples/simple-crypto-identity-example.js +84 -0
  56. package/dist/examples/timeout-test.js +227 -0
  57. package/dist/examples/zkproof-credentials-example.js +212 -0
  58. package/dist/examples/zkproof-example.js +201 -0
  59. package/dist/gundb/api.js +435 -0
  60. package/dist/gundb/crypto.js +283 -0
  61. package/dist/gundb/db.js +1946 -0
  62. package/dist/gundb/derive.js +232 -0
  63. package/dist/gundb/errors.js +76 -0
  64. package/dist/gundb/index.js +22 -0
  65. package/dist/gundb/rxjs.js +447 -0
  66. package/dist/gundb/types.js +5 -0
  67. package/dist/index.js +58 -0
  68. package/dist/interfaces/common.js +2 -0
  69. package/dist/interfaces/events.js +40 -0
  70. package/dist/interfaces/plugin.js +2 -0
  71. package/dist/interfaces/shogun.js +37 -0
  72. package/dist/managers/AuthManager.js +226 -0
  73. package/dist/managers/CoreInitializer.js +228 -0
  74. package/dist/managers/CryptoIdentityManager.js +366 -0
  75. package/dist/managers/EventManager.js +70 -0
  76. package/dist/managers/PluginManager.js +299 -0
  77. package/dist/plugins/base.js +50 -0
  78. package/dist/plugins/index.js +32 -0
  79. package/dist/plugins/nostr/index.js +20 -0
  80. package/dist/plugins/nostr/nostrConnector.js +419 -0
  81. package/dist/plugins/nostr/nostrConnectorPlugin.js +453 -0
  82. package/dist/plugins/nostr/nostrSigner.js +319 -0
  83. package/dist/plugins/nostr/types.js +2 -0
  84. package/dist/plugins/smartwallet/index.js +18 -0
  85. package/dist/plugins/smartwallet/smartWalletPlugin.js +511 -0
  86. package/dist/plugins/smartwallet/types.js +2 -0
  87. package/dist/plugins/web3/index.js +20 -0
  88. package/dist/plugins/web3/types.js +2 -0
  89. package/dist/plugins/web3/web3Connector.js +533 -0
  90. package/dist/plugins/web3/web3ConnectorPlugin.js +455 -0
  91. package/dist/plugins/web3/web3Signer.js +314 -0
  92. package/dist/plugins/webauthn/index.js +19 -0
  93. package/dist/plugins/webauthn/types.js +14 -0
  94. package/dist/plugins/webauthn/webauthn.js +496 -0
  95. package/dist/plugins/webauthn/webauthnPlugin.js +489 -0
  96. package/dist/plugins/webauthn/webauthnSigner.js +310 -0
  97. package/dist/plugins/zkproof/index.js +53 -0
  98. package/dist/plugins/zkproof/types.js +2 -0
  99. package/dist/plugins/zkproof/zkCredentials.js +213 -0
  100. package/dist/plugins/zkproof/zkProofConnector.js +198 -0
  101. package/dist/plugins/zkproof/zkProofPlugin.js +272 -0
  102. package/dist/storage/storage.js +145 -0
  103. package/dist/types/config/simplified-config.d.ts +114 -0
  104. package/dist/types/core.d.ts +305 -0
  105. package/dist/types/crypto/asymmetric.d.ts +6 -0
  106. package/dist/types/crypto/double-ratchet.d.ts +22 -0
  107. package/dist/types/crypto/file-encryption.d.ts +19 -0
  108. package/dist/types/crypto/hashing.d.ts +9 -0
  109. package/dist/types/crypto/index.d.ts +13 -0
  110. package/dist/types/crypto/mls-codec.d.ts +39 -0
  111. package/dist/types/crypto/mls.d.ts +130 -0
  112. package/dist/types/crypto/pgp.d.ts +95 -0
  113. package/dist/types/crypto/random-generation.d.ts +35 -0
  114. package/dist/types/crypto/sframe.d.ts +102 -0
  115. package/dist/types/crypto/signal-protocol.d.ts +26 -0
  116. package/dist/types/crypto/symmetric.d.ts +9 -0
  117. package/dist/types/crypto/types.d.ts +144 -0
  118. package/dist/types/crypto/utils.d.ts +22 -0
  119. package/dist/types/examples/auth-test.d.ts +8 -0
  120. package/dist/types/examples/crypto-identity-example.d.ts +5 -0
  121. package/dist/types/examples/crypto-working-test.d.ts +1 -0
  122. package/dist/types/examples/double-ratchet-test.d.ts +1 -0
  123. package/dist/types/examples/mls-advanced-example.d.ts +53 -0
  124. package/dist/types/examples/mls-sframe-test.d.ts +1 -0
  125. package/dist/types/examples/pgp-example.d.ts +75 -0
  126. package/dist/types/examples/quick-auth-test.d.ts +8 -0
  127. package/dist/types/examples/random-generation-test.d.ts +1 -0
  128. package/dist/types/examples/signal-protocol-test.d.ts +1 -0
  129. package/dist/types/examples/simple-api-test.d.ts +10 -0
  130. package/dist/types/examples/simple-crypto-identity-example.d.ts +6 -0
  131. package/dist/types/examples/timeout-test.d.ts +8 -0
  132. package/dist/types/examples/zkproof-credentials-example.d.ts +12 -0
  133. package/dist/types/examples/zkproof-example.d.ts +11 -0
  134. package/dist/types/gundb/api.d.ts +185 -0
  135. package/dist/types/gundb/crypto.d.ts +95 -0
  136. package/dist/types/gundb/db.d.ts +397 -0
  137. package/dist/types/gundb/derive.d.ts +21 -0
  138. package/dist/types/gundb/errors.d.ts +42 -0
  139. package/dist/types/gundb/index.d.ts +3 -0
  140. package/dist/types/gundb/rxjs.d.ts +110 -0
  141. package/dist/types/gundb/types.d.ts +255 -0
  142. package/dist/types/index.d.ts +16 -0
  143. package/dist/types/interfaces/common.d.ts +85 -0
  144. package/dist/types/interfaces/events.d.ts +131 -0
  145. package/dist/types/interfaces/plugin.d.ts +162 -0
  146. package/dist/types/interfaces/shogun.d.ts +208 -0
  147. package/dist/types/managers/AuthManager.d.ts +72 -0
  148. package/dist/types/managers/CoreInitializer.d.ts +40 -0
  149. package/dist/types/managers/CryptoIdentityManager.d.ts +102 -0
  150. package/dist/types/managers/EventManager.d.ts +49 -0
  151. package/dist/types/managers/PluginManager.d.ts +145 -0
  152. package/dist/types/plugins/base.d.ts +35 -0
  153. package/dist/types/plugins/index.d.ts +18 -0
  154. package/dist/types/plugins/nostr/index.d.ts +4 -0
  155. package/dist/types/plugins/nostr/nostrConnector.d.ts +119 -0
  156. package/dist/types/plugins/nostr/nostrConnectorPlugin.d.ts +163 -0
  157. package/dist/types/plugins/nostr/nostrSigner.d.ts +105 -0
  158. package/dist/types/plugins/nostr/types.d.ts +122 -0
  159. package/dist/types/plugins/smartwallet/index.d.ts +2 -0
  160. package/dist/types/plugins/smartwallet/smartWalletPlugin.d.ts +67 -0
  161. package/dist/types/plugins/smartwallet/types.d.ts +80 -0
  162. package/dist/types/plugins/web3/index.d.ts +4 -0
  163. package/dist/types/plugins/web3/types.d.ts +107 -0
  164. package/dist/types/plugins/web3/web3Connector.d.ts +129 -0
  165. package/dist/types/plugins/web3/web3ConnectorPlugin.d.ts +160 -0
  166. package/dist/types/plugins/web3/web3Signer.d.ts +114 -0
  167. package/dist/types/plugins/webauthn/index.d.ts +3 -0
  168. package/dist/types/plugins/webauthn/types.d.ts +183 -0
  169. package/dist/types/plugins/webauthn/webauthn.d.ts +129 -0
  170. package/dist/types/plugins/webauthn/webauthnPlugin.d.ts +179 -0
  171. package/dist/types/plugins/webauthn/webauthnSigner.d.ts +91 -0
  172. package/dist/types/plugins/zkproof/index.d.ts +48 -0
  173. package/dist/types/plugins/zkproof/types.d.ts +123 -0
  174. package/dist/types/plugins/zkproof/zkCredentials.d.ts +112 -0
  175. package/dist/types/plugins/zkproof/zkProofConnector.d.ts +46 -0
  176. package/dist/types/plugins/zkproof/zkProofPlugin.d.ts +76 -0
  177. package/dist/types/storage/storage.d.ts +51 -0
  178. package/dist/types/utils/errorHandler.d.ts +119 -0
  179. package/dist/types/utils/eventEmitter.d.ts +39 -0
  180. package/dist/types/utils/seedPhrase.d.ts +50 -0
  181. package/dist/types/utils/validation.d.ts +27 -0
  182. package/dist/utils/errorHandler.js +246 -0
  183. package/dist/utils/eventEmitter.js +79 -0
  184. package/dist/utils/seedPhrase.js +97 -0
  185. package/dist/utils/validation.js +81 -0
  186. package/package.json +10 -57
@@ -0,0 +1,533 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Web3Connector = void 0;
7
+ /**
8
+ * The MetaMaskAuth class provides functionality for connecting, signing up, and logging in using MetaMask.
9
+ */
10
+ const ethers_1 = require("ethers");
11
+ const errorHandler_1 = require("../../utils/errorHandler");
12
+ const eventEmitter_1 = require("../../utils/eventEmitter");
13
+ const derive_1 = __importDefault(require("../../gundb/derive"));
14
+ /**
15
+ * Class for MetaMask connection
16
+ */
17
+ class Web3Connector extends eventEmitter_1.EventEmitter {
18
+ constructor(config = {}) {
19
+ super();
20
+ this.MESSAGE_TO_SIGN = "I Love Shogun!";
21
+ this.DEFAULT_CONFIG = {
22
+ cacheDuration: 30 * 60 * 1000, // 30 minutes
23
+ maxRetries: 3,
24
+ retryDelay: 1000,
25
+ timeout: 60000,
26
+ };
27
+ this.signatureCache = new Map();
28
+ this.provider = null;
29
+ this.customProvider = null;
30
+ this.customWallet = null;
31
+ this.config = { ...this.DEFAULT_CONFIG, ...config };
32
+ this.initProvider();
33
+ this.setupEventListeners();
34
+ }
35
+ /**
36
+ * Initialize the provider synchronously with fallback mechanisms
37
+ * to handle conflicts between multiple wallet providers
38
+ */
39
+ initProvider() {
40
+ if (typeof window !== "undefined") {
41
+ try {
42
+ // Check if ethereum is available from any provider
43
+ const ethereumProvider = this.getAvailableEthereumProvider();
44
+ if (ethereumProvider) {
45
+ this.provider = new ethers_1.ethers.BrowserProvider(ethereumProvider);
46
+ }
47
+ else {
48
+ console.warn("No compatible Ethereum provider found");
49
+ }
50
+ }
51
+ catch (error) {
52
+ console.error("Failed to initialize BrowserProvider", error);
53
+ }
54
+ }
55
+ else {
56
+ console.warn("Window object not available (non-browser environment)");
57
+ }
58
+ }
59
+ /**
60
+ * Get available Ethereum provider from multiple possible sources
61
+ */
62
+ getAvailableEthereumProvider() {
63
+ if (typeof window === "undefined")
64
+ return undefined;
65
+ // Define provider sources with priority order
66
+ const providerSources = [
67
+ // Check if we have providers in the _ethereumProviders registry (from index.html)
68
+ {
69
+ source: () => window._ethereumProviders && window._ethereumProviders[0],
70
+ name: "Registry Primary",
71
+ },
72
+ { source: () => window.ethereum, name: "Standard ethereum" },
73
+ {
74
+ source: () => window.web3?.currentProvider,
75
+ name: "Legacy web3",
76
+ },
77
+ { source: () => window.metamask, name: "MetaMask specific" },
78
+ {
79
+ source: () => window.ethereum?.providers?.find((p) => p.isMetaMask),
80
+ name: "MetaMask from providers array",
81
+ },
82
+ {
83
+ source: () => window.ethereum?.providers?.[0],
84
+ name: "First provider in array",
85
+ },
86
+ // Try known provider names
87
+ {
88
+ source: () => window.enkrypt?.providers?.ethereum,
89
+ name: "Enkrypt",
90
+ },
91
+ {
92
+ source: () => window.coinbaseWalletExtension,
93
+ name: "Coinbase",
94
+ },
95
+ { source: () => window.trustWallet, name: "Trust Wallet" },
96
+ // Use special registry if available
97
+ {
98
+ source: () => Array.isArray(window._ethereumProviders)
99
+ ? window._ethereumProviders.find((p) => !p._isProxy)
100
+ : undefined,
101
+ name: "Registry non-proxy",
102
+ },
103
+ ];
104
+ // Try each provider source
105
+ for (const { source, name } of providerSources) {
106
+ try {
107
+ const provider = source();
108
+ if (provider && typeof provider.request === "function") {
109
+ return provider;
110
+ }
111
+ }
112
+ catch (error) {
113
+ // Continue to next provider source
114
+ console.warn(`Error checking provider ${name}:`, error);
115
+ continue;
116
+ }
117
+ }
118
+ // No provider found
119
+ console.warn("No compatible Ethereum provider found");
120
+ return undefined;
121
+ }
122
+ /**
123
+ * Initialize the BrowserProvider (async method for explicit calls)
124
+ */
125
+ async setupProvider() {
126
+ try {
127
+ if (typeof window !== "undefined") {
128
+ // Check if ethereum is available from any provider
129
+ const ethereumProvider = this.getAvailableEthereumProvider();
130
+ if (ethereumProvider) {
131
+ this.provider = new ethers_1.ethers.BrowserProvider(ethereumProvider);
132
+ }
133
+ else {
134
+ console.warn("No compatible Ethereum provider found");
135
+ }
136
+ }
137
+ else {
138
+ console.warn("Window object not available (non-browser environment)");
139
+ }
140
+ }
141
+ catch (error) {
142
+ console.error("Failed to initialize BrowserProvider", error);
143
+ }
144
+ }
145
+ /**
146
+ * Setup MetaMask event listeners using BrowserProvider
147
+ */
148
+ setupEventListeners() {
149
+ if (this.provider) {
150
+ // Listen for network changes through ethers provider
151
+ this.provider.on("network", (newNetwork, oldNetwork) => {
152
+ this.emit("chainChanged", newNetwork);
153
+ });
154
+ // Listen for account changes through the detected provider
155
+ try {
156
+ const ethereumProvider = this.getAvailableEthereumProvider();
157
+ if (ethereumProvider?.on) {
158
+ ethereumProvider.on("accountsChanged", (accounts) => {
159
+ this.emit("accountsChanged", accounts);
160
+ });
161
+ // Also listen for chainChanged events directly
162
+ ethereumProvider.on("chainChanged", (chainId) => {
163
+ this.emit("chainChanged", { chainId });
164
+ });
165
+ }
166
+ }
167
+ catch (error) {
168
+ console.warn("Failed to setup account change listeners", error);
169
+ }
170
+ }
171
+ }
172
+ /**
173
+ * Cleanup event listeners
174
+ */
175
+ cleanup() {
176
+ if (this.provider) {
177
+ this.provider.removeAllListeners();
178
+ }
179
+ this.removeAllListeners();
180
+ }
181
+ /**
182
+ * Get cached signature if valid
183
+ */
184
+ getCachedSignature(address) {
185
+ const cached = this.signatureCache.get(address);
186
+ if (!cached)
187
+ return null;
188
+ const now = Date.now();
189
+ if (now - cached.timestamp > this.config.cacheDuration) {
190
+ this.signatureCache.delete(address);
191
+ return null;
192
+ }
193
+ // Check for invalid/empty signature
194
+ if (!cached.signature ||
195
+ typeof cached.signature !== "string" ||
196
+ cached.signature.length < 16) {
197
+ console.warn(`Invalid cached signature for address ${address} (length: ${cached.signature ? cached.signature.length : 0}), deleting from cache.`);
198
+ this.signatureCache.delete(address);
199
+ return null;
200
+ }
201
+ return cached.signature;
202
+ }
203
+ /**
204
+ * Cache signature
205
+ */
206
+ cacheSignature(address, signature) {
207
+ this.signatureCache.set(address, {
208
+ signature,
209
+ timestamp: Date.now(),
210
+ address,
211
+ });
212
+ }
213
+ /**
214
+ * Validates that the address is valid
215
+ */
216
+ validateAddress(address) {
217
+ if (!address) {
218
+ throw new Error("Address not provided");
219
+ }
220
+ try {
221
+ const normalizedAddress = String(address).trim().toLowerCase();
222
+ if (!ethers_1.ethers.isAddress(normalizedAddress)) {
223
+ throw new Error("Invalid address format");
224
+ }
225
+ return ethers_1.ethers.getAddress(normalizedAddress);
226
+ }
227
+ catch (error) {
228
+ errorHandler_1.ErrorHandler.handle(errorHandler_1.ErrorType.VALIDATION, "INVALID_ADDRESS", "Invalid Ethereum address provided", error);
229
+ throw error;
230
+ }
231
+ }
232
+ /**
233
+ * Connects to MetaMask with retry logic using BrowserProvider
234
+ */
235
+ async connectMetaMask() {
236
+ try {
237
+ if (!this.provider) {
238
+ this.initProvider();
239
+ if (!this.provider) {
240
+ throw new Error("MetaMask is not available. Please install MetaMask extension.");
241
+ }
242
+ }
243
+ // First check if we can get the provider
244
+ const ethereumProvider = this.getAvailableEthereumProvider();
245
+ if (!ethereumProvider) {
246
+ throw new Error("No compatible Ethereum provider found");
247
+ }
248
+ // Richiedi esplicitamente l'accesso all'account MetaMask
249
+ let accounts = [];
250
+ // Try multiple methods of requesting accounts for compatibility
251
+ try {
252
+ // Try the provider we found first
253
+ accounts = await ethereumProvider.request({
254
+ method: "eth_requestAccounts",
255
+ });
256
+ }
257
+ catch (requestError) {
258
+ console.warn("First account request failed, trying window.ethereum:", requestError);
259
+ // Fallback to window.ethereum if available and different
260
+ if (window.ethereum && window.ethereum !== ethereumProvider) {
261
+ try {
262
+ accounts = await window.ethereum.request({
263
+ method: "eth_requestAccounts",
264
+ });
265
+ }
266
+ catch (fallbackError) {
267
+ console.error("All account request methods failed", fallbackError);
268
+ throw new Error("User denied account access");
269
+ }
270
+ }
271
+ else {
272
+ throw new Error("User denied account access");
273
+ }
274
+ }
275
+ if (!accounts || accounts.length === 0) {
276
+ }
277
+ for (let attempt = 1; attempt <= this.config.maxRetries; attempt++) {
278
+ try {
279
+ const signer = await this.provider.getSigner();
280
+ const address = await signer.getAddress();
281
+ if (!address) {
282
+ console.error("No address returned from signer");
283
+ throw new Error("No address returned from signer");
284
+ }
285
+ this.emit("connected", { address });
286
+ return {
287
+ success: true,
288
+ address,
289
+ };
290
+ }
291
+ catch (error) {
292
+ console.error(`Attempt ${attempt} failed:`, error);
293
+ if (attempt === this.config.maxRetries) {
294
+ throw error;
295
+ }
296
+ // Wait before retrying
297
+ await new Promise((resolve) => setTimeout(resolve, this.config.retryDelay));
298
+ }
299
+ }
300
+ throw new Error("Failed to get signer after all attempts");
301
+ }
302
+ catch (error) {
303
+ console.error("Failed to connect to MetaMask:", error);
304
+ errorHandler_1.ErrorHandler.handle(errorHandler_1.ErrorType.WEBAUTHN, "METAMASK_CONNECTION_ERROR", error.message ?? "Unknown error while connecting to MetaMask", error);
305
+ return { success: false, error: error.message };
306
+ }
307
+ }
308
+ /**
309
+ * Generates credentials for the given address
310
+ */
311
+ async generateCredentials(address) {
312
+ try {
313
+ const validAddress = this.validateAddress(address);
314
+ // Check if we have a cached signature
315
+ const cachedSignature = this.getCachedSignature(validAddress);
316
+ if (cachedSignature) {
317
+ return this.generateCredentialsFromSignature(validAddress, cachedSignature);
318
+ }
319
+ // Request signature with timeout
320
+ let signature;
321
+ try {
322
+ signature = await this.requestSignatureWithTimeout(validAddress, this.MESSAGE_TO_SIGN, this.config.timeout);
323
+ }
324
+ catch (signingError) {
325
+ // Gestione del fallimento di firma
326
+ console.warn(`Failed to get signature: ${signingError}. Using fallback method.`);
327
+ throw signingError;
328
+ }
329
+ // Cache the signature
330
+ this.cacheSignature(validAddress, signature);
331
+ return this.generateCredentialsFromSignature(validAddress, signature);
332
+ }
333
+ catch (error) {
334
+ errorHandler_1.ErrorHandler.handle(errorHandler_1.ErrorType.WEBAUTHN, "CREDENTIALS_GENERATION_ERROR", error.message ?? "Error generating MetaMask credentials", error);
335
+ throw error;
336
+ }
337
+ }
338
+ /**
339
+ * Generates credentials from a signature
340
+ */
341
+ async generateCredentialsFromSignature(address, signature) {
342
+ const hashedAddress = ethers_1.ethers.keccak256(ethers_1.ethers.toUtf8Bytes(address));
343
+ const salt = `${address}_${signature}`;
344
+ return await (0, derive_1.default)(hashedAddress, salt, {
345
+ includeP256: true,
346
+ });
347
+ }
348
+ /**
349
+ * Generates fallback credentials (for testing/development)
350
+ */
351
+ generateFallbackCredentials(address) {
352
+ console.warn("Using fallback credentials generation for address:", address);
353
+ // Generate a deterministic but insecure fallback
354
+ const fallbackSignature = ethers_1.ethers.keccak256(ethers_1.ethers.toUtf8Bytes(address + "fallback"));
355
+ return {
356
+ username: address.toLowerCase(),
357
+ password: fallbackSignature,
358
+ message: this.MESSAGE_TO_SIGN,
359
+ signature: fallbackSignature,
360
+ };
361
+ }
362
+ /**
363
+ * Checks if MetaMask is available
364
+ */
365
+ static isMetaMaskAvailable() {
366
+ if (typeof window === "undefined") {
367
+ return false;
368
+ }
369
+ // Check multiple possible sources
370
+ const sources = [
371
+ () => window.ethereum,
372
+ () => window.web3?.currentProvider,
373
+ () => window.metamask,
374
+ () => window._ethereumProviders?.[0],
375
+ ];
376
+ for (const source of sources) {
377
+ try {
378
+ const provider = source();
379
+ if (provider && typeof provider.request === "function") {
380
+ return true;
381
+ }
382
+ }
383
+ catch {
384
+ // Continue to next source
385
+ }
386
+ }
387
+ return false;
388
+ }
389
+ /**
390
+ * Requests signature with timeout
391
+ */
392
+ requestSignatureWithTimeout(address, message, timeout = 30000) {
393
+ return new Promise((resolve, reject) => {
394
+ const timeoutId = setTimeout(() => {
395
+ reject(new Error("Signature request timed out"));
396
+ }, timeout);
397
+ const cleanup = () => {
398
+ clearTimeout(timeoutId);
399
+ };
400
+ const errorHandler = (error) => {
401
+ cleanup();
402
+ reject(error);
403
+ };
404
+ const initializeAndSign = async () => {
405
+ try {
406
+ const signer = await this.provider.getSigner();
407
+ const signerAddress = await signer.getAddress();
408
+ // Verify the signer address matches the expected address
409
+ if (signerAddress.toLowerCase() !== address.toLowerCase()) {
410
+ throw new Error(`Signer address (${signerAddress}) does not match expected address (${address})`);
411
+ }
412
+ const signature = await signer.signMessage(message);
413
+ cleanup();
414
+ resolve(signature);
415
+ }
416
+ catch (error) {
417
+ console.error("Failed to request signature:", error);
418
+ errorHandler(error);
419
+ }
420
+ };
421
+ initializeAndSign();
422
+ });
423
+ }
424
+ /**
425
+ * Checks if the connector is available
426
+ */
427
+ isAvailable() {
428
+ return Web3Connector.isMetaMaskAvailable();
429
+ }
430
+ /**
431
+ * Sets a custom provider for testing/development
432
+ */
433
+ setCustomProvider(rpcUrl, privateKey) {
434
+ try {
435
+ this.customProvider = new ethers_1.ethers.JsonRpcProvider(rpcUrl);
436
+ this.customWallet = new ethers_1.ethers.Wallet(privateKey, this.customProvider);
437
+ }
438
+ catch (error) {
439
+ throw new Error(`Error configuring provider: ${error.message ?? "Unknown error"}`);
440
+ }
441
+ }
442
+ /**
443
+ * Get active signer instance using BrowserProvider
444
+ */
445
+ async getSigner() {
446
+ try {
447
+ if (this.customWallet) {
448
+ return this.customWallet;
449
+ }
450
+ if (!this.provider) {
451
+ this.initProvider();
452
+ }
453
+ if (!this.provider) {
454
+ throw new Error("Provider not initialized");
455
+ }
456
+ return await this.provider.getSigner();
457
+ }
458
+ catch (error) {
459
+ throw new Error(`Unable to get Ethereum signer: ${error.message || "Unknown error"}`);
460
+ }
461
+ }
462
+ /**
463
+ * Get active provider instance using BrowserProvider
464
+ */
465
+ async getProvider() {
466
+ if (this.customProvider) {
467
+ return this.customProvider;
468
+ }
469
+ if (!this.provider) {
470
+ this.initProvider();
471
+ }
472
+ return this.provider;
473
+ }
474
+ /**
475
+ * Generate deterministic password from signature
476
+ * @param signature - Cryptographic signature
477
+ * @returns 64-character hex string
478
+ * @throws {Error} For invalid signature
479
+ */
480
+ async generatePassword(signature) {
481
+ if (!signature) {
482
+ throw new Error("Invalid signature");
483
+ }
484
+ const hash = ethers_1.ethers.keccak256(ethers_1.ethers.toUtf8Bytes(signature));
485
+ return hash.slice(2, 66); // Remove 0x and use first 32 bytes
486
+ }
487
+ /**
488
+ * Verify message signature
489
+ * @param message - Original signed message
490
+ * @param signature - Cryptographic signature
491
+ * @returns Recovered Ethereum address
492
+ * @throws {Error} For invalid inputs
493
+ */
494
+ async verifySignature(message, signature) {
495
+ if (!message || !signature) {
496
+ throw new Error("Invalid message or signature");
497
+ }
498
+ try {
499
+ return ethers_1.ethers.verifyMessage(message, signature);
500
+ }
501
+ catch (error) {
502
+ throw new Error("Invalid message or signature");
503
+ }
504
+ }
505
+ /**
506
+ * Get browser-based Ethereum signer
507
+ * @returns Browser provider signer
508
+ * @throws {Error} If MetaMask not detected
509
+ */
510
+ async getEthereumSigner() {
511
+ if (!Web3Connector.isMetaMaskAvailable()) {
512
+ throw new Error("MetaMask not found. Please install MetaMask to continue.");
513
+ }
514
+ try {
515
+ const ethereum = window.ethereum;
516
+ await ethereum.request({
517
+ method: "eth_requestAccounts",
518
+ });
519
+ const provider = new ethers_1.ethers.BrowserProvider(ethereum);
520
+ return provider.getSigner();
521
+ }
522
+ catch (error) {
523
+ throw new Error(`Error accessing MetaMask: ${error.message ?? "Unknown error"}`);
524
+ }
525
+ }
526
+ }
527
+ exports.Web3Connector = Web3Connector;
528
+ if (typeof window !== "undefined") {
529
+ window.Web3Connector = Web3Connector;
530
+ }
531
+ else if (typeof global !== "undefined") {
532
+ global.Web3Connector = Web3Connector;
533
+ }