Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Add IndexedDB support to persist the private key generated by Se… #68

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

pallavi240303
Copy link
Collaborator

@pallavi240303 pallavi240303 commented Jan 15, 2025

No description provided.

Copy link

coderabbitai bot commented Jan 15, 2025

Walkthrough

The pull request introduces enhancements to the secret management system by adding an IndexedDB-based storage mechanism. The SecretManager class is updated to support an optional IndexedDBStore, which allows for persistent storage of private keys. The changes improve error handling, initialization processes, and provide more robust logging for key management operations. A new IndexedDBStore class is implemented to handle asynchronous database interactions, complementing the existing storage interfaces.

Changes

File Change Summary
packages/core/src/lib/secretManager/secretManager.ts - Added IndexedDBStore as an optional constructor parameter
- Enhanced initialize() method with error handling and store initialization
- Updated getMasterPrivKey() to use secretStore
- Added logging to generateSecret() and signMessage() methods
packages/utils/src/lib/store/index.ts - Added export for indexedDbStorage
packages/utils/src/lib/store/indexedDbStorage.ts - New IndexedDBStore class implementing IStore interface
- Methods for database initialization, item retrieval, storage, and removal
packages/utils/src/lib/store/store.interface.ts - Added optional getAsyncItem() method
- Added optional initialize() method

Sequence Diagram

sequenceDiagram
    participant SM as SecretManager
    participant IDB as IndexedDBStore
    participant WC as WalletClient

    SM->>IDB: initialize()
    IDB-->>SM: Database ready
    SM->>IDB: getAsyncItem(privateKey)
    alt Key exists in store
        IDB-->>SM: Return stored key
    else No stored key
        SM->>WC: Derive private key
        SM->>IDB: setItem(privateKey)
        IDB-->>SM: Key stored
    end
Loading

Poem

🐰 A Rabbit's Ode to Secret Storage 🔐

In IndexedDB, my secrets hide,
With keys that safely now reside,
No more fears of data's flight,
Stored with cryptographic might!

Hop, hop, hooray for secure ways! 🕵️‍♀️

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (4)
packages/core/src/lib/secretManager/secretManager.ts (1)

28-28: Initialize secretStore after checking for custom store

The assignment of this.secretStore should occur after verifying if a custom store is provided to ensure correct initialization.

Apply this diff to improve initialization:

       this.walletClient = walletClient;
-      this.secretStore = store ?? new IndexedDBStore();
+      this.secretStore = store ? store : new IndexedDBStore();
packages/utils/src/lib/store/store.interface.ts (3)

34-35: Add JSDoc documentation for the new methods.

The new methods lack documentation. Please add JSDoc comments to maintain consistency with the existing methods and improve code maintainability.

Add documentation like this:

+  /**
+   * Retrieves an item asynchronously from the store using the provided key.
+   * @param {string} key - The key of the item to retrieve.
+   * @returns {AsyncResult<string, null>} A result containing the item if found, or null if not found.
+   */
   getAsyncItem?(key: string): AsyncResult<string, null>;

+  /**
+   * Initializes the store asynchronously. This should be called before using the store.
+   * @returns {Promise<void>} A promise that resolves when initialization is complete.
+   */
   initialize?(): Promise<void>;

Line range hint 38-40: Add private key related constants to StoreKeys enum.

Since this PR adds IndexedDB support for persisting private keys, consider adding relevant constants to the StoreKeys enum.

Add a constant like this:

 export enum StoreKeys {
   AUTH_TOKEN = 'auth_token',
+  PRIVATE_KEY = 'private_key',
 }

Line range hint 1-40: Consider architectural implications of mixing sync and async storage methods.

The interface now supports both synchronous (getItem) and asynchronous (getAsyncItem) storage operations. While this maintains backward compatibility, it could lead to confusion about which method to use. Consider:

  1. Adding documentation explaining when to use each method
  2. Potentially deprecating the sync methods in favor of async ones
  3. Or splitting into separate interfaces for sync and async storage
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 80c54b8 and 1274fba.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (4)
  • packages/core/src/lib/secretManager/secretManager.ts (3 hunks)
  • packages/utils/src/lib/store/index.ts (1 hunks)
  • packages/utils/src/lib/store/indexedDbStorage.ts (1 hunks)
  • packages/utils/src/lib/store/store.interface.ts (2 hunks)
