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

diego/wallet poc #754

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

diego/wallet poc #754

wants to merge 3 commits into from

Conversation

diegoalzate
Copy link
Contributor

@diegoalzate diegoalzate commented Aug 8, 2024

  • add wallet poc
  • add wallet poc routes

Summary by CodeRabbit

  • New Features

    • Introduced fetchSIWENonce and fetchSIWESession functions for nonce retrieval and user session management.
    • Added SIWEButton for wallet authentication, enhancing user experience with improved sign-in and sign-out feedback.
    • Integrated SIWEProvider and ConnectKitProvider for seamless Ethereum authentication and wallet connectivity.
  • Bug Fixes

    • Updated function names for verification processes to improve clarity and maintainability.
  • Documentation

    • Enhanced API exports to include new authentication and session management functions, reflecting the updated capabilities.
  • Chores

    • Added new dependencies to support enhanced functionality related to Ethereum authentication and state management.

Copy link

vercel bot commented Aug 8, 2024

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

Name Status Preview Comments Updated (UTC)
forum-frontend ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 8, 2024 3:43pm

Copy link
Contributor

coderabbitai bot commented Aug 8, 2024

Walkthrough

This update introduces new functionalities centered around the "Sign-In with Ethereum" (SIWE) protocol, enhancing user authentication and session management. Key additions include functions to fetch nonces and sessions, a dedicated verification process, and a new button component for wallet interactions. These changes improve the overall architecture, enabling a seamless user experience while ensuring robust error handling and API integrations.

Changes

Files Change Summary
packages/api/src/fetchSIWENonce.ts Introduced fetchSIWENonce function for retrieving a nonce from a server, with error handling that returns null on failure.
packages/api/src/fetchSIWESession.ts Added fetchSIWESession function to obtain user session details, including error handling and response parsing.
packages/api/src/postSIWEVerify.ts New postSIWEVerify function for server-side signature verification, returning user data or null if failed.
packages/api/src/postZupassVerify.ts Renamed postVerify to postZupassVerify without changing logic, refining the function's purpose.
packages/api/src/index.ts Updated exports to include new SIWE-related functions and replaced postVerify with postZupassVerify.
packages/berlin/package.json Added new dependencies: connectkit, siwe, viem, and wagmi to enhance wallet connectivity and state management.
packages/berlin/src/components/header/Header.tsx Replaced ZupassLoginButton with SIWEButton, altering the login button implementation for improved authentication flow.
packages/berlin/src/components/siwe-button/SIWEButton.tsx Introduced SIWEButton for wallet authentication management, displaying the user's wallet status and handling sign-in/out processes.
packages/berlin/src/components/siwe-button/index.ts Created an index file to simplify imports for SIWEButton.
packages/berlin/src/components/zupass-button/ZupassLoginButton.tsx Updated verification function reference from postVerify to postZupassVerify in ZupassLoginButton component.
packages/berlin/src/main.tsx Integrated SIWEProvider and ConnectKitProvider for enhanced authentication and wallet connectivity, along with updated rendering logic to improve user experience.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SIWEButton
    participant API
    participant Server

    User->>SIWEButton: Clicks Sign In
    SIWEButton->>API: fetchSIWENonce()
    API->>Server: GET /api/auth/siwe/nonce
    Server-->>API: Returns nonce
    API-->>SIWEButton: Returns nonce
    SIWEButton->>API: postSIWEVerify(nonce, signature)
    API->>Server: POST /api/auth/siwe/verify
    Server-->>API: Returns user data
    API-->>SIWEButton: Returns user data
    SIWEButton-->>User: Displays wallet address
Loading

🐰 In a world of code, bright and clear,
With SIWE's magic, no need to fear!
Fetch your nonce, verify with glee,
A hop to the future, come join me!
Checking wallets, signing in,
Let's celebrate this joyful win! 🌟


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

Outside diff range, codebase verification and nitpick comments (5)
packages/api/src/fetchSIWENonce.ts (1)

14-14: Enhance error logging.

Include more context in the error log, such as the server URL, to aid in debugging.

- console.error('Error fetching nonce:', error);
+ console.error(`Error fetching nonce from ${serverUrl}:`, error);
packages/api/src/fetchSIWESession.ts (1)

21-21: Enhance error logging.

Include more context in the error log, such as the server URL, to aid in debugging.

- console.error('Error fetching user:', error);
+ console.error(`Error fetching session from ${serverUrl}:`, error);
packages/api/src/postSIWEVerify.ts (1)

28-28: Enhance error logging.

Include more context in the error log, such as the server URL, to aid in debugging.

- console.error('Error during POST verify request:', error);
+ console.error(`Error during POST verify request to ${serverUrl}:`, error);
packages/berlin/src/components/siwe-button/SIWEButton.tsx (1)

6-64: Well-structured component: SIWEButton.

