Skip to content

Add useAuthToken hook for in-app wallet authentication #7120

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

Merged

Conversation

jnsdls
Copy link
Member

@jnsdls jnsdls commented May 22, 2025

Add useAuthToken hook for in-app wallet authentication

This PR adds a new React hook useAuthToken() that returns a JWT authentication token for the currently active in-app wallet. This token can be used to authorize API calls to backend servers.

Key changes:

  • Added useAuthToken() hook that returns the auth token when an in-app wallet is active
  • Modified the InAppConnector interface to expose the storage property
  • Updated the wallet interface to include a getAuthToken() method for in-app wallets
  • Implemented token retrieval in the in-app wallet core implementation

The hook ensures the token is only returned when the active wallet is an in-app wallet and matches the active account.

Example usage:

function MyComponent() {
  const authToken = useAuthToken();

  const fetchData = async () => {
    const response = await fetch('https://api.example.com/data', {
      headers: {
        'Authorization': `Bearer ${authToken}`
      }
    });
    // ... handle response
  };
}

Summary by CodeRabbit

  • New Features
    • Introduced a new hook to retrieve authentication tokens for in-app wallets, enabling secure authorization for API calls.
    • Added support for authentication token management within the wallet lifecycle.
  • Documentation
    • Added usage examples and clarifications regarding authentication token availability for wallets.

PR-Codex overview

This PR focuses on enhancing wallet functionality by introducing an authToken feature for in-app wallets, making storage public, and adding a new hook to retrieve the authentication token.

Detailed summary

  • Changed storage from private to public in native-connector.ts and web-connector.ts.
  • Added getAuthToken method to the wallet interface in wallet.ts.
  • Included storage in the InAppConnector interface.
  • Implemented authToken retrieval in createInAppWallet.
  • Added useAuthToken hook to fetch the authentication token for the active wallet.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Copy link

vercel bot commented May 22, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
docs-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 22, 2025 6:10pm
login ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 22, 2025 6:10pm
thirdweb_playground ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 22, 2025 6:10pm
thirdweb-www ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 22, 2025 6:10pm
wallet-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 22, 2025 6:10pm

Copy link

changeset-bot bot commented May 22, 2025

⚠️ No Changeset found

Latest commit: 3f6f8cb

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

coderabbitai bot commented May 22, 2025

Walkthrough

A new React hook, useAuthToken, was introduced to provide JWT authentication tokens from the active wallet when available. The wallet infrastructure was updated to support retrieving and managing authentication tokens, including changes to wallet interfaces and connectors. Relevant exports were updated to include the new hook.

Changes

File(s) Change Summary
packages/thirdweb/src/react/core/hooks/wallets/useAuthToken.ts Added useAuthToken hook to return JWT auth token for the active wallet if available.
packages/thirdweb/src/wallets/interfaces/wallet.ts Added optional getAuthToken method to the Wallet interface.
packages/thirdweb/src/wallets/in-app/core/interfaces/connector.ts Added storage property to InAppConnector interface.
packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts Added internal authToken state and getAuthToken method to wallet object; manages token on connect/disconnect.
packages/thirdweb/src/wallets/in-app/native/native-connector.ts,
.../web-connector.ts
Changed storage property visibility from private to public in both connector classes.
packages/thirdweb/src/exports/react.ts,
.../react.native.ts
Exported useAuthToken from wallet hooks; adjusted export order for useAdminWallet.

Sequence Diagram(s)

sequenceDiagram
    participant ReactComponent
    participant useAuthToken
    participant useActiveWallet
    participant useActiveAccount
    participant Wallet

    ReactComponent->>useAuthToken: Call hook
    useAuthToken->>useActiveWallet: Get active wallet
    useAuthToken->>useActiveAccount: Get active account
    alt Wallet has getAuthToken and account matches
        useAuthToken->>Wallet: getAuthToken()
        Wallet-->>useAuthToken: Return JWT token
        useAuthToken-->>ReactComponent: Return token
    else Not available
        useAuthToken-->>ReactComponent: Return null
    end
Loading
sequenceDiagram
    participant User
    participant Wallet
    participant ConnectorStorage

    User->>Wallet: connect() or autoConnect()
    Wallet->>ConnectorStorage: Retrieve auth cookie
    alt Success
        ConnectorStorage-->>Wallet: Return auth token
        Wallet->>Wallet: Set authToken
    else Failure
        ConnectorStorage-->>Wallet: Error
        Wallet->>Wallet: Set authToken to null
    end
    User->>Wallet: disconnect()
    Wallet->>Wallet: Reset authToken to null