🔇 Additional comments (2)
packages/core/src/lib/secretManager/secretManager.ts (1)

65-70: Handle potential errors when setting the private key in the store

When storing the private key using setItem, consider handling potential errors that might occur during the operation.

Ensure that errors during setItem are caught and handled appropriately.

packages/utils/src/lib/store/index.ts (1)

3-3: LGTM!

The new export statement correctly adds the indexedDbStorage module to the public API.

Comment on lines +55 to +68
getItem(key: string): string | null {
if (!this.db) {
throw new Error('Database not initialized');
}
const transaction = this.db.transaction([this.STORE_NAME], 'readonly');
const store = transaction.objectStore(this.STORE_NAME);
const request = store.get(key.toLowerCase());

let result = null;
request.onsuccess = () => {
result = request.result || null;
};
return result;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Synchronous getItem method will not work due to IndexedDB's asynchronous nature

The getItem method attempts to perform a synchronous operation using the asynchronous IndexedDB API. The result will always be null because the onsuccess callback executes after the return statement. IndexedDB does not support synchronous operations, so the method should be made asynchronous.

Apply this diff to correct the issue:

-  getItem(key: string): string | null {
+  async getItem(key: string): Promise<string | null> {
     if (!this.db) {
       throw new Error('Database not initialized');
     }
     const transaction = this.db.transaction([this.STORE_NAME], 'readonly');
     const store = transaction.objectStore(this.STORE_NAME);
     const request = store.get(key.toLowerCase());

-    let result = null;
-    request.onsuccess = () => {
-      result = request.result || null;
-    };
-    return result;
+    return new Promise<string | null>((resolve, reject) => {
+      request.onsuccess = () => {
+        resolve(request.result || null);
+      };
+      request.onerror = () => {
+        reject(null);
+      };
+    });
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
getItem(key: string): string | null {
if (!this.db) {
throw new Error('Database not initialized');
}
const transaction = this.db.transaction([this.STORE_NAME], 'readonly');
const store = transaction.objectStore(this.STORE_NAME);
const request = store.get(key.toLowerCase());
let result = null;
request.onsuccess = () => {
result = request.result || null;
};
return result;
}
async getItem(key: string): Promise<string | null> {
if (!this.db) {
throw new Error('Database not initialized');
}
const transaction = this.db.transaction([this.STORE_NAME], 'readonly');
const store = transaction.objectStore(this.STORE_NAME);
const request = store.get(key.toLowerCase());
return new Promise<string | null>((resolve, reject) => {
request.onsuccess = () => {
resolve(request.result || null);
};
request.onerror = () => {
reject(null);
};
});
}

Comment on lines +171 to +172
console.log('Generated secret:', secret);
console.log('Generated secret hash:', secretHash);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Do not log generated secret and secret hash

Logging the generated secret and its hash can compromise security by exposing sensitive information.

Remove the log statements:

-   console.log('Generated secret:', secret);
-   console.log('Generated secret hash:', secretHash);

if (!this.privKey) {
return Err('No private key found');
}
console.log('Master private key:', this.privKey);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid logging the master private key

The master private key should not be logged as it poses a significant security risk.

Remove the log statement:

-   console.log('Master private key:', this.privKey);

Comment on lines +112 to +116
console.log('Signature derived:', signature);
this.privKey = trim0x(sha256(signature));
this.emit('initialized', true);

console.log('Private key derived:', this.privKey);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove console logs that expose sensitive information

Logging sensitive data such as signatures and private keys can lead to security vulnerabilities. These values should not be logged.

Apply this diff to remove sensitive logs:

    console.log('Signature derived:', signature);
    this.privKey = trim0x(sha256(signature));
    this.emit('initialized', true);

-   console.log('Private key derived:', this.privKey);

Committable suggestion skipped: line range outside the PR's diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant