shogun-core 3.3.7 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +1378 -1221
  2. package/dist/browser/shogun-core.js +78074 -45286
  3. package/dist/browser/shogun-core.js.map +1 -1
  4. package/dist/core.js +2 -3
  5. package/dist/examples/simple-api-test.js +90 -65
  6. package/dist/examples/zkproof-credentials-example.js +218 -0
  7. package/dist/examples/zkproof-example.js +206 -0
  8. package/dist/gundb/api.js +111 -467
  9. package/dist/index.js +10 -1
  10. package/dist/interfaces/shogun.js +2 -2
  11. package/dist/managers/AuthManager.js +0 -2
  12. package/dist/managers/CoreInitializer.js +9 -12
  13. package/dist/plugins/index.js +9 -21
  14. package/dist/plugins/nostr/nostrConnectorPlugin.js +2 -2
  15. package/dist/plugins/webauthn/webauthn.js +20 -7
  16. package/dist/plugins/webauthn/webauthnPlugin.js +101 -17
  17. package/dist/plugins/zkproof/index.js +53 -0
  18. package/dist/plugins/zkproof/zkCredentials.js +213 -0
  19. package/dist/plugins/zkproof/zkProofConnector.js +198 -0
  20. package/dist/plugins/zkproof/zkProofPlugin.js +272 -0
  21. package/dist/types/core.d.ts +1 -1
  22. package/dist/types/examples/simple-api-test.d.ts +6 -1
  23. package/dist/types/examples/zkproof-credentials-example.d.ts +12 -0
  24. package/dist/types/examples/zkproof-example.d.ts +11 -0
  25. package/dist/types/gundb/api.d.ts +77 -165
  26. package/dist/types/gundb/types.d.ts +1 -1
  27. package/dist/types/index.d.ts +1 -0
  28. package/dist/types/interfaces/events.d.ts +3 -3
  29. package/dist/types/interfaces/shogun.d.ts +9 -24
  30. package/dist/types/plugins/index.d.ts +5 -3
  31. package/dist/types/plugins/webauthn/types.d.ts +22 -1
  32. package/dist/types/plugins/webauthn/webauthn.d.ts +1 -1
  33. package/dist/types/plugins/webauthn/webauthnPlugin.d.ts +23 -2
  34. package/dist/types/plugins/zkproof/index.d.ts +48 -0
  35. package/dist/types/plugins/zkproof/types.d.ts +123 -0
  36. package/dist/types/plugins/zkproof/zkCredentials.d.ts +112 -0
  37. package/dist/types/plugins/zkproof/zkProofConnector.d.ts +46 -0
  38. package/dist/types/plugins/zkproof/zkProofPlugin.d.ts +76 -0
  39. package/dist/types/utils/seedPhrase.d.ts +50 -0
  40. package/dist/types/utils/validation.d.ts +2 -2
  41. package/dist/utils/seedPhrase.js +97 -0
  42. package/dist/utils/validation.js +3 -1
  43. package/package.json +14 -8
  44. package/dist/examples/api-test.js +0 -273
  45. package/dist/migration-test.js +0 -96
  46. package/dist/plugins/oauth/index.js +0 -8
  47. package/dist/plugins/oauth/oauthConnector.js +0 -759
  48. package/dist/plugins/oauth/oauthPlugin.js +0 -400
  49. package/dist/types/examples/api-test.d.ts +0 -12
  50. package/dist/types/migration-test.d.ts +0 -16
  51. package/dist/types/plugins/oauth/index.d.ts +0 -3
  52. package/dist/types/plugins/oauth/oauthConnector.d.ts +0 -110
  53. package/dist/types/plugins/oauth/oauthPlugin.d.ts +0 -91
  54. package/dist/types/plugins/oauth/types.d.ts +0 -114
  55. /package/dist/plugins/{oauth → zkproof}/types.js +0 -0
package/dist/core.js CHANGED
@@ -318,13 +318,12 @@ class ShogunCore {
318
318
  }
319
319
  }
320
320
  exports.ShogunCore = ShogunCore;
321
- ShogunCore.API_VERSION = "^3.0.11";
321
+ ShogunCore.API_VERSION = "^3.3.8";
322
322
  // Global declarations are handled in the original core.ts file
323
323
  // to avoid conflicts, we only set the window properties here
