UNPKG

shogun-core

Version:

SHOGUN CORE - Core library for Shogun Ecosystem

358 lines (357 loc) 18.9 kB
/** * Zero-Knowledge Proof Authentication Example * * This example demonstrates how to use the ZK-Proof plugin with Shogun Core * for privacy-preserving authentication using Semaphore protocol. */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; import { Gun } from '../index.js'; import { ShogunCore } from '../core.js'; // Example 1: Basic ZK-Proof signup and login function basicExample() { return __awaiter(this, void 0, void 0, function () { var gunInstance, shogun, zkPlugin, signupResult, savedTrapdoor, loginResult; var _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: console.log('=== Basic ZK-Proof Authentication Example ===\n'); gunInstance = Gun({ peers: [ 'https://g3ru5bwxmezpuu3ktnoclbpiw4.srv.us/gun', 'https://5eh4twk2f62autunsje4panime.srv.us/gun', ], radisk: false, localStorage: false, // Enable for testing - allows offline operations // Reduce log noise from SEA verification errors (these are expected when checking invalid credentials) log: function () { }, // Disable Gun.js console logging to reduce noise }); shogun = new ShogunCore({ gunInstance: gunInstance, zkproof: { enabled: true, defaultGroupId: 'my-app-users', }, }); // Wait for plugin initialization return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 100); })]; case 1: // Wait for plugin initialization _c.sent(); zkPlugin = shogun.getPlugin('zkproof'); if (!zkPlugin) { console.error('ZK-Proof plugin not available'); return [2 /*return*/]; } // SIGN UP - Generate new anonymous identity console.log('1. Creating new ZK identity...'); return [4 /*yield*/, zkPlugin.signUp()]; case 2: signupResult = _c.sent(); if (!signupResult.success) return [3 /*break*/, 4]; console.log('✅ Signup successful!'); console.log(" Username (commitment): ".concat(signupResult.username)); console.log(" User Public Key: ".concat((_a = signupResult.userPub) === null || _a === void 0 ? void 0 : _a.slice(0, 16), "...")); console.log('\n⚠️ CRITICAL: Save this trapdoor for account recovery:'); console.log(" Trapdoor: ".concat(signupResult.seedPhrase, "\n")); savedTrapdoor = signupResult.seedPhrase; // Logout shogun.logout(); console.log('2. Logged out\n'); // LOGIN - Authenticate with trapdoor console.log('3. Logging in with trapdoor...'); return [4 /*yield*/, zkPlugin.login(savedTrapdoor)]; case 3: loginResult = _c.sent(); if (loginResult.success) { console.log('✅ Login successful!'); console.log(" Username: ".concat(loginResult.username)); console.log(" User Public Key: ".concat((_b = loginResult.userPub) === null || _b === void 0 ? void 0 : _b.slice(0, 16), "...")); console.log(" Auth Method: ".concat(loginResult.authMethod)); } else { console.error('❌ Login failed:', loginResult.error); } return [3 /*break*/, 5]; case 4: console.error('❌ Signup failed:', signupResult.error); _c.label = 5; case 5: return [2 /*return*/]; } }); }); } // Example 2: Deterministic identity generation function deterministicExample() { return __awaiter(this, void 0, void 0, function () { var gunInstance, shogun, zkPlugin, seed, signupResult, identity2; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: console.log('\n=== Deterministic ZK Identity Example ===\n'); gunInstance = Gun({ peers: [ 'https://lindanode.scobrudot.dev/gun', 'https://shogunnode.scobrudot.dev/gun', ], radisk: false, localStorage: false, // Enable for testing - allows offline operations // Reduce log noise from SEA verification errors (these are expected when checking invalid credentials) log: function () { }, // Disable Gun.js console logging to reduce noise }); shogun = new ShogunCore({ gunInstance: gunInstance, zkproof: { enabled: true, deterministic: true, }, }); // Wait for plugin initialization return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 100); })]; case 1: // Wait for plugin initialization _b.sent(); zkPlugin = shogun.getPlugin('zkproof'); if (!zkPlugin) { console.error('ZK-Proof plugin not available'); return [2 /*return*/]; } seed = 'my-secret-seed-phrase-12345'; console.log('1. Creating identity from seed...'); return [4 /*yield*/, zkPlugin.signUp(seed)]; case 2: signupResult = _b.sent(); if (!signupResult.success) return [3 /*break*/, 4]; console.log('✅ Identity created from seed'); console.log(" Commitment: ".concat(signupResult.username)); return [4 /*yield*/, zkPlugin.generateIdentity(seed)]; case 3: identity2 = _b.sent(); console.log('\n2. Regenerating from same seed...'); console.log(" Same commitment? ".concat(identity2.commitment === ((_a = signupResult.username) === null || _a === void 0 ? void 0 : _a.replace('zk_', '')))); _b.label = 4; case 4: return [2 /*return*/]; } }); }); } // Example 3: Generate and verify ZK proofs function proofExample() { return __awaiter(this, void 0, void 0, function () { var gunInstance, shogun, zkPlugin, identity, proof, verificationResult; return __generator(this, function (_a) { switch (_a.label) { case 0: console.log('\n=== ZK Proof Generation & Verification Example ===\n'); gunInstance = Gun({ peers: [ 'https://lindanode.scobrudot.dev/gun', 'https://shogunnode.scobrudot.dev/gun', ], radisk: false, localStorage: false, // Enable for testing - allows offline operations // Reduce log noise from SEA verification errors (these are expected when checking invalid credentials) log: function () { }, // Disable Gun.js console logging to reduce noise }); shogun = new ShogunCore({ gunInstance: gunInstance, zkproof: { enabled: true, defaultGroupId: 'proof-demo-group', }, }); // Wait for plugin initialization return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 100); })]; case 1: // Wait for plugin initialization _a.sent(); zkPlugin = shogun.getPlugin('zkproof'); if (!zkPlugin) { console.error('ZK-Proof plugin not available'); return [2 /*return*/]; } // Create identity console.log('1. Generating identity...'); return [4 /*yield*/, zkPlugin.generateIdentity()]; case 2: identity = _a.sent(); console.log(" Commitment: ".concat(identity.commitment.slice(0, 16), "...")); // Add to group console.log('\n2. Adding to group...'); zkPlugin.addToGroup(identity.commitment, 'proof-demo-group'); // Generate proof of membership console.log('\n3. Generating ZK proof...'); return [4 /*yield*/, zkPlugin.generateProof(identity, { groupId: 'proof-demo-group', message: 'I am a member of this group', scope: 'membership-verification', })]; case 3: proof = _a.sent(); console.log(' Proof generated!'); console.log(" Merkle root: ".concat(proof.merkleTreeRoot.slice(0, 16), "...")); console.log(" Nullifier hash: ".concat(proof.nullifierHash.slice(0, 16), "...")); // Verify the proof console.log('\n4. Verifying proof...'); return [4 /*yield*/, zkPlugin.verifyProof(proof)]; case 4: verificationResult = _a.sent(); if (verificationResult.verified) { console.log('✅ Proof verified successfully!'); console.log(' User proved group membership without revealing identity'); } else { console.error('❌ Proof verification failed'); } return [2 /*return*/]; } }); }); } // Example 4: Multi-device scenario function multiDeviceExample() { return __awaiter(this, void 0, void 0, function () { var gunInstance1, shogun1, zkPlugin1, signupResult, trapdoor, gunInstance2, shogun2, zkPlugin2, loginResult; return __generator(this, function (_a) { switch (_a.label) { case 0: console.log('\n=== Multi-Device ZK Authentication Example ===\n'); // Device 1: Create account console.log('📱 DEVICE 1: Creating account...'); gunInstance1 = Gun({ peers: [ 'https://lindanode.scobrudot.dev/gun', 'https://shogunnode.scobrudot.dev/gun', ], radisk: false, localStorage: false, // Enable for testing - allows offline operations // Reduce log noise from SEA verification errors (these are expected when checking invalid credentials) log: function () { }, // Disable Gun.js console logging to reduce noise }); shogun1 = new ShogunCore({ gunInstance: gunInstance1, zkproof: { enabled: true }, }); // Wait for plugin initialization return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 100); })]; case 1: // Wait for plugin initialization _a.sent(); zkPlugin1 = shogun1.getPlugin('zkproof'); return [4 /*yield*/, zkPlugin1.signUp()]; case 2: signupResult = _a.sent(); console.log('✅ Account created on Device 1'); console.log(" Commitment: ".concat(signupResult.username)); trapdoor = signupResult.seedPhrase; console.log("\n\uD83D\uDCDD User writes down trapdoor: ".concat(trapdoor.slice(0, 20), "...")); // Device 2: Import account console.log('\n💻 DEVICE 2: Importing account with trapdoor...'); gunInstance2 = Gun({ peers: [ 'https://lindanode.scobrudot.dev/gun', 'https://shogunnode.scobrudot.dev/gun', ], radisk: false, localStorage: false, // Enable for testing - allows offline operations // Reduce log noise from SEA verification errors (these are expected when checking invalid credentials) log: function () { }, // Disable Gun.js console logging to reduce noise }); shogun2 = new ShogunCore({ gunInstance: gunInstance2, zkproof: { enabled: true }, }); // Wait for plugin initialization return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 100); })]; case 3: // Wait for plugin initialization _a.sent(); zkPlugin2 = shogun2.getPlugin('zkproof'); return [4 /*yield*/, zkPlugin2.login(trapdoor)]; case 4: loginResult = _a.sent(); if (loginResult.success) { console.log('✅ Successfully logged in on Device 2'); console.log(" Same user: ".concat(loginResult.username === signupResult.username)); console.log('\n🎉 Multi-device authentication working!'); } return [2 /*return*/]; } }); }); } // Run examples function main() { return __awaiter(this, void 0, void 0, function () { var error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 4, , 5]); // Run all examples return [4 /*yield*/, basicExample()]; case 1: // Run all examples _a.sent(); return [4 /*yield*/, deterministicExample()]; case 2: _a.sent(); // await proofExample(); // Requires ZK circuit files - see README for setup return [4 /*yield*/, multiDeviceExample()]; case 3: // await proofExample(); // Requires ZK circuit files - see README for setup _a.sent(); console.log('\n✨ All examples completed successfully!'); return [3 /*break*/, 5]; case 4: error_1 = _a.sent(); console.error('\n❌ Error running examples:', error_1); return [3 /*break*/, 5]; case 5: process.exit(0); return [2 /*return*/]; } }); }); } // Run if executed directly if (require.main === module) { main(); } export { basicExample, deterministicExample, proofExample, multiDeviceExample };