Skip to content

Conversation

@ic4l4s9c
Copy link

@ic4l4s9c ic4l4s9c commented Nov 3, 2025

Description

Switches cryptographic api from node:crypto to the one provided by @better-auth/utils.

Impact

Simplifies integration of this plugin in runtimes that don't fully support node:crypto API, such as Convex.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)

Checklist

  • My code follows the style guidelines of this project (Ultracite/Biome)
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings or errors
  • I have added tests that prove my fix is effective or that my feature works (no new tests needed)
  • New and existing unit tests pass locally with my changes
  • I have run npm run type-check and it passes
  • I have run npx ultracite check and it passes

Testing

Since verifyTelegramAuth and verifyMiniAppInitData are now async, but preserve the same signature, I modified the current tests to work with async function calls.

Summary by CodeRabbit

  • Bug Fixes

    • Telegram and Mini App verification now uses asynchronous processing with added freshness validation for enhanced security.
  • Chores

    • Updated external utility dependencies.

@coderabbitai
Copy link

coderabbitai bot commented Nov 3, 2025

Walkthrough

The PR converts Telegram and Mini App verification functions from synchronous to asynchronous implementations, integrating an external utility library (@better-auth/utils) for HMAC operations, and adds authentication timestamp freshness validation via a maxAge parameter.

Changes

Cohort / File(s) Summary
Dependencies
package.json
Added @better-auth/utils: ^0.3.0 as a new dependency; fixed lint-staged configuration structure.
Async Verification Core
src/verify.ts
Converted verifyTelegramAuth and verifyMiniAppInitData to async functions returning Promise<boolean>. Migrated HMAC computation from node:crypto to @better-auth/utils (importKey + sign API). Added auth_date freshness check via maxAge parameter for Telegram verification. Updated secret key derivation and hash comparison logic for both functions.
Endpoint Integration
src/index.ts
Updated four endpoints (signInWithTelegram, linkTelegram, signInWithMiniApp, validateMiniApp) to await async verification calls; preserved existing error handling (401/404 for invalid state) and success paths.
Test Suite
src/verify.test.ts
Converted all test cases to async/await patterns; verification function calls now await their Promise results across valid, invalid, and edge-case scenarios (maxAge tolerance, data ordering, tampered data).

Sequence Diagram

sequenceDiagram
    participant Client
    participant Endpoint
    participant VerifyFn
    participant UtilsLib

    Client->>Endpoint: POST /signIn (Telegram/MiniApp data)
    Endpoint->>VerifyFn: await verifyTelegramAuth(data, token, maxAge)
    VerifyFn->>UtilsLib: importKey(secret)
    UtilsLib-->>VerifyFn: crypto key
    VerifyFn->>UtilsLib: sign(key, data)
    UtilsLib-->>VerifyFn: calculatedHash
    
    alt Hash matches & auth valid
        VerifyFn-->>Endpoint: Promise<true>
        Endpoint->>Endpoint: Process authentication
        Endpoint-->>Client: 200 + session token
    else Hash mismatch or expired
        VerifyFn-->>Endpoint: Promise<false>
        Endpoint-->>Client: 401 Unauthorized
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • src/verify.ts: Requires careful review of the HMAC migration logic, ensuring the new @better-auth/utils API produces identical verification results; auth_date freshness check logic and Promise flow.
  • src/index.ts: Verify all four endpoints properly await verification calls and error handling remains consistent.
  • src/verify.test.ts: Confirm async/await patterns are correctly applied; spot-check test data generation and edge cases (maxAge, tampered data) still validate the expected behavior.

Poem

🐰 A rabbit hops through async time,
Where promises and hashes intertwine,
From sync to await, the flow runs free,
Fresh timestamps guard authenticity! 🔐✨

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'feat: switch to cryptographic api provided by @better-auth/utils' directly and clearly summarizes the main change in the changeset. The title accurately reflects that the primary modification is replacing the cryptographic API from node:crypto with the one provided by @better-auth/utils, which is evident from the changes across package.json, src/verify.ts, src/index.ts, and src/verify.test.ts. The title is concise, specific, and follows conventional commit formatting.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1791282 and 7645490.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • package.json (1 hunks)
  • src/index.ts (4 hunks)
  • src/verify.test.ts (15 hunks)
  • src/verify.ts (4 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
src/verify.ts (1)
src/types.ts (1)
  • TelegramAuthData (4-12)
src/verify.test.ts (1)
src/verify.ts (2)
  • verifyTelegramAuth (12-47)
  • verifyMiniAppInitData (97-141)
src/index.ts (1)
src/verify.ts (2)
  • verifyTelegramAuth (12-47)
  • verifyMiniAppInitData (97-141)
🔇 Additional comments (10)
package.json (1)

73-76: LGTM! Clean dependency addition.

The @better-auth/utils dependency correctly supports the crypto API migration. The caret version range (^0.3.0) is appropriate for a utility library.

src/verify.test.ts (2)

49-116: LGTM! Comprehensive async test coverage.

The test suite correctly validates the async verification functions. Using node:crypto for test data generation is a good practice—it confirms compatibility between the Node.js crypto implementation and @better-auth/utils.


657-789: LGTM! Mini App verification tests properly updated.

All Mini App verification tests correctly await the async verifyMiniAppInitData function. The test helper createValidInitData continues to use node:crypto, which validates cross-implementation compatibility.

src/verify.ts (3)

1-2: LGTM! Clean migration to runtime-agnostic crypto API.

The switch from node:crypto to @better-auth/utils achieves the PR's goal of supporting non-Node runtimes (e.g., Convex).


12-47: LGTM! Async Telegram authentication verification.

The async conversion is clean and preserves all verification logic:

  • Timestamp freshness validation (maxAge)
  • Data-check-string construction
  • HMAC-SHA256 verification using the new API

The new crypto API pattern (importKeysign) correctly replaces the Node.js crypto operations.


97-141: LGTM! Async Mini App verification with correct secret key derivation.

The Mini App verification correctly implements the Telegram-specific flow:

  • Secret key derived via HMAC-SHA256("WebAppData", bot_token) (line 132)
  • Alphabetical parameter sorting for data-check-string
  • Proper HMAC verification with the derived secret

The test suite validates compatibility with the reference implementation.

src/index.ts (4)

118-122: LGTM! Proper async verification in sign-in flow.

The verifyTelegramAuth call is correctly awaited, maintaining the existing error handling and authentication flow.


250-254: LGTM! Proper async verification in link flow.

The verifyTelegramAuth call is correctly awaited in the account linking endpoint, preserving all validation logic.


421-421: LGTM! Proper async verification in Mini App sign-in.

The verifyMiniAppInitData call is correctly awaited, maintaining the conditional verification logic based on miniAppValidateInitData.


555-559: LGTM! Proper async verification in Mini App validation.

The verifyMiniAppInitData call is correctly awaited in the validation endpoint, preserving the response structure.


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.

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.

1 participant