Loading

Suggested reviewers

  • jnsdls

📜 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 3f6f8cb and 526b6b5.

📒 Files selected for processing (8)
  • packages/thirdweb/src/exports/react.native.ts (1 hunks)
  • packages/thirdweb/src/exports/react.ts (1 hunks)
  • packages/thirdweb/src/react/core/hooks/wallets/useAuthToken.ts (1 hunks)
  • packages/thirdweb/src/wallets/in-app/core/interfaces/connector.ts (2 hunks)
  • packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts (4 hunks)
  • packages/thirdweb/src/wallets/in-app/native/native-connector.ts (1 hunks)
  • packages/thirdweb/src/wallets/in-app/web/lib/web-connector.ts (1 hunks)
  • packages/thirdweb/src/wallets/interfaces/wallet.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/thirdweb/src/wallets/in-app/native/native-connector.ts
  • packages/thirdweb/src/wallets/in-app/core/interfaces/connector.ts
  • packages/thirdweb/src/exports/react.ts
  • packages/thirdweb/src/wallets/in-app/web/lib/web-connector.ts
  • packages/thirdweb/src/exports/react.native.ts
  • packages/thirdweb/src/wallets/interfaces/wallet.ts
  • packages/thirdweb/src/react/core/hooks/wallets/useAuthToken.ts
  • packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Unit Tests
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Build Packages
  • GitHub Check: Lint Packages
  • GitHub Check: Size
  • GitHub Check: Analyze (javascript)
✨ Finishing Touches
  • 📝 Generate Docstrings

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

@github-actions github-actions bot added packages SDK Involves changes to the thirdweb SDK labels May 22, 2025
Copy link
Member Author

jnsdls commented May 22, 2025


How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • merge-queue - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

This stack of pull requests is managed by Graphite. Learn more about stacking.

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

🔭 Outside diff range comments (1)
packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts (1)

58-201: 💡 Verification agent

🧩 Analysis chain

Consider implementing token expiration handling.

JWT tokens typically have an expiration time. There's currently no mechanism to refresh the token when it expires or to check if it's still valid before returning it.

Consider adding a token validation and refresh mechanism, especially if the tokens have short lifespans. This could involve:

  1. Parsing the JWT to check its expiration time
  2. Implementing a refresh mechanism when tokens are near expiration
  3. Adding a validation check in the getAuthToken method

Example implementation for the getAuthToken method:

getAuthToken: () => {
  if (authToken && isTokenExpired(authToken)) {
    // Either return null for expired tokens or trigger a refresh
    // Could also set up a background refresh mechanism
    return null;
  }
  return authToken;
},

🌐 Web query:

How to check if a JWT token is expired in JavaScript?

💡 Result:

How to Check if a JWT Token Is Expired in JavaScript

To determine if a JWT (JSON Web Token) is expired in JavaScript, the most common approach is to decode the token's payload, read the exp (expiration) claim, and compare it with the current time. Here’s a step-by-step guide:

1. Understanding JWT Structure and Expiration

  • A JWT consists of three parts separated by dots: header, payload, and signature.
  • The payload contains claims, including the exp claim, which is the expiration time as a Unix timestamp (in seconds)[6][7].
  • If the current time (in seconds) is greater than or equal to exp, the token is expired[4][6][7].

2. Decoding the Token and Checking Expiry

You can use pure JavaScript to decode the payload and check if the token has expired. The following function does this:

const isTokenExpired = (token) => {
  if (!token) return true;
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    // `exp` is in seconds, Date.now() in milliseconds
    return Date.now() >= payload.exp * 1000;
  } catch (e) {
    // If token can't be decoded, treat as expired
    return true;
  }
};
  • atob decodes the base64-encoded payload.
  • payload.exp gives the expiration timestamp (seconds since epoch).
  • Date.now() returns the current time in milliseconds, so multiply exp by 1000 for comparison.

3. Using Libraries

Several libraries can automate this check:

  • jwt-check-expiration: A lightweight package to check JWT expiration in the browser[2].
  • jwt-decode: Popular for decoding JWTs, but you still need to compare the exp claim manually.

