shogun-core 3.0.3 → 3.0.4

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 (95) hide show
  1. package/package.json +1 -1
  2. package/dist/browser/shogun-core.js +0 -92128
  3. package/dist/browser/shogun-core.js.map +0 -1
  4. package/dist/config/simplified-config.js +0 -230
  5. package/dist/core.js +0 -338
  6. package/dist/gundb/crypto.js +0 -268
  7. package/dist/gundb/db.js +0 -1833
  8. package/dist/gundb/derive.js +0 -229
  9. package/dist/gundb/errors.js +0 -66
  10. package/dist/gundb/index.js +0 -6
  11. package/dist/gundb/restricted-put.js +0 -81
  12. package/dist/gundb/rxjs.js +0 -445
  13. package/dist/gundb/simple-api.js +0 -438
  14. package/dist/gundb/types.js +0 -4
  15. package/dist/index.js +0 -16
  16. package/dist/interfaces/common.js +0 -1
  17. package/dist/interfaces/events.js +0 -36
  18. package/dist/interfaces/plugin.js +0 -1
  19. package/dist/interfaces/shogun.js +0 -34
  20. package/dist/managers/AuthManager.js +0 -225
  21. package/dist/managers/CoreInitializer.js +0 -234
  22. package/dist/managers/EventManager.js +0 -67
  23. package/dist/managers/PluginManager.js +0 -296
  24. package/dist/migration-test.js +0 -91
  25. package/dist/plugins/base.js +0 -47
  26. package/dist/plugins/index.js +0 -15
  27. package/dist/plugins/nostr/index.js +0 -4
  28. package/dist/plugins/nostr/nostrConnector.js +0 -413
  29. package/dist/plugins/nostr/nostrConnectorPlugin.js +0 -446
  30. package/dist/plugins/nostr/nostrSigner.js +0 -313
  31. package/dist/plugins/nostr/types.js +0 -1
  32. package/dist/plugins/oauth/index.js +0 -3
  33. package/dist/plugins/oauth/oauthConnector.js +0 -753
  34. package/dist/plugins/oauth/oauthPlugin.js +0 -396
  35. package/dist/plugins/oauth/types.js +0 -1
  36. package/dist/plugins/web3/index.js +0 -4
  37. package/dist/plugins/web3/types.js +0 -1
  38. package/dist/plugins/web3/web3Connector.js +0 -528
  39. package/dist/plugins/web3/web3ConnectorPlugin.js +0 -448
  40. package/dist/plugins/web3/web3Signer.js +0 -308
  41. package/dist/plugins/webauthn/index.js +0 -3
  42. package/dist/plugins/webauthn/types.js +0 -11
  43. package/dist/plugins/webauthn/webauthn.js +0 -478
  44. package/dist/plugins/webauthn/webauthnPlugin.js +0 -398
  45. package/dist/plugins/webauthn/webauthnSigner.js +0 -304
  46. package/dist/storage/storage.js +0 -147
  47. package/dist/types/config/simplified-config.d.ts +0 -114
  48. package/dist/types/core.d.ts +0 -305
  49. package/dist/types/gundb/crypto.d.ts +0 -95
  50. package/dist/types/gundb/db.d.ts +0 -404
  51. package/dist/types/gundb/derive.d.ts +0 -21
  52. package/dist/types/gundb/errors.d.ts +0 -42
  53. package/dist/types/gundb/index.d.ts +0 -3
  54. package/dist/types/gundb/restricted-put.d.ts +0 -15
  55. package/dist/types/gundb/rxjs.d.ts +0 -110
  56. package/dist/types/gundb/simple-api.d.ts +0 -90
  57. package/dist/types/gundb/types.d.ts +0 -264
  58. package/dist/types/index.d.ts +0 -14
  59. package/dist/types/interfaces/common.d.ts +0 -85
  60. package/dist/types/interfaces/events.d.ts +0 -131
  61. package/dist/types/interfaces/plugin.d.ts +0 -162
  62. package/dist/types/interfaces/shogun.d.ts +0 -215
  63. package/dist/types/managers/AuthManager.d.ts +0 -72
  64. package/dist/types/managers/CoreInitializer.d.ts +0 -40
  65. package/dist/types/managers/EventManager.d.ts +0 -49
  66. package/dist/types/managers/PluginManager.d.ts +0 -145
  67. package/dist/types/migration-test.d.ts +0 -16
  68. package/dist/types/plugins/base.d.ts +0 -35
  69. package/dist/types/plugins/index.d.ts +0 -14
  70. package/dist/types/plugins/nostr/index.d.ts +0 -4
  71. package/dist/types/plugins/nostr/nostrConnector.d.ts +0 -119
  72. package/dist/types/plugins/nostr/nostrConnectorPlugin.d.ts +0 -163
  73. package/dist/types/plugins/nostr/nostrSigner.d.ts +0 -105
  74. package/dist/types/plugins/nostr/types.d.ts +0 -122
  75. package/dist/types/plugins/oauth/index.d.ts +0 -3
  76. package/dist/types/plugins/oauth/oauthConnector.d.ts +0 -110
  77. package/dist/types/plugins/oauth/oauthPlugin.d.ts +0 -91
  78. package/dist/types/plugins/oauth/types.d.ts +0 -114
  79. package/dist/types/plugins/web3/index.d.ts +0 -4
  80. package/dist/types/plugins/web3/types.d.ts +0 -107
  81. package/dist/types/plugins/web3/web3Connector.d.ts +0 -129
  82. package/dist/types/plugins/web3/web3ConnectorPlugin.d.ts +0 -160
  83. package/dist/types/plugins/web3/web3Signer.d.ts +0 -114
  84. package/dist/types/plugins/webauthn/index.d.ts +0 -3
  85. package/dist/types/plugins/webauthn/types.d.ts +0 -162
  86. package/dist/types/plugins/webauthn/webauthn.d.ts +0 -129
  87. package/dist/types/plugins/webauthn/webauthnPlugin.d.ts +0 -158
  88. package/dist/types/plugins/webauthn/webauthnSigner.d.ts +0 -91
  89. package/dist/types/storage/storage.d.ts +0 -50
  90. package/dist/types/utils/errorHandler.d.ts +0 -119
  91. package/dist/types/utils/eventEmitter.d.ts +0 -39
  92. package/dist/types/utils/validation.d.ts +0 -27
  93. package/dist/utils/errorHandler.js +0 -241
  94. package/dist/utils/eventEmitter.js +0 -76
  95. package/dist/utils/validation.js +0 -72
