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

Support Card2K into Dotman (close minevn/dotman#54) #63

Open
wants to merge 6 commits into
base: master
Choose a base branch
from

Conversation

tranlong5252
Copy link
Contributor

@tranlong5252 tranlong5252 commented Jan 29, 2025

Summary by CodeRabbit

  • New Features

    • Added support for a new card provider named "card2k".
    • Introduced a new card charging API integration with partner ID and partner key authentication.
    • Implemented an MD5 hash utility method for secure request signing.
    • Added a new property for PIN management in card processing.
  • Improvements

    • Enhanced card transaction processing with additional status checking and logging capabilities.
    • Expanded data retrieval to include PIN values in card waiting records.

Copy link

coderabbitai bot commented Jan 29, 2025

Walkthrough

The pull request introduces a new card provider named "card2k" to the dotman plugin. This involves adding a new case in the CardProvider class to handle the provider, alongside the creation of a Card2KCP class that manages interactions with a card charging API. Additionally, a utility method for computing MD5 hashes is introduced in the Utils class. The implementation supports extracting partner credentials, generating request parameters, processing API responses, and managing card transaction statuses. Changes also include the addition of a pin property in the CardWaiting class and modifications to the LogDAO class to fetch this new property.

Changes

File Change Summary
dotman-plugin/src/main/java/net/minevn/dotman/providers/CardProvider.kt Added new provider case for "card2k", extracting partnerId and partnerKey for Card2KCP initialization
dotman-plugin/src/main/java/net/minevn/dotman/providers/types/Card2KCP.kt New class implementing card charging API interactions with methods for request generation, response parsing, and card status management
dotman-plugin/src/main/java/net/minevn/dotman/utils/Utils.kt Added md5() extension method for computing MD5 hash of strings
dotman-plugin/src/main/java/net/minevn/dotman/card/CardWaiting.kt Added pin property to CardWaiting class and updated toCard() method to include pin
dotman-plugin/src/main/java/net/minevn/dotman/database/LogDAO.kt Modified getWaitingCards to include fetching pin value for CardWaiting objects

Sequence Diagram

sequenceDiagram
    participant User
    participant CardProvider
    participant Card2KCP
    participant CardAPI
    
    User->>CardProvider: Initiate card transaction
    CardProvider->>Card2KCP: Create with partner credentials
    Card2KCP->>Card2KCP: Generate request parameters
    Card2KCP->>CardAPI: Send card verification request
    CardAPI-->>Card2KCP: Return response
    Card2KCP->>Card2KCP: Parse response
    Card2KCP->>User: Update transaction status
Loading

Poem

🐰 A rabbit's tale of cards anew,
Card2K joins the charging crew!
With MD5 and partner's might,
Transactions dance with pure delight 🎉
A plugin's magic, swift and bright! 💳


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

🧹 Nitpick comments (6)
dotman-plugin/src/main/java/net/minevn/dotman/providers/types/Card2KCP.kt (5)

14-18: Add constructor parameter validation for robustness.

Currently, the constructor assumes non-empty, valid strings. If the config is missing or empty, it might lead to unexpected issues or empty credentials. Consider validating or logging warnings if partnerId/partnerKey are blank or malformed.

 class Card2KCP(private val partnerId: String, private val partnerKey: String) : CardProvider() {
     init {
+        require(partnerId.isNotEmpty()) { "partnerId must not be empty" }
+        require(partnerKey.isNotEmpty()) { "partnerKey must not be empty" }
         statusCards = CardType.entries.filter { it.getTypeId() != null }.associateWith { true }
     }
 }

20-21: Consider making API URLs configurable.

These strings are currently hardcoded. If they ever change or if you need to target a test environment, you might want to store them in a config file or constants.

Also applies to: 22-23


35-46: Use a logger instead of direct printing for production environments.

Line 36 currently prints the raw response. Logging is generally preferable and can be filtered for different log levels, improving observability. Also, ensure not to log sensitive data in production.


66-66: Avoid reliance on enum index ordering.

Relying on the position in CardPrice.entries might break if a new price is inserted in the middle. If the API strictly correlates to ordinal values, freeze or carefully govern the enum’s order or store a custom property for priceId.


91-91: Confirm card status updates handle concurrency.

updateStatus() delegates to checkWaitingCards(), which iterates waiting cards. If large volumes of card checks are performed, ensure concurrency or performance is not an issue. Consider caching or throttling if needed.

dotman-plugin/src/main/java/net/minevn/dotman/providers/CardProvider.kt (1)

52-56: Validate or log absent config values.

Though using !! ensures non-null, if partner-id or partner-key is missing in the config, the plugin will crash. Consider safer retrieval with fallback or meaningful error messages.

-                    val partnerId = config.getString("partner-id")!!
-                    val partnerKey = config.getString("partner-key")
+                    val partnerId = config.getString("partner-id").orEmpty()
+                    val partnerKey = config.getString("partner-key").orEmpty()
+                    if (partnerId.isBlank() || partnerKey.isBlank()) {
+                        throw IllegalStateException("partner-id or partner-key is missing or empty in configuration")
+                    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 42e670e and cf6b252.

📒 Files selected for processing (3)
  • dotman-plugin/src/main/java/net/minevn/dotman/providers/CardProvider.kt (2 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/providers/types/Card2KCP.kt (1 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/utils/Utils.kt (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (5)
dotman-plugin/src/main/java/net/minevn/dotman/providers/types/Card2KCP.kt (3)

24-33: Ensure secure or unique request IDs if needed.

Using only uppercase letters for the request_id might be acceptable for simpler integration. However, if the API or integration requires more uniqueness or security, consider adding digits or using a UUID. Also, confirm if the partner’s system requires the same ID for subsequent checks.


48-51: Confirm correct “waiting” state handling.

After marking the log as “waiting,” ensure downstream logic genuinely transitions the card to a processed or failed state. Otherwise, waiting logs might remain indefinite if not properly updated afterward.


53-64: Verify correct mapping for multiple card types.

Mapping both VIETTEL, MOBIFONE, VINAPHONE, GATE, and VIETNAMOBILE to "VNMOBI" can be confusing or incorrect if the API expects different codes for each. Ensure the external API indeed treats them all as the same telecommunication type code.

dotman-plugin/src/main/java/net/minevn/dotman/utils/Utils.kt (1)

109-111: Avoid MD5 for security-critical operations.

MD5 is considered weak for cryptographic purposes. If the external API mandates MD5, that’s fine. Otherwise, consider a more secure alternative (e.g., SHA-256). Also, confirm that the partner’s documentation explicitly requires MD5.

dotman-plugin/src/main/java/net/minevn/dotman/providers/CardProvider.kt (1)

7-7: Import usage looks fine.

No concerns regarding the import for Card2KCP.

@tranlong5252 tranlong5252 changed the title Support Card2K into Dotman Support Card2K into Dotman (resolve#54) Jan 29, 2025
@tranlong5252 tranlong5252 changed the title Support Card2K into Dotman (resolve#54) Support Card2K into Dotman (resolve!54) Jan 29, 2025
@tranlong5252 tranlong5252 changed the title Support Card2K into Dotman (resolve!54) Support Card2K into Dotman (resolve #54) Jan 29, 2025
@tranlong5252 tranlong5252 changed the title Support Card2K into Dotman (resolve #54) Support Card2K into Dotman (close #54) Jan 29, 2025
@tranlong5252 tranlong5252 changed the title Support Card2K into Dotman (close #54) Support Card2K into Dotman (close minevn/dotman#54) Jan 29, 2025
@tranlong5252 tranlong5252 linked an issue Jan 29, 2025 that may be closed by this pull request
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: 1

♻️ Duplicate comments (1)
dotman-plugin/src/main/java/net/minevn/dotman/providers/types/Card2KCP.kt (1)

37-46: ⚠️ Potential issue

Unify the response success logic.

The parseResponse method sets isSuccess = (status == "1"), while in isProcessed() you set isSuccess = (status == "success") and treat every non-“wait” status as processed. This discrepancy can lead to confusing or incorrect status handling. Consider consolidating these two checks to ensure consistent success criteria and processed logic.

This issue is similar to a previous review comment regarding misaligned isSuccess and actual return conditions, so marking it as a duplicate.

Also applies to: 67-88

🧹 Nitpick comments (4)
dotman-plugin/src/main/java/net/minevn/dotman/providers/types/Card2KCP.kt (4)

19-21: Consider making the API URLs configurable.

Currently, getApiUrl() and getCardCheckUrl() return hard-coded URLs, which can be problematic if the endpoint changes or you need to support multiple environments (e.g. development vs. production). Adding a configuration property (in a config file or environment variable) to store these URLs would make the code more flexible and maintainable.


23-25: Generate a truly unique request_id.

The request_id logic uses random uppercase letters. While this might work for testing or small-scale usage, collisions can still occur. Consider using a more robust approach to ensure uniqueness, such as UUID.randomUUID().toString().


34-35: Replace println with proper logging.

Using println(response) for logging may be less transparent in a production environment. Consider using a logging framework (e.g., SLF4J or any existing logger in the project) to manage log levels and outputs.


65-66: Avoid relying on ordinal positions in CardPrice.

(CardPrice.entries.indexOf(this) + 1).toString() depends on the index of the enum in the list. If the order of entries changes, the stored or expected price ID can become incorrect. Consider giving each enum a dedicated ID field and returning that instead.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8865925 and 7be1747.

📒 Files selected for processing (2)
  • dotman-plugin/src/main/java/net/minevn/dotman/providers/CardProvider.kt (2 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/providers/types/Card2KCP.kt (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • dotman-plugin/src/main/java/net/minevn/dotman/providers/CardProvider.kt

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1e58968 and 64e69f3.

📒 Files selected for processing (2)
  • dotman-plugin/src/main/java/net/minevn/dotman/card/CardWaiting.kt (1 hunks)
  • dotman-plugin/src/main/java/net/minevn/dotman/database/LogDAO.kt (1 hunks)
🔇 Additional comments (2)
dotman-plugin/src/main/java/net/minevn/dotman/card/CardWaiting.kt (2)

7-7: LGTM! Good choice of default value for backward compatibility.

The addition of the pin property with a default empty string value ensures backward compatibility with existing code.


15-15: LGTM! Correctly propagates pin value to Card constructor.

The toCard() function now properly passes the pin value to the Card constructor while maintaining the existing functionality.

@@ -104,6 +104,7 @@ abstract class LogDAO : DataAccess() {
getInt("id"),
getString("uuid"),
getString("seri"),
getString("pin"),
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify secure handling of sensitive PIN data.

While the implementation correctly retrieves the PIN from the database, ensure that:

  1. The PIN is stored securely in the database (e.g., hashed or encrypted).
  2. The PIN is transmitted securely between components.
  3. The PIN is not logged or exposed in debug/error messages.

Run this script to check for potential PIN exposure in logs:


🏁 Script executed:

#!/bin/bash
# Description: Check for potential PIN exposure in logs or debug statements

# Search for PIN logging
rg -i 'log|debug|info|error|warn' -A 5 -B 5 | rg -i 'pin|card'

Length of output: 27277


Security Concern: Ensure Secure Handling of PIN Data

The code retrieves the PIN with getString("pin") (e.g., in dotman-plugin/src/main/java/net/minevn/dotman/database/LogDAO.kt, line 107). Please verify and enforce the following:

  • Secure Storage: Confirm that the PIN is not stored in plaintext. It should be hashed or encrypted at rest.
  • Secure Transmission: Ensure the PIN is transmitted between components using secure, encrypted channels.
  • Avoid Inadvertent Exposure: The Card.toString() method (in dotman-plugin/src/main/java/net/minevn/dotman/card/Card.kt) includes the PIN, which could lead to accidental logging of sensitive data. Consider removing or masking the PIN in any diagnostic or debug outputs.

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

Successfully merging this pull request may close these issues.

Hỗ trợ Card2K
2 participants