The SIWEButton component is well-structured and effectively manages sign-in and sign-out states with Ethereum. Consider adding error handling for the signIn and signOut functions to improve robustness, especially in case of network or user-related errors.

+  const handleSignIn = async () => {
+    try {
+      await signIn();
+    } catch (error) {
+      console.error('Sign-in failed:', error);
+    }
+  };

+  const handleSignOut = async () => {
+    try {
+      await signOut();
+    } catch (error) {
+      console.error('Sign-out failed:', error);
+    }
+  };
packages/berlin/src/main.tsx (1)

17-30: Refactor to secure sensitive information.

The walletConnectProjectId is hardcoded in packages/berlin/src/main.tsx. To enhance security, consider retrieving this sensitive information from environment variables or a secure configuration management system instead of hardcoding it directly in the source code.

  • File: packages/berlin/src/main.tsx
  • Line: 18 (where walletConnectProjectId is set)
Analysis chain

Ensure the security of sensitive information.

The config creation is well-structured. Verify that the walletConnectProjectId is securely managed and not exposed inappropriately.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that sensitive information like `walletConnectProjectId` is not exposed inappropriately.

# Test: Search for occurrences of `walletConnectProjectId` in the codebase. Expect: No hardcoded sensitive information.
rg --type js --type ts 'walletConnectProjectId'

Length of output: 140

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 99ad1a0 and a66d330.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (11)
  • packages/api/src/fetchSIWENonce.ts (1 hunks)
  • packages/api/src/fetchSIWESession.ts (1 hunks)
  • packages/api/src/index.ts (1 hunks)
  • packages/api/src/postSIWEVerify.ts (1 hunks)
  • packages/api/src/postZupassVerify.ts (1 hunks)
  • packages/berlin/package.json (2 hunks)
  • packages/berlin/src/components/header/Header.tsx (2 hunks)
  • packages/berlin/src/components/siwe-button/SIWEButton.tsx (1 hunks)
  • packages/berlin/src/components/siwe-button/index.ts (1 hunks)
  • packages/berlin/src/components/zupass-button/ZupassLoginButton.tsx (2 hunks)
  • packages/berlin/src/main.tsx (1 hunks)
Files skipped from review due to trivial changes (3)
  • packages/api/src/postZupassVerify.ts
  • packages/berlin/package.json
  • packages/berlin/src/components/siwe-button/index.ts
Additional context used
Biome
packages/berlin/src/main.tsx

[error] 55-55: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

Additional comments not posted (7)
packages/api/src/index.ts (2)

43-45: New exports: SIWE-related functions.

The addition of postSIWEVerify, fetchSIWENonce, and fetchSIWESession exports aligns with the introduction of SIWE functionality. Ensure these modules are correctly implemented and integrated.


37-37: Export change: postZupassVerify.

The export of postVerify has been replaced with postZupassVerify. Ensure that this change aligns with the intended functionality and that all references to postVerify have been updated accordingly.

Verification successful

Export change verified: postZupassVerify is correctly integrated.

The transition from postVerify to postZupassVerify has been successfully implemented. The postZupassVerify function is defined, exported, and used appropriately in the codebase.

  • postZupassVerify is defined in postZupassVerify.ts.
  • It is exported in index.ts.
  • It is used in ZupassLoginButton.tsx.

No occurrences of postVerify were found, indicating a complete update.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all references to `postVerify` are updated to `postZupassVerify`.

# Test: Search for the usage of `postVerify`. Expect: No occurrences of `postVerify`.
rg --type ts $'postVerify'

Length of output: 25


Script:

#!/bin/bash
# Description: Verify all references to `postZupassVerify` are present and used correctly.

# Test: Search for the usage of `postZupassVerify`. Expect: Occurrences of `postZupassVerify`.
rg --type ts $'postZupassVerify'

Length of output: 379

packages/berlin/src/components/zupass-button/ZupassLoginButton.tsx (1)

Line range hint 11-29:
Updated verification function: postZupassVerify.

The mutation function has been updated to use postZupassVerify. Ensure that this function provides the necessary verification logic and that all dependent components are aware of this change.

packages/berlin/src/main.tsx (2)

6-13: Imports and configuration setup look good.

The new imports related to Ethereum authentication and wallet connectivity are appropriate and align with the objectives of the PR.


62-76: Rendering logic changes are well-implemented.

The integration of WagmiProvider, SIWEProvider, and ConnectKitProvider enhances the application's architecture and aligns with the PR objectives.

packages/berlin/src/components/header/Header.tsx (2)

31-31: Import change to SIWEButton is appropriate.

The replacement of ZupassLoginButton with SIWEButton aligns with the shift towards Ethereum-based authentication.


72-72: Integration of SIWEButton is correct.

The SIWEButton is well-integrated into the Header component, supporting the transition to Ethereum-based authentication.


