shogun-core 5.0.0 → 5.1.2

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