shogun-core 3.3.7 β†’ 4.0.0

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 (55) hide show
  1. package/README.md +1378 -1221
  2. package/dist/browser/shogun-core.js +78074 -45286
  3. package/dist/browser/shogun-core.js.map +1 -1
  4. package/dist/core.js +2 -3
  5. package/dist/examples/simple-api-test.js +90 -65
  6. package/dist/examples/zkproof-credentials-example.js +218 -0
  7. package/dist/examples/zkproof-example.js +206 -0
  8. package/dist/gundb/api.js +111 -467
  9. package/dist/index.js +10 -1
  10. package/dist/interfaces/shogun.js +2 -2
  11. package/dist/managers/AuthManager.js +0 -2
  12. package/dist/managers/CoreInitializer.js +9 -12
  13. package/dist/plugins/index.js +9 -21
  14. package/dist/plugins/nostr/nostrConnectorPlugin.js +2 -2
  15. package/dist/plugins/webauthn/webauthn.js +20 -7
  16. package/dist/plugins/webauthn/webauthnPlugin.js +101 -17
  17. package/dist/plugins/zkproof/index.js +53 -0
  18. package/dist/plugins/zkproof/zkCredentials.js +213 -0
  19. package/dist/plugins/zkproof/zkProofConnector.js +198 -0
  20. package/dist/plugins/zkproof/zkProofPlugin.js +272 -0
  21. package/dist/types/core.d.ts +1 -1
  22. package/dist/types/examples/simple-api-test.d.ts +6 -1
  23. package/dist/types/examples/zkproof-credentials-example.d.ts +12 -0
  24. package/dist/types/examples/zkproof-example.d.ts +11 -0
  25. package/dist/types/gundb/api.d.ts +77 -165
  26. package/dist/types/gundb/types.d.ts +1 -1
  27. package/dist/types/index.d.ts +1 -0
  28. package/dist/types/interfaces/events.d.ts +3 -3
  29. package/dist/types/interfaces/shogun.d.ts +9 -24
  30. package/dist/types/plugins/index.d.ts +5 -3
  31. package/dist/types/plugins/webauthn/types.d.ts +22 -1
  32. package/dist/types/plugins/webauthn/webauthn.d.ts +1 -1
  33. package/dist/types/plugins/webauthn/webauthnPlugin.d.ts +23 -2
  34. package/dist/types/plugins/zkproof/index.d.ts +48 -0
  35. package/dist/types/plugins/zkproof/types.d.ts +123 -0
  36. package/dist/types/plugins/zkproof/zkCredentials.d.ts +112 -0
  37. package/dist/types/plugins/zkproof/zkProofConnector.d.ts +46 -0
  38. package/dist/types/plugins/zkproof/zkProofPlugin.d.ts +76 -0
  39. package/dist/types/utils/seedPhrase.d.ts +50 -0
  40. package/dist/types/utils/validation.d.ts +2 -2
  41. package/dist/utils/seedPhrase.js +97 -0
  42. package/dist/utils/validation.js +3 -1
  43. package/package.json +14 -8
  44. package/dist/examples/api-test.js +0 -273
  45. package/dist/migration-test.js +0 -96
  46. package/dist/plugins/oauth/index.js +0 -8
  47. package/dist/plugins/oauth/oauthConnector.js +0 -759
  48. package/dist/plugins/oauth/oauthPlugin.js +0 -400
  49. package/dist/types/examples/api-test.d.ts +0 -12
  50. package/dist/types/migration-test.d.ts +0 -16
  51. package/dist/types/plugins/oauth/index.d.ts +0 -3
  52. package/dist/types/plugins/oauth/oauthConnector.d.ts +0 -110
  53. package/dist/types/plugins/oauth/oauthPlugin.d.ts +0 -91
  54. package/dist/types/plugins/oauth/types.d.ts +0 -114
  55. /package/dist/plugins/{oauth β†’ zkproof}/types.js +0 -0
package/README.md CHANGED
@@ -1,1221 +1,1378 @@
1
- # Shogun Core πŸ“¦
2
-
3
- [![npm](https://img.shields.io/badge/npm-v2.0.0-blue)](https://www.npmjs.com/package/shogun-core)
4
- [![License](https://img.shields.io/badge/license-MIT-yellow)](https://opensource.org/licenses/MIT)
5
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.3.3-blue)](https://www.typescriptlang.org/)
6
- [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/scobru/shogun-core)
7
-
8
- ## Overview
9
-
10
- Shogun Core is a comprehensive SDK for building decentralized applications (dApps) that simplifies authentication, wallet management, and decentralized data storage. It combines GunDB's peer-to-peer networking with modern authentication standards and blockchain integration to provide a secure, user-friendly foundation for Web3 applications.
11
-
12
- ## Features
13
-
14
- - πŸ” **Multiple Authentication Methods**: Traditional username/password, WebAuthn (biometrics), Web3 (MetaMask), Nostr, and OAuth
15
- - 🌐 **Decentralized Storage**: Built on GunDB for peer-to-peer data synchronization
16
- - πŸ”Œ **Plugin System**: Extensible architecture with built-in plugins for various authentication methods
17
- - πŸ“± **Reactive Programming**: RxJS integration for real-time data streams
18
- - πŸ›‘οΈ **Security**: End-to-end encryption and secure key management
19
- - 🎯 **TypeScript**: Full TypeScript support with comprehensive type definitions
20
- - πŸ“‘ **Event System**: Typed event system for monitoring authentication and data changes
21
- - πŸ”‘ **Password Recovery**: Secure password hint system with security questions
22
- - βœ… **Type Consistency**: Unified return types across all authentication methods
23
- - πŸš€ **Simplified Architecture**: Focused on core functionality with reduced complexity
24
- - ⭐ **Simple API**: Easy-to-use wrapper for common operations with minimal complexity
25
- - πŸ”— **Advanced Chaining**: Powerful chaining operations for complex nested data structures
26
- - πŸ‘€ **User Space Management**: Complete CRUD operations for user-specific data storage
27
- - ⚑ **Quick Start**: Rapid initialization with pre-configured setups
28
- - πŸŽ›οΈ **Configuration Presets**: Pre-built configurations for common use cases
29
-
30
- ## Recent Updates (v2.0.1)
31
-
32
- ### πŸ”§ **Critical Bug Fixes**
33
-
34
- - **πŸ”§ FIXED: Remove Operations**: Fixed critical bug in `remove()` and `removeUserData()` methods that was causing `TypeError: Cannot read properties of null (reading 'err')`
35
- - **πŸ”§ IMPROVED: User Data Operations**: Rewrote all user data methods to use direct Gun user node for better reliability and error handling
36
- - **πŸ”§ ENHANCED: Error Handling**: Added proper null checking and improved error logging throughout the user data operations
37
-
38
- ### βœ… **Major API Improvements & Simplification (v2.0.0)**
39
-
40
- - **⭐ NEW: Simple API Layer**: Added `SimpleGunAPI` with simplified methods for common operations
41
- - **⭐ NEW: Advanced Chaining**: Added `node()`, `chain()`, and `getNode()` methods for powerful data chaining
42
- - **⭐ NEW: User Space Management**: Complete CRUD operations for user-specific data storage
43
- - **⭐ NEW: Quick Start Functions**: `quickStart()` and `QuickStart` class for rapid initialization
44
- - **⭐ NEW: Improved Type System**: Reduced `any` usage with better TypeScript types
45
- - **⭐ NEW: Configuration Presets**: Pre-built configurations for common use cases
46
- - **⭐ NEW: Advanced API Features**: Comprehensive plugin management, peer network control, advanced user management, and security systems
47
- - **Removed Non-Essential Functions**: Eliminated debug/testing functions, rate limiting system, frozen space system, and complex username management
48
- - **Enhanced Advanced Features**: Maintained and improved advanced plugin management, peer network management, and user tracking systems
49
- - **Streamlined Event System**: Enhanced event system with better type safety and comprehensive event handling
50
- - **Enhanced Core Focus**: Maintained password hint system with security questions and comprehensive user management
51
- - **Improved Maintainability**: Better organized codebase with clear separation between simple and advanced APIs
52
- - **Better Performance**: Optimized operations with advanced peer management and user tracking
53
-
54
- ### πŸ”§ **Bug Fixes & Improvements**
55
-
56
- **Fixed Critical Remove Operations Bug**:
57
- - Fixed `TypeError: Cannot read properties of null (reading 'err')` in `remove()` and `removeUserData()` methods
58
- - Added proper null checking: `ack && ack.err` instead of just `ack.err`
59
- - All user data operations now use direct Gun user node for better reliability
60
- - Improved error handling and logging throughout user data operations
61
-
62
- ### ⚠️ **BREAKING CHANGES**
63
-
64
- - **🚨 REMOVED: Array Functions**: `putUserArray()`, `getUserArray()`, `addToUserArray()`, `removeFromUserArray()`, `updateInUserArray()` have been **REMOVED** due to GunDB compatibility issues
65
- - **⚠️ DEPRECATED: Global Array Functions**: `putArray()`, `getArray()`, `addToArray()`, `removeFromArray()`, `updateInArray()` are deprecated and show warnings
66
- - **βœ… MIGRATION**: Use **Collections** or **Direct GunDB Operations** instead (see examples below)
67
-
68
- ## Recent Updates (v1.7.0)
69
-
70
- ### βœ… **Type System Fixes**
71
-
72
- - **Unified Return Types**: All authentication methods now use consistent `AuthResult` and `SignUpResult` types
73
- - **Enhanced SignUpResult**: Extended to support OAuth redirects and provider-specific data
74
- - **Type Safety**: Fixed TypeScript inconsistencies across all plugins
75
- - **API Standardization**: All plugins implement unified `login()` and `signUp()` interfaces
76
-
77
- ## Installation
78
-
79
- ```bash
80
- npm install shogun-core
81
- # or
82
- yarn add shogun-core
83
- ```
84
-
85
- ## Quick Start
86
-
87
- ### ⭐ **NEW: Simple API Setup (Recommended)**
88
-
89
- ```typescript
90
- import { quickStart, Gun } from "shogun-core";
91
-
92
- // Create Gun instance
93
- const gun = Gun({
94
- peers: ['https://gun-manhattan.herokuapp.com/gun']
95
- });
96
-
97
- // Quick start with simple API
98
- const shogun = quickStart(gun, 'my-app');
99
- await shogun.init();
100
-
101
- // Use simplified API
102
- const user = await shogun.api.signup('alice', 'password123');
103
- if (user) {
104
- console.log('User created:', user.username);
105
-
106
- // User space operations
107
- await shogun.api.updateProfile({
108
- name: 'Alice',
109
- email: 'alice@example.com'
110
- });
111
-
112
- await shogun.api.saveSettings({
113
- theme: 'dark',
114
- language: 'en'
115
- });
116
-
117
- // Create collections
118
- await shogun.api.createCollection('todos', {
119
- '1': { text: 'Learn Shogun Core', done: false },
120
- '2': { text: 'Build dApp', done: false }
121
- });
122
- }
123
- ```
124
-
125
- ### Advanced Setup (Full Features)
126
-
127
- ```typescript
128
- import { ShogunCore } from "shogun-core";
129
-
130
- // Define your list of Gun peers
131
- const relays = [
132
- "wss://ruling-mastodon-improved.ngrok-free.app/gun",
133
- "https://gun-manhattan.herokuapp.com/gun",
134
- "https://peer.wallie.io/gun",
135
- ];
136
-
137
- // Initialize Shogun Core with plugins
138
- const shogun = new ShogunCore({
139
- peers: relays,
140
- scope: "my-awesome-app",
141
- authToken: "YOUR_GUN_SUPER_PEER_SECRET", // Optional, for private peers
142
-
143
- // Enable and configure Web3 (e.g., MetaMask) authentication
144
- web3: {
145
- enabled: true,
146
- },
147
-
148
- // Enable and configure WebAuthn (biometrics, security keys)
149
- webauthn: {
150
- enabled: true,
151
- rpName: "My Awesome App", // Name of your application
152
- rpId: window.location.hostname, // Relying party ID
153
- },
154
-
155
- // Enable and configure Nostr
156
- nostr: {
157
- enabled: true,
158
- },
159
-
160
- // Enable and configure OAuth providers
161
- oauth: {
162
- enabled: true,
163
- usePKCE: true, // Recommended for SPAs
164
- allowUnsafeClientSecret: true, // Required for Google OAuth
165
- providers: {
166
- google: {
167
- clientId: "YOUR_GOOGLE_CLIENT_ID",
168
- clientSecret: "YOUR_GOOGLE_CLIENT_SECRET", // Required for Google even with PKCE
169
- redirectUri: "http://localhost:3000/auth/callback",
170
- scope: ["openid", "email", "profile"],
171
- },
172
- },
173
- },
174
- });
175
-
176
- // Initialize the SDK
177
- await shogun.initialize();
178
-
179
- console.log("Shogun Core initialized!");
180
- ```
181
-
182
- ## ⭐ **NEW: Simple API**
183
-
184
- The Simple API provides an easy-to-use interface for common operations with minimal complexity. Perfect for beginners or when you need quick setup.
185
-
186
- ### Simple API Methods
187
-
188
- ```typescript
189
- import { quickStart, Gun } from "shogun-core";
190
-
191
- const gun = Gun({ peers: ['https://gun-manhattan.herokuapp.com/gun'] });
192
- const shogun = quickStart(gun, 'my-app');
193
- await shogun.init();
194
-
195
- // Authentication
196
- const user = await shogun.api.signup('username', 'password');
197
- const loginResult = await shogun.api.login('username', 'password');
198
- shogun.api.logout();
199
- const isLoggedIn = shogun.api.isLoggedIn();
200
-
201
- // Basic data operations
202
- await shogun.api.put('path/to/data', { value: 'hello' });
203
- const data = await shogun.api.get('path/to/data');
204
- await shogun.api.set('path/to/data', { value: 'updated' });
205
- await shogun.api.remove('path/to/data');
206
-
207
- // Advanced chaining operations (NEW!)
208
- // Direct Gun node chaining - recommended for complex operations
209
- await shogun.api.node('users').get('alice').get('profile').put({ name: 'Alice' });
210
- const profile = await shogun.api.node('users').get('alice').get('profile').once();
211
-
212
- // Simplified chaining wrapper
213
- await shogun.api.chain('users').get('alice').get('settings').put({ theme: 'dark' });
214
- const settings = await shogun.api.chain('users').get('alice').get('settings').once();
215
-
216
- // Get Gun node for advanced operations like .map()
217
- const userNode = shogun.api.getNode('users');
218
- userNode.map((user, userId) => console.log(`User ${userId}:`, user));
219
-
220
- // User space operations (requires login)
221
- await shogun.api.putUserData('preferences', { theme: 'dark' });
222
- const prefs = await shogun.api.getUserData('preferences');
223
- await shogun.api.removeUserData('preferences');
224
-
225
- // Profile management
226
- await shogun.api.updateProfile({
227
- name: 'John Doe',
228
- email: 'john@example.com',
229
- bio: 'Developer'
230
- });
231
- const profile = await shogun.api.getProfile();
232
-
233
- // Settings and preferences
234
- await shogun.api.saveSettings({ language: 'en', notifications: true });
235
- const settings = await shogun.api.getSettings();
236
-
237
- await shogun.api.savePreferences({ theme: 'dark', fontSize: 14 });
238
- const preferences = await shogun.api.getPreferences();
239
-
240
- // Collections (recommended for structured data)
241
- // Note: Array functions (putUserArray, getUserArray, etc.) have been removed due to GunDB compatibility issues
242
- // Use collections or direct GunDB operations instead:
243
-
244
- // Option 1: Collections (recommended for most use cases)
245
- await shogun.api.createCollection('todos', {
246
- '1': { text: 'Learn Shogun Core', done: false },
247
- '2': { text: 'Build dApp', done: false }
248
- });
249
-
250
- await shogun.api.addToCollection('todos', '3', {
251
- text: 'Deploy to production',
252
- done: false
253
- });
254
-
255
- const todos = await shogun.api.getCollection('todos');
256
- await shogun.api.removeFromCollection('todos', '2');
257
-
258
- // Option 2: Direct GunDB operations for complex nested data
259
- await shogun.api.node('users').get('alice').get('todos').get('1').put({
260
- text: 'Learn Shogun Core',
261
- done: false
262
- });
263
-
264
- // Utility methods
265
- const currentUser = shogun.api.getCurrentUser();
266
- const userExists = await shogun.api.userExists('username');
267
- const user = await shogun.api.getUser('username');
268
- ```
269
-
270
- ## πŸ”— **NEW: Advanced Chaining Operations**
271
-
272
- Shogun Core now supports powerful chaining operations for complex data structures. You have three options depending on your needs:
273
-
274
- ### 1. **Direct Gun Node Chaining (Recommended)**
275
-
276
- Use `node()` for full Gun.js functionality with chaining:
277
-
278
- ```typescript
279
- // Store nested data
280
- await shogun.api.node('users').get('alice').get('profile').put({
281
- name: 'Alice Smith',
282
- email: 'alice@example.com',
283
- preferences: {
284
- theme: 'dark',
285
- language: 'en'
286
- }
287
- });
288
-
289
- // Read nested data
290
- const profile = await shogun.api.node('users').get('alice').get('profile').once();
291
-
292
- // Update specific fields
293
- await shogun.api.node('users').get('alice').get('profile').get('preferences').get('theme').put('light');
294
-
295
- // Iterate over collections
296
- shogun.api.node('users').map((user, userId) => {
297
- console.log(`User ${userId}:`, user);
298
- });
299
-
300
- // Complex chaining
301
- await shogun.api.node('projects').get('my-app').get('tasks').get('1').put({
302
- title: 'Implement authentication',
303
- status: 'completed',
304
- assignee: 'alice'
305
- });
306
- ```
307
-
308
- ### 2. **Simplified Chaining Wrapper**
309
-
310
- Use `chain()` for simplified chaining with error handling:
311
-
312
- ```typescript
313
- // Simplified chaining with built-in error handling
314
- const success = await shogun.api.chain('users').get('alice').get('settings').put({
315
- notifications: true,
316
- privacy: 'private'
317
- });
318
-
319
- if (success) {
320
- console.log('Settings saved successfully');
321
- }
322
-
323
- // Read with simplified chaining
324
- const settings = await shogun.api.chain('users').get('alice').get('settings').once();
325
- ```
326
-
327
- ### 3. **Get Gun Node for Advanced Operations**
328
-
329
- Use `getNode()` for advanced Gun.js operations:
330
-
331
- ```typescript
332
- // Get node for advanced operations
333
- const usersNode = shogun.api.getNode('users');
334
-
335
- // Use all Gun.js methods
336
- usersNode.map((user, userId) => {
337
- console.log(`Processing user ${userId}`);
338
- return user;
339
- });
340
-
341
- // Chain from the node
342
- const aliceProfile = await usersNode.get('alice').get('profile').once();
343
- ```
344
-
345
- ### Chaining Examples
346
-
347
- ```typescript
348
- // User management system
349
- await shogun.api.node('users').get('alice').put({
350
- profile: {
351
- name: 'Alice',
352
- email: 'alice@example.com'
353
- },
354
- settings: {
355
- theme: 'dark',
356
- notifications: true
357
- },
358
- posts: {
359
- '1': { title: 'Hello World', content: 'My first post' },
360
- '2': { title: 'GunDB is awesome', content: 'Learning decentralized storage' }
361
- }
362
- });
363
-
364
- // Blog system
365
- await shogun.api.node('blog').get('posts').get('2024-01-15').put({
366
- title: 'Getting Started with Shogun Core',
367
- author: 'alice',
368
- content: 'Shogun Core makes decentralized apps easy...',
369
- tags: ['tutorial', 'decentralized', 'web3'],
370
- comments: {
371
- '1': { author: 'bob', text: 'Great tutorial!' },
372
- '2': { author: 'charlie', text: 'Very helpful, thanks!' }
373
- }
374
- });
375
-
376
- // E-commerce system
377
- await shogun.api.node('shop').get('products').get('laptop-001').put({
378
- name: 'Gaming Laptop',
379
- price: 1299.99,
380
- stock: 15,
381
- reviews: {
382
- '1': { user: 'alice', rating: 5, comment: 'Amazing performance!' },
383
- '2': { user: 'bob', rating: 4, comment: 'Good value for money' }
384
- }
385
- });
386
-
387
- // Read complex nested data
388
- const product = await shogun.api.node('shop').get('products').get('laptop-001').once();
389
- console.log('Product:', product.name);
390
- console.log('Reviews:', product.reviews);
391
-
392
- // Update nested data
393
- await shogun.api.node('shop').get('products').get('laptop-001').get('stock').put(12);
394
- ```
395
-
396
- ### Best Practices for Chaining
397
-
398
- 1. **Use `node()` for most operations** - It provides full Gun.js functionality
399
- 2. **Use `chain()` for simplified error handling** - Good for beginners
400
- 3. **Use `getNode()` for advanced operations** - When you need Gun.js methods like `.map()`
401
- 4. **Keep paths descriptive** - Use meaningful path segments like `users/alice/profile`
402
- 5. **Handle errors appropriately** - Chaining operations can fail, always check results
403
-
404
- ## Plugin Authentication APIs
405
-
406
- Shogun Core provides a unified plugin system for different authentication methods. Each plugin implements standardized `login()` and `signUp()` methods that return consistent `AuthResult` and `SignUpResult` objects.
407
-
408
- ### Core Types - βœ… **FIXED & UNIFIED**
409
-
410
- ```typescript
411
- // Authentication result interface - used by login methods
412
- interface AuthResult {
413
- success: boolean;
414
- error?: string;
415
- userPub?: string; // User's public key
416
- username?: string; // Username or identifier
417
- sessionToken?: string; // Session token if applicable
418
- authMethod?: AuthMethod; // Authentication method used
419
- sea?: {
420
- // GunDB SEA pair for session persistence
421
- pub: string;
422
- priv: string;
423
- epub: string;
424
- epriv: string;
425
- };
426
- // OAuth-specific properties
427
- redirectUrl?: string; // OAuth redirect URL
428
- pendingAuth?: boolean; // Indicates pending OAuth flow
429
- message?: string; // Status message
430
- provider?: string; // OAuth provider name
431
- isNewUser?: boolean; // True if this was a registration
432
- user?: {
433
- // OAuth user data
434
- userPub?: string;
435
- username?: string;
436
- email?: string;
437
- name?: string;
438
- picture?: string;
439
- oauth?: {
440
- provider: string;
441
- id: string;
442
- email?: string;
443
- name?: string;
444
- picture?: string;
445
- lastLogin: number;
446
- };
447
- };
448
- }
449
-
450
- // Sign up result interface - used by signUp methods βœ… ENHANCED
451
- interface SignUpResult {
452
- success: boolean;
453
- userPub?: string;
454
- username?: string;
455
- pub?: string;
456
- error?: string;
457
- message?: string;
458
- wallet?: any;
459
- isNewUser?: boolean;
460
- authMethod?: AuthMethod; // βœ… ADDED
461
- sessionToken?: string; // βœ… ADDED
462
- sea?: { pub: string; priv: string; epub: string; epriv: string }; // SEA pair for session persistence
463
- // OAuth flow support - βœ… ADDED
464
- redirectUrl?: string;
465
- pendingAuth?: boolean;
466
- provider?: string;
467
- user?: OAuthUserInfo; // βœ… ADDED
468
- }
469
-
470
- // Supported authentication methods
471
- type AuthMethod =
472
- | "password"
473
- | "webauthn"
474
- | "web3"
475
- | "nostr"
476
- | "oauth"
477
- | "bitcoin"
478
- | "pair";
479
- ```
480
-
481
- ### 1. Traditional Authentication
482
-
483
- Direct username/password authentication using ShogunCore methods:
484
-
485
- ```typescript
486
- // Sign up a new user - Returns SignUpResult βœ…
487
- const signUpResult: SignUpResult = await shogun.signUp("username", "password");
488
- if (signUpResult.success) {
489
- console.log("User created:", signUpResult.username);
490
- console.log("Is new user:", signUpResult.isNewUser);
491
- console.log("Auth method:", signUpResult.authMethod);
492
- }
493
-
494
- // Login with username and password - Returns AuthResult βœ…
495
- const loginResult: AuthResult = await shogun.login("username", "password");
496
- if (loginResult.success) {
497
- console.log("Logged in as:", loginResult.username);
498
- console.log("User public key:", loginResult.userPub);
499
- }
500
- ```
501
-
502
- ### 2. Web3 Plugin API
503
-
504
- Ethereum wallet authentication via MetaMask or other Web3 providers:
505
-
506
- ```typescript
507
- const web3Plugin = shogun.getPlugin<Web3ConnectorPlugin>("web3");
508
-
509
- if (web3Plugin && web3Plugin.isAvailable()) {
510
- // Connect to MetaMask
511
- const connectionResult = await web3Plugin.connectMetaMask();
512
-
513
- if (connectionResult.success) {
514
- const address = connectionResult.address!;
515
-
516
- // Login with Web3 wallet - Returns AuthResult βœ…
517
- const loginResult: AuthResult = await web3Plugin.login(address);
518
- if (loginResult.success) {
519
- console.log("Web3 login successful");
520
- console.log("User public key:", loginResult.userPub);
521
- }
522
-
523
- // Register new user with Web3 wallet - Returns SignUpResult βœ…
524
- const signUpResult: SignUpResult = await web3Plugin.signUp(address);
525
- if (signUpResult.success) {
526
- console.log("Web3 registration successful");
527
- console.log("Is new user:", signUpResult.isNewUser);
528
- }
529
- }
530
- }
531
-
532
- // Plugin Interface - βœ… FIXED TYPES
533
- interface Web3ConnectorPluginInterface {
534
- // Authentication methods
535
- login(address: string): Promise<AuthResult>; // βœ… CORRECT
536
- signUp(address: string): Promise<SignUpResult>; // βœ… FIXED
537
-
538
- // Connection methods
539
- isAvailable(): boolean;
540
- connectMetaMask(): Promise<ConnectionResult>;
541
- getProvider(): Promise<ethers.JsonRpcProvider | ethers.BrowserProvider>;
542
- getSigner(): Promise<ethers.Signer>;
543
-
544
- // Credential management
545
- generateCredentials(address: string): Promise<ISEAPair>;
546
- generatePassword(signature: string): Promise<string>;
547
- verifySignature(message: string, signature: string): Promise<string>;
548
- }
549
- ```
550
-
551
- ### 3. WebAuthn Plugin API
552
-
553
- Biometric and hardware key authentication:
554
-
555
- ```typescript
556
- const webauthnPlugin = shogun.getPlugin<WebauthnPlugin>("webauthn");
557
-
558
- if (webauthnPlugin && webauthnPlugin.isSupported()) {
559
- // Register new user with WebAuthn - Returns SignUpResult βœ…
560
- const signUpResult: SignUpResult = await webauthnPlugin.signUp("username");
561
- if (signUpResult.success) {
562
- console.log("WebAuthn registration successful");
563
- console.log("User public key:", signUpResult.userPub);
564
- }
565
-
566
- // Authenticate existing user - Returns AuthResult βœ…
567
- const loginResult: AuthResult = await webauthnPlugin.login("username");
568
- if (loginResult.success) {
569
- console.log("WebAuthn authentication successful");
570
- console.log("Auth method:", loginResult.authMethod); // "webauthn"
571
- }
572
- }
573
-
574
- // Plugin Interface - βœ… FIXED TYPES
575
- interface WebauthnPluginInterface {
576
- // Authentication methods
577
- login(username: string): Promise<AuthResult>; // βœ… CORRECT
578
- signUp(username: string): Promise<SignUpResult>; // βœ… FIXED
579
-
580
- // Capability checks
581
- isSupported(): boolean;
582
-
583
- // WebAuthn-specific methods
584
- register(username: string, displayName?: string): Promise<WebAuthnCredential>;
585
- authenticate(username?: string): Promise<WebAuthnCredential>;
586
- generateCredentials(
587
- username: string,
588
- pair?: ISEAPair | null,
589
- login?: boolean
590
- ): Promise<WebAuthnUniformCredentials>;
591
- }
592
- ```
593
-
594
- ### 4. Nostr Plugin API
595
-
596
- Bitcoin wallet and Nostr protocol authentication:
597
-
598
- ```typescript
599
- const nostrPlugin = shogun.getPlugin<NostrConnectorPlugin>("nostr");
600
-
601
- if (nostrPlugin && nostrPlugin.isAvailable()) {
602
- // Connect to Nostr wallet (Bitcoin extension)
603
- const connectionResult = await nostrPlugin.connectNostrWallet();
604
-
605
- if (connectionResult.success) {
606
- const address = connectionResult.address!;
607
-
608
- // Login with Nostr/Bitcoin wallet - Returns AuthResult βœ…
609
- const loginResult: AuthResult = await nostrPlugin.login(address);
610
- if (loginResult.success) {
611
- console.log("Nostr login successful");
612
- console.log("Auth method:", loginResult.authMethod); // "nostr"
613
- }
614
-
615
- // Register with Nostr/Bitcoin wallet - Returns SignUpResult βœ…
616
- const signUpResult: SignUpResult = await nostrPlugin.signUp(address);
617
- if (signUpResult.success) {
618
- console.log("Nostr registration successful");
619
- console.log("Is new user:", signUpResult.isNewUser);
620
- }
621
- }
622
- }
623
-
624
- // Plugin Interface - βœ… FIXED TYPES
625
- interface NostrConnectorPluginInterface {
626
- // Authentication methods
627
- login(address: string): Promise<AuthResult>; // βœ… CORRECT
628
- signUp(address: string): Promise<SignUpResult>; // βœ… FIXED
629
-
630
- // Connection methods
631
- isAvailable(): boolean;
632
- connectBitcoinWallet(
633
- type?: "alby" | "nostr" | "manual"
634
- ): Promise<ConnectionResult>;
635
- connectNostrWallet(): Promise<ConnectionResult>;
636
-
637
- // Credential and signature management
638
- generateCredentials(
639
- address: string,
640
- signature: string,
641
- message: string
642
- ): Promise<NostrConnectorCredentials>;
643
- verifySignature(
644
- message: string,
645
- signature: string,
646
- address: string
647
- ): Promise<boolean>;
648
- generatePassword(signature: string): Promise<string>;
649
- }
650
- ```
651
-
652
- ### 5. OAuth Plugin API
653
-
654
- Social login with external providers (Google, GitHub, etc.):
655
-
656
- ```typescript
657
- const oauthPlugin = shogun.getPlugin<OAuthPlugin>("oauth");
658
-
659
- if (oauthPlugin && oauthPlugin.isSupported()) {
660
- // Get available providers
661
- const providers = oauthPlugin.getAvailableProviders(); // ["google", "github", ...]
662
-
663
- // Initiate signup with OAuth - Returns SignUpResult with redirect βœ…
664
- const signUpResult: SignUpResult = await oauthPlugin.signUp("google");
665
- if (signUpResult.success && signUpResult.redirectUrl) {
666
- // Redirect user to OAuth provider
667
- window.location.href = signUpResult.redirectUrl;
668
- }
669
-
670
- // Handle OAuth callback (after redirect back from provider) - Returns AuthResult βœ…
671
- const callbackResult: AuthResult = await oauthPlugin.handleOAuthCallback(
672
- "google",
673
- authCode, // From URL params
674
- state // From URL params
675
- );
676
-
677
- if (callbackResult.success) {
678
- console.log("OAuth authentication successful");
679
- if (callbackResult.user) {
680
- console.log("User email:", callbackResult.user.email);
681
- console.log("User name:", callbackResult.user.name);
682
- }
683
- }
684
- }
685
-
686
- // Plugin Interface - βœ… FIXED TYPES
687
- interface OAuthPluginInterface {
688
- // Authentication methods
689
- login(provider: OAuthProvider): Promise<AuthResult>; // βœ… CORRECT
690
- signUp(provider: OAuthProvider): Promise<SignUpResult>; // βœ… FIXED
691
-
692
- // OAuth flow management
693
- isSupported(): boolean;
694
- getAvailableProviders(): OAuthProvider[];
695
- initiateOAuth(provider: OAuthProvider): Promise<OAuthConnectionResult>;
696
- completeOAuth(
697
- provider: OAuthProvider,
698
- authCode: string,
699
- state?: string
700
- ): Promise<OAuthConnectionResult>;
701
- handleOAuthCallback(
702
- provider: OAuthProvider,
703
- authCode: string,
704
- state: string
705
- ): Promise<AuthResult>;
706
-
707
- // Credential management
708
- generateCredentials(
709
- userInfo: OAuthUserInfo,
710
- provider: OAuthProvider
711
- ): Promise<OAuthCredentials>;
712
- }
713
- ```
714
-
715
- ### Browser Usage (via CDN)
716
-
717
- You can also use Shogun Core directly in the browser by including it from a CDN. This is ideal for static sites or lightweight applications.
718
-
719
- ```html
720
- <!DOCTYPE html>
721
- <html>
722
- <head>
723
- <title>Shogun Core in Browser</title>
724
- </head>
725
- <body>
726
- <h1>My dApp</h1>
727
- <!-- Required dependencies for Shogun Core -->
728
- <script src="https://cdn.jsdelivr.net/npm/gun/gun.js"></script>
729
- <script src="https://cdn.jsdelivr.net/npm/gun/sea.js"></script>
730
-
731
- <!-- Shogun Core library -->
732
- <script src="https://cdn.jsdelivr.net/npm/shogun-core/dist/browser/shogun-core.js"></script>
733
-
734
- <script>
735
- // Access the global Shogun Core function
736
- const shogunCore = window.SHOGUN_CORE({
737
- peers: ["https://gun-manhattan.herokuapp.com/gun"],
738
- scope: "my-browser-app",
739
- web3: { enabled: true },
740
- webauthn: {
741
- enabled: true,
742
- rpName: "My Browser dApp",
743
- rpId: window.location.hostname,
744
- },
745
- });
746
-
747
- console.log("Shogun Core initialized in browser!", shogunCore);
748
-
749
- async function connectWallet() {
750
- if (shogunCore.hasPlugin("web3")) {
751
- const web3Plugin = shogunCore.getPlugin("web3");
752
- try {
753
- const provider = await web3Plugin.getProvider();
754
- const signer = provider.getSigner();
755
- const address = await signer.getAddress();
756
- await web3Plugin.login(address);
757
- console.log("Logged in with address:", address);
758
- } catch (error) {
759
- console.error("Web3 login failed:", error);
760
- }
761
- }
762
- }
763
- </script>
764
- </body>
765
- </html>
766
- ```
767
-
768
- ## API Reference
769
-
770
- ### ⭐ **Simple API Methods**
771
-
772
- #### Authentication
773
- - `signup(username: string, password: string): Promise<UserInfo | null>` - Create new user account
774
- - `login(username: string, password: string): Promise<UserInfo | null>` - Authenticate with username/password
775
- - `logout(): void` - Logout current user
776
- - `isLoggedIn(): boolean` - Check if user is authenticated
777
-
778
- #### Data Operations
779
- - `get<T>(path: string): Promise<T | null>` - Get data from path
780
- - `put<T>(path: string, data: T): Promise<boolean>` - Store data at path
781
- - `set<T>(path: string, data: T): Promise<boolean>` - Update data at path
782
- - `remove(path: string): Promise<boolean>` - Remove data from path
783
-
784
- #### Advanced Chaining Operations (NEW!)
785
- - `node(path: string): GunNode` - Get Gun node for direct chaining (recommended)
786
- - `chain(path: string): ChainingWrapper` - Get simplified chaining wrapper
787
- - `getNode(path: string): GunNode` - Get Gun node for advanced operations like .map()
788
-
789
- #### User Space Operations
790
- - `putUserData<T>(path: string, data: T): Promise<boolean>` - Store user-specific data
791
- - `getUserData<T>(path: string): Promise<T | null>` - Get user-specific data
792
- - `setUserData<T>(path: string, data: T): Promise<boolean>` - Update user-specific data
793
- - `removeUserData(path: string): Promise<boolean>` - Remove user-specific data
794
- - `getAllUserData(): Promise<Record<string, unknown> | null>` - Get all user data
795
-
796
- #### Profile & Settings
797
- - `updateProfile(profileData: ProfileData): Promise<boolean>` - Update user profile
798
- - `getProfile(): Promise<Record<string, unknown> | null>` - Get user profile
799
- - `saveSettings(settings: Record<string, unknown>): Promise<boolean>` - Save user settings
800
- - `getSettings(): Promise<Record<string, unknown> | null>` - Get user settings
801
- - `savePreferences(preferences: Record<string, unknown>): Promise<boolean>` - Save user preferences
802
- - `getPreferences(): Promise<Record<string, unknown> | null>` - Get user preferences
803
-
804
- #### Collections
805
- - `createCollection<T>(name: string, items: Record<string, T>): Promise<boolean>` - Create user collection
806
- - `addToCollection<T>(name: string, itemId: string, item: T): Promise<boolean>` - Add item to collection
807
- - `getCollection(name: string): Promise<Record<string, unknown> | null>` - Get collection
808
- - `removeFromCollection(name: string, itemId: string): Promise<boolean>` - Remove item from collection
809
-
810
- #### Utility Functions
811
- - `arrayToIndexedObject<T>(arr: T[]): Record<string, T>` - Convert array to indexed object (helper)
812
- - `indexedObjectToArray<T>(indexedObj: Record<string, T>): T[]` - Convert indexed object to array (helper)
813
-
814
- #### ⚠️ **REMOVED FUNCTIONS**
815
- The following array functions have been **REMOVED** due to GunDB compatibility issues:
816
- - `putUserArray()`, `getUserArray()`, `addToUserArray()`, `removeFromUserArray()`, `updateInUserArray()`
817
-
818
- **Use collections or direct GunDB operations instead** (see examples above).
819
-
820
- ### Advanced API Methods
821
-
822
- #### Core Authentication
823
- - `login(username: string, password: string): Promise<AuthResult>` - Authenticate with username/password
824
- - `loginWithPair(pair: ISEAPair): Promise<AuthResult>` - Authenticate directly with a GunDB SEA pair
825
- - `signUp(username: string, password: string, email?: string, pair?: ISEAPair | null): Promise<SignUpResult>` - Create new user account
826
- - `logout(): void` - Logout current user
827
- - `isLoggedIn(): boolean` - Check if user is authenticated
828
- - `setAuthMethod(method: AuthMethod): void` - Set authentication method
829
- - `getAuthMethod(): AuthMethod | undefined` - Get current authentication method
830
- - `saveCredentials(credentials: any): Promise<void>` - Save user credentials
831
-
832
- #### Plugin Management
833
- - `getPlugin<T>(name: string): T | undefined` - Get plugin by name
834
- - `hasPlugin(name: string): boolean` - Check if plugin exists
835
- - `register(plugin: ShogunPlugin): void` - Register custom plugin
836
- - `unregister(pluginName: string): void` - Remove plugin
837
- - `getPluginsInfo(): Array<{name: string; version: string; category?: PluginCategory; description?: string}>` - Get detailed plugin information
838
- - `getPluginCount(): number` - Get total number of plugins
839
- - `getPluginsInitializationStatus(): Record<string, {initialized: boolean; error?: string}>` - Check plugin initialization status
840
- - `getPluginsByCategory(category: PluginCategory): ShogunPlugin[]` - Get plugins by category
841
- - `validatePluginSystem(): {...}` - Validate plugin system health
842
- - `reinitializeFailedPlugins(): {...}` - Reinitialize failed plugins
843
- - `checkPluginCompatibility(): {...}` - Check plugin compatibility
844
- - `getPluginSystemDebugInfo(): {...}` - Get comprehensive debug information
845
-
846
- #### Peer Network Management (Database)
847
- - `addPeer(peer: string): void` - Add new peer to network
848
- - `removePeer(peer: string): void` - Remove peer from network
849
- - `getCurrentPeers(): string[]` - Get currently connected peers
850
- - `getAllConfiguredPeers(): string[]` - Get all configured peers
851
- - `getPeerInfo(): {[peer: string]: {connected: boolean; status: string}}` - Get detailed peer information
852
- - `reconnectToPeer(peer: string): void` - Reconnect to specific peer
853
- - `resetPeers(newPeers?: string[]): void` - Reset all peers and optionally add new ones
854
-
855
- #### Advanced User Management (Database)
856
- - `getUserByAlias(alias: string): Promise<{...}>` - Get user by alias/username
857
- - `getUserDataByPub(userPub: string): Promise<{...}>` - Get user by public key
858
- - `getUserPubByEpub(epub: string): Promise<string | null>` - Get user public key by encryption key
859
- - `getUserAliasByPub(userPub: string): Promise<string | null>` - Get user alias by public key
860
- - `getAllRegisteredUsers(): Promise<Array<{...}>>` - Get all registered users
861
- - `updateUserLastSeen(userPub: string): Promise<void>` - Update user's last seen timestamp
862
-
863
- #### Password Recovery & Security (Database)
864
- - `setPasswordHintWithSecurity(username: string, password: string, hint: string, securityQuestions: string[], securityAnswers: string[]): Promise<{success: boolean; error?: string}>` - Set up password recovery
865
- - `forgotPassword(username: string, securityAnswers: string[]): Promise<{success: boolean; hint?: string; error?: string}>` - Recover password
866
-
867
- #### Error Handling & Debugging
868
- - `getRecentErrors(count?: number): ShogunError[]` - Get recent errors for debugging
869
-
870
- #### Event Handling
871
- - `on<K extends keyof ShogunEventMap>(eventName: K, listener: Function): this` - Subscribe to typed events
872
- - `off<K extends keyof ShogunEventMap>(eventName: K, listener: Function): this` - Unsubscribe from events
873
- - `once<K extends keyof ShogunEventMap>(eventName: K, listener: Function): this` - Subscribe to one-time events
874
- - `emit<K extends keyof ShogunEventMap>(eventName: K, data?: ShogunEventMap[K]): boolean` - Emit custom events
875
- - `removeAllListeners(eventName?: string | symbol): this` - Remove all event listeners
876
-
877
- ### Configuration Options
878
-
879
- ```typescript
880
- interface ShogunCoreConfig {
881
- peers?: string[]; // GunDB peer URLs
882
- scope?: string; // Application scope
883
- authToken?: string; // GunDB super peer secret
884
- appToken?: string; // Application token
885
-
886
- // Plugin configurations
887
- webauthn?: {
888
- enabled?: boolean;
889
- rpName?: string;
890
- rpId?: string;
891
- };
892
-
893
- web3?: {
894
- enabled?: boolean;
895
- };
896
-
897
- nostr?: {
898
- enabled?: boolean;
899
- };
900
-
901
- oauth?: {
902
- enabled?: boolean;
903
- usePKCE?: boolean;
904
- allowUnsafeClientSecret?: boolean;
905
- providers?: Record<string, any>;
906
- };
907
-
908
- // Timeouts
909
- timeouts?: {
910
- login?: number;
911
- signup?: number;
912
- operation?: number;
913
- };
914
- }
915
- ```
916
-
917
- ## Event System
918
-
919
- Shogun Core provides a comprehensive typed event system for monitoring authentication and data changes:
920
-
921
- ```typescript
922
- // Available events with their data types
923
- interface ShogunEventMap {
924
- "auth:login": AuthEventData; // User logged in
925
- "auth:logout": void; // User logged out
926
- "auth:signup": AuthEventData; // New user registered
927
- "plugin:registered": { name: string; version?: string; category?: string }; // Plugin registered
928
- "plugin:unregistered": { name: string }; // Plugin unregistered
929
- debug: { action: string; [key: string]: any }; // Debug information
930
- error: ErrorEventData; // Error occurred
931
- }
932
-
933
- // Listen for authentication events with full type safety
934
- shogun.on("auth:login", (data) => {
935
- console.log("User logged in:", data.username);
936
- console.log("Authentication method:", data.method);
937
- if (data.provider) {
938
- console.log("OAuth provider:", data.provider);
939
- }
940
- });
941
-
942
- shogun.on("auth:logout", () => {
943
- console.log("User logged out");
944
- });
945
-
946
- shogun.on("auth:signup", (data) => {
947
- console.log("New user signed up:", data.username);
948
- });
949
-
950
- // Listen for errors
951
- shogun.on("error", (error) => {
952
- console.error("Shogun error:", error.message);
953
- });
954
- ```
955
-
956
- ## Password Recovery System
957
-
958
- Shogun Core includes a secure password recovery system using security questions:
959
-
960
- ```typescript
961
- // Set password hint with security questions
962
- await shogun.db.setPasswordHint(
963
- "username",
964
- "password",
965
- "My favorite color",
966
- ["What is your favorite color?", "What was your first pet's name?"],
967
- ["blue", "fluffy"]
968
- );
969
-
970
- // Recover password using security answers
971
- const result = await shogun.db.forgotPassword("username", ["blue", "fluffy"]);
972
-
973
- if (result.success) {
974
- console.log("Password hint:", result.hint);
975
- }
976
- ```
977
-
978
- Note: The cryptographic wallet derivation feature has been removed in v1.9.5 to simplify the architecture.
979
-
980
- ## Error Handling
981
-
982
- Shogun Core includes comprehensive error handling with typed errors:
983
-
984
- ```typescript
985
- import { ShogunError, ErrorType } from "shogun-core";
986
-
987
- try {
988
- await shogun.login("username", "password");
989
- } catch (error) {
990
- if (error instanceof ShogunError) {
991
- switch (error.type) {
992
- case ErrorType.AUTHENTICATION:
993
- console.error("Invalid credentials");
994
- break;
995
- case ErrorType.NETWORK:
996
- console.error("Network connection failed");
997
- break;
998
- default:
999
- console.error("Unknown error:", error.message);
1000
- }
1001
- }
1002
- }
1003
- ```
1004
-
1005
- ## Contributing
1006
-
1007
- We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
1008
-
1009
- ## License
1010
-
1011
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
1012
-
1013
- ## SHIP Standards (Shogun Interface Proposals)
1014
-
1015
- Shogun Core implements **SHIP standards** - modular, composable protocols for decentralized applications:
1016
-
1017
- - **[SHIP-00](./ship/SHIP_00.md)**: Identity & Authentication Foundation
1018
- - **[SHIP-01](./ship/SHIP_01.md)**: Decentralized Encrypted Messaging
1019
- - **[SHIP-02](./ship/SHIP_02.md)**: Ethereum HD Wallet & Transaction Sending
1020
- - **[SHIP-03](./ship/SHIP_03.md)**: Dual-Key Stealth Addresses (ERC-5564)
1021
- - **[SHIP-04](./ship/SHIP_04.md)**: Multi-Modal Authentication (OAuth/WebAuthn/Web3/Nostr)
1022
-
1023
- See [ship/README.md](./ship/README.md) for complete SHIP documentation and examples.
1024
-
1025
- ## Advanced Features
1026
-
1027
- For advanced use cases and comprehensive API coverage, see the [Advanced API Features](./API.md#advanced-api-features) section which includes:
1028
-
1029
- - **Advanced Plugin Management**: Plugin health monitoring, compatibility checking, and system validation
1030
- - **Peer Network Management**: Dynamic peer connection management and network monitoring
1031
- - **Advanced User Management**: Comprehensive user lookup, tracking, and metadata management
1032
- - **Password Recovery & Security**: Secure password hint system with security questions
1033
- - **Error Handling & Debugging**: Advanced error tracking and debugging capabilities
1034
- - **Event System**: Complete event handling reference with type safety
1035
- - **Database Lifecycle**: Advanced database initialization and management
1036
-
1037
- ## Support
1038
-
1039
- - πŸ“– [Documentation](https://shogun-core-docs.vercel.app/)
1040
- - πŸ“š [Advanced API Reference](./API.md#advanced-api-features)
1041
- - πŸ’¬ [Telegram Community](t.me/shogun_eco)
1042
- - πŸ› [Issue Tracker](https://github.com/scobru/shogun-core/issues)
1043
-
1044
- # SHOGUN CORE
1045
-
1046
- Core library for Shogun Ecosystem
1047
-
1048
- ## Testing
1049
-
1050
- This project includes a comprehensive test suite that covers all major functionality and has been recently updated to align with the current codebase structure.
1051
-
1052
- ### βœ… **Test Suite Status (Updated)**
1053
-
1054
- - **βœ… All Tests Passing**: 659/659 tests pass successfully
1055
- - **βœ… Plugin System**: Complete plugin functionality testing
1056
- - **βœ… Authentication Methods**: All auth methods (WebAuthn, Web3, Nostr, OAuth) tested
1057
- - **βœ… Simple API**: Full coverage of SimpleGunAPI functionality
1058
- - **βœ… Error Handling**: Comprehensive error handling and edge case testing
1059
- - **βœ… Browser Compatibility**: Cross-browser support validation
1060
- - **βœ… Integration Tests**: End-to-end functionality testing
1061
-
1062
- ### Test Coverage
1063
-
1064
- This project includes a comprehensive test suite that covers:
1065
-
1066
- ### Unit Tests
1067
-
1068
- - **Validation Utils** (`src/__tests__/utils/validation.test.ts`)
1069
- - Username validation
1070
- - Email validation
1071
- - OAuth provider validation
1072
- - Username generation from identity
1073
- - Deterministic password generation
1074
-
1075
- - **Error Handler** (`src/__tests__/utils/errorHandler.test.ts`)
1076
- - Error creation and handling
1077
- - Error statistics and logging
1078
- - Retry logic
1079
- - External logger integration
1080
-
1081
- - **Event Emitter** (`src/__tests__/utils/eventEmitter.test.ts`)
1082
- - Event registration and emission
1083
- - Listener management
1084
- - Error handling in listeners
1085
- - Symbol events support
1086
-
1087
- - **Storage** (`src/__tests__/storage/storage.test.ts`)
1088
- - Memory and localStorage operations
1089
- - Error handling
1090
- - Test mode behavior
1091
- - Data persistence
1092
-
1093
- ### Integration Tests
1094
-
1095
- - **ShogunCore** (`src/__tests__/integration/shogunCore.test.ts`)
1096
- - Plugin system validation
1097
- - Authentication methods
1098
- - Event system
1099
- - Configuration handling
1100
- - Error handling
1101
-
1102
- ### Browser Compatibility Tests
1103
-
1104
- - **Compatibility** (`src/__tests__/browser/compatibility.test.ts`)
1105
- - localStorage availability
1106
- - Crypto API support
1107
- - WebAuthn detection
1108
- - Web3 provider detection
1109
- - Event system compatibility
1110
- - TextEncoder/TextDecoder support
1111
- - Fetch API compatibility
1112
- - URL API compatibility
1113
- - Performance API compatibility
1114
- - Console API compatibility
1115
-
1116
- ## Running Tests
1117
-
1118
- You can eseguire i test sia dalla root del monorepo sia entrando nella cartella `shogun-core`.
1119
-
1120
- Inside `shogun-core/` directory:
1121
-
1122
- ```bash
1123
- # Install deps
1124
- yarn install
1125
-
1126
- # Tutti i test (una sola esecuzione) con coverage
1127
- yarn test:ci
1128
-
1129
- # Watch mode
1130
- yarn test:watch
1131
-
1132
- # Coverage (report HTML in coverage/lcov-report/index.html)
1133
- yarn coverage
1134
-
1135
- # Solo i test dei plugin
1136
- yarn test src/__tests__/plugins
1137
-
1138
- # Evita conflitti di config Jest (se servisse)
1139
- yarn jest --ci --coverage --watchAll=false --config jest.config.js
1140
- ```
1141
-
1142
- From repository root (senza cambiare directory):
1143
-
1144
- ```bash
1145
- # Install deps
1146
- yarn --cwd shogun-core install
1147
-
1148
- # Tutti i test con coverage (CI‑like)
1149
- yarn --cwd shogun-core test:ci
1150
-
1151
- # Solo plugin tests
1152
- yarn --cwd shogun-core test src/__tests__/plugins
1153
-
1154
- # Coverage
1155
- yarn --cwd shogun-core coverage
1156
-
1157
- # Watch mode
1158
- yarn --cwd shogun-core test:watch
1159
-
1160
- # Se compaiono piΓΉ configurazioni Jest, specifica esplicitamente il config file
1161
- yarn --cwd shogun-core jest --ci --coverage --watchAll=false --config jest.config.js
1162
- ```
1163
-
1164
- CI & QA scripts:
1165
-
1166
- ```bash
1167
- # Mutation testing (Stryker) – piΓΉ lento, richiede devDeps installate
1168
- yarn --cwd shogun-core mutation
1169
-
1170
- # SAST (Semgrep) – richiede semgrep installato (es. `pip install semgrep`)
1171
- yarn --cwd shogun-core sast
1172
- ```
1173
-
1174
- ## Test Coverage
1175
-
1176
- The test suite provides comprehensive coverage of:
1177
-
1178
- - βœ… **Utility Functions** - 100% coverage
1179
- - βœ… **Error Handling** - 100% coverage
1180
- - βœ… **Event System** - 100% coverage
1181
- - βœ… **Storage Operations** - 100% coverage
1182
- - βœ… **Plugin System** - API validation
1183
- - βœ… **Browser Compatibility** - Cross-browser support
1184
- - βœ… **Configuration Validation** - Config handling
1185
-
1186
- ## Test Philosophy
1187
-
1188
- These tests are designed to be **realistic and non-intrusive**:
1189
-
1190
- - **No codebase modifications** - Tests work with existing code
1191
- - **Comprehensive coverage** - All public APIs tested
1192
- - **Error resilience** - Tests error handling and edge cases
1193
- - **Browser compatibility** - Cross-browser support validation
1194
- - **Performance aware** - Tests don't impact runtime performance
1195
-
1196
- ## Test Structure
1197
-
1198
- ```
1199
- src/__tests__/
1200
- β”œβ”€β”€ setup.ts # Global test setup
1201
- β”œβ”€β”€ utils/
1202
- β”‚ β”œβ”€β”€ validation.test.ts # Validation utility tests
1203
- β”‚ β”œβ”€β”€ errorHandler.test.ts # Error handling tests
1204
- β”‚ └── eventEmitter.test.ts # Event system tests
1205
- β”œβ”€β”€ storage/
1206
- β”‚ └── storage.test.ts # Storage operation tests
1207
- β”œβ”€β”€ integration/
1208
- β”‚ └── shogunCore.test.ts # Core integration tests
1209
- └── browser/
1210
- └── compatibility.test.ts # Browser compatibility tests
1211
- ```
1212
-
1213
- ## Adding New Tests
1214
-
1215
- When adding new tests:
1216
-
1217
- 1. Follow the existing test structure
1218
- 2. Use descriptive test names
1219
- 3. Test both success and failure cases
1220
- 4. Mock external dependencies appropriately
1221
- 5. Ensure tests are isolated and repeatable
1
+ # Shogun Core πŸ“¦
2
+
3
+ [![npm](https://img.shields.io/badge/npm-v2.0.0-blue)](https://www.npmjs.com/package/shogun-core)
4
+ [![License](https://img.shields.io/badge/license-MIT-yellow)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.3.3-blue)](https://www.typescriptlang.org/)
6
+ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/scobru/shogun-core)
7
+
8
+ ## Overview
9
+
10
+ Shogun Core is a comprehensive SDK for building decentralized applications (dApps) that simplifies authentication, wallet management, and decentralized data storage. It combines GunDB's peer-to-peer networking with modern authentication standards and blockchain integration to provide a secure, user-friendly foundation for Web3 applications.
11
+
12
+ ## Features
13
+
14
+ - πŸ” **Multiple Authentication Methods**: Traditional username/password, WebAuthn (biometrics), Web3 (MetaMask), Nostr, and ZK-Proof (anonymous)
15
+ - 🌐 **Decentralized Storage**: Built on GunDB for peer-to-peer data synchronization
16
+ - πŸ”Œ **Plugin System**: Extensible architecture with built-in plugins for various authentication methods
17
+ - πŸ“± **Reactive Programming**: RxJS integration for real-time data streams
18
+ - πŸ›‘οΈ **Security**: End-to-end encryption and secure key management
19
+ - 🎯 **TypeScript**: Full TypeScript support with comprehensive type definitions
20
+ - πŸ“‘ **Event System**: Typed event system for monitoring authentication and data changes
21
+ - πŸ”‘ **Password Recovery**: Secure password hint system with security questions
22
+ - βœ… **Type Consistency**: Unified return types across all authentication methods
23
+ - πŸš€ **Simplified Architecture**: Focused on core functionality with reduced complexity
24
+ - ⭐ **Simple API**: Easy-to-use wrapper for common operations with minimal complexity
25
+ - πŸ”— **Advanced Chaining**: Powerful chaining operations for complex nested data structures
26
+ - πŸ‘€ **User Space Management**: Complete CRUD operations for user-specific data storage
27
+ - ⚑ **Quick Start**: Rapid initialization with pre-configured setups
28
+ - πŸŽ›οΈ **Configuration Presets**: Pre-built configurations for common use cases
29
+
30
+ ## Recent Updates (v2.0.1)
31
+
32
+ ### πŸ”§ **Critical Bug Fixes**
33
+
34
+ - **πŸ”§ FIXED: Remove Operations**: Fixed critical bug in `remove()` and `removeUserData()` methods that was causing `TypeError: Cannot read properties of null (reading 'err')`
35
+ - **πŸ”§ IMPROVED: User Data Operations**: Rewrote all user data methods to use direct Gun user node for better reliability and error handling
36
+ - **πŸ”§ ENHANCED: Error Handling**: Added proper null checking and improved error logging throughout the user data operations
37
+
38
+ ### βœ… **Major API Improvements & Simplification (v2.1.0)**
39
+
40
+ - **⭐ STREAMLINED: Simple API Layer**: Simplified `SimpleGunAPI` to focus on high-level helpers only
41
+ - Direct database access via `api.database` for basic operations (get, put, auth, etc.)
42
+ - Helper methods for standardized data: profile, settings, preferences, collections
43
+ - Array/Object conversion utilities for GunDB
44
+ - Removed redundant wrapper methods to reduce complexity
45
+ - **⭐ NEW: Quick Start Functions**: `quickStart()`, `autoQuickStart()` classes for rapid initialization
46
+ - **⭐ NEW: Improved Type System**: Reduced `any` usage with better TypeScript types
47
+ - **⭐ NEW: Configuration Presets**: Pre-built configurations for common use cases
48
+ - **⭐ NEW: Advanced API Features**: Comprehensive plugin management, peer network control, advanced user management, and security systems
49
+ - **Enhanced Advanced Features**: Maintained and improved advanced plugin management, peer network management, and user tracking systems
50
+ - **Streamlined Event System**: Enhanced event system with better type safety and comprehensive event handling
51
+ - **Improved Maintainability**: Better organized codebase with clear separation of concerns
52
+ - **Better Performance**: Optimized operations with reduced abstraction layers
53
+
54
+ ### πŸ”§ **Bug Fixes & Improvements**
55
+
56
+ **Fixed Critical Remove Operations Bug**:
57
+ - Fixed `TypeError: Cannot read properties of null (reading 'err')` in `remove()` and `removeUserData()` methods
58
+ - Added proper null checking: `ack && ack.err` instead of just `ack.err`
59
+ - All user data operations now use direct Gun user node for better reliability
60
+ - Improved error handling and logging throughout user data operations
61
+
62
+ ### ⚠️ **BREAKING CHANGES**
63
+
64
+ - **🚨 REMOVED: Array Functions**: `putUserArray()`, `getUserArray()`, `addToUserArray()`, `removeFromUserArray()`, `updateInUserArray()` have been **REMOVED** due to GunDB compatibility issues
65
+ - **⚠️ DEPRECATED: Global Array Functions**: `putArray()`, `getArray()`, `addToArray()`, `removeFromArray()`, `updateInArray()` are deprecated and show warnings
66
+ - **βœ… MIGRATION**: Use **Collections** or **Direct GunDB Operations** instead (see examples below)
67
+
68
+ ## Recent Updates (v1.7.0)
69
+
70
+ ### βœ… **Type System Fixes**
71
+
72
+ - **Unified Return Types**: All authentication methods now use consistent `AuthResult` and `SignUpResult` types
73
+ - **Enhanced SignUpResult**: Extended to support provider-specific authentication data
74
+ - **Type Safety**: Fixed TypeScript inconsistencies across all plugins
75
+ - **API Standardization**: All plugins implement unified `login()` and `signUp()` interfaces
76
+
77
+ ## Installation
78
+
79
+ ```bash
80
+ npm install shogun-core
81
+ # or
82
+ yarn add shogun-core
83
+ ```
84
+
85
+ ## Quick Start
86
+
87
+ ### ⭐ **NEW: Simple API Setup (Recommended)**
88
+
89
+ ```typescript
90
+ import { quickStart, Gun } from "shogun-core";
91
+
92
+ // Create Gun instance
93
+ const gun = Gun({
94
+ peers: ['https://gun-manhattan.herokuapp.com/gun']
95
+ });
96
+
97
+ // Quick start with simple API
98
+ const shogun = quickStart(gun, 'my-app');
99
+ await shogun.init();
100
+
101
+ // Use simplified API
102
+ const user = await shogun.api.signup('alice', 'password123');
103
+ if (user) {
104
+ console.log('User created:', user.username);
105
+
106
+ // User space operations
107
+ await shogun.api.updateProfile({
108
+ name: 'Alice',
109
+ email: 'alice@example.com'
110
+ });
111
+
112
+ await shogun.api.saveSettings({
113
+ theme: 'dark',
114
+ language: 'en'
115
+ });
116
+
117
+ // Create collections
118
+ await shogun.api.createCollection('todos', {
119
+ '1': { text: 'Learn Shogun Core', done: false },
120
+ '2': { text: 'Build dApp', done: false }
121
+ });
122
+ }
123
+ ```
124
+
125
+ ### Advanced Setup (Full Features)
126
+
127
+ ```typescript
128
+ import { ShogunCore } from "shogun-core";
129
+
130
+ // Define your list of Gun peers
131
+ const relays = [
132
+ "wss://ruling-mastodon-improved.ngrok-free.app/gun",
133
+ "https://gun-manhattan.herokuapp.com/gun",
134
+ "https://peer.wallie.io/gun",
135
+ ];
136
+
137
+ // Initialize Shogun Core with plugins
138
+ const shogun = new ShogunCore({
139
+ peers: relays,
140
+ scope: "my-awesome-app",
141
+ authToken: "YOUR_GUN_SUPER_PEER_SECRET", // Optional, for private peers
142
+
143
+ // Enable and configure Web3 (e.g., MetaMask) authentication
144
+ web3: {
145
+ enabled: true,
146
+ },
147
+
148
+ // Enable and configure WebAuthn (biometrics, security keys)
149
+ webauthn: {
150
+ enabled: true,
151
+ rpName: "My Awesome App", // Name of your application
152
+ rpId: window.location.hostname, // Relying party ID
153
+ },
154
+
155
+ // Enable and configure Nostr
156
+ nostr: {
157
+ enabled: true,
158
+ },
159
+
160
+ // Enable and configure ZK-Proof (anonymous authentication)
161
+ zkproof: {
162
+ enabled: true,
163
+ defaultGroupId: "my-app-users",
164
+ },
165
+ });
166
+
167
+ console.log("Shogun Core initialized!");
168
+ ```
169
+
170
+ ## ⭐ **NEW: Simple API**
171
+
172
+ The Simple API provides an easy-to-use interface for common operations with minimal complexity. Perfect for beginners or when you need quick setup.
173
+
174
+ ### Simple API Methods
175
+
176
+ ```typescript
177
+ import { quickStart, Gun } from "shogun-core";
178
+
179
+ const gun = Gun({ peers: ['https://gun-manhattan.herokuapp.com/gun'] });
180
+ const shogun = quickStart(gun, 'my-app');
181
+ await shogun.init();
182
+
183
+ const api = shogun.api;
184
+ const db = api.database; // Access database directly for basic operations
185
+
186
+ // ===== BASIC OPERATIONS (use database) =====
187
+
188
+ // Authentication
189
+ const user = await db.signUp('username', 'password');
190
+ const loginResult = await db.login('username', 'password');
191
+ db.logout();
192
+ const isLoggedIn = db.isLoggedIn();
193
+
194
+ // Basic data operations
195
+ await db.put('path/to/data', { value: 'hello' });
196
+ const data = await db.getData('path/to/data');
197
+ await db.set('path/to/data', { value: 'updated' });
198
+ await db.remove('path/to/data');
199
+
200
+ // Gun node for advanced operations like .map()
201
+ const userNode = db.get('users');
202
+ userNode.map((user, userId) => console.log(`User ${userId}:`, user));
203
+
204
+ // ===== HELPER METHODS (use api) =====
205
+
206
+ // Profile management (standardized location)
207
+ await api.updateProfile({
208
+ name: 'John Doe',
209
+ email: 'john@example.com',
210
+ bio: 'Developer'
211
+ });
212
+ const profile = await api.getProfile();
213
+
214
+ // Settings and preferences (standardized locations)
215
+ await api.saveSettings({ language: 'en', notifications: true });
216
+ const settings = await api.getSettings();
217
+
218
+ await api.savePreferences({ theme: 'dark', fontSize: 14 });
219
+ const preferences = await api.getPreferences();
220
+
221
+ // Collections (standardized location for user collections)
222
+ await api.createCollection('todos', {
223
+ '1': { text: 'Learn Shogun Core', done: false },
224
+ '2': { text: 'Build dApp', done: false }
225
+ });
226
+
227
+ await api.addToCollection('todos', '3', {
228
+ text: 'Deploy to production',
229
+ done: false
230
+ });
231
+
232
+ const todos = await api.getCollection('todos');
233
+ await api.removeFromCollection('todos', '2');
234
+
235
+ // Array utilities for GunDB
236
+ const items = [
237
+ { id: '1', name: 'Item 1' },
238
+ { id: '2', name: 'Item 2' }
239
+ ];
240
+ const indexed = api.arrayToIndexedObject(items); // Convert for GunDB storage
241
+ const restored = api.indexedObjectToArray(indexed); // Convert back
242
+ ```
243
+
244
+ ## πŸ”— **Advanced Gun Operations**
245
+
246
+ For advanced Gun.js operations, use the database instance directly via `api.database` or `shogun.database`:
247
+
248
+ ```typescript
249
+ const db = api.database; // or shogun.database
250
+
251
+ // Store nested data with Gun chaining
252
+ await db.get('users').get('alice').get('profile').put({
253
+ name: 'Alice Smith',
254
+ email: 'alice@example.com',
255
+ preferences: {
256
+ theme: 'dark',
257
+ language: 'en'
258
+ }
259
+ });
260
+
261
+ // Read nested data
262
+ const profile = await db.get('users').get('alice').get('profile').once().then();
263
+
264
+ // Update specific fields
265
+ await db.get('users').get('alice').get('profile').get('preferences').get('theme').put('light');
266
+
267
+ // Iterate over collections with .map()
268
+ db.get('users').map((user, userId) => {
269
+ console.log(`User ${userId}:`, user);
270
+ });
271
+
272
+ // Complex chaining for nested structures
273
+ await db.get('projects').get('my-app').get('tasks').get('1').put({
274
+ title: 'Implement authentication',
275
+ status: 'completed',
276
+ assignee: 'alice'
277
+ });
278
+
279
+ // Access Gun instance directly if needed
280
+ const gunInstance = db.gun;
281
+ gunInstance.get('some-path').on((data) => {
282
+ console.log('Real-time data:', data);
283
+ });
284
+ ```
285
+
286
+ ### Chaining Examples
287
+
288
+ ```typescript
289
+ const db = shogun.database; // or api.database
290
+
291
+ // User management system
292
+ await db.get('users').get('alice').put({
293
+ profile: {
294
+ name: 'Alice',
295
+ email: 'alice@example.com'
296
+ },
297
+ settings: {
298
+ theme: 'dark',
299
+ notifications: true
300
+ },
301
+ posts: {
302
+ '1': { title: 'Hello World', content: 'My first post' },
303
+ '2': { title: 'GunDB is awesome', content: 'Learning decentralized storage' }
304
+ }
305
+ });
306
+
307
+ // Blog system
308
+ await db.get('blog').get('posts').get('2024-01-15').put({
309
+ title: 'Getting Started with Shogun Core',
310
+ author: 'alice',
311
+ content: 'Shogun Core makes decentralized apps easy...',
312
+ tags: ['tutorial', 'decentralized', 'web3'],
313
+ comments: {
314
+ '1': { author: 'bob', text: 'Great tutorial!' },
315
+ '2': { author: 'charlie', text: 'Very helpful, thanks!' }
316
+ }
317
+ });
318
+
319
+ // E-commerce system
320
+ await db.get('shop').get('products').get('laptop-001').put({
321
+ name: 'Gaming Laptop',
322
+ price: 1299.99,
323
+ stock: 15,
324
+ reviews: {
325
+ '1': { user: 'alice', rating: 5, comment: 'Amazing performance!' },
326
+ '2': { user: 'bob', rating: 4, comment: 'Good value for money' }
327
+ }
328
+ });
329
+
330
+ // Read complex nested data
331
+ const product = await db.get('shop').get('products').get('laptop-001').once().then();
332
+ console.log('Product:', product.name);
333
+ console.log('Reviews:', product.reviews);
334
+
335
+ // Update nested data
336
+ await db.get('shop').get('products').get('laptop-001').get('stock').put(12);
337
+ ```
338
+
339
+ ### Best Practices
340
+
341
+ 1. **Use `api.database` or `shogun.database` for direct Gun operations**
342
+ 2. **Use `api` helper methods for standardized data** - profile, settings, collections
343
+ 3. **Keep paths descriptive** - Use meaningful path segments like `users/alice/profile`
344
+ 4. **Handle errors appropriately** - Chaining operations can fail, always check results
345
+ 5. **Use helper methods for conventions** - updateProfile(), saveSettings(), etc. provide standardized locations
346
+
347
+ ## Plugin Authentication APIs
348
+
349
+ Shogun Core provides a unified plugin system for different authentication methods. Each plugin implements standardized `login()` and `signUp()` methods that return consistent `AuthResult` and `SignUpResult` objects.
350
+
351
+ ### Core Types - βœ… **FIXED & UNIFIED**
352
+
353
+ ```typescript
354
+ // Authentication result interface - used by login methods
355
+ interface AuthResult {
356
+ success: boolean;
357
+ error?: string;
358
+ userPub?: string; // User's public key
359
+ username?: string; // Username or identifier
360
+ sessionToken?: string; // Session token if applicable
361
+ authMethod?: AuthMethod; // Authentication method used
362
+ sea?: {
363
+ // GunDB SEA pair for session persistence
364
+ pub: string;
365
+ priv: string;
366
+ epub: string;
367
+ epriv: string;
368
+ };
369
+ // External auth flow properties
370
+ redirectUrl?: string; // Redirect URL for external auth
371
+ pendingAuth?: boolean; // Indicates pending auth flow
372
+ message?: string; // Status message
373
+ provider?: string; // Provider name
374
+ isNewUser?: boolean; // True if this was a registration
375
+ user?: {
376
+ // User data
377
+ userPub?: string;
378
+ username?: string;
379
+ email?: string;
380
+ name?: string;
381
+ picture?: string;
382
+ };
383
+ }
384
+
385
+ // Sign up result interface - used by signUp methods βœ… ENHANCED
386
+ interface SignUpResult {
387
+ success: boolean;
388
+ userPub?: string;
389
+ username?: string;
390
+ pub?: string;
391
+ error?: string;
392
+ message?: string;
393
+ wallet?: any;
394
+ isNewUser?: boolean;
395
+ authMethod?: AuthMethod; // βœ… ADDED
396
+ sessionToken?: string; // βœ… ADDED
397
+ sea?: { pub: string; priv: string; epub: string; epriv: string }; // SEA pair for session persistence
398
+ // Multi-device support (WebAuthn and ZK-Proof)
399
+ seedPhrase?: string; // BIP39 mnemonic or trapdoor for account recovery
400
+ // External auth flow support
401
+ redirectUrl?: string;
402
+ pendingAuth?: boolean;
403
+ provider?: string;
404
+ }
405
+
406
+ // Supported authentication methods
407
+ type AuthMethod =
408
+ | "password"
409
+ | "webauthn"
410
+ | "web3"
411
+ | "nostr"
412
+ | "zkproof"
413
+ | "pair";
414
+ ```
415
+
416
+ ### 1. Traditional Authentication
417
+
418
+ Direct username/password authentication using ShogunCore methods:
419
+
420
+ ```typescript
421
+ // Sign up a new user - Returns SignUpResult βœ…
422
+ const signUpResult: SignUpResult = await shogun.signUp("username", "password");
423
+ if (signUpResult.success) {
424
+ console.log("User created:", signUpResult.username);
425
+ console.log("Is new user:", signUpResult.isNewUser);
426
+ console.log("Auth method:", signUpResult.authMethod);
427
+ }
428
+
429
+ // Login with username and password - Returns AuthResult βœ…
430
+ const loginResult: AuthResult = await shogun.login("username", "password");
431
+ if (loginResult.success) {
432
+ console.log("Logged in as:", loginResult.username);
433
+ console.log("User public key:", loginResult.userPub);
434
+ }
435
+ ```
436
+
437
+ ### 2. Web3 Plugin API
438
+
439
+ Ethereum wallet authentication via MetaMask or other Web3 providers:
440
+
441
+ ```typescript
442
+ const web3Plugin = shogun.getPlugin<Web3ConnectorPlugin>("web3");
443
+
444
+ if (web3Plugin && web3Plugin.isAvailable()) {
445
+ // Connect to MetaMask
446
+ const connectionResult = await web3Plugin.connectMetaMask();
447
+
448
+ if (connectionResult.success) {
449
+ const address = connectionResult.address!;
450
+
451
+ // Login with Web3 wallet - Returns AuthResult βœ…
452
+ const loginResult: AuthResult = await web3Plugin.login(address);
453
+ if (loginResult.success) {
454
+ console.log("Web3 login successful");
455
+ console.log("User public key:", loginResult.userPub);
456
+ }
457
+
458
+ // Register new user with Web3 wallet - Returns SignUpResult βœ…
459
+ const signUpResult: SignUpResult = await web3Plugin.signUp(address);
460
+ if (signUpResult.success) {
461
+ console.log("Web3 registration successful");
462
+ console.log("Is new user:", signUpResult.isNewUser);
463
+ }
464
+ }
465
+ }
466
+
467
+ // Plugin Interface - βœ… FIXED TYPES
468
+ interface Web3ConnectorPluginInterface {
469
+ // Authentication methods
470
+ login(address: string): Promise<AuthResult>; // βœ… CORRECT
471
+ signUp(address: string): Promise<SignUpResult>; // βœ… FIXED
472
+
473
+ // Connection methods
474
+ isAvailable(): boolean;
475
+ connectMetaMask(): Promise<ConnectionResult>;
476
+ getProvider(): Promise<ethers.JsonRpcProvider | ethers.BrowserProvider>;
477
+ getSigner(): Promise<ethers.Signer>;
478
+
479
+ // Credential management
480
+ generateCredentials(address: string): Promise<ISEAPair>;
481
+ generatePassword(signature: string): Promise<string>;
482
+ verifySignature(message: string, signature: string): Promise<string>;
483
+ }
484
+ ```
485
+
486
+ ### 3. WebAuthn Plugin API
487
+
488
+ Biometric and hardware key authentication with **multi-device support via seed phrase**:
489
+
490
+ ```typescript
491
+ const webauthnPlugin = shogun.getPlugin<WebauthnPlugin>("webauthn");
492
+
493
+ if (webauthnPlugin && webauthnPlugin.isSupported()) {
494
+ // ⭐ NEW: Register with seed phrase for multi-device support
495
+ const signUpResult: SignUpResult = await webauthnPlugin.signUp("username", {
496
+ generateSeedPhrase: true // Generate BIP39 seed phrase (default: true)
497
+ });
498
+
499
+ if (signUpResult.success) {
500
+ console.log("WebAuthn registration successful");
501
+ console.log("User public key:", signUpResult.userPub);
502
+
503
+ // ⚠️ CRITICAL: Display seed phrase to user for backup
504
+ if (signUpResult.seedPhrase) {
505
+ console.log("πŸ”‘ SAVE THESE 12 WORDS:");
506
+ console.log(signUpResult.seedPhrase);
507
+ alert(`IMPORTANT: Write down these 12 words to access your account from other devices:\n\n${signUpResult.seedPhrase}`);
508
+ }
509
+ }
510
+
511
+ // ⭐ NEW: Import account on another device using seed phrase
512
+ const importResult = await webauthnPlugin.importFromSeed(
513
+ "username",
514
+ "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12"
515
+ );
516
+
517
+ if (importResult.success) {
518
+ console.log("Account imported successfully!");
519
+ }
520
+
521
+ // Authenticate existing user - Returns AuthResult βœ…
522
+ const loginResult: AuthResult = await webauthnPlugin.login("username");
523
+ if (loginResult.success) {
524
+ console.log("WebAuthn authentication successful");
525
+ console.log("Auth method:", loginResult.authMethod); // "webauthn"
526
+ }
527
+ }
528
+
529
+ // Plugin Interface - βœ… FIXED TYPES
530
+ interface WebauthnPluginInterface {
531
+ // Authentication methods
532
+ login(username: string): Promise<AuthResult>; // βœ… CORRECT
533
+ signUp(username: string): Promise<SignUpResult>; // βœ… FIXED
534
+
535
+ // Capability checks
536
+ isSupported(): boolean;
537
+
538
+ // WebAuthn-specific methods
539
+ register(username: string, displayName?: string): Promise<WebAuthnCredential>;
540
+ authenticate(username?: string): Promise<WebAuthnCredential>;
541
+ generateCredentials(
542
+ username: string,
543
+ pair?: ISEAPair | null,
544
+ login?: boolean
545
+ ): Promise<WebAuthnUniformCredentials>;
546
+ }
547
+ ```
548
+
549
+ ### 4. Nostr Plugin API
550
+
551
+ Bitcoin wallet and Nostr protocol authentication:
552
+
553
+ ```typescript
554
+ const nostrPlugin = shogun.getPlugin<NostrConnectorPlugin>("nostr");
555
+
556
+ if (nostrPlugin && nostrPlugin.isAvailable()) {
557
+ // Connect to Nostr wallet (Bitcoin extension)
558
+ const connectionResult = await nostrPlugin.connectNostrWallet();
559
+
560
+ if (connectionResult.success) {
561
+ const address = connectionResult.address!;
562
+
563
+ // Login with Nostr/Bitcoin wallet - Returns AuthResult βœ…
564
+ const loginResult: AuthResult = await nostrPlugin.login(address);
565
+ if (loginResult.success) {
566
+ console.log("Nostr login successful");
567
+ console.log("Auth method:", loginResult.authMethod); // "nostr"
568
+ }
569
+
570
+ // Register with Nostr/Bitcoin wallet - Returns SignUpResult βœ…
571
+ const signUpResult: SignUpResult = await nostrPlugin.signUp(address);
572
+ if (signUpResult.success) {
573
+ console.log("Nostr registration successful");
574
+ console.log("Is new user:", signUpResult.isNewUser);
575
+ }
576
+ }
577
+ }
578
+
579
+ // Plugin Interface - βœ… FIXED TYPES
580
+ interface NostrConnectorPluginInterface {
581
+ // Authentication methods
582
+ login(address: string): Promise<AuthResult>; // βœ… CORRECT
583
+ signUp(address: string): Promise<SignUpResult>; // βœ… FIXED
584
+
585
+ // Connection methods
586
+ isAvailable(): boolean;
587
+ connectBitcoinWallet(
588
+ type?: "alby" | "nostr" | "manual"
589
+ ): Promise<ConnectionResult>;
590
+ connectNostrWallet(): Promise<ConnectionResult>;
591
+
592
+ // Credential and signature management
593
+ generateCredentials(
594
+ address: string,
595
+ signature: string,
596
+ message: string
597
+ ): Promise<NostrConnectorCredentials>;
598
+ verifySignature(
599
+ message: string,
600
+ signature: string,
601
+ address: string
602
+ ): Promise<boolean>;
603
+ generatePassword(signature: string): Promise<string>;
604
+ }
605
+ ```
606
+
607
+ ### 5. ZK-Proof Plugin API
608
+
609
+ Zero-Knowledge Proof authentication for **anonymous, privacy-preserving authentication**:
610
+
611
+ ```typescript
612
+ const zkPlugin = shogun.getPlugin<ZkProofPlugin>("zkproof");
613
+
614
+ if (zkPlugin && zkPlugin.isAvailable()) {
615
+ // Sign up with ZK-Proof (creates anonymous identity)
616
+ const signUpResult: SignUpResult = await zkPlugin.signUp();
617
+
618
+ if (signUpResult.success) {
619
+ console.log("ZK-Proof registration successful");
620
+ console.log("Public commitment:", signUpResult.username);
621
+
622
+ // ⚠️ CRITICAL: Display trapdoor to user for backup
623
+ if (signUpResult.seedPhrase) {
624
+ console.log("πŸ”‘ SAVE THIS TRAPDOOR:");
625
+ console.log(signUpResult.seedPhrase);
626
+ alert(`IMPORTANT: Save this trapdoor to access your account:\n\n${signUpResult.seedPhrase}`);
627
+ }
628
+ }
629
+
630
+ // Login with trapdoor (anonymous authentication)
631
+ const loginResult: AuthResult = await zkPlugin.login(trapdoor);
632
+ if (loginResult.success) {
633
+ console.log("ZK-Proof login successful (anonymous)");
634
+ console.log("Auth method:", loginResult.authMethod); // "zkproof"
635
+ }
636
+ }
637
+
638
+ // Plugin Interface
639
+ interface ZkProofPluginInterface {
640
+ // Authentication methods
641
+ login(trapdoor: string): Promise<AuthResult>;
642
+ signUp(seed?: string): Promise<SignUpResult>;
643
+
644
+ // ZK identity management
645
+ generateIdentity(seed?: string): Promise<ZkIdentityData>;
646
+ restoreIdentity(trapdoor: string): Promise<ZkIdentityData>;
647
+ generateCredentials(identityData: ZkIdentityData): Promise<ISEAPair>;
648
+
649
+ // ZK proof operations
650
+ generateProof(identityData: ZkIdentityData, options?: ZkProofGenerationOptions): Promise<any>;
651
+ verifyProof(proof: any, treeDepth?: number): Promise<ZkProofVerificationResult>;
652
+
653
+ // Group management
654
+ addToGroup(commitment: string, groupId?: string): void;
655
+ isAvailable(): boolean;
656
+ }
657
+ ```
658
+
659
+ **Advanced: Verifiable Credentials**
660
+
661
+ ZK-Proof can also be used to prove attributes without revealing sensitive data:
662
+
663
+ ```typescript
664
+ import { ZkCredentials, CredentialType } from "shogun-core";
665
+
666
+ const zkCreds = new ZkCredentials();
667
+ const identity = await zkPlugin.generateIdentity();
668
+
669
+ // Prove age without revealing birthdate
670
+ const ageProof = await zkCreds.proveAge(
671
+ identity,
672
+ new Date("1990-01-01"),
673
+ 18
674
+ );
675
+ // βœ… Proves: "I am 18 or older"
676
+ // ❌ Does NOT reveal: actual birthdate or exact age
677
+
678
+ // Prove citizenship without revealing country
679
+ const citizenshipProof = await zkCreds.proveCitizenship(
680
+ identity,
681
+ "Italy",
682
+ "EU"
683
+ );
684
+ // βœ… Proves: "I am an EU citizen"
685
+ // ❌ Does NOT reveal: specific country or passport number
686
+
687
+ // Prove education without revealing institution
688
+ const eduProof = await zkCreds.proveEducation(
689
+ identity,
690
+ "Bachelor of Science",
691
+ "MIT",
692
+ 2020
693
+ );
694
+ // βœ… Proves: "I have a Bachelor of Science degree"
695
+ // ❌ Does NOT reveal: university name or grades
696
+
697
+ // Prove income without revealing exact amount
698
+ const incomeProof = await zkCreds.proveIncome(
699
+ identity,
700
+ 75000,
701
+ 50000,
702
+ "USD"
703
+ );
704
+ // βœ… Proves: "Income β‰₯ $50,000"
705
+ // ❌ Does NOT reveal: exact salary or employer
706
+ ```
707
+
708
+ **Use Cases:**
709
+ - Anonymous authentication
710
+ - Age verification (18+, 21+, etc.)
711
+ - Citizenship/residency proofs
712
+ - Education credentials
713
+ - Income verification for loans
714
+ - Employment status
715
+ - KYC compliance without revealing PII
716
+ - Anonymous voting and polls
717
+
718
+ See `src/examples/zkproof-credentials-example.ts` for complete examples.
719
+
720
+ ### Comparison of Authentication Methods
721
+
722
+ | Feature | Password | WebAuthn | Web3 | Nostr | ZK-Proof |
723
+ |---------|----------|----------|------|-------|----------|
724
+ | **Anonymous** | ❌ | ❌ | ❌ | ❌ | βœ… |
725
+ | **Multi-device** | βœ… | βœ… (seed) | βœ… | βœ… | βœ… (trapdoor) |
726
+ | **Hardware-free** | βœ… | ❌ | ❌ | ❌ | βœ… |
727
+ | **Privacy** | ⚠️ | ⚠️ | ⚠️ | ⚠️ | βœ… |
728
+ | **No wallet needed** | βœ… | βœ… | ❌ | ❌ | βœ… |
729
+ | **Verifiable credentials** | ❌ | ❌ | ❌ | ❌ | βœ… |
730
+ | **Group membership proofs** | ❌ | ❌ | ❌ | ❌ | βœ… |
731
+ | **Ease of use** | βœ…βœ…βœ… | βœ…βœ… | βœ…βœ… | βœ…βœ… | βœ…βœ… |
732
+
733
+ **Quick Setup:**
734
+ ```bash
735
+ # Install dependencies
736
+ yarn add shogun-core
737
+
738
+ # For ZK-Proof circuit files (optional, for advanced proofs)
739
+ cd shogun-core
740
+ yarn setup:zkproof
741
+
742
+ # Run examples
743
+ yarn zkproof:example
744
+ yarn zkproof:credentials
745
+ ```
746
+
747
+ ## ⭐ Multi-Device Support with Seed Phrases
748
+
749
+ WebAuthn authentication now supports **multi-device access** through BIP39 seed phrases, solving the device-bound limitation of traditional WebAuthn.
750
+
751
+ ### The Problem with Traditional WebAuthn
752
+
753
+ WebAuthn credentials are **device-specific** by design:
754
+ - Each device generates unique, non-exportable credentials
755
+ - Cannot transfer credentials between devices
756
+ - Changing devices means losing access to your account
757
+
758
+ ### The Shogun Core Solution: Seed Phrases
759
+
760
+ When you register with WebAuthn, Shogun Core generates a **12-word BIP39 mnemonic** (seed phrase):
761
+
762
+ ```typescript
763
+ const signUpResult = await webauthnPlugin.signUp("alice", {
764
+ generateSeedPhrase: true // Default: true
765
+ });
766
+
767
+ // ⚠️ CRITICAL: User MUST save these words!
768
+ console.log("Your seed phrase:", signUpResult.seedPhrase);
769
+ // Example: "abandon ability able about above absent absorb abstract absurd abuse access accident"
770
+ ```
771
+
772
+ ### Benefits
773
+
774
+ βœ… **Same Account, Multiple Devices**: Access your account from any device
775
+ βœ… **Account Recovery**: Restore access if you lose your device
776
+ βœ… **Decentralized**: No need for password reset emails or centralized recovery
777
+ βœ… **Compatible**: Works with any BIP39-compatible wallet
778
+ βœ… **Secure**: 128-bit entropy, cryptographically secure
779
+
780
+ ### Usage Examples
781
+
782
+ #### Registration on First Device (iPhone)
783
+
784
+ ```typescript
785
+ const webauthnPlugin = shogun.getPlugin<WebauthnPlugin>("webauthn");
786
+
787
+ // Register with Face ID
788
+ const result = await webauthnPlugin.signUp("alice", {
789
+ generateSeedPhrase: true
790
+ });
791
+
792
+ if (result.success && result.seedPhrase) {
793
+ // Display to user with clear warning
794
+ showSeedPhraseBackupUI(result.seedPhrase);
795
+ // Example: "ability abandon about above absent absorb abstract absurd abuse access accident account"
796
+ }
797
+ ```
798
+
799
+ #### Import on Second Device (Windows PC)
800
+
801
+ ```typescript
802
+ // User enters their 12-word seed phrase
803
+ const seedPhrase = getUserInputSeedPhrase();
804
+
805
+ // Import account using seed phrase
806
+ const result = await webauthnPlugin.importFromSeed("alice", seedPhrase);
807
+
808
+ if (result.success) {
809
+ console.log("Account imported! You can now use Windows Hello.");
810
+ }
811
+ ```
812
+
813
+ ### User Interface Example
814
+
815
+ ```tsx
816
+ // React component for seed phrase backup
817
+ function SeedPhraseBackup({ seedPhrase }: { seedPhrase: string }) {
818
+ const words = seedPhrase.split(' ');
819
+
820
+ return (
821
+ <div className="seed-phrase-backup">
822
+ <h2>πŸ”‘ Save Your Recovery Phrase</h2>
823
+ <p><strong>Write down these 12 words in order</strong></p>
824
+ <p className="warning">
825
+ ⚠️ Without these words, you cannot recover your account or access it from other devices!
826
+ </p>
827
+
828
+ <div className="word-grid">
829
+ {words.map((word, index) => (
830
+ <div key={index} className="word-item">
831
+ <span className="word-number">{index + 1}.</span>
832
+ <span className="word-text">{word}</span>
833
+ </div>
834
+ ))}
835
+ </div>
836
+
837
+ <div className="actions">
838
+ <button onClick={() => downloadSeedPhrase(seedPhrase)}>
839
+ πŸ“₯ Download as Text File
840
+ </button>
841
+ <button onClick={() => printSeedPhrase(seedPhrase)}>
842
+ πŸ–¨οΈ Print on Paper
843
+ </button>
844
+ </div>
845
+
846
+ <label>
847
+ <input type="checkbox" required />
848
+ I have safely stored my 12-word recovery phrase
849
+ </label>
850
+ </div>
851
+ );
852
+ }
853
+ ```
854
+
855
+ ### Security Best Practices
856
+
857
+ 1. **Never store seed phrases digitally** - Write them on paper
858
+ 2. **Keep multiple backups** - Store in different secure locations
859
+ 3. **Never share your seed phrase** - Anyone with it can access your account
860
+ 4. **Verify before moving on** - Double-check you wrote it correctly
861
+ 5. **Use steel backup** - For maximum durability (fire/water proof)
862
+
863
+ ### Legacy Device-Bound Mode
864
+
865
+ If you don't need multi-device support, you can disable seed phrase generation:
866
+
867
+ ```typescript
868
+ const result = await webauthnPlugin.signUp("alice", {
869
+ generateSeedPhrase: false // Device-bound only
870
+ });
871
+ // No seed phrase returned - traditional WebAuthn behavior
872
+ ```
873
+
874
+ ### Browser Usage (via CDN)
875
+
876
+ You can also use Shogun Core directly in the browser by including it from a CDN. This is ideal for static sites or lightweight applications.
877
+
878
+ ```html
879
+ <!DOCTYPE html>
880
+ <html>
881
+ <head>
882
+ <title>Shogun Core in Browser</title>
883
+ </head>
884
+ <body>
885
+ <h1>My dApp</h1>
886
+ <!-- Required dependencies for Shogun Core -->
887
+ <script src="https://cdn.jsdelivr.net/npm/gun/gun.js"></script>
888
+ <script src="https://cdn.jsdelivr.net/npm/gun/sea.js"></script>
889
+
890
+ <!-- Shogun Core library -->
891
+ <script src="https://cdn.jsdelivr.net/npm/shogun-core/dist/browser/shogun-core.js"></script>
892
+
893
+ <script>
894
+ // Access the global Shogun Core function
895
+ const shogunCore = window.SHOGUN_CORE({
896
+ peers: ["https://gun-manhattan.herokuapp.com/gun"],
897
+ scope: "my-browser-app",
898
+ web3: { enabled: true },
899
+ webauthn: {
900
+ enabled: true,
901
+ rpName: "My Browser dApp",
902
+ rpId: window.location.hostname,
903
+ },
904
+ });
905
+
906
+ console.log("Shogun Core initialized in browser!", shogunCore);
907
+
908
+ async function connectWallet() {
909
+ if (shogunCore.hasPlugin("web3")) {
910
+ const web3Plugin = shogunCore.getPlugin("web3");
911
+ try {
912
+ const provider = await web3Plugin.getProvider();
913
+ const signer = provider.getSigner();
914
+ const address = await signer.getAddress();
915
+ await web3Plugin.login(address);
916
+ console.log("Logged in with address:", address);
917
+ } catch (error) {
918
+ console.error("Web3 login failed:", error);
919
+ }
920
+ }
921
+ }
922
+ </script>
923
+ </body>
924
+ </html>
925
+ ```
926
+
927
+ ## API Reference
928
+
929
+ ### ⭐ **Simple API Methods**
930
+
931
+ #### Authentication
932
+ - `signup(username: string, password: string): Promise<UserInfo | null>` - Create new user account
933
+ - `login(username: string, password: string): Promise<UserInfo | null>` - Authenticate with username/password
934
+ - `logout(): void` - Logout current user
935
+ - `isLoggedIn(): boolean` - Check if user is authenticated
936
+
937
+ #### Data Operations
938
+ - `get<T>(path: string): Promise<T | null>` - Get data from path
939
+ - `put<T>(path: string, data: T): Promise<boolean>` - Store data at path
940
+ - `set<T>(path: string, data: T): Promise<boolean>` - Update data at path
941
+ - `remove(path: string): Promise<boolean>` - Remove data from path
942
+
943
+ #### Advanced Chaining Operations (NEW!)
944
+ - `node(path: string): GunNode` - Get Gun node for direct chaining (recommended)
945
+ - `chain(path: string): ChainingWrapper` - Get simplified chaining wrapper
946
+ - `getNode(path: string): GunNode` - Get Gun node for advanced operations like .map()
947
+
948
+ #### User Space Operations
949
+ - `putUserData<T>(path: string, data: T): Promise<boolean>` - Store user-specific data
950
+ - `getUserData<T>(path: string): Promise<T | null>` - Get user-specific data
951
+ - `setUserData<T>(path: string, data: T): Promise<boolean>` - Update user-specific data
952
+ - `removeUserData(path: string): Promise<boolean>` - Remove user-specific data
953
+ - `getAllUserData(): Promise<Record<string, unknown> | null>` - Get all user data
954
+
955
+ #### Profile & Settings
956
+ - `updateProfile(profileData: ProfileData): Promise<boolean>` - Update user profile
957
+ - `getProfile(): Promise<Record<string, unknown> | null>` - Get user profile
958
+ - `saveSettings(settings: Record<string, unknown>): Promise<boolean>` - Save user settings
959
+ - `getSettings(): Promise<Record<string, unknown> | null>` - Get user settings
960
+ - `savePreferences(preferences: Record<string, unknown>): Promise<boolean>` - Save user preferences
961
+ - `getPreferences(): Promise<Record<string, unknown> | null>` - Get user preferences
962
+
963
+ #### Collections
964
+ - `createCollection<T>(name: string, items: Record<string, T>): Promise<boolean>` - Create user collection
965
+ - `addToCollection<T>(name: string, itemId: string, item: T): Promise<boolean>` - Add item to collection
966
+ - `getCollection(name: string): Promise<Record<string, unknown> | null>` - Get collection
967
+ - `removeFromCollection(name: string, itemId: string): Promise<boolean>` - Remove item from collection
968
+
969
+ #### Utility Functions
970
+ - `arrayToIndexedObject<T>(arr: T[]): Record<string, T>` - Convert array to indexed object (helper)
971
+ - `indexedObjectToArray<T>(indexedObj: Record<string, T>): T[]` - Convert indexed object to array (helper)
972
+
973
+ #### ⚠️ **REMOVED FUNCTIONS**
974
+ The following array functions have been **REMOVED** due to GunDB compatibility issues:
975
+ - `putUserArray()`, `getUserArray()`, `addToUserArray()`, `removeFromUserArray()`, `updateInUserArray()`
976
+
977
+ **Use collections or direct GunDB operations instead** (see examples above).
978
+
979
+ ### Advanced API Methods
980
+
981
+ #### Core Authentication
982
+ - `login(username: string, password: string): Promise<AuthResult>` - Authenticate with username/password
983
+ - `loginWithPair(pair: ISEAPair): Promise<AuthResult>` - Authenticate directly with a GunDB SEA pair
984
+ - `signUp(username: string, password: string, email?: string, pair?: ISEAPair | null): Promise<SignUpResult>` - Create new user account
985
+ - `logout(): void` - Logout current user
986
+ - `isLoggedIn(): boolean` - Check if user is authenticated
987
+ - `setAuthMethod(method: AuthMethod): void` - Set authentication method
988
+ - `getAuthMethod(): AuthMethod | undefined` - Get current authentication method
989
+ - `saveCredentials(credentials: any): Promise<void>` - Save user credentials
990
+
991
+ #### Plugin Management
992
+ - `getPlugin<T>(name: string): T | undefined` - Get plugin by name
993
+ - `hasPlugin(name: string): boolean` - Check if plugin exists
994
+ - `register(plugin: ShogunPlugin): void` - Register custom plugin
995
+ - `unregister(pluginName: string): void` - Remove plugin
996
+ - `getPluginsInfo(): Array<{name: string; version: string; category?: PluginCategory; description?: string}>` - Get detailed plugin information
997
+ - `getPluginCount(): number` - Get total number of plugins
998
+ - `getPluginsInitializationStatus(): Record<string, {initialized: boolean; error?: string}>` - Check plugin initialization status
999
+ - `getPluginsByCategory(category: PluginCategory): ShogunPlugin[]` - Get plugins by category
1000
+ - `validatePluginSystem(): {...}` - Validate plugin system health
1001
+ - `reinitializeFailedPlugins(): {...}` - Reinitialize failed plugins
1002
+ - `checkPluginCompatibility(): {...}` - Check plugin compatibility
1003
+ - `getPluginSystemDebugInfo(): {...}` - Get comprehensive debug information
1004
+
1005
+ #### Peer Network Management (Database)
1006
+ - `addPeer(peer: string): void` - Add new peer to network
1007
+ - `removePeer(peer: string): void` - Remove peer from network
1008
+ - `getCurrentPeers(): string[]` - Get currently connected peers
1009
+ - `getAllConfiguredPeers(): string[]` - Get all configured peers
1010
+ - `getPeerInfo(): {[peer: string]: {connected: boolean; status: string}}` - Get detailed peer information
1011
+ - `reconnectToPeer(peer: string): void` - Reconnect to specific peer
1012
+ - `resetPeers(newPeers?: string[]): void` - Reset all peers and optionally add new ones
1013
+
1014
+ #### Advanced User Management (Database)
1015
+ - `getUserByAlias(alias: string): Promise<{...}>` - Get user by alias/username
1016
+ - `getUserDataByPub(userPub: string): Promise<{...}>` - Get user by public key
1017
+ - `getUserPubByEpub(epub: string): Promise<string | null>` - Get user public key by encryption key
1018
+ - `getUserAliasByPub(userPub: string): Promise<string | null>` - Get user alias by public key
1019
+ - `getAllRegisteredUsers(): Promise<Array<{...}>>` - Get all registered users
1020
+ - `updateUserLastSeen(userPub: string): Promise<void>` - Update user's last seen timestamp
1021
+
1022
+ #### Password Recovery & Security (Database)
1023
+ - `setPasswordHintWithSecurity(username: string, password: string, hint: string, securityQuestions: string[], securityAnswers: string[]): Promise<{success: boolean; error?: string}>` - Set up password recovery
1024
+ - `forgotPassword(username: string, securityAnswers: string[]): Promise<{success: boolean; hint?: string; error?: string}>` - Recover password
1025
+
1026
+ #### Error Handling & Debugging
1027
+ - `getRecentErrors(count?: number): ShogunError[]` - Get recent errors for debugging
1028
+
1029
+ #### Event Handling
1030
+ - `on<K extends keyof ShogunEventMap>(eventName: K, listener: Function): this` - Subscribe to typed events
1031
+ - `off<K extends keyof ShogunEventMap>(eventName: K, listener: Function): this` - Unsubscribe from events
1032
+ - `once<K extends keyof ShogunEventMap>(eventName: K, listener: Function): this` - Subscribe to one-time events
1033
+ - `emit<K extends keyof ShogunEventMap>(eventName: K, data?: ShogunEventMap[K]): boolean` - Emit custom events
1034
+ - `removeAllListeners(eventName?: string | symbol): this` - Remove all event listeners
1035
+
1036
+ ### Configuration Options
1037
+
1038
+ ```typescript
1039
+ interface ShogunCoreConfig {
1040
+ peers?: string[]; // GunDB peer URLs
1041
+ scope?: string; // Application scope
1042
+ authToken?: string; // GunDB super peer secret
1043
+ appToken?: string; // Application token
1044
+
1045
+ // Plugin configurations
1046
+ webauthn?: {
1047
+ enabled?: boolean;
1048
+ rpName?: string;
1049
+ rpId?: string;
1050
+ };
1051
+
1052
+ web3?: {
1053
+ enabled?: boolean;
1054
+ };
1055
+
1056
+ nostr?: {
1057
+ enabled?: boolean;
1058
+ };
1059
+
1060
+ zkproof?: {
1061
+ enabled?: boolean;
1062
+ defaultGroupId?: string;
1063
+ deterministic?: boolean;
1064
+ };
1065
+
1066
+ // Timeouts
1067
+ timeouts?: {
1068
+ login?: number;
1069
+ signup?: number;
1070
+ operation?: number;
1071
+ };
1072
+ }
1073
+ ```
1074
+
1075
+ ## Event System
1076
+
1077
+ Shogun Core provides a comprehensive typed event system for monitoring authentication and data changes:
1078
+
1079
+ ```typescript
1080
+ // Available events with their data types
1081
+ interface ShogunEventMap {
1082
+ "auth:login": AuthEventData; // User logged in
1083
+ "auth:logout": void; // User logged out
1084
+ "auth:signup": AuthEventData; // New user registered
1085
+ "plugin:registered": { name: string; version?: string; category?: string }; // Plugin registered
1086
+ "plugin:unregistered": { name: string }; // Plugin unregistered
1087
+ debug: { action: string; [key: string]: any }; // Debug information
1088
+ error: ErrorEventData; // Error occurred
1089
+ }
1090
+
1091
+ // Listen for authentication events with full type safety
1092
+ shogun.on("auth:login", (data) => {
1093
+ console.log("User logged in:", data.username);
1094
+ console.log("Authentication method:", data.method);
1095
+ if (data.provider) {
1096
+ console.log("Provider:", data.provider);
1097
+ }
1098
+ });
1099
+
1100
+ shogun.on("auth:logout", () => {
1101
+ console.log("User logged out");
1102
+ });
1103
+
1104
+ shogun.on("auth:signup", (data) => {
1105
+ console.log("New user signed up:", data.username);
1106
+ });
1107
+
1108
+ // Listen for errors
1109
+ shogun.on("error", (error) => {
1110
+ console.error("Shogun error:", error.message);
1111
+ });
1112
+ ```
1113
+
1114
+ ## Password Recovery System
1115
+
1116
+ Shogun Core includes a secure password recovery system using security questions:
1117
+
1118
+ ```typescript
1119
+ // Set password hint with security questions
1120
+ await shogun.db.setPasswordHint(
1121
+ "username",
1122
+ "password",
1123
+ "My favorite color",
1124
+ ["What is your favorite color?", "What was your first pet's name?"],
1125
+ ["blue", "fluffy"]
1126
+ );
1127
+
1128
+ // Recover password using security answers
1129
+ const result = await shogun.db.forgotPassword("username", ["blue", "fluffy"]);
1130
+
1131
+ if (result.success) {
1132
+ console.log("Password hint:", result.hint);
1133
+ }
1134
+ ```
1135
+
1136
+ Note: The cryptographic wallet derivation feature has been removed in v1.9.5 to simplify the architecture.
1137
+
1138
+ ## Error Handling
1139
+
1140
+ Shogun Core includes comprehensive error handling with typed errors:
1141
+
1142
+ ```typescript
1143
+ import { ShogunError, ErrorType } from "shogun-core";
1144
+
1145
+ try {
1146
+ await shogun.login("username", "password");
1147
+ } catch (error) {
1148
+ if (error instanceof ShogunError) {
1149
+ switch (error.type) {
1150
+ case ErrorType.AUTHENTICATION:
1151
+ console.error("Invalid credentials");
1152
+ break;
1153
+ case ErrorType.NETWORK:
1154
+ console.error("Network connection failed");
1155
+ break;
1156
+ default:
1157
+ console.error("Unknown error:", error.message);
1158
+ }
1159
+ }
1160
+ }
1161
+ ```
1162
+
1163
+ ## Contributing
1164
+
1165
+ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
1166
+
1167
+ ## License
1168
+
1169
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
1170
+
1171
+ ## SHIP Standards (Shogun Interface Proposals)
1172
+
1173
+ Shogun Core implements **SHIP standards** - modular, composable protocols for decentralized applications:
1174
+
1175
+ - **[SHIP-00](./ship/SHIP_00.md)**: Identity & Authentication Foundation
1176
+ - **[SHIP-01](./ship/SHIP_01.md)**: Decentralized Encrypted Messaging
1177
+ - **[SHIP-02](./ship/SHIP_02.md)**: Ethereum HD Wallet & Transaction Sending
1178
+ - **[SHIP-03](./ship/SHIP_03.md)**: Dual-Key Stealth Addresses (ERC-5564)
1179
+ - **[SHIP-04](./ship/SHIP_04.md)**: Multi-Modal Authentication (WebAuthn/Web3/Nostr/ZK-Proof)
1180
+
1181
+ See [ship/README.md](./ship/README.md) for complete SHIP documentation and examples.
1182
+
1183
+ ## Advanced Features
1184
+
1185
+ For advanced use cases and comprehensive API coverage, see the [Advanced API Features](./API.md#advanced-api-features) section which includes:
1186
+
1187
+ - **Advanced Plugin Management**: Plugin health monitoring, compatibility checking, and system validation
1188
+ - **Peer Network Management**: Dynamic peer connection management and network monitoring
1189
+ - **Advanced User Management**: Comprehensive user lookup, tracking, and metadata management
1190
+ - **Password Recovery & Security**: Secure password hint system with security questions
1191
+ - **Error Handling & Debugging**: Advanced error tracking and debugging capabilities
1192
+ - **Event System**: Complete event handling reference with type safety
1193
+ - **Database Lifecycle**: Advanced database initialization and management
1194
+
1195
+ ## Support
1196
+
1197
+ - πŸ“– [Documentation](https://shogun-core-docs.vercel.app/)
1198
+ - πŸ“š [Advanced API Reference](./API.md#advanced-api-features)
1199
+ - πŸ’¬ [Telegram Community](t.me/shogun_eco)
1200
+ - πŸ› [Issue Tracker](https://github.com/scobru/shogun-core/issues)
1201
+
1202
+ # SHOGUN CORE
1203
+
1204
+ Core library for Shogun Ecosystem
1205
+
1206
+ ## Testing
1207
+
1208
+ This project includes a comprehensive test suite that covers all major functionality and has been recently updated to align with the current codebase structure.
1209
+
1210
+ ### βœ… **Test Suite Status (Updated)**
1211
+
1212
+ - **βœ… All Tests Passing**: 696+ tests pass successfully
1213
+ - **βœ… Plugin System**: Complete plugin functionality testing
1214
+ - **βœ… Authentication Methods**: All auth methods (WebAuthn, Web3, Nostr, ZK-Proof) tested
1215
+ - **βœ… Simple API**: Full coverage of SimpleGunAPI functionality
1216
+ - **βœ… Error Handling**: Comprehensive error handling and edge case testing
1217
+ - **βœ… Browser Compatibility**: Cross-browser support validation
1218
+ - **βœ… Integration Tests**: End-to-end functionality testing
1219
+
1220
+ ### Test Coverage
1221
+
1222
+ This project includes a comprehensive test suite that covers:
1223
+
1224
+ ### Unit Tests
1225
+
1226
+ - **Validation Utils** (`src/__tests__/utils/validation.test.ts`)
1227
+ - Username validation
1228
+ - Email validation
1229
+ - Username generation from identity
1230
+ - Deterministic password generation
1231
+
1232
+ - **Error Handler** (`src/__tests__/utils/errorHandler.test.ts`)
1233
+ - Error creation and handling
1234
+ - Error statistics and logging
1235
+ - Retry logic
1236
+ - External logger integration
1237
+
1238
+ - **Event Emitter** (`src/__tests__/utils/eventEmitter.test.ts`)
1239
+ - Event registration and emission
1240
+ - Listener management
1241
+ - Error handling in listeners
1242
+ - Symbol events support
1243
+
1244
+ - **Storage** (`src/__tests__/storage/storage.test.ts`)
1245
+ - Memory and localStorage operations
1246
+ - Error handling
1247
+ - Test mode behavior
1248
+ - Data persistence
1249
+
1250
+ ### Integration Tests
1251
+
1252
+ - **ShogunCore** (`src/__tests__/integration/shogunCore.test.ts`)
1253
+ - Plugin system validation
1254
+ - Authentication methods
1255
+ - Event system
1256
+ - Configuration handling
1257
+ - Error handling
1258
+
1259
+ ### Browser Compatibility Tests
1260
+
1261
+ - **Compatibility** (`src/__tests__/browser/compatibility.test.ts`)
1262
+ - localStorage availability
1263
+ - Crypto API support
1264
+ - WebAuthn detection
1265
+ - Web3 provider detection
1266
+ - Event system compatibility
1267
+ - TextEncoder/TextDecoder support
1268
+ - Fetch API compatibility
1269
+ - URL API compatibility
1270
+ - Performance API compatibility
1271
+ - Console API compatibility
1272
+
1273
+ ## Running Tests
1274
+
1275
+ You can eseguire i test sia dalla root del monorepo sia entrando nella cartella `shogun-core`.
1276
+
1277
+ Inside `shogun-core/` directory:
1278
+
1279
+ ```bash
1280
+ # Install deps
1281
+ yarn install
1282
+
1283
+ # Tutti i test (una sola esecuzione) con coverage
1284
+ yarn test:ci
1285
+
1286
+ # Watch mode
1287
+ yarn test:watch
1288
+
1289
+ # Coverage (report HTML in coverage/lcov-report/index.html)
1290
+ yarn coverage
1291
+
1292
+ # Solo i test dei plugin
1293
+ yarn test src/__tests__/plugins
1294
+
1295
+ # Evita conflitti di config Jest (se servisse)
1296
+ yarn jest --ci --coverage --watchAll=false --config jest.config.js
1297
+ ```
1298
+
1299
+ From repository root (senza cambiare directory):
1300
+
1301
+ ```bash
1302
+ # Install deps
1303
+ yarn --cwd shogun-core install
1304
+
1305
+ # Tutti i test con coverage (CI‑like)
1306
+ yarn --cwd shogun-core test:ci
1307
+
1308
+ # Solo plugin tests
1309
+ yarn --cwd shogun-core test src/__tests__/plugins
1310
+
1311
+ # Coverage
1312
+ yarn --cwd shogun-core coverage
1313
+
1314
+ # Watch mode
1315
+ yarn --cwd shogun-core test:watch
1316
+
1317
+ # Se compaiono piΓΉ configurazioni Jest, specifica esplicitamente il config file
1318
+ yarn --cwd shogun-core jest --ci --coverage --watchAll=false --config jest.config.js
1319
+ ```
1320
+
1321
+ CI & QA scripts:
1322
+
1323
+ ```bash
1324
+ # Mutation testing (Stryker) – piΓΉ lento, richiede devDeps installate
1325
+ yarn --cwd shogun-core mutation
1326
+
1327
+ # SAST (Semgrep) – richiede semgrep installato (es. `pip install semgrep`)
1328
+ yarn --cwd shogun-core sast
1329
+ ```
1330
+
1331
+ ## Test Coverage
1332
+
1333
+ The test suite provides comprehensive coverage of:
1334
+
1335
+ - βœ… **Utility Functions** - 100% coverage
1336
+ - βœ… **Error Handling** - 100% coverage
1337
+ - βœ… **Event System** - 100% coverage
1338
+ - βœ… **Storage Operations** - 100% coverage
1339
+ - βœ… **Plugin System** - API validation
1340
+ - βœ… **Browser Compatibility** - Cross-browser support
1341
+ - βœ… **Configuration Validation** - Config handling
1342
+
1343
+ ## Test Philosophy
1344
+
1345
+ These tests are designed to be **realistic and non-intrusive**:
1346
+
1347
+ - **No codebase modifications** - Tests work with existing code
1348
+ - **Comprehensive coverage** - All public APIs tested
1349
+ - **Error resilience** - Tests error handling and edge cases
1350
+ - **Browser compatibility** - Cross-browser support validation
1351
+ - **Performance aware** - Tests don't impact runtime performance
1352
+
1353
+ ## Test Structure
1354
+
1355
+ ```
1356
+ src/__tests__/
1357
+ β”œβ”€β”€ setup.ts # Global test setup
1358
+ β”œβ”€β”€ utils/
1359
+ β”‚ β”œβ”€β”€ validation.test.ts # Validation utility tests
1360
+ β”‚ β”œβ”€β”€ errorHandler.test.ts # Error handling tests
1361
+ β”‚ └── eventEmitter.test.ts # Event system tests
1362
+ β”œβ”€β”€ storage/
1363
+ β”‚ └── storage.test.ts # Storage operation tests
1364
+ β”œβ”€β”€ integration/
1365
+ β”‚ └── shogunCore.test.ts # Core integration tests
1366
+ └── browser/
1367
+ └── compatibility.test.ts # Browser compatibility tests
1368
+ ```
1369
+
1370
+ ## Adding New Tests
1371
+
1372
+ When adding new tests:
1373
+
1374
+ 1. Follow the existing test structure
1375
+ 2. Use descriptive test names
1376
+ 3. Test both success and failure cases
1377
+ 4. Mock external dependencies appropriately
1378
+ 5. Ensure tests are isolated and repeatable