324
324
  if (typeof window !== "undefined") {
325
- window.SHOGUN_CORE = (config) => {
325
+ window.Shogun = (config) => {
326
326
  return new ShogunCore(config);
327
327
  };
328
- window.SHOGUN_CORE_CLASS = ShogunCore;
329
328
  }
330
329
  exports.default = ShogunCore;
@@ -1,87 +1,112 @@
1
1
  "use strict";
2
2
  /**
3
- * Esempio semplice che mostra le differenze principali tra i metodi API
3
+ * Example showing how to use the simplified ShogunCore API
4
+ *
5
+ * The API has been streamlined:
6
+ * - AutoQuickStart: Quick initialization helper
7
+ * - api.database: Direct access to DataBase for basic operations (get, put, set, remove, auth)
8
+ * - api helper methods: High-level helpers for profile, settings, collections, and array utilities
4
9
  */
5
10
  Object.defineProperty(exports, "__esModule", { value: true });
6
11
  exports.simpleAPITest = simpleAPITest;
7
12
  const api_1 = require("../gundb/api");
8
13
  async function simpleAPITest() {
9
- console.log("šŸš€ Test semplice API ShogunCore\n");
10
- // Setup
14
+ console.log("šŸš€ ShogunCore Simplified API Example\n");
15
+ // === QUICK START ===
16
+ console.log("šŸ“¦ === INITIALIZATION ===\n");
17
+ // Use AutoQuickStart for easy setup
11
18
  const quickStart = new api_1.AutoQuickStart({
12
19
  peers: ["https://peer.wallie.io/gun"],
13
20
  appScope: "simple-test",
14
21
  });
15
22
  await quickStart.init();
23
+ // Access the API and database
16
24
  const api = quickStart.api;
17
- // === DIFFERENZE PRINCIPALI ===
18
- console.log("šŸ“Š === DIFFERENZE GET ===\n");
19
- // 1. get() - restituisce dati direttamente
20
- const data1 = await api.get("test/path");
21
- console.log('get("test/path"):', data1); // null o dati
22
- // 2. getNode() - restituisce nodo Gun per chaining
23
- const node1 = api.getNode("test/path");
24
- console.log('getNode("test/path"):', typeof node1); // "object" (Gun node)
25
- // 3. node() - alias di getNode()
26
- const node2 = api.node("test/path");
27
- console.log('node("test/path"):', typeof node2); // "object" (Gun node)
28
- // 4. chain() - wrapper con metodi di convenienza
29
- const chain1 = api.chain("test/path");
30
- console.log('chain("test/path"):', Object.keys(chain1)); // ['get', 'put', 'set', 'once', 'then', 'map']
31
- console.log("\nšŸ’¾ === DIFFERENZE PUT/SET ===\n");
25
+ const db = api.database; // Direct access to DataBase for basic operations
26
+ console.log("Initialized successfully!");
27
+ console.log("- api: provides helper methods");
28
+ console.log("- db (api.database): provides full DataBase functionality\n");
29
+ // === BASIC OPERATIONS (via database) ===
30
+ console.log("šŸ’¾ === BASIC OPERATIONS (use api.database) ===\n");
32
31
  const testData = { message: "Hello World", timestamp: Date.now() };
33
- // 1. put() - salva dati globali
34
- const putResult = await api.put("global/data", testData);
35
- console.log("put() result:", putResult); // true/false
36
- // 2. set() - come put() ma semantica diversa
37
- const setResult = await api.set("global/data2", {
38
- ...testData,
39
- method: "set",
40
- });
41
- console.log("set() result:", setResult); // true/false
42
- // Verifica
43
- const retrieved1 = await api.get("global/data");
44
- const retrieved2 = await api.get("global/data2");
45
- console.log("Retrieved put data:", retrieved1);
46
- console.log("Retrieved set data:", retrieved2);
47
- console.log("\nšŸ—‘ļø === DIFFERENZE REMOVE ===\n");
48
- // remove() - rimuove dati globali
49
- const removeResult = await api.remove("global/data2");
50
- console.log("remove() result:", removeResult); // true/false
51
- const afterRemove = await api.get("global/data2");
52
- console.log("Data after remove:", afterRemove); // null
53
- console.log("\nšŸ” === TEST AUTENTICAZIONE ===\n");
54
- // Signup e login
32
+ // Use db for basic operations
33
+ await db.put("global/data", testData);
34
+ console.log("āœ“ Saved data with db.put()");
35
+ const retrieved = await db.getData("global/data");
36
+ console.log("āœ“ Retrieved data with db.getData():", retrieved);
37
+ await db.remove("global/data");
38
+ console.log("āœ“ Removed data with db.remove()\n");
39
+ // === AUTHENTICATION (via database) ===
40
+ console.log("šŸ” === AUTHENTICATION (use api.database) ===\n");
55
41
  const username = "testuser_" + Date.now();
56
42
  const password = "testpass123";
57
- const signupResult = await api.signup(username, password);
58
- console.log("Signup result:", signupResult);
59
- if (signupResult) {
60
- const loginResult = await api.login(username, password);
61
- console.log("Login result:", loginResult);
62
- if (loginResult) {
63
- console.log("\nšŸ‘¤ === OPERAZIONI UTENTE ===\n");
64
- // getUserData() - per dati utente
65
- const userData = await api.getUserData("profile");
66
- console.log('getUserData("profile"):', userData); // null o dati utente
67
- // putUserData() - salva dati utente
68
- const profileData = { name: "Test User", email: "test@example.com" };
69
- const putUserResult = await api.putUserData("profile", profileData);
70
- console.log("putUserData() result:", putUserResult); // true/false
71
- // Verifica dati utente
72
- const retrievedProfile = await api.getUserData("profile");
73
- console.log("Retrieved profile:", retrievedProfile);
74
- // removeUserData() - rimuove dati utente
75
- const removeUserResult = await api.removeUserData("profile");
76
- console.log("removeUserData() result:", removeUserResult); // true/false
77
- const afterRemoveUser = await api.getUserData("profile");
78
- console.log("User data after remove:", afterRemoveUser); // null
43
+ const signupResult = await db.signUp(username, password);
44
+ console.log("āœ“ Signup:", signupResult.success ? "Success" : "Failed");
45
+ if (signupResult.success) {
46
+ const loginResult = await db.login(username, password);
47
+ console.log("āœ“ Login:", loginResult.success ? "Success" : "Failed");
48
+ if (loginResult.success) {
49
+ console.log("āœ“ Current user:", db.getCurrentUser()?.alias, "\n");
50
+ // === HELPER METHODS (via api) ===
51
+ console.log("⭐ === HELPER METHODS (use api helpers) ===\n");
52
+ // Profile helper
53
+ await api.updateProfile({
54
+ name: "Test User",
55
+ email: "test@example.com",
56
+ bio: "Testing the simplified API",
57
+ });
58
+ console.log("āœ“ Profile updated with api.updateProfile()");
59
+ const profile = await api.getProfile();
60
+ console.log("āœ“ Profile retrieved:", profile);
61
+ // Settings helper
62
+ await api.saveSettings({
63
+ theme: "dark",
64
+ language: "en",
65
+ notifications: true,
66
+ });
67
+ console.log("āœ“ Settings saved with api.saveSettings()");
68
+ const settings = await api.getSettings();
69
+ console.log("āœ“ Settings retrieved:", settings);
70
+ // Collections helper
71
+ await api.createCollection("favorites", {
72
+ item1: { id: "item1", title: "First Item" },
73
+ item2: { id: "item2", title: "Second Item" },
74
+ });
75
+ console.log("āœ“ Collection created with api.createCollection()");
76
+ await api.addToCollection("favorites", "item3", {
77
+ id: "item3",
78
+ title: "Third Item",
79
+ });
80
+ console.log("āœ“ Item added with api.addToCollection()");
81
+ const collection = await api.getCollection("favorites");
82
+ console.log("āœ“ Collection retrieved:", collection);
83
+ // === ARRAY UTILITIES ===
84
+ console.log("\nšŸ”§ === ARRAY UTILITIES ===\n");
85
+ const items = [
86
+ { id: "1", name: "Item 1", value: 100 },
87
+ { id: "2", name: "Item 2", value: 200 },
88
+ { id: "3", name: "Item 3", value: 300 },
89
+ ];
90
+ // Convert array to GunDB-friendly indexed object
91
+ const indexed = api.arrayToIndexedObject(items);
92
+ console.log("āœ“ Array converted to indexed object:", indexed);
93
+ // Convert back to array
94
+ const restored = api.indexedObjectToArray(indexed);
95
+ console.log("āœ“ Indexed object converted back to array:", restored);
79
96
  // Logout
80
- api.logout();
81
- console.log("Logged out");
97
+ db.logout();
98
+ console.log("\nāœ“ Logged out");
82
99
  }
83
100
  }
84
- console.log("\nāœ… Test completato!");
101
+ console.log("\nāœ… Example completed!");
102
+ console.log("\nSummary:");
103
+ console.log("- Use AutoQuickStart for easy initialization");
104
+ console.log("- Use api.database for basic operations (get, put, auth, etc.)");
105
+ console.log("- Use api helper methods for high-level operations:");
106
+ console.log(" • updateProfile(), getProfile()");
107
+ console.log(" • saveSettings(), getSettings()");
108
+ console.log(" • createCollection(), addToCollection(), getCollection()");
109
+ console.log(" • arrayToIndexedObject(), indexedObjectToArray()");
85
110
  }
86
111
  // Esegui il test
87
112
  if (require.main === module) {
@@ -0,0 +1,218 @@
1
+ "use strict";
2
+ /**
3
+ * ZK-Proof Verifiable Credentials Example
4
+ *
5
+ * This demonstrates how to use ZK-Proof for proving attributes
6
+ * about documents and identity without revealing sensitive data
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.ageVerificationExample = ageVerificationExample;
10
+ exports.citizenshipExample = citizenshipExample;
11
+ exports.educationExample = educationExample;
12
+ exports.incomeExample = incomeExample;
13
+ exports.customCredentialExample = customCredentialExample;
14
+ const core_1 = require("../core");
15
+ const zkCredentials_1 = require("../plugins/zkproof/zkCredentials");
16
+ const shogun_relays_1 = require("shogun-relays");
17
+ const identity_1 = require("@semaphore-protocol/identity");
18
+ // Example 1: Age Verification
19
+ async function ageVerificationExample() {
20
+ console.log("=== Age Verification Example ===\n");
21
+ const relays = await (0, shogun_relays_1.forceListUpdate)();
22
+ const shogun = new core_1.ShogunCore({
23
+ gunOptions: { peers: relays },
24
+ zkproof: { enabled: true },
25
+ });
26
+ await new Promise((resolve) => setTimeout(resolve, 100));
27
+ const zkPlugin = shogun.getPlugin("zkproof");
28
+ if (!zkPlugin)
29
+ return;
30
+ // Create ZK identity
31
+ const identity = await zkPlugin.generateIdentity();
32
+ const semaphoreIdentity = new identity_1.Identity(identity.trapdoor);
33
+ // Create credentials manager
34
+ const zkCreds = new zkCredentials_1.ZkCredentials();
35
+ console.log("Scenario: User wants to prove they're 18+ without revealing birthdate\n");
36
+ // User's actual birthdate (PRIVATE)
37
+ const birthDate = new Date("1990-05-15");
38
+ const actualAge = Math.floor((Date.now() - birthDate.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
39
+ console.log(`Private data (NOT revealed):`);
40
+ console.log(` Birth date: ${birthDate.toDateString()}`);
41
+ console.log(` Actual age: ${actualAge}\n`);
42
+ try {
43
+ // Generate proof that age >= 18 WITHOUT revealing exact age
44
+ const ageProof = await zkCreds.proveAge(semaphoreIdentity, birthDate, 18);
45
+ console.log(`Public proof generated:`);
46
+ console.log(` Claim: "${ageProof.claim}"`);
47
+ console.log(` Type: ${ageProof.type}`);
48
+ console.log(` āœ… Birth date NOT revealed!`);
49
+ console.log(` āœ… Exact age NOT revealed!`);
50
+ // Anyone can verify the proof
51
+ const verification = await zkCreds.verifyCredential(ageProof);
52
+ console.log(`\nVerification result: ${verification.verified ? "āœ… VALID" : "āŒ INVALID"}`);
53
+ }
54
+ catch (error) {
55
+ console.log(`Note: Full proof generation requires circuit files`);
56
+ console.log(`Run: yarn setup:zkproof`);
57
+ }
58
+ }
59
+ // Example 2: Citizenship Verification
60
+ async function citizenshipExample() {
61
+ console.log("\n=== Citizenship Verification Example ===\n");
62
+ const relays = await (0, shogun_relays_1.forceListUpdate)();
63
+ const shogun = new core_1.ShogunCore({
64
+ gunOptions: { peers: relays },
65
+ zkproof: { enabled: true },
66
+ });
67
+ await new Promise((resolve) => setTimeout(resolve, 100));
68
+ const zkPlugin = shogun.getPlugin("zkproof");
69
+ if (!zkPlugin)
70
+ return;
71
+ const identity = await zkPlugin.generateIdentity();
72
+ const semaphoreIdentity = new identity_1.Identity(identity.trapdoor);
73
+ const zkCreds = new zkCredentials_1.ZkCredentials();
74
+ console.log("Scenario: Prove EU citizenship without revealing country\n");
75
+ console.log(`Private data (NOT revealed):`);
76
+ console.log(` Country: Italy`);
77
+ console.log(` Passport: IT123456789\n`);
78
+ try {
79
+ const citizenshipProof = await zkCreds.proveCitizenship(semaphoreIdentity, "Italy", "EU");
80
+ console.log(`Public proof:`);
81
+ console.log(` Claim: "${citizenshipProof.claim}"`);
82
+ console.log(` āœ… Specific country NOT revealed!`);
83
+ console.log(` āœ… Passport number NOT revealed!`);
84
+ }
85
+ catch (error) {
86
+ console.log(`Note: Full proof requires circuit files`);
87
+ }
88
+ }
89
+ // Example 3: Education Credentials
90
+ async function educationExample() {
91
+ console.log("\n=== Education Credential Example ===\n");
92
+ const relays = await (0, shogun_relays_1.forceListUpdate)();
93
+ const shogun = new core_1.ShogunCore({
94
+ gunOptions: { peers: relays },
95
+ zkproof: { enabled: true },
96
+ });
97
+ await new Promise((resolve) => setTimeout(resolve, 100));
98
+ const zkPlugin = shogun.getPlugin("zkproof");
99
+ if (!zkPlugin)
100
+ return;
101
+ const identity = await zkPlugin.generateIdentity();
102
+ const semaphoreIdentity = new identity_1.Identity(identity.trapdoor);
103
+ const zkCreds = new zkCredentials_1.ZkCredentials();
104
+ console.log("Scenario: Prove you have a degree without revealing details\n");
105
+ console.log(`Private data (NOT revealed):`);
106
+ console.log(` University: MIT`);
107
+ console.log(` Degree: Computer Science`);
108
+ console.log(` Year: 2020`);
109
+ console.log(` Grade: 110/110\n`);
110
+ try {
111
+ const eduProof = await zkCreds.proveEducation(semaphoreIdentity, "Bachelor of Science", "MIT", 2020);
112
+ console.log(`Public proof:`);
113
+ console.log(` Claim: "${eduProof.claim}"`);
114
+ console.log(` āœ… University name NOT revealed!`);
115
+ console.log(` āœ… Grades NOT revealed!`);
116
+ console.log(` āœ… Only proves you HAVE the degree`);
117
+ }
118
+ catch (error) {
119
+ console.log(`Note: Full proof requires circuit files`);
120
+ }
121
+ }
122
+ // Example 4: Income Verification
123
+ async function incomeExample() {
124
+ console.log("\n=== Income Verification Example ===\n");
125
+ const relays = await (0, shogun_relays_1.forceListUpdate)();
126
+ const shogun = new core_1.ShogunCore({
127
+ gunOptions: { peers: relays },
128
+ zkproof: { enabled: true },
129
+ });
130
+ await new Promise((resolve) => setTimeout(resolve, 100));
131
+ const zkPlugin = shogun.getPlugin("zkproof");
132
+ if (!zkPlugin)
133
+ return;
134
+ const identity = await zkPlugin.generateIdentity();
135
+ const semaphoreIdentity = new identity_1.Identity(identity.trapdoor);
136
+ const zkCreds = new zkCredentials_1.ZkCredentials();
137
+ console.log("Scenario: Apply for loan proving income > 50k without revealing exact salary\n");
138
+ console.log(`Private data (NOT revealed):`);
139
+ console.log(` Actual salary: 75,000 EUR`);
140
+ console.log(` Employer: Tech Company XYZ\n`);
141
+ try {
142
+ const incomeProof = await zkCreds.proveIncome(semaphoreIdentity, 75000, 50000, "EUR");
143
+ console.log(`Public proof sent to bank:`);
144
+ console.log(` Claim: "${incomeProof.claim}"`);
145
+ console.log(` āœ… Exact salary NOT revealed!`);
146
+ console.log(` āœ… Only proves income >= 50,000 EUR`);
147
+ console.log(`\n Bank sees: "This person earns at least 50k"`);
148
+ console.log(` Bank does NOT see: Actual amount or employer`);
149
+ }
150
+ catch (error) {
151
+ console.log(`Note: Full proof requires circuit files`);
152
+ }
153
+ }
154
+ // Example 5: Custom Credential
155
+ async function customCredentialExample() {
156
+ console.log("\n=== Custom Credential Example ===\n");
157
+ const relays = await (0, shogun_relays_1.forceListUpdate)();
158
+ const shogun = new core_1.ShogunCore({
159
+ gunOptions: { peers: relays },
160
+ zkproof: { enabled: true },
161
+ });
162
+ await new Promise((resolve) => setTimeout(resolve, 100));
163
+ const zkPlugin = shogun.getPlugin("zkproof");
164
+ if (!zkPlugin)
165
+ return;
166
+ const identity = await zkPlugin.generateIdentity();
167
+ const semaphoreIdentity = new identity_1.Identity(identity.trapdoor);
168
+ const zkCreds = new zkCredentials_1.ZkCredentials();
169
+ console.log("Scenario: Prove you're a verified developer without revealing GitHub profile\n");
170
+ console.log(`Private data (NOT revealed):`);
171
+ console.log(` GitHub: @johndoe`);
172
+ console.log(` Repositories: 150`);
173
+ console.log(` Stars: 5,234`);
174
+ console.log(` Years active: 8\n`);
175
+ try {
176
+ const devProof = await zkCreds.proveAttribute(semaphoreIdentity, {
177
+ type: zkCredentials_1.CredentialType.CUSTOM,
178
+ claim: "Verified GitHub developer with 5+ years experience",
179
+ privateData: {
180
+ githubUsername: "johndoe",
181
+ repositories: 150,
182
+ stars: 5234,
183
+ yearsActive: 8,
184
+ verified: true,
185
+ },
186
+ });
187
+ console.log(`Public proof:`);
188
+ console.log(` Claim: "${devProof.claim}"`);
189
+ console.log(` āœ… GitHub username NOT revealed!`);
190
+ console.log(` āœ… Exact stats NOT revealed!`);
191
+ console.log(` āœ… Privacy-preserving reputation proof`);
192
+ }
193
+ catch (error) {
194
+ console.log(`Note: Full proof requires circuit files`);
195
+ }
196
+ }
197
+ // Run all examples
198
+ async function main() {
199
+ console.log("šŸ” ZK-Proof Verifiable Credentials Examples");
200
+ console.log("==========================================\n");
201
+ try {
202
+ await ageVerificationExample();
203
+ await citizenshipExample();
204
+ await educationExample();
205
+ await incomeExample();
206
+ await customCredentialExample();
207
+ console.log("\n✨ All credential examples completed!");
208
+ console.log("\nā„¹ļø Note: These examples show the credential structure.");
209
+ console.log(" For full ZK proof generation, run: yarn setup:zkproof");
210
+ }
211
+ catch (error) {
212
+ console.error("\nāŒ Error:", error);
213
+ }
214
+ process.exit(0);
215
+ }
216
+ if (require.main === module) {
217
+ main();
218
+ }
@@ -0,0 +1,206 @@
1
+ "use strict";
2
+ /**
3
+ * Zero-Knowledge Proof Authentication Example
4
+ *
5
+ * This example demonstrates how to use the ZK-Proof plugin with Shogun Core
6
+ * for privacy-preserving authentication using Semaphore protocol.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.basicExample = basicExample;
10
+ exports.deterministicExample = deterministicExample;
11
+ exports.proofExample = proofExample;
12
+ exports.multiDeviceExample = multiDeviceExample;
13
+ const core_1 = require("../core");
14
+ const shogun_relays_1 = require("shogun-relays");
15
+ // Example 1: Basic ZK-Proof signup and login
16
+ async function basicExample() {
17
+ console.log("=== Basic ZK-Proof Authentication Example ===\n");
18
+ const relays = await (0, shogun_relays_1.forceListUpdate)();
19
+ // Initialize Shogun with ZK-Proof plugin
20
+ const shogun = new core_1.ShogunCore({
21
+ gunOptions: {
22
+ peers: relays,
23
+ },
24
+ zkproof: {
25
+ enabled: true,
26
+ defaultGroupId: "my-app-users",
27
+ },
28
+ });
29
+ // Wait for plugin initialization
30
+ await new Promise((resolve) => setTimeout(resolve, 100));
31
+ // Get the ZK-Proof plugin
32
+ const zkPlugin = shogun.getPlugin("zkproof");
33
+ if (!zkPlugin) {
34
+ console.error("ZK-Proof plugin not available");
35
+ return;
36
+ }
37
+ // SIGN UP - Generate new anonymous identity
38
+ console.log("1. Creating new ZK identity...");
39
+ const signupResult = await zkPlugin.signUp();
40
+ if (signupResult.success) {
41
+ console.log("āœ… Signup successful!");
42
+ console.log(` Username (commitment): ${signupResult.username}`);
43
+ console.log(` User Public Key: ${signupResult.userPub?.slice(0, 16)}...`);
44
+ console.log("\nāš ļø CRITICAL: Save this trapdoor for account recovery:");
45
+ console.log(` Trapdoor: ${signupResult.seedPhrase}\n`);
46
+ // Simulate user saving the trapdoor
47
+ const savedTrapdoor = signupResult.seedPhrase;
48
+ // Logout
49
+ shogun.logout();
50
+ console.log("2. Logged out\n");
51
+ // LOGIN - Authenticate with trapdoor
52
+ console.log("3. Logging in with trapdoor...");
53
+ const loginResult = await zkPlugin.login(savedTrapdoor);
54
+ if (loginResult.success) {
55
+ console.log("āœ… Login successful!");
56
+ console.log(` Username: ${loginResult.username}`);
57
+ console.log(` User Public Key: ${loginResult.userPub?.slice(0, 16)}...`);
58
+ console.log(` Auth Method: ${loginResult.authMethod}`);
59
+ }
60
+ else {
61
+ console.error("āŒ Login failed:", loginResult.error);
62
+ }
63
+ }
64
+ else {
65
+ console.error("āŒ Signup failed:", signupResult.error);
66
+ }
67
+ }
68
+ // Example 2: Deterministic identity generation
69
+ async function deterministicExample() {
70
+ console.log("\n=== Deterministic ZK Identity Example ===\n");
71
+ const relays = await (0, shogun_relays_1.forceListUpdate)();
72
+ const shogun = new core_1.ShogunCore({
73
+ gunOptions: {
74
+ peers: relays,
75
+ },
76
+ zkproof: {
77
+ enabled: true,
78
+ deterministic: true,
79
+ },
80
+ });
81
+ // Wait for plugin initialization
82
+ await new Promise((resolve) => setTimeout(resolve, 100));
83
+ const zkPlugin = shogun.getPlugin("zkproof");
84
+ if (!zkPlugin) {
85
+ console.error("ZK-Proof plugin not available");
86
+ return;
87
+ }
88
+ // Use a seed for deterministic generation
89
+ const seed = "my-secret-seed-phrase-12345";
90
+ console.log("1. Creating identity from seed...");
91
+ const signupResult = await zkPlugin.signUp(seed);
92
+ if (signupResult.success) {
93
+ console.log("āœ… Identity created from seed");
94
+ console.log(` Commitment: ${signupResult.username}`);
95
+ // With the same seed, you'll always get the same identity
96
+ const identity2 = await zkPlugin.generateIdentity(seed);
97
+ console.log("\n2. Regenerating from same seed...");
98
+ console.log(` Same commitment? ${identity2.commitment === signupResult.username?.replace("zk_", "")}`);
99
+ }
100
+ }
101
+ // Example 3: Generate and verify ZK proofs
102
+ async function proofExample() {
103
+ console.log("\n=== ZK Proof Generation & Verification Example ===\n");
104
+ const relays = await (0, shogun_relays_1.forceListUpdate)();
105
+ const shogun = new core_1.ShogunCore({
106
+ gunOptions: {
107
+ peers: relays,
108
+ },
109
+ zkproof: {
110
+ enabled: true,
111
+ defaultGroupId: "proof-demo-group",
112
+ },
113
+ });
114
+ // Wait for plugin initialization
115
+ await new Promise((resolve) => setTimeout(resolve, 100));
116
+ const zkPlugin = shogun.getPlugin("zkproof");
117
+ if (!zkPlugin) {
118
+ console.error("ZK-Proof plugin not available");
119
+ return;
120
+ }
121
+ // Create identity
122
+ console.log("1. Generating identity...");
123
+ const identity = await zkPlugin.generateIdentity();
124
+ console.log(` Commitment: ${identity.commitment.slice(0, 16)}...`);
125
+ // Add to group
126
+ console.log("\n2. Adding to group...");
127
+ zkPlugin.addToGroup(identity.commitment, "proof-demo-group");
128
+ // Generate proof of membership
129
+ console.log("\n3. Generating ZK proof...");
130
+ const proof = await zkPlugin.generateProof(identity, {
131
+ groupId: "proof-demo-group",
132
+ message: "I am a member of this group",
133
+ scope: "membership-verification",
134
+ });
135
+ console.log(" Proof generated!");
136
+ console.log(` Merkle root: ${proof.merkleTreeRoot.slice(0, 16)}...`);
137
+ console.log(` Nullifier hash: ${proof.nullifierHash.slice(0, 16)}...`);
138
+ // Verify the proof
139
+ console.log("\n4. Verifying proof...");
140
+ const verificationResult = await zkPlugin.verifyProof(proof);
141
+ if (verificationResult.verified) {
142
+ console.log("āœ… Proof verified successfully!");
143
+ console.log(" User proved group membership without revealing identity");
144
+ }
145
+ else {
146
+ console.error("āŒ Proof verification failed");
147
+ }
148
+ }
149
+ // Example 4: Multi-device scenario
150
+ async function multiDeviceExample() {
151
+ console.log("\n=== Multi-Device ZK Authentication Example ===\n");
152
+ const relays = await (0, shogun_relays_1.forceListUpdate)();
153
+ // Device 1: Create account
154
+ console.log("šŸ“± DEVICE 1: Creating account...");
155
+ const shogun1 = new core_1.ShogunCore({
156
+ gunOptions: {
157
+ peers: relays,
158
+ },
159
+ zkproof: { enabled: true },
160
+ });
161
+ // Wait for plugin initialization
162
+ await new Promise((resolve) => setTimeout(resolve, 100));
163
+ const zkPlugin1 = shogun1.getPlugin("zkproof");
164
+ const signupResult = await zkPlugin1.signUp();
165
+ console.log("āœ… Account created on Device 1");
166
+ console.log(` Commitment: ${signupResult.username}`);
167
+ // User writes down the trapdoor
168
+ const trapdoor = signupResult.seedPhrase;
169
+ console.log(`\nšŸ“ User writes down trapdoor: ${trapdoor.slice(0, 20)}...`);
170
+ // Device 2: Import account
171
+ console.log("\nšŸ’» DEVICE 2: Importing account with trapdoor...");
172
+ const shogun2 = new core_1.ShogunCore({
173
+ gunOptions: {
174
+ peers: relays,
175
+ },
176
+ zkproof: { enabled: true },
177
+ });
178
+ // Wait for plugin initialization
179
+ await new Promise((resolve) => setTimeout(resolve, 100));
180
+ const zkPlugin2 = shogun2.getPlugin("zkproof");
181
+ const loginResult = await zkPlugin2.login(trapdoor);
182
+ if (loginResult.success) {
183
+ console.log("āœ… Successfully logged in on Device 2");
184
+ console.log(` Same user: ${loginResult.username === signupResult.username}`);
185
+ console.log("\nšŸŽ‰ Multi-device authentication working!");
186
+ }
187
+ }
188
+ // Run examples
189
+ async function main() {
190
+ try {
191
+ // Run all examples
192
+ await basicExample();
193
+ await deterministicExample();
194
+ // await proofExample(); // Requires ZK circuit files - see README for setup
195
+ await multiDeviceExample();
196
+ console.log("\n✨ All examples completed successfully!");
197
+ }
198
+ catch (error) {
199
+ console.error("\nāŒ Error running examples:", error);
200
+ }
201
+ process.exit(0);
202
+ }
203
+ // Run if executed directly
204
+ if (require.main === module) {
205
+ main();
206
+ }