Skip to content

Conversation

@BoryaGames
Copy link

@BoryaGames BoryaGames commented Jan 3, 2026

Описание

Делает сокет более стабильным и обновляет вход до последнего API.

Тип изменений

  • Исправление бага
  • Новая функциональность
  • Улучшение документации
  • Рефакторинг

Связанные задачи / Issue

Ссылка на issue, если есть: #

Тестирование

Покажите пример кода, который проверяет изменения:

import asyncio
from pymax import SocketMaxClient

client = SocketMaxClient(phone="+79221231234")

try:
    asyncio.run(client.start())
except Exception as e:
    print(f"Client stopped with exception: {e}")

Summary by CodeRabbit

  • Updates

    • Application version bumped to 25.21.0 with updated build number.
  • New Features

    • Authentication now normalizes/formats phone numbers before sending.
  • Bug Fixes

    • SSL socket handshake behavior adjusted for improved stability.
  • Breaking Changes

    • Language field removed from authentication requests — request and resend flows no longer accept a language parameter.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 3, 2026

📝 Walkthrough

Walkthrough

Removed language from auth payloads and public methods, added internal phone-splitting helper, changed SSL-wrapped socket to blocking during handshake, and bumped default app version and build number. (45 words)

Changes

Cohort / File(s) Summary
Authentication & Payload Updates
src/pymax/mixins/auth.py, src/pymax/payloads.py
Added _split_phone(self, phone: str) -> str; removed language parameter from request_code and resend_code signatures; removed language field from RequestCodePayload; payloads now use split phone and AuthType values.
Socket Handshake Configuration
src/pymax/mixins/socket.py
Set the SSL-wrapped socket to blocking mode during handshake (changed socket blocking state handling).
Version Constants
src/pymax/static/constant.py
Updated DEFAULT_APP_VERSION from "25.12.14" to "25.21.0" and DEFAULT_BUILD_NUMBER from 0x97CB to 0x9E2A.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

  • Dev/1.2.2 #32: Modifies the same authentication payload/API surface (language field and auth request methods), directly related.

Poem

🐰 I split the numbers, snug and neat,
Gone is language from the authbeat,
Sockets pause to take their time,
Version signs in tidy rhyme,
Hop! The changes land — precise and sweet.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Критические исправления сокета/входа' (Critical socket/login fixes) partially aligns with changes—socket fix is present, but the PR includes broader auth API refactoring beyond traditional 'fixes,' making it somewhat incomplete.
Description check ✅ Passed The PR description follows the template structure with all required sections completed: description, type of changes (bug fix selected), related tasks, and testing example provided.
✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e2721ec and 34ab6c1.

📒 Files selected for processing (1)
  • src/pymax/mixins/auth.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/pymax/mixins/auth.py

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@ink-developer
Copy link
Collaborator

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 3, 2026

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

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/pymax/mixins/auth.py (2)

33-72: Critical: Phone formatting assumes fixed 12-character length.

Lines 52-54 format the phone number by hardcoding slice indices for exactly 12 characters:

split_phone = phone[0:2] + " " + phone[2:5] + " " + phone[5:8] + " " + phone[8:10] + " " + phone[10:12]

However, PHONE_REGEX from constant.py allows phone numbers with 10-15 digits (with optional +). This will cause an IndexError for phone numbers that don't have exactly 12 characters, or produce incorrect formatting for numbers with more than 12 characters.

The example in the PR uses +79221231234 (12 characters), but this logic won't handle other valid formats.

🔎 Proposed fix with length validation
 async def request_code(self, phone: str) -> str:
     """
     Запрашивает код аутентификации для указанного номера телефона и возвращает временный токен.
 
     Метод отправляет запрос на получение кода верификации на переданный номер телефона.
     Используется в процессе аутентификации или регистрации.
 
     :param phone: Номер телефона в международном формате.
     :type phone: str
     :return: Временный токен для дальнейшей аутентификации.
     :rtype: str
     :raises ValueError: Если полученные данные имеют неверный формат.
     :raises Error: Если сервер вернул ошибку.
 
     .. note::
         Используется только в пользовательском flow аутентификации.
     """
     self.logger.info("Requesting auth code")
 
-    split_phone = phone[0:2] + " " + phone[2:5] + " " + phone[5:8] + " " + phone[8:10] + " " + phone[10:12]
+    if len(phone) != 12:
+        raise ValueError(f"Phone number must be exactly 12 characters, got {len(phone)}")
+    split_phone = f"{phone[0:2]} {phone[2:5]} {phone[5:8]} {phone[8:10]} {phone[10:12]}"
     payload = RequestCodePayload(
         phone=split_phone, type=AuthType.START_AUTH
     ).model_dump(by_alias=True)

