shogun-core 4.2.4 → 4.2.6

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.
@@ -132720,6 +132720,17 @@ class ShogunCore {
132720
132720
  }
132721
132721
  });
132722
132722
  }
132723
+ /**
132724
+ * Manually initialize the Shogun SDK (for testing or delayed initialization)
132725
+ * @returns Promise that resolves when initialization is complete
132726
+ */
132727
+ async initialize() {
132728
+ // If already initialized, just wait a bit for any pending initialization
132729
+ if (this._gun) {
132730
+ return Promise.resolve();
132731
+ }
132732
+ return this.coreInitializer.initialize(this.config);
132733
+ }
132723
132734
  /**
132724
132735
  * Access to the Gun instance
132725
132736
  * @returns The Gun instance
@@ -134614,30 +134625,22 @@ class DataBase {
134614
134625
  }
134615
134626
  // Set the user instance
134616
134627
  this.user = this.gun.user();
134617
- // Run post-authentication tasks
134618
- try {
134619
- const postAuthResult = await this.runPostAuthOnAuthResult(username, authResult.userPub, authResult);
134620
- // Return the post-auth result which includes the complete user data
134621
- return postAuthResult;
134622
- }
134623
- catch (postAuthError) {
134624
- console.error(`Post-auth error: ${postAuthError}`);
134625
- // Even if post-auth fails, the user was created and authenticated successfully
134626
- return {
134627
- success: true,
134628
- userPub: authResult.userPub,
134629
- username: username,
134630
- isNewUser: true,
134631
- sea: this.gun.user()?._?.sea
134632
- ? {
134633
- pub: this.gun.user()._?.sea.pub,
134634
- priv: this.gun.user()._?.sea.priv,
134635
- epub: this.gun.user()._?.sea.epub,
134636
- epriv: this.gun.user()._?.sea.epriv,
134637
- }
134638
- : undefined,
134639
- };
134640
- }
134628
+ console.log(`[SIGNUP] Signup completed successfully for user: ${username}`);
134629
+ // Return the signup result
134630
+ return {
134631
+ success: true,
134632
+ userPub: authResult.userPub,
134633
+ username: username,
134634
+ isNewUser: true,
134635
+ sea: this.gun.user()?._?.sea
134636
+ ? {
134637
+ pub: this.gun.user()._?.sea.pub,
134638
+ priv: this.gun.user()._?.sea.priv,
134639
+ epub: this.gun.user()._?.sea.epub,
134640
+ epriv: this.gun.user()._?.sea.epriv,
134641
+ }
134642
+ : undefined,
134643
+ };
134641
134644
  }
134642
134645
  catch (error) {
134643
134646
  console.error(`Exception during signup for ${username}: ${error}`);
@@ -134675,467 +134678,6 @@ class DataBase {
134675
134678
  resolve({ success: true, userPub: pair.pub });
134676
134679
  });
134677
134680
  }
134678
- async runPostAuthOnAuthResult(username, userPub, authResult) {
134679
- console.log(`[POSTAUTH] Starting post-auth setup for user: ${username}, userPub: ${userPub}`);
134680
- try {
134681
- console.log(`[POSTAUTH] Validating parameters for user: ${username}`);
134682
- // Validate required parameters
134683
- if (!username ||
134684
- typeof username !== "string" ||
134685
- username.trim().length === 0) {
134686
- console.error(`[POSTAUTH] Invalid username provided: ${username}`);
134687
- throw new Error("Invalid username provided");
134688
- }
134689
- if (!userPub ||
134690
- typeof userPub !== "string" ||
134691
- userPub.trim().length === 0) {
134692
- console.error("[POSTAUTH] Invalid userPub provided:", {
134693
- userPub,
134694
- type: typeof userPub,
134695
- authResult,
134696
- });
134697
- throw new Error("Invalid userPub provided");
134698
- }
134699
- // Additional validation for userPub format
134700
- if (!userPub.includes(".") || userPub.length < 10) {
134701
- console.error(`[POSTAUTH] Invalid userPub format: ${userPub}`);
134702
- throw new Error("Invalid userPub format");
134703
- }
134704
- console.log(`[POSTAUTH] Parameters validated for user: ${username}`);
134705
- // Normalize username to prevent path issues
134706
- const normalizedUsername = username.trim().toLowerCase();
134707
- if (normalizedUsername.length === 0) {
134708
- console.error(`[POSTAUTH] Normalized username is empty for user: ${username}`);
134709
- throw new Error("Username cannot be empty");
134710
- }
134711
- console.log(`[POSTAUTH] Normalized username: ${normalizedUsername}`);
134712
- console.log(`[POSTAUTH] Checking if user exists: ${userPub}`);
134713
- const existingUser = await this.gun.get(userPub).then();
134714
- const isNewUser = !existingUser || !existingUser.alias;
134715
- console.log(`[POSTAUTH] User is ${isNewUser ? "NEW" : "EXISTING"}: ${userPub}`);
134716
- // Get user's encryption public key (epub) for comprehensive tracking
134717
- const userInstance = this.gun.user();
134718
- const userSea = userInstance?._?.sea;
134719
- const epub = userSea?.epub;
134720
- console.log(`[POSTAUTH] User epub retrieved: ${epub ? "yes" : "no"}`);
134721
- // Enhanced user tracking system
134722
- console.log(`[POSTAUTH] Setting up comprehensive user tracking for: ${normalizedUsername}`);
134723
- const trackingResult = await this.setupComprehensiveUserTracking(normalizedUsername, userPub, epub);
134724
- if (!trackingResult) {
134725
- console.error(`[POSTAUTH] Comprehensive user tracking setup failed for: ${normalizedUsername}`);
134726
- return {
134727
- success: false,
134728
- error: "Comprehensive user tracking setup failed",
134729
- };
134730
- }
134731
- console.log(`[POSTAUTH] User tracking setup completed successfully for: ${normalizedUsername}`);
134732
- const result = {
134733
- success: true,
134734
- userPub: userPub,
134735
- username: normalizedUsername,
134736
- isNewUser: isNewUser,
134737
- // Get the SEA pair from the user object
134738
- sea: userSea
134739
- ? {
134740
- pub: userSea.pub,
134741
- priv: userSea.priv,
134742
- epub: userSea.epub,
134743
- epriv: userSea.epriv,
134744
- }
134745
- : undefined,
134746
- };
134747
- console.log(`[POSTAUTH] Post-auth setup completed successfully for user: ${username}`);
134748
- return result;
134749
- }
134750
- catch (error) {
134751
- console.error(`[POSTAUTH] Error in post-authentication setup for ${username}:`, error);
134752
- return {
134753
- success: false,
134754
- error: `Post-authentication setup failed: ${error}`,
134755
- };
134756
- }
134757
- }
134758
- /**
134759
- * Sets up comprehensive user tracking system for agile user lookup
134760
- * Creates multiple indexes for efficient user discovery
134761
- */
134762
- async setupComprehensiveUserTracking(username, userPub, epub) {
134763
- console.log(`[TRACKING] Starting comprehensive user tracking setup for: ${username}, userPub: ${userPub}`);
134764
- try {
134765
- // 1. Create alias index: ~@alias -> userPub (for GunDB compatibility)
134766
- console.log(`[TRACKING] Step 1: Creating alias index for ${username}`);
134767
- const aliasIndexResult = await this.createAliasIndex(username, userPub);
134768
- if (!aliasIndexResult) {
134769
- console.error(`[TRACKING] Failed to create alias index for ${username}`);
134770
- return false;
134771
- }
134772
- console.log(`[TRACKING] Step 1 completed: Alias index created for ${username}`);
134773
- // 2. Create username mapping: usernames/alias -> userPub
134774
- console.log(`[TRACKING] Step 2: Creating username mapping for ${username}`);
134775
- const usernameMappingResult = await this.createUsernameMapping(username, userPub);
134776
- if (!usernameMappingResult) {
134777
- console.error(`[TRACKING] Failed to create username mapping for ${username}`);
134778
- return false;
134779
- }
134780
- console.log(`[TRACKING] Step 2 completed: Username mapping created for ${username}`);
134781
- // 3. Create user registry: users/userPub -> user data
134782
- console.log(`[TRACKING] Step 3: Creating user registry for ${username}`);
134783
- const userRegistryResult = await this.createUserRegistry(username, userPub, epub);
134784
- if (!userRegistryResult) {
134785
- console.error(`[TRACKING] Failed to create user registry for ${username}`);
134786
- return false;
134787
- }
134788
- console.log(`[TRACKING] Step 3 completed: User registry created for ${username}`);
134789
- // 4. Create reverse lookup: userPub -> alias
134790
- console.log(`[TRACKING] Step 4: Creating reverse lookup for ${username}`);
134791
- const reverseLookupResult = await this.createReverseLookup(username, userPub);
134792
- if (!reverseLookupResult) {
134793
- console.error(`[TRACKING] Failed to create reverse lookup for ${username}`);
134794
- return false;
134795
- }
134796
- console.log(`[TRACKING] Step 4 completed: Reverse lookup created for ${username}`);
134797
- // 5. Create epub index: epubKeys/epub -> userPub (for encryption lookups)
134798
- if (epub) {
134799
- console.log(`[TRACKING] Step 5: Creating epub index for ${username}`);
134800
- const epubIndexResult = await this.createEpubIndex(epub, userPub);
134801
- if (!epubIndexResult) {
134802
- console.error(`[TRACKING] Failed to create epub index for ${username}`);
134803
- return false;
134804
- }
134805
- console.log(`[TRACKING] Step 5 completed: Epub index created for ${username}`);
134806
- }
134807
- else {
134808
- console.log(`[TRACKING] Step 5 skipped: No epub available for ${username}`);
134809
- }
134810
- // 6. Create user metadata in user's own node
134811
- console.log(`[TRACKING] Step 6: Creating user metadata for ${username}`);
134812
- const userMetadataResult = await this.createUserMetadata(username, userPub, epub);
134813
- if (!userMetadataResult) {
134814
- console.error(`[TRACKING] Failed to create user metadata for ${username}`);
134815
- return false;
134816
- }
134817
- console.log(`[TRACKING] Step 6 completed: User metadata created for ${username}`);
134818
- console.log(`[TRACKING] Comprehensive user tracking setup completed successfully for: ${username}`);
134819
- return true;
134820
- }
134821
- catch (error) {
134822
- console.error(`[TRACKING] Error in comprehensive user tracking setup for ${username}:`, error);
134823
- // Don't throw - continue with other operations
134824
- return false;
134825
- }
134826
- }
134827
- /**
134828
- * Creates alias index following GunDB pattern: ~@alias -> userPub
134829
- */
134830
- async createAliasIndex(username, userPub) {
134831
- try {
134832
- const aliasNode = this.gun.get(`~@${username}`);
134833
- // For Gun.js alias validation to pass, the data must be exactly equal to the key
134834
- // The key is `~@${username}`, so we store that as the data
134835
- return new Promise((resolve) => {
134836
- aliasNode.put(`~@${username}`, (ack) => {
134837
- if (ack && ack.err) {
134838
- console.error(`Error creating alias index: ${ack.err}`);
134839
- resolve(false);
134840
- }
134841
- else {
134842
- resolve(true);
134843
- }
134844
- });
134845
- });
134846
- }
134847
- catch (error) {
134848
- console.error(`Error creating alias index: ${error}`);
134849
- return false;
134850
- }
134851
- }
134852
- /**
134853
- * Creates username mapping: usernames/alias -> userPub
134854
- */
134855
- async createUsernameMapping(username, userPub) {
134856
- try {
134857
- return new Promise((resolve) => {
134858
- this.node
134859
- .get("usernames")
134860
- .get(username)
134861
- .put(userPub, (ack) => {
134862
- if (ack && ack.err) {
134863
- console.error(`Error creating username mapping: ${ack.err}`);
134864
- resolve(false);
134865
- }
134866
- else {
134867
- resolve(true);
134868
- }
134869
- });
134870
- });
134871
- }
134872
- catch (error) {
134873
- console.error(`Error creating username mapping: ${error}`);
134874
- return false;
134875
- }
134876
- }
134877
- /**
134878
- * Creates user registry: users/userPub -> user data
134879
- */
134880
- async createUserRegistry(username, userPub, epub) {
134881
- try {
134882
- const userData = {
134883
- username: username,
134884
- userPub: userPub,
134885
- epub: epub,
134886
- registeredAt: Date.now().toString(),
134887
- lastSeen: Date.now().toString(),
134888
- };
134889
- return new Promise((resolve) => {
134890
- this.node
134891
- .get("users")
134892
- .get(userPub)
134893
- .put(userData, (ack) => {
134894
- if (ack && ack.err) {
134895
- console.error(`Error creating user registry: ${ack.err}`);
134896
- resolve(false);
134897
- }
134898
- else {
134899
- resolve(true);
134900
- }
134901
- });
134902
- });
134903
- }
134904
- catch (error) {
134905
- console.error(`Error creating user registry: ${error}`);
134906
- return false;
134907
- }
134908
- }
134909
- /**
134910
- * Creates reverse lookup: userPub -> alias
134911
- */
134912
- async createReverseLookup(username, userPub) {
134913
- try {
134914
- const ack = await this.node
134915
- .get("userAliases")
134916
- .get(userPub)
134917
- .put(username)
134918
- .then();
134919
- if (ack.err) {
134920
- console.error(`Error creating reverse lookup: ${ack.err}`);
134921
- return false;
134922
- }
134923
- else {
134924
- return true;
134925
- }
134926
- }
134927
- catch (error) {
134928
- console.error(`Error creating reverse lookup: ${error}`);
134929
- return false;
134930
- }
134931
- }
134932
- /**
134933
- * Creates epub index: epubKeys/epub -> userPub
134934
- */
134935
- async createEpubIndex(epub, userPub) {
134936
- try {
134937
- return new Promise((resolve) => {
134938
- this.node
134939
- .get("epubKeys")
134940
- .get(epub)
134941
- .put(userPub, (ack) => {
134942
- if (ack && ack.err) {
134943
- console.error(`Error creating epub index: ${ack.err}`);
134944
- resolve(false);
134945
- }
134946
- else {
134947
- resolve(true);
134948
- }
134949
- });
134950
- });
134951
- }
134952
- catch (error) {
134953
- console.error(`Error creating epub index: ${error}`);
134954
- return false;
134955
- }
134956
- }
134957
- /**
134958
- * Creates user metadata in user's own node
134959
- */
134960
- async createUserMetadata(username, userPub, epub) {
134961
- try {
134962
- const userMetadata = {
134963
- username: username,
134964
- epub: epub,
134965
- registeredAt: Date.now(),
134966
- lastSeen: Date.now(),
134967
- };
134968
- return new Promise((resolve) => {
134969
- this.gun.get(userPub).put(userMetadata, (ack) => {
134970
- if (ack && ack.err) {
134971
- console.error(`Error creating user metadata: ${ack.err}`);
134972
- resolve(false);
134973
- }
134974
- else {
134975
- resolve(true);
134976
- }
134977
- });
134978
- });
134979
- }
134980
- catch (error) {
134981
- console.error(`Error creating user metadata: ${error}`);
134982
- return false;
134983
- }
134984
- }
134985
- /**
134986
- * Gets user information by alias using the comprehensive tracking system
134987
- * @param alias Username/alias to lookup
134988
- * @returns Promise resolving to user information or null if not found
134989
- */
134990
- async getUserByAlias(alias) {
134991
- try {
134992
- const normalizedAlias = alias.trim().toLowerCase();
134993
- if (!normalizedAlias) {
134994
- return null;
134995
- }
134996
- // Method 1: Try GunDB standard alias lookup (~@alias)
134997
- try {
134998
- const aliasData = await this.gun.get(`~@${normalizedAlias}`).then();
134999
- if (aliasData && aliasData["~pubKeyOfUser"]) {
135000
- const userPub = aliasData["~pubKeyOfUser"]["#"] || aliasData["~pubKeyOfUser"];
135001
- if (userPub) {
135002
- const userData = await this.getUserDataByPub(userPub);
135003
- if (userData) {
135004
- return userData;
135005
- }
135006
- }
135007
- }
135008
- }
135009
- catch (error) {
135010
- console.error(`GunDB alias lookup failed for ${normalizedAlias}:`, error);
135011
- }
135012
- // Method 2: Try username mapping (usernames/alias -> userPub)
135013
- try {
135014
- const userPub = await this.node
135015
- .get("usernames")
135016
- .get(normalizedAlias)
135017
- .then();
135018
- if (userPub) {
135019
- const userData = await this.getUserDataByPub(userPub);
135020
- if (userData) {
135021
- return userData;
135022
- }
135023
- }
135024
- }
135025
- catch (error) {
135026
- console.error(`Username mapping lookup failed for ${normalizedAlias}:`, error);
135027
- }
135028
- return null;
135029
- }
135030
- catch (error) {
135031
- console.error(`Error looking up user by alias ${alias}:`, error);
135032
- return null;
135033
- }
135034
- }
135035
- /**
135036
- * Gets user information by public key
135037
- * @param userPub User's public key
135038
- * @returns Promise resolving to user information or null if not found
135039
- */
135040
- async getUserDataByPub(userPub) {
135041
- try {
135042
- if (!userPub || typeof userPub !== "string") {
135043
- return null;
135044
- }
135045
- // Method 1: Try user registry (users/userPub -> user data)
135046
- try {
135047
- const userData = await this.node.get("users").get(userPub).then();
135048
- if (userData && userData.username) {
135049
- return {
135050
- userPub: userData.userPub || userPub,
135051
- epub: userData.epub || null,
135052
- username: userData.username,
135053
- registeredAt: userData.registeredAt || 0,
135054
- lastSeen: userData.lastSeen || 0,
135055
- };
135056
- }
135057
- }
135058
- catch (error) {
135059
- console.error(`User registry lookup failed for ${userPub}:`, error);
135060
- }
135061
- // Method 2: Try user's own node
135062
- try {
135063
- const userNodeData = await this.gun.get(userPub).then();
135064
- if (userNodeData && userNodeData.username) {
135065
- return {
135066
- userPub: userPub,
135067
- epub: userNodeData.epub || null,
135068
- username: userNodeData.username,
135069
- registeredAt: userNodeData.registeredAt || 0,
135070
- lastSeen: userNodeData.lastSeen || 0,
135071
- };
135072
- }
135073
- }
135074
- catch (error) {
135075
- console.error(`User node lookup failed for ${userPub}:`, error);
135076
- }
135077
- return null;
135078
- }
135079
- catch (error) {
135080
- console.error(`Error looking up user data by pub ${userPub}:`, error);
135081
- return null;
135082
- }
135083
- }
135084
- /**
135085
- * Gets user public key by encryption public key (epub)
135086
- * @param epub User's encryption public key
135087
- * @returns Promise resolving to user public key or null if not found
135088
- */
135089
- async getUserPubByEpub(epub) {
135090
- try {
135091
- if (!epub || typeof epub !== "string") {
135092
- return null;
135093
- }
135094
- const userPub = await this.node.get("epubKeys").get(epub).then();
135095
- return userPub || null;
135096
- }
135097
- catch (error) {
135098
- console.error(`Error looking up user pub by epub ${epub}:`, error);
135099
- return null;
135100
- }
135101
- }
135102
- /**
135103
- * Gets user alias by public key
135104
- * @param userPub User's public key
135105
- * @returns Promise resolving to user alias or null if not found
135106
- */
135107
- async getUserAliasByPub(userPub) {
135108
- try {
135109
- if (!userPub || typeof userPub !== "string") {
135110
- return null;
135111
- }
135112
- const alias = await this.node.get("userAliases").get(userPub).then();
135113
- return alias || null;
135114
- }
135115
- catch (error) {
135116
- console.error(`Error looking up user alias by pub ${userPub}:`, error);
135117
- return null;
135118
- }
135119
- }
135120
- /**
135121
- * Gets all registered users (for admin purposes)
135122
- * @returns Promise resolving to array of user information
135123
- */
135124
- async getAllRegisteredUsers() {
135125
- try {
135126
- const users = [];
135127
- // Get all users from the users registry
135128
- const usersNode = this.node.get("users");
135129
- // Note: This is a simplified approach. In a real implementation,
135130
- // you might want to use Gun's map functionality or iterate through
135131
- // known user public keys
135132
- return users;
135133
- }
135134
- catch (error) {
135135
- console.error(`Error getting all registered users:`, error);
135136
- return [];
135137
- }
135138
- }
135139
134681
  /**
135140
134682
  * Updates user's last seen timestamp
135141
134683
  * @param userPub User's public key
@@ -135250,17 +134792,7 @@ class DataBase {
135250
134792
  error: "Authentication failed: No user pub returned.",
135251
134793
  };
135252
134794
  }
135253
- // Pass the userPub to runPostAuthOnAuthResult
135254
- try {
135255
- await this.runPostAuthOnAuthResult(alias, userPub, {
135256
- success: true,
135257
- userPub: userPub,
135258
- });
135259
- }
135260
- catch (postAuthError) {
135261
- console.error(`Post-auth error during login: ${postAuthError}`);
135262
- // Continue with login even if post-auth fails
135263
- }
134795
+ console.log(`[LOGIN] Login completed successfully for user: ${username}`);
135264
134796
  // Update user's last seen timestamp
135265
134797
  try {
135266
134798
  await this.updateUserLastSeen(userPub);
@@ -135303,10 +134835,7 @@ class DataBase {
135303
134835
  error: `User '${username}' not found. Please check your username or register first.`,
135304
134836
  };
135305
134837
  }
135306
- await this.runPostAuthOnAuthResult(username, pair.pub || "", {
135307
- success: true,
135308
- userPub: pair.pub,
135309
- });
134838
+ console.log(`[LOGIN] Login with pair completed for user: ${username}`);
135310
134839
  try {
135311
134840
  await this.updateUserLastSeen(pair.pub);
135312
134841
  }