export async function fetchSIWENonce({ serverUrl }: ApiRequest<unknown>): Promise<string | null> {
try {
const response = await fetch(`${serverUrl}/api/auth/siwe/nonce`);
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding timeout to fetch request.

To prevent the request from hanging indefinitely, consider implementing a timeout mechanism.

Comment on lines +7 to +12
const response = await fetch(`${serverUrl}/api/auth/siwe/session`, {
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding timeout to fetch request.

Implement a timeout mechanism to prevent the request from hanging indefinitely.

Comment on lines +12 to +19
const response = await fetch(`${serverUrl}/api/auth/siwe/verify`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message, signature }),
});
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding timeout to fetch request.

Implement a timeout mechanism to prevent the request from hanging indefinitely.

Comment on lines +32 to +61
const siweConfig: SIWEConfig = {
createMessage: ({ nonce, address, chainId }) =>
new SiweMessage({
version: '1',
domain: window.location.host,
uri: window.location.origin,
address,
chainId,
nonce,
// Human-readable ASCII assertion that the user will sign, and it must not contain `\n`.
statement: 'Sign in With Ethereum.',
}).prepareMessage(),
getNonce: async () =>
fetchSIWENonce({ serverUrl: import.meta.env.VITE_SERVER_URL }).then((nonce) => nonce ?? ''),
verifyMessage: async ({ message, signature }) =>
postSIWEVerify({
serverUrl: import.meta.env.VITE_SERVER_URL,
message,
signature,
}).then((res) => !!res),
getSession: async () =>
fetchSIWESession({ serverUrl: import.meta.env.VITE_SERVER_URL }).then((session) => ({
address: session?.address as `0x${string}`,
chainId: isNaN(Number(session?.chainId)) ? 0 : Number(session?.chainId),
})),
signOut: async () =>
logout({
serverUrl: import.meta.env.VITE_SERVER_URL,
}).then((res) => res.ok),
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix isNaN usage in siweConfig.

The siweConfig object is well-structured, but replace isNaN with Number.isNaN for better type safety.

-      chainId: isNaN(Number(session?.chainId)) ? 0 : Number(session?.chainId),
+      chainId: Number.isNaN(Number(session?.chainId)) ? 0 : Number(session?.chainId),
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
const siweConfig: SIWEConfig = {
createMessage: ({ nonce, address, chainId }) =>
new SiweMessage({
version: '1',
domain: window.location.host,
uri: window.location.origin,
address,
chainId,
nonce,
// Human-readable ASCII assertion that the user will sign, and it must not contain `\n`.
statement: 'Sign in With Ethereum.',
}).prepareMessage(),
getNonce: async () =>
fetchSIWENonce({ serverUrl: import.meta.env.VITE_SERVER_URL }).then((nonce) => nonce ?? ''),
verifyMessage: async ({ message, signature }) =>
postSIWEVerify({
serverUrl: import.meta.env.VITE_SERVER_URL,
message,
signature,
}).then((res) => !!res),
getSession: async () =>
fetchSIWESession({ serverUrl: import.meta.env.VITE_SERVER_URL }).then((session) => ({
address: session?.address as `0x${string}`,
chainId: isNaN(Number(session?.chainId)) ? 0 : Number(session?.chainId),
})),
signOut: async () =>
logout({
serverUrl: import.meta.env.VITE_SERVER_URL,
}).then((res) => res.ok),
};
const siweConfig: SIWEConfig = {
createMessage: ({ nonce, address, chainId }) =>
new SiweMessage({
version: '1',
domain: window.location.host,
uri: window.location.origin,
address,
chainId,
nonce,
// Human-readable ASCII assertion that the user will sign, and it must not contain `\n`.
statement: 'Sign in With Ethereum.',
}).prepareMessage(),
getNonce: async () =>
fetchSIWENonce({ serverUrl: import.meta.env.VITE_SERVER_URL }).then((nonce) => nonce ?? ''),
verifyMessage: async ({ message, signature }) =>
postSIWEVerify({
serverUrl: import.meta.env.VITE_SERVER_URL,
message,
signature,
}).then((res) => !!res),
getSession: async () =>
fetchSIWESession({ serverUrl: import.meta.env.VITE_SERVER_URL }).then((session) => ({
address: session?.address as `0x${string}`,
chainId: Number.isNaN(Number(session?.chainId)) ? 0 : Number(session?.chainId),
})),
signOut: async () =>
logout({
serverUrl: import.meta.env.VITE_SERVER_URL,
}).then((res) => res.ok),
};
Tools
Biome

[error] 55-55: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

@MartinBenediktBusch MartinBenediktBusch linked an issue Aug 9, 2024 that may be closed by this pull request
@diegoalzate diegoalzate removed their assignment Aug 12, 2024
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.

wallet login
1 participant