Alternative: If the server requires this specific format, consider creating a helper method to validate and format phone numbers, then reuse it in both request_code and resend_code.


74-107: Critical: Duplicate phone formatting logic with same IndexError risk.

The same hardcoded 12-character phone formatting logic from request_code is duplicated here on line 87. This has the identical bug: it will fail with IndexError for phone numbers that aren't exactly 12 characters.

🔎 Proposed fix: Extract formatting logic into a helper method

Add a helper method to avoid duplication:

def _format_phone_for_api(self, phone: str) -> str:
    """Format phone number for API request (requires exactly 12 characters)."""
    if len(phone) != 12:
        raise ValueError(f"Phone number must be exactly 12 characters, got {len(phone)}")
    return f"{phone[0:2]} {phone[2:5]} {phone[5:8]} {phone[8:10]} {phone[10:12]}"

Then use it in both methods:

 async def request_code(self, phone: str) -> str:
     self.logger.info("Requesting auth code")
-    split_phone = phone[0:2] + " " + phone[2:5] + " " + phone[5:8] + " " + phone[8:10] + " " + phone[10:12]
+    split_phone = self._format_phone_for_api(phone)
     payload = RequestCodePayload(
         phone=split_phone, type=AuthType.START_AUTH
     ).model_dump(by_alias=True)
 async def resend_code(self, phone: str) -> str:
     self.logger.info("Resending auth code")
-    split_phone = phone[0:2] + " " + phone[2:5] + " " + phone[5:8] + " " + phone[8:10] + " " + phone[10:12]
+    split_phone = self._format_phone_for_api(phone)
     payload = RequestCodePayload(
         phone=split_phone, type=AuthType.RESEND
     ).model_dump(by_alias=True)
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dac1959 and e2721ec.

📒 Files selected for processing (4)
  • src/pymax/mixins/auth.py
  • src/pymax/mixins/socket.py
  • src/pymax/payloads.py
  • src/pymax/static/constant.py
💤 Files with no reviewable changes (1)
  • src/pymax/payloads.py
🧰 Additional context used
🧬 Code graph analysis (1)
src/pymax/mixins/auth.py (2)
src/pymax/payloads.py (1)
  • RequestCodePayload (56-58)
src/pymax/static/enum.py (1)
  • AuthType (173-177)
🪛 Ruff (0.14.10)
src/pymax/static/constant.py

80-80: Standard pseudo-random generators are not suitable for cryptographic purposes

(S311)


81-81: Standard pseudo-random generators are not suitable for cryptographic purposes

(S311)

🔇 Additional comments (4)
src/pymax/mixins/socket.py (1)

197-221: SSL handshake blocking mode: defensive but reasonable.

The explicit setblocking(True) on line 215 after wrapping ensures the SSL socket operates in blocking mode, even though the raw socket was already configured this way on line 204. While this appears redundant, it's defensive coding that guarantees consistency regardless of wrap_socket implementation details.

Since all socket I/O operations use run_in_executor (lines 256, 300, 321, 490), blocking mode is the correct choice and aligns with the PR's goal of improving socket stability.

src/pymax/static/constant.py (2)

83-83: Verify the new build number is valid.

The build number has been updated from 0x97CB (38859) to 0x9E2A (40490). Confirm this build number is recognized by the server and aligns with the updated app version.


79-79: Update README examples to reflect the new app version.

The version "25.21.0" passes all internal validation checks (requirement is ≥ "25.12.13"), but the documentation examples in README.md (lines 68 and 83) still reference the outdated "25.12.13" version and should be updated to match.

src/pymax/mixins/auth.py (1)

33-33: No language parameter removal detected in current code.

The review comment asserts that a language parameter has been removed from request_code and resend_code, but the current method signatures at lines 33 and 74 show only a phone: str parameter. The RequestCodePayload class contains only phone and type fields with no language field. Additionally, there are zero references to "language" throughout the file, and all existing calls to these methods use only the phone parameter.

Likely an incorrect or invalid review comment.

@ink-developer
Copy link
Collaborator

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 3, 2026

✅ 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.

@ink-developer ink-developer merged commit 3296226 into MaxApiTeam:dev/1.2.6 Jan 3, 2026
1 check passed
@BoryaGames BoryaGames deleted the dev/1.2.6 branch January 3, 2026 15:16
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