4. Notes and Best Practices

  • This client-side check is useful for preventing unnecessary API calls or for UI state management.
  • Security-critical validation (like actual access control) should always be performed on the server, with signature verification.
  • Handle tokens that cannot be decoded gracefully by treating them as expired[4].

5. Summary Table

Step Action Reference
Decode JWT payload Use atob(token.split('.')[1]) [4][7][6]
Extract exp claim Get expiration timestamp from payload [6][7]
Compare with now Date.now() >= exp * 1000 (returns true if expired) [4][8]

This approach is widely used in React and other JavaScript frameworks for session management and proactive token refresh[1][8].

Citations:


Implement Token Expiration and Refresh in getAuthToken

The current getAuthToken simply returns the stored JWT without any expiry check or refresh logic. To prevent returning expired tokens (and avoid silent failures), add a validation step and, when possible, a refresh mechanism:

• File to update:

  • packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts
  • Method: getAuthToken

• Steps:

  1. Create or import a utility, e.g. isTokenExpired(token: string): boolean, that decodes the JWT’s exp claim and compares it to Date.now().
  2. Change getAuthToken to:
    • Check authToken; return null if missing or expired.
    • Optionally attempt to refresh via your connector (e.g. connector.storage.getAuthCookie() or a new refreshAuthToken() helper) before returning.
  3. If you surface token refresh errors, ensure callers handle them (or fall back to a fresh connect()).

Example diff:

- getAuthToken: () => authToken,
+ getAuthToken: async () => {
+   if (!authToken || isTokenExpired(authToken)) {
+     // Try refreshing the token
+     try {
+       const connector = await getOrCreateInAppWalletConnector(client, connectorFactory, ecosystem);
+       authToken = await connector.storage.getAuthCookie();
+     } catch {
+       return null;
+     }
+   }
+   return authToken;
+ },

• Add a helper in e.g. src/utils/jwt.ts:

