shogun-core 4.2.6 β†’ 5.1.1

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