Repository navigation
Conversation
WalkthroughThe changes transition the key management system from using unencrypted keypair files to encrypted keystore files protected by user passwords. The Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant CLI
participant BaseAction
participant FileSystem
User->>CLI: Run keygen create command
CLI->>BaseAction: createKeypairAction()
BaseAction->>User: Prompt for password (and confirm)
User->>BaseAction: Enter password
BaseAction->>BaseAction: Generate wallet & encrypt with password
BaseAction->>FileSystem: Write encrypted keystore file
FileSystem-->>BaseAction: Confirm write
BaseAction->>CLI: Show success message
sequenceDiagram
participant User
participant CLI
participant BaseAction
participant FileSystem
CLI->>BaseAction: getPrivateKey()
BaseAction->>FileSystem: Check for keystore file
alt Keystore exists and valid
BaseAction->>User: Prompt for password (up to 3 attempts)
User->>BaseAction: Enter password
BaseAction->>BaseAction: Decrypt keystore
BaseAction->>CLI: Return private key
else Keystore missing/invalid
BaseAction->>User: Prompt to create new keypair
User->>BaseAction: Confirm
BaseAction->>BaseAction: createKeypair()
BaseAction->>CLI: Return new private key
end
Poem
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
npm error Exit handler never called! ✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (3)
src/lib/interfaces/KeystoreData.ts (1)
1-5: Add JSDoc documentation for the interface.Consider adding JSDoc comments to document the purpose of each field in the interface for better maintainability.
+/** + * Represents the structure of an encrypted keystore file + */ export interface KeystoreData { + /** Version of the keystore format */ version: number; + /** Encrypted wallet data in JSON string format */ encrypted: string; + /** Ethereum address associated with the keystore */ address: string; }tests/libs/baseAction.test.ts (1)
110-119: Remove duplicate process.exit mock.The
process.exitis already mocked in thebeforeEachhook (line 38). This duplicate mock is unnecessary and could cause confusion.test("should confirm prompt and exit when declined", async () => { vi.mocked(inquirer.prompt).mockResolvedValue({confirmAction: false}); - const processExitSpy = vi.spyOn(process, "exit").mockImplementation(() => { - throw new Error("process exited"); - }); await expect(baseAction["confirmPrompt"]("Are you sure?")).rejects.toThrow("process exited"); expect(inquirer.prompt).toHaveBeenCalled(); expect(processExitSpy).toHaveBeenCalledWith(0); });src/lib/actions/BaseAction.ts (1)
1-208: Consider architectural improvements for better separation of concerns.The implementation successfully achieves the PR objectives of replacing the insecure keypair system with encrypted keystore. For future enhancements, consider:
- Separation of Concerns: Extract UI operations (prompts, spinners) into a separate class to improve testability and reusability
- Error Handling Strategy: Replace
process.exit()calls with a proper error handling strategy using exceptions- Security Enhancements:
- Consider implementing session timeout for decrypted private keys
- Add option to clear sensitive data from memory after use
- Implement key derivation with salt for additional security
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
src/commands/keygen/create.ts(1 hunks)src/commands/keygen/index.ts(1 hunks)src/lib/accounts/KeypairManager.ts(0 hunks)src/lib/actions/BaseAction.ts(2 hunks)src/lib/interfaces/KeystoreData.ts(1 hunks)tests/actions/create.test.ts(1 hunks)tests/libs/accounts/KeypairManager.test.ts(0 hunks)tests/libs/baseAction.test.ts(3 hunks)
💤 Files with no reviewable changes (2)
- src/lib/accounts/KeypairManager.ts
- tests/libs/accounts/KeypairManager.test.ts
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/commands/keygen/index.ts (1)
src/commands/keygen/create.ts (2)
CreateKeypairOptions(3-6)KeypairCreator(8-23)
tests/libs/baseAction.test.ts (1)
src/lib/actions/BaseAction.ts (1)
BaseAction(13-208)
src/lib/actions/BaseAction.ts (2)
src/lib/config/ConfigFileManager.ts (1)
ConfigFileManager(5-51)src/lib/interfaces/KeystoreData.ts (1)
KeystoreData(1-5)
🔇 Additional comments (7)
src/commands/keygen/index.ts (1)
12-17: LGTM! Terminology and async handling are correctly updated.The changes properly reflect the transition to encrypted keystores and correctly handle the asynchronous nature of the keystore creation process.
src/commands/keygen/create.ts (1)
13-22: LGTM! Async implementation and messaging are consistent.The method correctly handles the asynchronous keystore creation with appropriate spinner feedback messages.
tests/actions/create.test.ts (1)
10-44: LGTM! Test refactoring provides better isolation.The tests correctly mock internal methods and properly test the async behavior of keystore creation. The terminology updates are consistent throughout.
tests/libs/baseAction.test.ts (1)
198-439: Excellent test coverage for keystore management.The test suite comprehensively covers all aspects of the new keystore functionality including:
- Password validation and retry logic
- Keystore format validation
- Encryption/decryption flows
- Error handling and edge cases
- File system operations
Great work on ensuring robust test coverage!
src/lib/actions/BaseAction.ts (3)
9-11: LGTM! Appropriate imports for keystore functionality.The addition of ethers for wallet encryption and file system utilities aligns well with the PR's objective of implementing encrypted keystore storage.
39-46: Well-implemented type guard for keystore validation.The method correctly validates the keystore structure with proper TypeScript type predicate syntax. The version check ensures forward compatibility.
125-141: Well-implemented secure password prompt.Good use of inquirer's password type with masking and appropriate validation for empty passwords.
| protected async createKeypair(outputPath: string, overwrite: boolean): Promise<string> { | ||
| const finalOutputPath = this.getFilePath(outputPath); | ||
| this.stopSpinner(); | ||
|
|
||
| if (existsSync(finalOutputPath) && !overwrite) { | ||
| this.failSpinner(`The file at ${finalOutputPath} already exists. Use the '--overwrite' option to replace it.`); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| const wallet = ethers.Wallet.createRandom(); | ||
|
|
||
| const password = await this.promptPassword("Enter password to encrypt your keystore:"); | ||
| const confirmPassword = await this.promptPassword("Confirm password:"); | ||
|
|
||
| if (password !== confirmPassword) { | ||
| this.failSpinner("Passwords do not match"); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| if (password.length < 8) { | ||
| this.failSpinner("Password must be at least 8 characters long"); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| const encryptedJson = await wallet.encrypt(password); | ||
|
|
||
| const keystoreData: KeystoreData = { | ||
| version: 1, | ||
| encrypted: encryptedJson, | ||
| address: wallet.address, | ||
| }; | ||
|
|
||
| writeFileSync(finalOutputPath, JSON.stringify(keystoreData, null, 2)); | ||
| this.writeConfig('keyPairPath', finalOutputPath); | ||
|
|
||
| return wallet.privateKey; | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Use async file operations and consider enhancing password validation.
The keypair creation logic is well-structured, but consider these improvements:
- Replace
writeFileSyncwith asyncwriteFileto avoid blocking - Extract magic number for minimum password length
- Consider adding password complexity requirements beyond just length
- Replace
process.exitcalls with error throwing
+ private static readonly MIN_PASSWORD_LENGTH = 8;
+
protected async createKeypair(outputPath: string, overwrite: boolean): Promise<string> {
const finalOutputPath = this.getFilePath(outputPath);
this.stopSpinner();
if (existsSync(finalOutputPath) && !overwrite) {
this.failSpinner(`The file at ${finalOutputPath} already exists. Use the '--overwrite' option to replace it.`);
- process.exit(1);
+ throw new Error(`File already exists at ${finalOutputPath}`);
}
const wallet = ethers.Wallet.createRandom();
const password = await this.promptPassword("Enter password to encrypt your keystore:");
const confirmPassword = await this.promptPassword("Confirm password:");
if (password !== confirmPassword) {
this.failSpinner("Passwords do not match");
- process.exit(1);
+ throw new Error("Passwords do not match");
}
- if (password.length < 8) {
- this.failSpinner("Password must be at least 8 characters long");
- process.exit(1);
+ if (password.length < BaseAction.MIN_PASSWORD_LENGTH) {
+ this.failSpinner(`Password must be at least ${BaseAction.MIN_PASSWORD_LENGTH} characters long`);
+ throw new Error(`Password too short`);
}
const encryptedJson = await wallet.encrypt(password);
const keystoreData: KeystoreData = {
version: 1,
encrypted: encryptedJson,
address: wallet.address,
};
- writeFileSync(finalOutputPath, JSON.stringify(keystoreData, null, 2));
+ const { writeFile } = await import('fs/promises');
+ await writeFile(finalOutputPath, JSON.stringify(keystoreData, null, 2));
this.writeConfig('keyPairPath', finalOutputPath);
return wallet.privateKey;
}Consider adding password strength validation to ensure better security:
private validatePasswordStrength(password: string): string | true {
if (password.length < BaseAction.MIN_PASSWORD_LENGTH) {
return `Password must be at least ${BaseAction.MIN_PASSWORD_LENGTH} characters long`;
}
// Add additional checks for complexity
if (!/[A-Z]/.test(password) || !/[a-z]/.test(password) || !/[0-9]/.test(password)) {
return "Password must contain uppercase, lowercase, and numeric characters";
}
return true;
}🤖 Prompt for AI Agents
In src/lib/actions/BaseAction.ts lines 87 to 123, replace the synchronous
writeFileSync call with the asynchronous writeFile to prevent blocking. Define a
constant for the minimum password length instead of using the magic number 8
directly. Add a password complexity validation method that checks for uppercase,
lowercase, and numeric characters, and use it to validate the password instead
of just length. Finally, replace all process.exit calls with throwing errors to
allow proper error handling and avoid abrupt termination.
| private async decryptKeystore(keystoreData: KeystoreData, attempt: number = 1): Promise<string> { | ||
| try { | ||
| const message = attempt === 1 | ||
| ? "Enter password to decrypt keystore:" | ||
| : `Invalid password. Attempt ${attempt}/3 - Enter password to decrypt keystore:`; | ||
| const password = await this.promptPassword(message); | ||
| const wallet = await ethers.Wallet.fromEncryptedJson(keystoreData.encrypted, password); | ||
| return wallet.privateKey; | ||
| } catch (error) { | ||
| if (attempt >= 3) { | ||
| this.failSpinner("Maximum password attempts exceeded (3/3)."); | ||
| process.exit(1); | ||
| } | ||
| return await this.decryptKeystore(keystoreData, attempt + 1); | ||
| } | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider throwing an error instead of calling process.exit for better testability.
The method implementation is solid with good retry logic and user feedback. However, there are a few improvements to consider:
- Replace
process.exit(1)with throwing an error to make the code more testable and library-friendly - Extract the magic number
3to a class constant - Consider adding a delay between attempts to further prevent brute-force attacks
+ private static readonly MAX_PASSWORD_ATTEMPTS = 3;
+
private async decryptKeystore(keystoreData: KeystoreData, attempt: number = 1): Promise<string> {
try {
const message = attempt === 1
? "Enter password to decrypt keystore:"
- : `Invalid password. Attempt ${attempt}/3 - Enter password to decrypt keystore:`;
+ : `Invalid password. Attempt ${attempt}/${BaseAction.MAX_PASSWORD_ATTEMPTS} - Enter password to decrypt keystore:`;
const password = await this.promptPassword(message);
const wallet = await ethers.Wallet.fromEncryptedJson(keystoreData.encrypted, password);
return wallet.privateKey;
} catch (error) {
- if (attempt >= 3) {
- this.failSpinner("Maximum password attempts exceeded (3/3).");
- process.exit(1);
+ if (attempt >= BaseAction.MAX_PASSWORD_ATTEMPTS) {
+ this.failSpinner(`Maximum password attempts exceeded (${BaseAction.MAX_PASSWORD_ATTEMPTS}/${BaseAction.MAX_PASSWORD_ATTEMPTS}).`);
+ throw new Error("Maximum password attempts exceeded");
}
+ // Add delay to prevent rapid attempts
+ await new Promise(resolve => setTimeout(resolve, 1000));
return await this.decryptKeystore(keystoreData, attempt + 1);
}
}🤖 Prompt for AI Agents
In src/lib/actions/BaseAction.ts around lines 22 to 37, replace the call to
process.exit(1) with throwing a specific error to improve testability and avoid
abrupt termination. Extract the maximum retry count (currently 3) into a
class-level constant for easier configuration and clarity. Additionally, add a
short delay (e.g., using a timeout or sleep function) between retry attempts to
help mitigate brute-force password guessing.
| protected async getPrivateKey(): Promise<string> { | ||
| const keypairPath = this.getConfigByKey("keyPairPath"); | ||
|
|
||
| if (!keypairPath || !existsSync(keypairPath)) { | ||
| await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?"); | ||
| return await this.createKeypair("./keypair.json", false); | ||
| } | ||
|
|
||
| const keystoreData = JSON.parse(readFileSync(keypairPath, "utf-8")); | ||
|
|
||
| if (!this.isValidKeystoreFormat(keystoreData)) { | ||
| this.failSpinner("Invalid keystore format. Expected encrypted keystore file."); | ||
| await this.confirmPrompt("Would you like to create a new keypair?"); | ||
| return await this.createKeypair("./keypair.json", true); | ||
| } | ||
| await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?"); | ||
| this.keypairManager.createKeypair(); | ||
| return this.keypairManager.getPrivateKey(); | ||
|
|
||
| return await this.decryptKeystore(keystoreData); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Improve error handling and make keystore path configurable.
The method handles missing and invalid keystore files well, but there are a few improvements to consider:
- Add try-catch for
readFileSyncto handle corrupted files gracefully - Make the default keystore path configurable instead of hardcoding "./keypair.json"
- Consider splitting the method to follow Single Responsibility Principle
+ private static readonly DEFAULT_KEYSTORE_PATH = "./keystore.json";
+
protected async getPrivateKey(): Promise<string> {
const keypairPath = this.getConfigByKey("keyPairPath");
if (!keypairPath || !existsSync(keypairPath)) {
await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?");
- return await this.createKeypair("./keypair.json", false);
+ return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, false);
}
- const keystoreData = JSON.parse(readFileSync(keypairPath, "utf-8"));
+ let keystoreData: any;
+ try {
+ keystoreData = JSON.parse(readFileSync(keypairPath, "utf-8"));
+ } catch (error) {
+ this.failSpinner("Failed to read or parse keystore file.");
+ await this.confirmPrompt("Would you like to create a new keypair?");
+ return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, true);
+ }
if (!this.isValidKeystoreFormat(keystoreData)) {
this.failSpinner("Invalid keystore format. Expected encrypted keystore file.");
await this.confirmPrompt("Would you like to create a new keypair?");
- return await this.createKeypair("./keypair.json", true);
+ return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, true);
}
return await this.decryptKeystore(keystoreData);
}📝 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.
| protected async getPrivateKey(): Promise<string> { | |
| const keypairPath = this.getConfigByKey("keyPairPath"); | |
| if (!keypairPath || !existsSync(keypairPath)) { | |
| await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?"); | |
| return await this.createKeypair("./keypair.json", false); | |
| } | |
| const keystoreData = JSON.parse(readFileSync(keypairPath, "utf-8")); | |
| if (!this.isValidKeystoreFormat(keystoreData)) { | |
| this.failSpinner("Invalid keystore format. Expected encrypted keystore file."); | |
| await this.confirmPrompt("Would you like to create a new keypair?"); | |
| return await this.createKeypair("./keypair.json", true); | |
| } | |
| await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?"); | |
| this.keypairManager.createKeypair(); | |
| return this.keypairManager.getPrivateKey(); | |
| return await this.decryptKeystore(keystoreData); | |
| } | |
| private static readonly DEFAULT_KEYSTORE_PATH = "./keystore.json"; | |
| protected async getPrivateKey(): Promise<string> { | |
| const keypairPath = this.getConfigByKey("keyPairPath"); | |
| if (!keypairPath || !existsSync(keypairPath)) { | |
| await this.confirmPrompt("Keypair file not found. Would you like to create a new keypair?"); | |
| return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, false); | |
| } | |
| let keystoreData: any; | |
| try { | |
| keystoreData = JSON.parse(readFileSync(keypairPath, "utf-8")); | |
| } catch (error) { | |
| this.failSpinner("Failed to read or parse keystore file."); | |
| await this.confirmPrompt("Would you like to create a new keypair?"); | |
| return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, true); | |
| } | |
| if (!this.isValidKeystoreFormat(keystoreData)) { | |
| this.failSpinner("Invalid keystore format. Expected encrypted keystore file."); | |
| await this.confirmPrompt("Would you like to create a new keypair?"); | |
| return await this.createKeypair(BaseAction.DEFAULT_KEYSTORE_PATH, true); | |
| } | |
| return await this.decryptKeystore(keystoreData); | |
| } |
🤖 Prompt for AI Agents
In src/lib/actions/BaseAction.ts around lines 68 to 85, improve error handling
by wrapping the readFileSync call in a try-catch block to gracefully handle
corrupted or unreadable keystore files. Replace the hardcoded default keystore
path "./keypair.json" with a configurable option, possibly passed as a parameter
or retrieved from configuration. Refactor the method by splitting it into
smaller functions, each handling a single responsibility such as checking file
existence, validating format, and decrypting the keystore, to enhance
readability and maintainability.
🔐 Implement Encrypted Keystore Security
Overview
Replaces the insecure
keypairManagersystem with enterprise-grade encrypted keystore functionality using ethers.js HDNodeWallet encryption. Centralizes all keystore logic in BaseAction to eliminate code duplication and prevent cyclic import issues across commands.🚀 Key Features
Security Enhancements
Architecture Improvements
error.message.includes())UX Improvements
🛠️ Technical Implementation
Centralized BaseAction Design
Benefits of Centralization
Security Features
Keystore Format
{ "version": 1, "encrypted": "ethers-encrypted-json-wallet", "address": "0x..." }📋 Breaking Changes
keypairManagerclass and all referencesgetPrivateKey()now handles encrypted keystore directlycreateKeypair()returns private key instead of void🧪 Testing Coverage
promptPassword, validation, retry mechanisms🔄 Migration Path
📈 Benefits
Files Changed:
src/lib/actions/BaseAction.ts- Centralized keystore implementationsrc/commands/keygen/create.ts- Updated integrationsrc/lib/interfaces/KeystoreData.ts- New type definitionstests/libs/baseAction.test.ts- Comprehensive test coverageFiles Removed:
src/lib/accounts/KeypairManager.ts- Logic moved to BaseActiontests/libs/accounts/KeypairManager.test.ts- Tests consolidatedSecurity Review: ✅ All private keys encrypted, proper attempt limiting, no plain text storage
Summary by CodeRabbit
New Features
Bug Fixes
Tests