export function isTokenExpired(token: string): boolean {
  try {
    const { exp } = JSON.parse(atob(token.split('.')[1]));
    return Date.now() >= exp * 1000;
  } catch {
    return true;
  }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 88533d9 and bed6e2f.

📒 Files selected for processing (6)
  • packages/thirdweb/src/react/core/hooks/wallets/useAuthToken.ts (1 hunks)
  • packages/thirdweb/src/wallets/in-app/core/interfaces/connector.ts (2 hunks)
  • packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts (4 hunks)
  • packages/thirdweb/src/wallets/in-app/native/native-connector.ts (1 hunks)
  • packages/thirdweb/src/wallets/in-app/web/lib/web-connector.ts (1 hunks)
  • packages/thirdweb/src/wallets/interfaces/wallet.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Lint Packages
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Unit Tests
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (9)
packages/thirdweb/src/wallets/in-app/web/lib/web-connector.ts (1)

53-53: Changed property visibility from private to public

The storage property has been changed from private to public to support the new authentication token functionality. This enables the in-app wallet to access the storage for retrieving auth tokens.

packages/thirdweb/src/wallets/in-app/native/native-connector.ts (1)

32-32: Changed property visibility from private to public

The storage property has been changed from private to public to maintain consistent interface implementation with the InAppConnector interface. This change enables the new authentication token functionality.

packages/thirdweb/src/wallets/in-app/core/interfaces/connector.ts (2)

3-3: Added import for ClientScopedStorage type

Added the import for ClientScopedStorage type to support the new storage property in the interface.


42-42: Added storage property to the InAppConnector interface

Added a required storage property of type ClientScopedStorage to the interface. This change formalizes the public storage requirement for all in-app wallet connector implementations, enabling the auth token functionality.

packages/thirdweb/src/wallets/interfaces/wallet.ts (1)

154-165: Added getAuthToken method to the Wallet interface

Added a new conditional method getAuthToken that's only available for in-app wallets. This method returns the authentication token for the wallet, which can be used for making authorized API calls. The documentation and typings are well-structured with a clear example of usage.

packages/thirdweb/src/react/core/hooks/wallets/useAuthToken.ts (1)

4-42: Well-implemented auth token hook with clear documentation.

The useAuthToken hook is well-designed and follows React best practices. It correctly checks for all necessary conditions before returning the auth token, and includes comprehensive JSDoc documentation with a practical usage example.

packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts (3)

58-58: LGTM: Auth token state initialization.

The auth token state is properly initialized as null.


62-62: LGTM: Auth token accessor implementation.

The getAuthToken method correctly exposes the current auth token state.


201-201: LGTM: Auth token cleanup on disconnect.

Properly resets the auth token to null when disconnecting the wallet.

@jnsdls jnsdls force-pushed the Add_useAuthToken_hook_for_in-app_wallet_authentication branch 2 times, most recently from 4e5b8b4 to db54597 Compare May 22, 2025 04:55
Copy link

codecov bot commented May 22, 2025

Codecov Report

Attention: Patch coverage is 93.75000% with 1 line in your changes missing coverage. Please review.

Project coverage is 55.61%. Comparing base (f31116e) to head (526b6b5).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...dweb/src/wallets/in-app/core/wallet/in-app-core.ts 93.33% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #7120   +/-   ##
=======================================
  Coverage   55.61%   55.61%           
=======================================
  Files         902      902           
  Lines       58162    58177   +15     
  Branches     4087     4085    -2     
=======================================
+ Hits        32344    32356   +12     
- Misses      25713    25716    +3     
  Partials      105      105           
Flag Coverage Δ
packages 55.61% <93.75%> (+<0.01%) ⬆️
Files with missing lines Coverage Δ
...irdweb/src/wallets/in-app/web/lib/web-connector.ts 47.61% <100.00%> (ø)
...dweb/src/wallets/in-app/core/wallet/in-app-core.ts 72.01% <93.33%> (+1.57%) ⬆️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Contributor

github-actions bot commented May 22, 2025

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 56.62 KB (0%) 1.2 s (0%) 136 ms (+111.14% 🔺) 1.3 s
thirdweb (cjs) 309.13 KB (0%) 6.2 s (0%) 594 ms (+4.47% 🔺) 6.8 s
thirdweb (minimal + tree-shaking) 5.69 KB (0%) 114 ms (0%) 44 ms (+544.89% 🔺) 158 ms
thirdweb/chains (tree-shaking) 531 B (0%) 11 ms (0%) 6 ms (+115.65% 🔺) 16 ms
thirdweb/react (minimal + tree-shaking) 19.5 KB (0%) 390 ms (0%) 58 ms (+490.04% 🔺) 448 ms

Copy link
Contributor

graphite-app bot commented May 22, 2025

Merge activity

# Add `useAuthToken` hook for in-app wallet authentication

This PR adds a new React hook `useAuthToken()` that returns a JWT authentication token for the currently active in-app wallet. This token can be used to authorize API calls to backend servers.

Key changes:
- Added `useAuthToken()` hook that returns the auth token when an in-app wallet is active
- Modified the `InAppConnector` interface to expose the storage property
- Updated the wallet interface to include a `getAuthToken()` method for in-app wallets
- Implemented token retrieval in the in-app wallet core implementation

The hook ensures the token is only returned when the active wallet is an in-app wallet and matches the active account.

Example usage:
```tsx
function MyComponent() {
  const authToken = useAuthToken();

  const fetchData = async () => {
    const response = await fetch('https://api.example.com/data', {
      headers: {
        'Authorization': `Bearer ${authToken}`
      }
    });
    // ... handle response
  };
}
```

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
	- Introduced a new hook to retrieve authentication tokens for in-app wallets, enabling secure authorization for API calls.
- **Documentation**
	- Added usage examples and clarifications regarding authentication token availability for wallets.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

<!-- start pr-codex -->

---

## PR-Codex overview
This PR focuses on enhancing the wallet functionality by introducing an authentication token feature and updating the visibility of certain properties. It adds a method for retrieving an authentication token and modifies the storage property to be public.

### Detailed summary
- Changed `storage` property from `private` to `public` in `native-connector.ts` and `web-connector.ts`.
- Added `getAuthToken` method to the wallet interface in `wallet.ts` with documentation.
- Included `storage` in the `InAppConnector` interface.
- Implemented `authToken` handling in `createInAppWallet` function.
- Created `useAuthToken` hook for retrieving the JWT of the active wallet.

> ✨ Ask PR-Codex anything about this PR by commenting with `/codex {your question}`

<!-- end pr-codex -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
packages SDK Involves changes to the thirdweb SDK
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants