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

New: handle oneZero scrape #628

Open
wants to merge 2 commits into
base: feature/one-zerop-bank
Choose a base branch
from

Conversation

shaiu
Copy link
Contributor

@shaiu shaiu commented Nov 25, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for two-factor authentication with OTP token management for bank scraping
    • Introduced a new GetOtp component for handling OTP input
  • Improvements

    • Enhanced bank scraping process to handle two-factor authentication more robustly
    • Streamlined transaction import and configuration management
  • Removed

    • Removed deprecated financial account details retrieval function

The updates focus on improving authentication and scraping processes for bank transactions.

Copy link

coderabbitai bot commented Nov 25, 2024

Walkthrough

The pull request introduces enhancements to the configuration management and transaction import processes, with a focus on two-factor authentication handling. A new function updateOtpLongTermToken is added to the configuration manager to update OTP tokens for specific accounts. The bank scraper now includes more robust two-factor authentication logic for the OneZero bank, with improved event handling and token management. Additionally, some code simplification occurs in the import transactions and setup helpers modules, and a new GetOtp component is integrated into the renderer's App component.

Changes

File Change Summary
packages/main/src/backend/configManager/configManager.ts Added updateOtpLongTermToken method to update OTP long-term tokens for specific accounts
packages/main/src/backend/import/bankScraper.ts Enhanced two-factor authentication handling for OneZero bank, added eventPublisher parameter to scrape function
packages/main/src/backend/import/importTransactions.ts Removed getFinancialAccountDetails function, simplified imports and transaction enrichment
packages/main/src/manual/setupHelpers.ts Removed commented-out code for financial account details
packages/renderer/src/components/App.tsx Added GetOtp component to the render method
packages/renderer/src/components/GetOtp.tsx Updated import path for useConfigStore

Sequence Diagram

sequenceDiagram
    participant Scraper
    participant EventPublisher
    participant IPC
    participant ConfigManager

    Scraper->>EventPublisher: Trigger Two-Factor Auth
    EventPublisher->>IPC: Request OTP
    IPC-->>EventPublisher: Receive OTP
    Scraper->>Scraper: Get Long-Term Token
    Scraper->>ConfigManager: Update OTP Long-Term Token
    ConfigManager-->>Scraper: Token Updated
Loading

Poem

🐰 A rabbit's tale of tokens bright,
Of scraping banks with OTP might,
Config updates, smooth and clean,
Two-factor dance, a digital scene,
Hop hop hooray, our code takes flight! 🔐

✨ 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
Contributor

Pull request has been marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@github-actions github-actions bot added the Stale label Jan 25, 2025
@baruchiro
Copy link
Collaborator

@coderabbitai review

Copy link

coderabbitai bot commented Jan 26, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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: 0

🧹 Nitpick comments (4)
packages/main/src/backend/import/bankScraper.ts (2)

9-9: Type safety in .map(...)
Casting key as CompanyTypes is reasonable. If the codebase expands or new keys are introduced, consider adding runtime checks to avoid potential type mismatches.


38-38: Progress event callback
Emitting concise progress messages keeps the UI responsive. Consider logging or storing payload details if deeper analysis is needed later.

packages/renderer/src/components/App.tsx (1)

13-13: Render GetOtp
Placing <GetOtp /> within the main app ensures the OTP modal is always available. Ensure that the modal’s visibility logic remains controlled via the store to avoid unexpected pop-ups.

packages/main/src/backend/configManager/configManager.ts (1)

39-54: Consider enhancing type safety and validation.

While the implementation is generally good, there are a few improvements to consider:

  1. The type assertion on line 45-47 could be replaced with a more precise type definition
  2. Consider validating the otpLongTermToken format/structure before updating

Here's a suggested improvement:

