Skip to content

fix: make /send endpoint minimal #36

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

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

Conversation

helloscoopa
Copy link

@helloscoopa helloscoopa commented Jul 17, 2025

User description

  • Remove whitelist configurations
  • Make API_SEND_HMAC_SECRET and API_SEND_FROM_USER_ID mandatory configurations when CONFIGOR_API_SEND_ENABLED is true

PR Type

Enhancement


Description

  • Remove whitelist configurations for sender accounts

  • Make sender ID configurable via environment variable

  • Switch from usernames to Telegram IDs for identification

  • Require mandatory HMAC secret and sender ID configuration


Changes diagram

flowchart LR
  A["API Request"] --> B["Validate Sender ID"]
  B --> C["Get Users by Telegram ID"]
  C --> D["Check Balance"]
  D --> E["Admin Approval?"]
  E -->|Yes| F["Create Pending Transaction"]
  E -->|No| G["Execute Transfer"]
  F --> H["Send Approval Request"]
  G --> I["Send Confirmations"]
Loading

Changes walkthrough 📝

Relevant files
Enhancement
4 files
pending_transactions.go
Update pending transaction execution to use Telegram IDs 
+21/-7   
pending_transaction.go
Replace username fields with Telegram ID fields                   
+11/-11 
send.go
Remove whitelist and Lightning address support, use Telegram IDs
+36/-93 
api_approval.go
Update approval system to use Telegram IDs                             
+38/-12 
Configuration changes
2 files
send_config.go
Remove whitelist config, add sender ID configuration         
+5/-5     
config.go
Update API configuration structure and validation               
+19/-21 
Tests
1 files
test_pay_api.sh
Update test script to use Telegram ID format                         
+6/-2     

Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • Summary by CodeRabbit

    • New Features

      • API send operations now use a fixed, configurable sender Telegram user ID and require recipient IDs to be numeric Telegram user IDs.
    • Refactor

      • Simplified transaction and approval flows by replacing username-based identification with Telegram user IDs.
      • Removed support for sending to Lightning addresses and usernames; only numeric Telegram user IDs are accepted as recipients.
      • Improved error messages and logging to reference user IDs.
    • Chores

      • Updated configuration requirements to enforce explicit sender user ID and HMAC secret.
      • Adjusted test scripts to match the new payload structure using numeric Telegram user IDs.

    @helloscoopa helloscoopa self-assigned this Jul 17, 2025
    Copy link

    coderabbitai bot commented Jul 17, 2025

    Walkthrough

    This change refactors the send and pending transaction APIs to use Telegram numeric user IDs instead of usernames for sender and recipient identification. It removes sender whitelisting, enforces a fixed sender ID from configuration, and updates related data structures, approval logic, and test scripts to align with these changes.

    Changes

    Files/Paths Change Summary
    internal/api/pending_transaction.go, internal/api/admin/pending_transactions.go Changed PendingTransaction struct to use FromUserId/ToUserId (int64) instead of usernames; updated logic for loading and executing transactions to use user IDs and cached user objects.
    internal/api/send.go Refactored send endpoint to use a fixed sender Telegram user ID from config, removed sender whitelist, restricted recipient to numeric Telegram user IDs only; updated logging and error handling accordingly.
    internal/api/send_config.go, internal/config.go Removed whitelisted sender logic; added FromUserId config field; enforced required config for API send module.
    internal/telegram/api_approval.go Replaced username-based recipient handling with user ID and user object fields in approval data and logic; updated function signatures and messages.
    test_pay_api.sh Updated test script payload to use numeric Telegram user IDs for "to" field; clarified comments and removed "from" field.

    Sequence Diagram(s)

    sequenceDiagram
        participant API Client
        participant API Service
        participant Config
        participant UserStore
        participant Admin
        participant TelegramBot
    
        API Client->>API Service: POST /api/send {to: userId, amount, memo}
        API Service->>Config: GetAPIFromUserId()
        API Service->>UserStore: Load fromUser by fixed ID
        API Service->>UserStore: Load toUser by provided userId
        API Service->>API Service: Create PendingTransaction (with user IDs)
        API Service->>TelegramBot: CreateAPIApprovalRequest(fromUser, toUserId, ...)
        TelegramBot->>Admin: Notify approval request
    
        Admin->>TelegramBot: Approve/Reject via Telegram
        TelegramBot->>API Service: approveAPITransactionHandler
        API Service->>UserStore: Load users by IDs (if needed)
        API Service->>API Service: Execute transaction
    
    Loading

    Possibly related PRs

    Suggested labels

    Review effort 4/5, Possible security concern

    Poem

    A hop, a leap, IDs in tow,
    No more usernames—just numbers flow!
    Whitelists gone, the sender’s set,
    Approval’s swift—no need to fret.
    Rabbits cheer for code so neat,
    Numeric paths make bots complete!
    🐇✨

    ✨ Finishing Touches
    • 📝 Generate Docstrings

    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.

    ❤️ 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.
      • Explain this complex logic.
      • 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 explain this code block.
      • @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 explain its main purpose.
      • @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.

    Support

    Need 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)

    • @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.
    • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
    • @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

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Error Handling

    The error handling when parsing fromUserId contains a bug where it logs fromUserId before it's successfully parsed, which could cause runtime errors or misleading log messages.

    log.Errorf("[api/send] Invalid sender Telegram ID %d: %v", fromUserId, err)
    RespondError(w, "Invalid sender configuration")
    return
    Configuration Validation

    The configuration validation uses panic() for missing required fields, which could cause the entire application to crash during startup. Consider using more graceful error handling.

    	if Configuration.API.Send.HMACSecret == "" {
    		panic(fmt.Errorf("API Send is enabled but CONFIGOR_API_SEND_HMAC_SECRET is not configured"))
    	}
    
    	if Configuration.API.Send.FromUserId == "" {
    		panic(fmt.Errorf("API Send is enabled but CONFIGOR_API_SEND_FROM_USER_ID is not configured"))
    	}
    }
    Data Consistency

    The fallback logic for loading users from IDs when user objects are not available could lead to inconsistent state if the user lookup fails but the transaction continues processing.

    if pendingTx.FromUser != nil {
    	fromUser = pendingTx.FromUser
    } else {
    	// Fallback: reload from ID if user object not available
    	fromUser, err = telegram.GetUserByTelegramID(pendingTx.FromUserId, *s.bot)
    	if err != nil {
    		return fmt.Errorf("sender user %d no longer exists or has no wallet: %v", pendingTx.FromUserId, err)
    	}
    }
    
    if pendingTx.ToUser != nil {
    	toUser = pendingTx.ToUser
    } else {
    	// Fallback: reload from ID if user object not available
    	toUser, err = telegram.GetUserByTelegramID(pendingTx.ToUserId, *s.bot)
    	if err != nil {
    		return fmt.Errorf("recipient user %d no longer exists or has no wallet: %v", pendingTx.ToUserId, err)
    	}
    }

    Copy link

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Fix error logging variable usage

    The error log uses fromUserId before it's successfully parsed, which will print
    garbage values. Use fromUserIdStr in the error message instead since that's the
    actual invalid input.

    internal/api/send.go [131-138]

     // Parse sender Telegram ID
     fromUserIdStr := GetAPIFromUserId()
     fromUserId, err := strconv.ParseInt(fromUserIdStr, 10, 64)
     if err != nil {
    -    log.Errorf("[api/send] Invalid sender Telegram ID %d: %v", fromUserId, err)
    +    log.Errorf("[api/send] Invalid sender Telegram ID %s: %v", fromUserIdStr, err)
         RespondError(w, "Invalid sender configuration")
         return
     }
    • Apply / Chat
    Suggestion importance[1-10]: 6

    __

    Why: The suggestion correctly identifies a bug where the error log uses fromUserId after parsing failed, which would log a zero value instead of the actual invalid input string fromUserIdStr.

    Low
    • More

    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

    🔭 Outside diff range comments (1)
    internal/api/send.go (1)

    91-98: Update isTelegramID to properly validate the full Telegram ID range

    The current regex (^[0-9]{5,15}$) is too restrictive—Telegram IDs start at 1 and can be as large as 2⁵²−1 (≈4.5×10¹⁵), which is up to 16 digits. I recommend refactoring to:

    • Strip the leading “@”
    • Ensure the remaining string is all digits
    • Parse it into a uint64
    • Check it’s between 1 and (1<<52)-1

    Example replacement in internal/api/send.go (lines 91–98):

     func isTelegramID(identifier string) bool {
    -   // Remove @ prefix if present
    -   identifier = strings.TrimPrefix(identifier, "@")
    -   // Check if it's all digits and has reasonable length for Telegram ID
    -   match, _ := regexp.MatchString(`^[0-9]{5,15}$`, identifier)
    -   return match
    +   identifier = strings.TrimPrefix(identifier, "@")
    +   // must be digits only
    +   if !regexp.MustCompile(`^\d+$`).MatchString(identifier) {
    +       return false
    +   }
    +   id, err := strconv.ParseUint(identifier, 10, 64)
    +   if err != nil {
    +       return false
    +   }
    +   const maxTelegramID = (1<<52) - 1
    +   return id >= 1 && id <= maxTelegramID
     }
    • internal/api/send.go: adjust import to include strconv and use a compiled digit-only regex.
    📜 Review details

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

    📥 Commits

    Reviewing files that changed from the base of the PR and between 3eb944a and a3d201a.

    📒 Files selected for processing (7)
    • internal/api/admin/pending_transactions.go (2 hunks)
    • internal/api/pending_transaction.go (3 hunks)
    • internal/api/send.go (6 hunks)
    • internal/api/send_config.go (1 hunks)
    • internal/config.go (3 hunks)
    • internal/telegram/api_approval.go (6 hunks)
    • test_pay_api.sh (1 hunks)
    🧰 Additional context used
    🧬 Code Graph Analysis (3)
    internal/api/send_config.go (1)
    internal/config.go (1)
    • Configuration (13-21)
    internal/telegram/api_approval.go (5)
    internal/lnbits/types.go (1)
    • User (24-39)
    internal/telegram/database.go (1)
    • GetUserByTelegramID (164-175)
    internal/utils/number_format.go (1)
    • FormatSats (37-64)
    internal/telegram/bot.go (1)
    • TipBot (25-34)
    internal/telegram/users.go (1)
    • GetUserStr (29-38)
    internal/api/pending_transaction.go (3)
    internal/api/send.go (1)
    • SendRequest (19-23)
    internal/lnbits/types.go (1)
    • User (24-39)
    internal/telegram/database.go (1)
    • GetUserByTelegramID (164-175)
    🔇 Additional comments (21)
    internal/api/send_config.go (1)

    37-40: LGTM! Clean implementation of the new fixed sender ID approach.

    The function correctly retrieves the configured sender Telegram ID, replacing the previous whitelist-based approach. This aligns perfectly with the PR objective of simplifying the /send endpoint.

    test_pay_api.sh (1)

    8-13: LGTM! Test script correctly reflects the new API contract.

    The updated comments and payload format properly align with the refactored API that now uses numeric Telegram user IDs and a fixed sender ID from configuration.

    internal/api/admin/pending_transactions.go (1)

    130-152: LGTM! Improved user loading logic with proper fallback.

    The optimization to use cached user objects when available is excellent for performance, and the fallback to loading by Telegram ID correctly aligns with the new ID-based architecture. Error handling and messaging are appropriately updated.

    internal/config.go (3)

    57-57: Minor formatting improvement.

    Good addition of blank line for better code organization and readability.


    82-92: LGTM! Configuration struct properly refactored for fixed sender approach.

    The removal of WhitelistedSenders and addition of FromUserId correctly implements the new architecture that enforces a single, fixed sender ID instead of a whitelist-based approach.


    190-199: Excellent enforcement of mandatory configuration.

    The validation logic correctly ensures that both HMACSecret and FromUserId are configured when the API Send module is enabled. Using panic for configuration validation at startup is appropriate and prevents runtime issues.

    internal/api/pending_transaction.go (4)

    19-20: LGTM! Proper migration to ID-based user identification.

    The change from username strings to Telegram user ID integers is a significant improvement that aligns with Telegram's primary identifier system and provides more reliable user identification.


    42-43: LGTM! Constructor properly updated for new architecture.

    The function signature correctly accepts the fromUserId parameter, and the transaction ID generation using numeric user IDs is more reliable than the previous username-based approach.


    50-51: LGTM! Struct initialization correctly uses user IDs.

    The field assignments properly store the numeric Telegram user IDs, maintaining consistency with the new ID-based architecture.


    125-140: LGTM! User loading logic properly migrated to ID-based approach.

    The function correctly loads users by their Telegram IDs instead of usernames, with appropriate error logging that reflects the new ID-based system. The graceful error handling allows the system to continue functioning even if user loading fails.

    internal/telegram/api_approval.go (5)

    29-31: LGTM! Struct fields properly support the transition to user IDs.

    The addition of FromUserId, ToUser, and ToUserId fields aligns well with the migration from username-based to ID-based user identification.


    66-79: LGTM! Efficient user retrieval with proper fallback.

    Good implementation of using cached user data when available and falling back to database lookup only when necessary. The error handling appropriately notifies the user of failures.


    132-132: LGTM! Consistent with the new user object structure.

    The success message correctly uses the username from the user object.


    177-192: LGTM! Robust user display name handling.

    Excellent implementation with multiple fallback options for displaying the recipient. The code gracefully handles cases where user lookup fails or users don't have usernames.


    212-214: LGTM! Proper data storage for approval tracking.

    The approval data correctly stores both the user ID and the user object (when available) for efficient retrieval later.

    internal/api/send.go (6)

    20-20: LGTM! Simplified request structure aligns with PR objectives.

    The removal of the "from" field and restriction to numeric Telegram IDs simplifies the API and improves security by enforcing a fixed sender.


    141-144: LGTM! Clear validation for recipient field.

    The validation correctly enforces that only numeric Telegram IDs are accepted as recipients.


    169-183: LGTM! Robust recipient lookup with proper error handling.

    The code correctly parses the numeric ID and performs user lookup with appropriate error messages for both parsing and lookup failures.


    197-197: LGTM! Correct parameter passing for pending transaction.

    The pending transaction creation correctly includes the sender's Telegram ID.


    208-220: LGTM! Proper approval flow with ID-based responses.

    The approval request correctly uses the recipient's user ID, and the response fields appropriately use the string representations of the IDs.


    280-281: LGTM! Consistent response format for successful transactions.

    The response correctly uses string representations of the user IDs, maintaining consistency with the approval flow.

    Comment on lines +131 to +138
    // Parse sender Telegram ID
    fromUserIdStr := GetAPIFromUserId()
    fromUserId, err := strconv.ParseInt(fromUserIdStr, 10, 64)
    if err != nil {
    log.Errorf("[api/send] Invalid sender Telegram ID %d: %v", fromUserId, err)
    RespondError(w, "Invalid sender configuration")
    return
    }
    Copy link

    Choose a reason for hiding this comment

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

    ⚠️ Potential issue

    Fix variable usage in error logging.

    There's a bug in the error logging - fromUserId is used before it's assigned from the parsing result.

    -		log.Errorf("[api/send] Invalid sender Telegram ID %d: %v", fromUserId, err)
    +		log.Errorf("[api/send] Invalid sender Telegram ID %s: %v", fromUserIdStr, err)
    📝 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
    // Parse sender Telegram ID
    fromUserIdStr := GetAPIFromUserId()
    fromUserId, err := strconv.ParseInt(fromUserIdStr, 10, 64)
    if err != nil {
    log.Errorf("[api/send] Invalid sender Telegram ID %d: %v", fromUserId, err)
    RespondError(w, "Invalid sender configuration")
    return
    }
    // Parse sender Telegram ID
    fromUserIdStr := GetAPIFromUserId()
    fromUserId, err := strconv.ParseInt(fromUserIdStr, 10, 64)
    if err != nil {
    log.Errorf("[api/send] Invalid sender Telegram ID %s: %v", fromUserIdStr, err)
    RespondError(w, "Invalid sender configuration")
    return
    }
    🤖 Prompt for AI Agents
    In internal/api/send.go around lines 131 to 138, the error log uses fromUserId
    before it is assigned, causing incorrect logging. Replace fromUserId in the log
    message with fromUserIdStr, which holds the original string value that failed to
    parse, to correctly reflect the invalid input in the error log.
    

    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.

    1 participant