@@ -1,413 +0,0 @@
1
- /**
2
- * The BitcoinWallet class provides functionality for connecting, signing up, and logging in using Bitcoin wallets.
3
- * Supports Alby and Nostr extensions, as well as manual key management.
4
- */
5
- import { ethers } from "ethers";
6
- import { verifyEvent, finalizeEvent, utils as nostrUtils, getEventHash, } from "nostr-tools";
7
- import { EventEmitter } from "../../utils/eventEmitter";
8
- import derive from "../../gundb/derive";
9
- import { generateUsernameFromIdentity } from "../../utils/validation";
10
- export const MESSAGE_TO_SIGN = "I Love Shogun!";
11
- /**
12
- * Class for Bitcoin wallet connections and operations
13
- */
14
- class NostrConnector extends EventEmitter {
15
- DEFAULT_CONFIG = {
16
- cacheDuration: 24 * 60 * 60 * 1000, // 24 hours instead of 30 minutes for better UX
17
- maxRetries: 3,
18
- retryDelay: 1000,
19
- timeout: 60000,
20
- network: "mainnet",
21
- useApi: false,
22
- };
23
- config;
24
- signatureCache = new Map();
25
- // Connection state
26
- connectedAddress = null;
27
- connectedType = null;
28
- manualKeyPair = null;
29
- constructor(config = {}) {
30
- super();
31
- this.config = { ...this.DEFAULT_CONFIG, ...config };
32
- this.setupEventListeners();
33
- }
34
- /**
35
- * Setup event listeners
36
- */
37
- setupEventListeners() {
38
- // Currently no global events to listen to
39
- // This would be the place to add listeners for wallet connections/disconnections
40
- }
41
- /**
42
- * Clear signature cache for a specific address or all addresses
43
- */
44
- clearSignatureCache(address) {
45
- if (address) {
46
- // Clear cache for specific address
47
- this.signatureCache.delete(address);
48
- try {
49
- const localStorageKey = `shogun_bitcoin_sig_${address}`;
50
- localStorage.removeItem(localStorageKey);
51
- console.log(`Cleared signature cache for address: ${address.substring(0, 10)}...`);
52
- }
53
- catch (error) {
54
- console.error("Error clearing signature cache from localStorage:", error);
55
- }
56
- }
57
- else {
58
- // Clear all signature caches
59
- this.signatureCache.clear();
60
- try {
61
- // Find and remove all shogun_bitcoin_sig_ keys
62
- const keysToRemove = [];
63
- for (let i = 0; i < localStorage.length; i++) {
64
- const key = localStorage.key(i);
65
- if (key && key.startsWith("shogun_bitcoin_sig_")) {
66
- keysToRemove.push(key);
67
- }
68
- }
69
- keysToRemove.forEach((key) => localStorage.removeItem(key));
70
- console.log(`Cleared all signature caches (${keysToRemove.length} entries)`);
71
- }
72
- catch (error) {
73
- console.error("Error clearing all signature caches from localStorage:", error);
74
- }
75
- }
76
- }
77
- /**
78
- * Check if Nostr extension is available
79
- */
80
- isNostrExtensionAvailable() {
81
- return typeof window !== "undefined" && !!window.nostr;
82
- }
83
- /**
84
- * Check if any Bitcoin wallet is available
85
- */
86
- isAvailable() {
87
- return this.isNostrExtensionAvailable() || this.manualKeyPair !== null;
88
- }
89
- /**
90
- * Connect to a wallet type
91
- */
92
- async connectWallet(type = "nostr") {
93
- console.log(`Connecting to Bitcoin wallet via ${type}...`);
94
- try {
95
- let result;
96
- // Attempt to connect to the specified wallet type
97
- switch (type) {
98
- case "alby":
99
- console.log("[nostrConnector] Alby is deprecated, redirecting to Nostr");
100
- result = await this.connectNostr();
101
- break;
102
- case "nostr":
103
- result = await this.connectNostr();
104
- break;
105
- case "manual":
106
- result = await this.connectManual();
107
- break;
108
- default:
109
- throw new Error(`Unsupported wallet type: ${type}`);
110
- }
111
- if (result.success && result.address) {
112
- this.connectedAddress = result.address;
113
- this.connectedType = type;
114
- console.log(`Successfully connected to ${type} wallet: ${result.address}`);
115
- this.emit("wallet_connected", {
116
- address: result.address,
117
- type: this.connectedType,
118
- });
119
- }
120
- return result;
121
- }
122
- catch (error) {
123
- console.error(`Error connecting to ${type} wallet:`, error);
124
- return {
125
- success: false,
126
- error: error.message || "Failed to connect to wallet",
127
- };
128
- }
129
- }
130
- /**
131
- * Connect to Nostr extension
132
- */
133
- async connectNostr() {
134
- if (!this.isNostrExtensionAvailable()) {
135
- return {
136
- success: false,
137
- error: "Nostr extension is not available. Please install a Nostr compatible extension like nos2x, Alby, or Coracle.",
138
- };
139
- }
140
- try {
141
- console.log("[nostrConnector] Attempting to connect to Nostr extension...");
142
- // Get public key from Nostr extension
143
- const pubKey = await window.nostr.getPublicKey();
144
- if (!pubKey) {
145
- throw new Error("Could not get public key from Nostr extension");
146
- }
147
- console.log(`[nostrConnector] Successfully connected to Nostr extension: ${pubKey.substring(0, 10)}...`);
148
- this.connectedAddress = pubKey;
149
- this.connectedType = "nostr";
150
- // Emit connected event
151
- this.emit("connected", { address: pubKey, type: "nostr" });
152
- const username = `nostr_${pubKey.substring(0, 10)}`;
153
- return {
154
- success: true,
155
- address: pubKey,
156
- username,
157
- extensionType: "nostr",
158
- };
159
- }
160
- catch (error) {
161
- console.error("[nostrConnector] Nostr connection error:", error);
162
- // Provide more specific error messages
163
- if (error.message && error.message.includes("User rejected")) {
164
- throw new Error("Nostr connection was rejected by the user");
165
- }
166
- else if (error.message && error.message.includes("not available")) {
167
- throw new Error("Nostr extension is not available or not properly installed");
168
- }
169
- else {
170
- throw new Error(`Nostr connection error: ${error.message}`);
171
- }
172
- }
173
- }
174
- /**
175
- * Set up manual key pair for connection
176
- */
177
- async connectManual() {
178
- // For manual connection, we'd need to have a keypair set
179
- if (!this.manualKeyPair) {
180
- return {
181
- success: false,
182
- error: "No manual key pair configured. Use setKeyPair() first.",
183
- };
184
- }
185
- this.connectedAddress = this.manualKeyPair.address;
186
- this.connectedType = "manual";
187
- // Emit connected event
188
- this.emit("connected", {
189
- address: this.manualKeyPair.address,
190
- type: "manual",
191
- });
192
- const username = `btc_${this.manualKeyPair.address.substring(0, 10)}`;
193
- return {
194
- success: true,
195
- address: this.manualKeyPair.address,
196
- username,
197
- extensionType: "manual",
198
- };
199
- }
200
- /**
201
- * Set a manual key pair for use
202
- */
203
- setKeyPair(keyPair) {
204
- this.manualKeyPair = keyPair;
205
- if (keyPair.address) {
206
- this.connectedAddress = keyPair.address;
207
- this.connectedType = "manual";
208
- }
209
- }
210
- /**
211
- * Generate credentials using Nostr: username deterministico e chiave GunDB derivata dall'address
212
- */
213
- async generateCredentials(address, signature, message) {
214
- const username = generateUsernameFromIdentity("nostr", { id: address });
215
- // Usa un hashing robusto di address con keccak256
216
- const hashedAddress = ethers.keccak256(ethers.toUtf8Bytes(address));
217
- // Include la signature nel salt per aggiungere un ulteriore livello di sicurezza
218
- const salt = `${username}_${address}_${message}_${signature}`;
219
- const key = await derive(hashedAddress, salt, { includeP256: true });
220
- return { username, key, message, signature };
221
- }
222
- /**
223
- * Generate a password from a signature
224
- */
225
- async generatePassword(signature) {
226
- if (!signature) {
227
- throw new Error("Invalid signature");
228
- }
229
- try {
230
- // Create a deterministic hash from the signature using a secure algorithm
231
- const normalizedSig = signature.toLowerCase().replace(/[^a-f0-9]/g, "");
232
- const passwordHash = ethers.sha256(ethers.toUtf8Bytes(normalizedSig));
233
- return passwordHash;
234
- }
235
- catch (error) {
236
- console.error("Error generating password:", error);
237
- throw new Error("Failed to generate password from signature");
238
- }
239
- }
240
- /**
241
- * Verify a signature
242
- */
243
- async verifySignature(message, signature, address) {
244
- try {
245
- // Ensure address is a string
246
- const addressStr = typeof address === "object"
247
- ? address.address || JSON.stringify(address)
248
- : String(address);
249
- console.log(`Verifying signature for address: ${addressStr}`);
250
- if (!signature || !message || !addressStr) {
251
- console.error("Invalid message, signature, or address for verification");
252
- return false;
253
- }
254
- // For Nostr wallet type, use nostr-tools for verification
255
- if (this.connectedType === "nostr" || this.connectedType === "alby") {
256
- try {
257
- // Reconstruct the exact event that was signed
258
- const eventData = {
259
- kind: 1,
260
- created_at: 0, // IMPORTANT: Use the same fixed timestamp used for signing
261
- tags: [],
262
- content: message,
263
- pubkey: addressStr,
264
- };
265
- const event = {
266
- ...eventData,
267
- id: getEventHash(eventData),
268
- sig: signature,
269
- };
270
- return verifyEvent(event);
271
- }
272
- catch (verifyError) {
273
- console.error("Error in Nostr signature verification:", verifyError);
274
- return false;
275
- }
276
- }
277
- else if (this.connectedType === "manual" && this.manualKeyPair) {
278
- console.log("[nostrConnector] Manual verification for keypair");
279
- // For manual keypairs, we MUST use a secure verification method.
280
- if (!this.manualKeyPair.privateKey) {
281
- console.error("Manual verification failed: private key is missing.");
282
- return false;
283
- }
284
- try {
285
- const eventData = {
286
- kind: 1,
287
- created_at: 0, // IMPORTANT: Use the same fixed timestamp used for signing
288
- tags: [],
289
- content: message,
290
- pubkey: addressStr,
291
- };
292
- const event = {
293
- ...eventData,
294
- id: getEventHash(eventData),
295
- sig: signature,
296
- };
297
- return verifyEvent(event);
298
- }
299
- catch (manualVerifyError) {
300
- console.error("Error in manual signature verification:", manualVerifyError);
301
- return false;
302
- }
303
- }
304
- console.warn("No specific verification method available, signature cannot be fully verified");
305
- return false;
306
- }
307
- catch (error) {
308
- console.error("Error verifying signature:", error);
309
- return false;
310
- }
311
- }
312
- /**
313
- * Get the currently connected address
314
- */
315
- getConnectedAddress() {
316
- return this.connectedAddress;
317
- }
318
- /**
319
- * Get the currently connected wallet type
320
- */
321
- getConnectedType() {
322
- return this.connectedType;
323
- }
324
- /**
325
- * Request a signature from the connected wallet
326
- */
327
- async requestSignature(address, message) {
328
- if (!this.connectedType) {
329
- throw new Error("No wallet connected");
330
- }
331
- try {
332
- switch (this.connectedType) {
333
- case "alby":
334
- case "nostr":
335
- if (this.connectedType === "alby") {
336
- console.warn("Alby is deprecated, using Nostr functionality for signature request");
337
- }
338
- console.log("[nostrConnector] Requesting Nostr signature for message:", message);
339
- if (!window.nostr) {
340
- throw new Error("Nostr extension not available");
341
- }
342
- // For Nostr, we need to create an event to sign with a fixed timestamp
343
- const eventData = {
344
- kind: 1,
345
- created_at: 0, // IMPORTANT: Use a fixed timestamp to make signatures verifiable
346
- tags: [],
347
- content: message,
348
- pubkey: address,
349
- };
350
- const nostrEvent = {
351
- ...eventData,
352
- id: getEventHash(eventData),
353
- sig: "", // This will be filled by window.nostr.signEvent
354
- };
355
- const signedEvent = await window.nostr.signEvent(nostrEvent);
356
- console.log("Received Nostr signature:", signedEvent.sig.substring(0, 20) + "...");
357
- return signedEvent.sig;
358
- case "manual":
359
- console.log("[nostrConnector] Using manual key pair for signature");
360
- if (!this.manualKeyPair || !this.manualKeyPair.privateKey) {
361
- throw new Error("No manual key pair available or private key missing");
362
- }
363
- // Use nostr-tools to sign securely
364
- const manualEventData = {
365
- kind: 1,
366
- created_at: 0, // IMPORTANT: Use a fixed timestamp
367
- tags: [],
368
- content: message,
369
- pubkey: this.manualKeyPair.address,
370
- };
371
- const eventTemplate = {
372
- ...manualEventData,
373
- id: getEventHash(manualEventData),
374
- sig: "", // This will be filled by finalizeEvent
375
- };
376
- const privateKeyBytes = nostrUtils.hexToBytes(this.manualKeyPair.privateKey);
377
- const signedEventManual = await finalizeEvent(eventTemplate, privateKeyBytes);
378
- console.log("Generated manual signature:", signedEventManual.sig.substring(0, 20) + "...");
379
- return signedEventManual.sig;
380
- default:
381
- throw new Error(`Unsupported wallet type: ${this.connectedType}`);
382
- }
383
- }
384
- catch (error) {
385
- console.error("Error requesting signature:", error);
386
- throw new Error(`Failed to get signature: ${error.message}`);
387
- }
388
- }
389
- /**
390
- * Cleanup event listeners
391
- */
392
- cleanup() {
393
- this.removeAllListeners();
394
- this.connectedAddress = null;
395
- this.connectedType = null;
396
- this.manualKeyPair = null;
397
- }
398
- }
399
- // Funzione helper per derivare chiavi Nostr/Bitcoin (come per Web3/WebAuthn)
400
- export async function deriveNostrKeys(address, signature, message) {
401
- // Usa solo l'address per rendere le credenziali deterministiche
402
- const salt = `${address}_${message}`;
403
- return await derive(address, salt, {
404
- includeP256: true,
405
- });
406
- }
407
- if (typeof window !== "undefined") {
408
- window.NostrConnector = NostrConnector;
409
- }
410
- else if (typeof global !== "undefined") {
411
- global.NostrConnector = NostrConnector;
412
- }
413
- export { NostrConnector };