+interface AccountWithLoginFields {
+  key: CompanyTypes;
+  loginFields: {
+    otpLongTermToken: string;
+  };
+}

 export async function updateOtpLongTermToken(
   key: CompanyTypes,
   otpLongTermToken: string,
   configPath: string = configFilePath,
 ): Promise<void> {
   const config = await getConfig(configPath);
-  const account = config.scraping.accountsToScrape.find((acc) => acc.key === key) as {
-    loginFields: { otpLongTermToken: string };
-  };
+  const account = config.scraping.accountsToScrape.find((acc): acc is AccountWithLoginFields => 
+    acc.key === key && 'loginFields' in acc && 'otpLongTermToken' in acc.loginFields
+  );
   if (account) {
+    if (!otpLongTermToken || typeof otpLongTermToken !== 'string') {
+      throw new Error('Invalid OTP long-term token format');
+    }
     account.loginFields.otpLongTermToken = otpLongTermToken;
     await updateConfig(configPath, config);
   } else {
     throw new Error(`Account with key ${key} not found`);
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d8c5f47 and 09f6b09.

📒 Files selected for processing (6)
  • packages/main/src/backend/configManager/configManager.ts (2 hunks)
  • packages/main/src/backend/import/bankScraper.ts (2 hunks)
  • packages/main/src/backend/import/importTransactions.ts (3 hunks)
  • packages/main/src/manual/setupHelpers.ts (0 hunks)
  • packages/renderer/src/components/App.tsx (2 hunks)
  • packages/renderer/src/components/GetOtp.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/main/src/manual/setupHelpers.ts
🔇 Additional comments (16)
packages/main/src/backend/import/bankScraper.ts (10)

2-2: Add clarity on usage of SCRAPERS imports
No functional issues identified. If future expansions require customizing scrapers, keep the import path consistent and well-documented.


3-3: Validate electron IPC usage
Importing ipcMain is appropriate here, but ensure usage remains restricted to the main process context. Consider future modularization if more IPC functionalities appear.


4-4: Confirm event-based architecture
Introducing EventPublisher from EventEmitter is a good approach for decoupling event dispatch logic from the core scraping flow. No immediate issues.


5-5: Centralize OTP token updates
Using updateOtpLongTermToken from the config manager is clean and maintainable. This ensures OTP management is centralized.


25-25: New eventPublisher parameter
Adding eventPublisher is a neat way to handle external event emission. Ensure every call site passes a valid EventPublisher instance.


28-32: Scraper options structure
Good to see the relevant fields (companyId, startDate, etc.) consolidated here. Setting verbose: false by default may hamper debugging; ensure it meets project requirements.


36-36: Empty line
No meaningful change.


39-39: Empty line
No meaningful change.


40-56: Implement 2FA flow for oneZero
This block introduces a well-structured approach for OTP retrieval and long-term token generation. Pointers:

  1. Consider encrypting the otpLongTermToken if stored on disk.
  2. Handle user inactivity or canceled OTP entry gracefully.
    Overall, logic is sound and extends the scraper flow robustly.

58-58: Return scraper results
Returning await scraper.scrape(credentials) is appropriate for an async function. Ensure error handling from the scraper is surfaced for debugging.

packages/renderer/src/components/App.tsx (1)

4-4: Import GetOtp
Neatly imported from ./GetOtp. This separation of OTP logic into its own component helps keep App cleaner.

packages/renderer/src/components/GetOtp.tsx (1)

4-4: Use of relative import
Switching to a relative path for useConfigStore confirms the code structure. Verify consistency across the codebase for store imports.

packages/main/src/backend/configManager/configManager.ts (1)

7-7: LGTM!

The import of CompanyTypes from 'israeli-bank-scrapers-core' is appropriate for type safety.

packages/main/src/backend/import/importTransactions.ts (3)

17-17: LGTM!

The addition of ImporterEvent to the imports is appropriate for handling OTP-related events.


120-120: LGTM!

Adding the eventPublisher parameter to bankScraper.scrape enables proper event handling for OTP flows.


172-177: LGTM!

The simplified return statement improves code readability without changing functionality.

@github-actions github-actions bot removed the Stale label Jan 27, 2025
Copy link
Collaborator

@baruchiro baruchiro left a comment

Choose a reason for hiding this comment

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

Didn't finished the review, הילדה שלי התעוררה 🤷‍♂️

BTW, I don't remember, but are you using the OTP support introduced on israeli-bank-scrapers here eshaham/israeli-bank-scrapers#760?

Comment on lines +39 to +43
export async function updateOtpLongTermToken(
key: CompanyTypes,
otpLongTermToken: string,
configPath: string = configFilePath,
): Promise<void> {
Copy link
Collaborator

Choose a reason for hiding this comment

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

rename to companyId

Suggested change
export async function updateOtpLongTermToken(
key: CompanyTypes,
otpLongTermToken: string,
configPath: string = configFilePath,
): Promise<void> {
export async function updateOtpLongTermToken(
companyId: CompanyTypes,
otpLongTermToken: string,
configPath: string = configFilePath,
): Promise<void> {

Comment on lines +48 to +53
if (account) {
account.loginFields.otpLongTermToken = otpLongTermToken;
await updateConfig(configPath, config);
} else {
throw new Error(`Account with key ${key} not found`);
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

return early: if not account, throw. Otherwise, continue.

Suggested change
if (account) {
account.loginFields.otpLongTermToken = otpLongTermToken;
await updateConfig(configPath, config);
} else {
throw new Error(`Account with key ${key} not found`);
}
if (!account) {
throw new Error(`Account with key ${key} not found`);
}
account.loginFields.otpLongTermToken = otpLongTermToken;
await updateConfig(configPath, config);

Comment on lines 7 to 10
export const inputVendors = Object.keys(SCRAPERS)
// Deprecated. see https://github.com/eshaham/israeli-bank-scrapers/blob/07ecd3de0c4aa051f119aa943493f0cda943158c/src/definitions.ts#L26-L29
.filter((key) => key !== CompanyTypes.hapoalimBeOnline)
.map((key) => ({
key,
...SCRAPERS[key as CompanyTypes],
}));
.map((key) => ({ key, ...SCRAPERS[key as CompanyTypes] }));

Copy link
Collaborator

Choose a reason for hiding this comment

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

don't remove this comment

Comment on lines +40 to +56
if (companyId === CompanyTypes.oneZero) {
const creds = credentials as typeof credentials & { otpLongTermToken: string; phoneNumber: string };
if (!creds.otpLongTermToken) {
await scraper.triggerTwoFactorAuth(creds.phoneNumber);
await eventPublisher.emit(EventNames.GET_OTP);
const otpCode = await new Promise<string>((resolve) => {
ipcMain.once('get-otp-response', (event, input) => resolve(input));
});
const result = await scraper.getLongTermTwoFactorToken(otpCode);
if ('longTermTwoFactorAuthToken' in result) {
await updateOtpLongTermToken(companyId, result.longTermTwoFactorAuthToken);
creds.otpLongTermToken = result.longTermTwoFactorAuthToken;
} else {
throw new Error('Failed to get long-term two-factor auth token');
}
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

This function must be extracted into a function. More than that, think when more banks will require OTP, I expect the "if" to be extracted into a function to.

I hope you understand what I mean. Here should be only handleOtp function, and inside it there will be if-else/switch-case that will direct into bank-specific function.

Comment on lines +43 to +44
await scraper.triggerTwoFactorAuth(creds.phoneNumber);
await eventPublisher.emit(EventNames.GET_OTP);
Copy link
Collaborator

Choose a reason for hiding this comment

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

  1. Use emitProgressEvent instead of eventPublisher.emit.
  2. Is the scraper not emitting events of OTP itself?

Comment on lines +45 to +47
const otpCode = await new Promise<string>((resolve) => {
ipcMain.once('get-otp-response', (event, input) => resolve(input));
});
Copy link
Collaborator

Choose a reason for hiding this comment

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

All IPC calls are declared here: packages/main/src/handlers/index.ts

I expect this call to follow that pattern.

if (companyId === CompanyTypes.oneZero) {
const creds = credentials as typeof credentials & { otpLongTermToken: string; phoneNumber: string };
if (!creds.otpLongTermToken) {
await scraper.triggerTwoFactorAuth(creds.phoneNumber);
Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm not sure how the process is implemented, but I see the triggerTwoFactorAuth is called during the scraping on israeli-bank-scrapers, see triggerTwoFactorAuth, so why running it in our code too?

Comment on lines +48 to +54
const result = await scraper.getLongTermTwoFactorToken(otpCode);
if ('longTermTwoFactorAuthToken' in result) {
await updateOtpLongTermToken(companyId, result.longTermTwoFactorAuthToken);
creds.otpLongTermToken = result.longTermTwoFactorAuthToken;
} else {
throw new Error('Failed to get long-term two-factor auth token');
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

use result.success

Suggested change
const result = await scraper.getLongTermTwoFactorToken(otpCode);
if ('longTermTwoFactorAuthToken' in result) {
await updateOtpLongTermToken(companyId, result.longTermTwoFactorAuthToken);
creds.otpLongTermToken = result.longTermTwoFactorAuthToken;
} else {
throw new Error('Failed to get long-term two-factor auth token');
}
const result = await scraper.getLongTermTwoFactorToken(otpCode);
if (result.success) {
await updateOtpLongTermToken(companyId, result.longTermTwoFactorAuthToken);
creds.otpLongTermToken = result.longTermTwoFactorAuthToken;
} else {
throw new Error('Failed to get long-term two-factor auth token');
}

Comment on lines 93 to 94
}

Copy link
Collaborator

Choose a reason for hiding this comment

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

What is it? I see it is unused..?

If it is not related to your work, I prefer you to open a new PR for this, so if there will be a problem with this remove, it will be easy to revert it.

Comment on lines 171 to 175
const hash = calculateTransactionHash(transaction, companyId, accountNumber);
// const category = categoryCalculation.getCategoryNameByTransactionDescription(transaction.description);
const enrichedTransaction: EnrichedTransaction = {
return {
...transaction,
accountNumber,
// category,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Oh I see we don't have a category calculation anymore.

Anyway, please return the comment back.

Yes, I agree that developer should avoid code comments, but this project is in low maintainance and I prefer to keep such comments for the next time I will search something.

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.

2 participants